lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
4f2c654b00f5df680394a1b81f3a2a2075d0cf38
0
ChiralBehaviors/Tron
/* * Copyright (c) 2013 ChiralBehaviors LLC, 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.chiralbehaviors.tron; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayDeque; import java.util.Deque; import java.util.concurrent.Callable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Finite State Machine implementation. * * @author hhildebrand * * @param <Transitions> the transition interface * @param <Context> the fsm context interface */ public final class Fsm<Context, Transitions> { private static class PendingTransition implements InvocationHandler { private volatile Object[] args; private volatile Method method; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (this.method != null) { throw new IllegalStateException( String.format("Pop transition '%s' has already been established", method.toGenericString())); } this.method = method; this.args = args; return null; } } private static final Logger DEFAULT_LOG = LoggerFactory.getLogger(Fsm.class); private static final ThreadLocal<Fsm<?, ?>> thisFsm = new ThreadLocal<>(); /** * Construct a new instance of a finite state machine. * * @param fsmContext - the object used as the action context for this FSM * @param transitions - the interface class used to define the transitions for * this FSM * @param transitionsCL - the class loader to be used to load the transitions * interface class * @param initialState - the initial state of the FSM * @param sync - true if this FSM is to synchronize state transitions. * This is required for multi-threaded use of the FSM * @return the Fsm instance */ public static <Context, Transitions> Fsm<Context, Transitions> construct(Context fsmContext, Class<Transitions> transitions, ClassLoader transitionsCL, Enum<?> initialState, boolean sync) { if (!transitions.isAssignableFrom(initialState.getClass())) { throw new IllegalArgumentException( String.format("Supplied initial state '%s' does not implement the transitions interface '%s'", initialState, transitions)); } Fsm<Context, Transitions> fsm = new Fsm<>(fsmContext, sync, transitions, transitionsCL); @SuppressWarnings("unchecked") Transitions initial = (Transitions) initialState; fsm.current = initial; return fsm; } /** * Construct a new instance of a finite state machine with a default * ClassLoader. */ public static <Context, Transitions> Fsm<Context, Transitions> construct(Context fsmContext, Class<Transitions> transitions, Enum<?> initialState, boolean sync) { return construct(fsmContext, transitions, fsmContext.getClass().getClassLoader(), initialState, sync); } /** * * @return the Context of the currently executing Fsm */ public static <Context> Context thisContext() { @SuppressWarnings("unchecked") Fsm<Context, ?> fsm = (Fsm<Context, ?>) thisFsm.get(); return fsm.getContext(); } /** * * @return the currrently executing Fsm */ public static <Context, Transitions> Fsm<Context, Transitions> thisFsm() { @SuppressWarnings("unchecked") Fsm<Context, Transitions> fsm = (Fsm<Context, Transitions>) thisFsm.get(); return fsm; } private final Context context; private volatile Transitions current; private volatile Logger log; private volatile String name = ""; private volatile boolean pendingPop = false; private volatile Transitions pendingPush; private volatile PendingTransition popTransition; private volatile Transitions previous; private final Transitions proxy; private final Deque<Transitions> stack = new ArrayDeque<>(); private final Lock sync; private volatile String transition; private final Class<Transitions> transitionsType; private volatile PendingTransition pushTransition; Fsm(Context context, boolean sync, Class<Transitions> transitionsType, ClassLoader transitionsCL) { this.context = context; this.sync = sync ? new ReentrantLock() : null; this.transitionsType = transitionsType; this.log = DEFAULT_LOG; @SuppressWarnings("unchecked") Transitions facade = (Transitions) Proxy.newProxyInstance(transitionsCL, new Class<?>[] { transitionsType }, transitionsHandler()); proxy = facade; } /** * Execute the initial state's entry action. Note that we do not guard against * multiple invocations. */ public void enterStartState() { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Entering start state %s", name, prettyPrint(current))); } executeEntryAction(); } /** * * @return the action context object of this Fsm */ public Context getContext() { return context; } /** * * @return the current state of the Fsm */ public Transitions getCurrentState() { return locked(() -> { Transitions transitions = current; return transitions; }); } /** * * @return the logger used by this Fsm */ public Logger getLog() { return locked(() -> { Logger c = log; return c; }); } public String getName() { return name; } /** * * @return the previous state of the Fsm, or null if no previous state */ public Transitions getPreviousState() { return locked(() -> { Transitions transitions = previous; return transitions; }); } /** * @return the invalid transition excepiton based current transition attempt */ public InvalidTransition invalidTransitionOn() { return new InvalidTransition(String.format("[%s] %s.%s", name, prettyPrint(current), transition)); } /** * * @return the String representation of the current transition */ public String getTransition() { return locked(() -> { final String c = transition; return c; }); } /** * * @return the Transitions object that drives this Fsm through its transitions */ public Transitions getTransitions() { return proxy; } /** * Pop the state off of the stack of pushed states. This state will become the * current state of the Fsm. Answer the Transitions object that may be used to * send a transition to the popped state. * * @return the Transitions object that may be used to send a transition to the * popped state. */ public Transitions pop() { if (pendingPop) { throw new IllegalStateException(String.format("[%s] State has already been popped", name)); } if (pendingPush != null) { throw new IllegalStateException(String.format("[%s] Cannot pop after pushing", name)); } if (stack.size() == 0) { throw new IllegalStateException(String.format("[%s] State stack is empty", name)); } pendingPop = true; popTransition = new PendingTransition(); @SuppressWarnings("unchecked") Transitions pendingTransition = (Transitions) Proxy.newProxyInstance(context.getClass().getClassLoader(), new Class<?>[] { transitionsType }, popTransition); return pendingTransition; } public String prettyPrint(Transitions state) { if (state == null) { return "null"; } Class<?> enclosingClass = state.getClass().getEnclosingClass(); return String.format("%s.%s", (enclosingClass != null ? enclosingClass : state.getClass()).getSimpleName(), ((Enum<?>) state).name()); } /** * Push the current state of the Fsm on the state stack. The supplied state * becomes the current state of the Fsm * * @param state - the new current state of the Fsm. */ public Transitions push(Transitions state) { if (state == null) { throw new IllegalStateException(String.format("[%s] Cannot push a null state", name)); } if (pendingPush != null) { throw new IllegalStateException(String.format("[%s] Cannot push state twice", name)); } if (pendingPop) { throw new IllegalStateException(String.format("[%s] Cannot push after pop", name)); } pushTransition = new PendingTransition(); pendingPush = state; @SuppressWarnings("unchecked") Transitions pendingTransition = (Transitions) Proxy.newProxyInstance(context.getClass().getClassLoader(), new Class<?>[] { transitionsType }, pushTransition); return pendingTransition; } /** * Set the Logger for this Fsm. * * @param log - the Logger of this Fsm */ public void setLog(Logger log) { this.log = log; } public void setName(String name) { this.name = name; } public <R> R synchonizeOnState(Callable<R> call) throws Exception { return locked(call); } public void synchonizeOnState(Runnable call) { locked(() -> { call.run(); return null; }); } @Override public String toString() { return String.format("Fsm [name = %s, current=%s, previous=%s, transition=%s]", name, prettyPrint(current), prettyPrint(previous), getTransition()); } private void executeEntryAction() { for (Method action : current.getClass().getDeclaredMethods()) { if (action.isAnnotationPresent(Entry.class)) { action.setAccessible(true); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Entry action: %s.%s", name, prettyPrint(current), prettyPrint(action))); } try { // For entry actions with parameters, inject the context if (action.getParameterTypes().length > 0) action.invoke(current, context); else action.invoke(current, new Object[] {}); return; } catch (IllegalAccessException | IllegalArgumentException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } throw new IllegalStateException(targetException); } } } } private void executeExitAction() { for (Method action : current.getClass().getDeclaredMethods()) { if (action.isAnnotationPresent(Exit.class)) { action.setAccessible(true); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Exit action: %s.%s", name, prettyPrint(current), prettyPrint(action))); } try { // For exit action with parameters, inject the context if (action.getParameterTypes().length > 0) action.invoke(current, context); else action.invoke(current, new Object[] {}); return; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException(e); } } } } /** * The Jesus Nut * * @param t - the transition to fire * @param arguments - the transition arguments * @return */ private Object fire(Method t, Object[] arguments) { if (t == null) { return null; } Fsm<?, ?> previousFsm = thisFsm.get(); thisFsm.set(this); previous = current; if (!transitionsType.isAssignableFrom(t.getReturnType())) { try { return t.invoke(current, arguments); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException(e); } } try { return locked(() -> { transition = prettyPrint(t); Transitions nextState; Transitions pinned = current; try { nextState = fireTransition(lookupTransition(t), arguments); } catch (InvalidTransition e) { nextState = fireTransition(lookupDefaultTransition(e, t), arguments); } if (pinned == current) { transitionTo(nextState); } else { if (nextState != null && log.isTraceEnabled()) { log.trace(String.format("[%s] Eliding Transition %s -> %s, pinned state: %s", name, prettyPrint(current), prettyPrint(nextState), prettyPrint(pinned))); } } return null; }); } finally { thisFsm.set(previousFsm); } } /** * Fire the concrete transition of the current state * * @param stateTransition - the transition method to execute * @param arguments - the arguments of the method * * @return the next state */ @SuppressWarnings("unchecked") private Transitions fireTransition(Method stateTransition, Object[] arguments) { if (stateTransition.isAnnotationPresent(Default.class)) { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Default transition: %s.%s", prettyPrint(current)), getTransition(), name); } try { return (Transitions) stateTransition.invoke(current, (Object[]) null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException(String.format("Unable to invoke transition %s,%s", prettyPrint(current), prettyPrint(stateTransition)), e); } } if (log.isTraceEnabled()) { log.trace(String.format("[%s] Transition: %s.%s", name, prettyPrint(current), getTransition())); } try { return (Transitions) stateTransition.invoke(current, arguments); } catch (IllegalAccessException | IllegalArgumentException e) { throw new IllegalStateException(String.format("Unable to invoke transition %s.%s", prettyPrint(current), prettyPrint(stateTransition)), e.getCause()); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof InvalidTransition) { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Invalid transition %s.%s", name, prettyPrint(current), getTransition())); } throw (InvalidTransition) e.getTargetException(); } if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } throw new IllegalStateException(String.format("[%s] Unable to invoke transition %s.%s", name, prettyPrint(current), prettyPrint(stateTransition)), e.getTargetException()); } } private <T> T locked(Callable<T> call) { final Lock lock = sync; if (lock != null) { lock.lock(); } try { return call.call(); } catch (RuntimeException e) { throw (RuntimeException) e; } catch (Exception e) { throw new IllegalStateException(e); } finally { if (lock != null) { lock.unlock(); } } } private Method lookupDefaultTransition(InvalidTransition previousException, Method t) { // look for a @Default transition for the state singleton for (Method defaultTransition : current.getClass().getDeclaredMethods()) { if (defaultTransition.isAnnotationPresent(Default.class)) { defaultTransition.setAccessible(true); return defaultTransition; } } // look for a @Default transition for the state on the enclosing enum class for (Method defaultTransition : current.getClass().getMethods()) { if (defaultTransition.isAnnotationPresent(Default.class)) { defaultTransition.setAccessible(true); return defaultTransition; } } if (previousException == null) { throw new InvalidTransition(String.format(prettyPrint(t))); } else { throw previousException; } } /** * Lookup the transition. * * @param t - the transition defined in the interface * @return the transition Method for the current state matching the interface * definition */ private Method lookupTransition(Method t) { Method stateTransition = null; try { // First we try declared methods on the state stateTransition = current.getClass().getMethod(t.getName(), t.getParameterTypes()); } catch (NoSuchMethodException | SecurityException e1) { throw new IllegalStateException( String.format("Inconcievable! The state %s does not implement the transition %s", prettyPrint(current), prettyPrint(t))); } stateTransition.setAccessible(true); return stateTransition; } /** * Ye olde tyme state transition * * @param nextState - the next state of the Fsm */ private void normalTransition(Transitions nextState) { if (nextState == null) { // internal loopback transition if (log.isTraceEnabled()) { log.trace(String.format("[%s] Internal loopback: %s", name, prettyPrint(current))); } return; } executeExitAction(); if (log.isTraceEnabled()) { log.trace(String.format("[%s] State transition: %s -> %s", name, prettyPrint(current), prettyPrint(nextState))); } current = nextState; executeEntryAction(); } /** * Execute the exit action of the current state. Set current state to popped * state of the stack. Execute any pending transition on the current state. */ private void popTransition() { pendingPop = false; previous = current; Transitions pop = stack.pop(); PendingTransition pendingTransition = popTransition; popTransition = null; executeExitAction(); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Popping(%s) from: %s to: %s", name, stack.size() + 1, prettyPrint(previous), prettyPrint(pop))); } current = pop; if (pendingTransition != null) { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Pop transition: %s.%s", name, prettyPrint(current), prettyPrint(pendingTransition.method))); } fire(pendingTransition.method, pendingTransition.args); } } private String prettyPrint(Method transition) { StringBuilder builder = new StringBuilder(); if (transition != null) { builder.append(transition.getName()); builder.append('('); Class<?>[] parameters = transition.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { builder.append(parameters[i].getSimpleName()); if (i != parameters.length - 1) { builder.append(", "); } } builder.append(')'); } else { builder.append("loopback"); } return builder.toString(); } /** * Push the current state of the Fsm to the stack. If non null, transition the * Fsm to the nextState, execute the entry action of that state. Set the current * state of the Fsm to the pending push state, executing the entry action on * that state * * @param nextState */ private void pushTransition(Transitions nextState) { Transitions pushed = pendingPush; pendingPush = null; normalTransition(nextState); stack.push(current); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Pushing(%s) %s -> %s", name, stack.size(), prettyPrint(current), prettyPrint(pushed))); } current = pushed; Transitions pinned = current; PendingTransition pushTrns = pushTransition; pushTransition = null; executeEntryAction(); if (pushTrns != null) { if (current != pinned) { log.trace(String.format("[%s] Eliding push transition %s.%s pinned: %s", name, prettyPrint(current), prettyPrint(pushTrns.method), prettyPrint(pinned))); } else { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Push transition: %s.%s", name, prettyPrint(current), prettyPrint(pushTrns.method))); } fire(pushTrns.method, pushTrns.args); } } } private InvocationHandler transitionsHandler() { return new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return fire(method, args); } }; } /** * Transition to the next state * * @param nextState */ private void transitionTo(Transitions nextState) { if (pendingPush != null) { pushTransition(nextState); } else if (pendingPop) { popTransition(); } else { normalTransition(nextState); } } }
framework/src/main/java/com/chiralbehaviors/tron/Fsm.java
/* * Copyright (c) 2013 ChiralBehaviors LLC, 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.chiralbehaviors.tron; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayDeque; import java.util.Deque; import java.util.concurrent.Callable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Finite State Machine implementation. * * @author hhildebrand * * @param <Transitions> the transition interface * @param <Context> the fsm context interface */ public final class Fsm<Context, Transitions> { private static class PendingTransition implements InvocationHandler { private volatile Object[] args; private volatile Method method; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (this.method != null) { throw new IllegalStateException( String.format("Pop transition '%s' has already been established", method.toGenericString())); } this.method = method; this.args = args; return null; } } private static final Logger DEFAULT_LOG = LoggerFactory.getLogger(Fsm.class); private static final ThreadLocal<Fsm<?, ?>> thisFsm = new ThreadLocal<>(); /** * Construct a new instance of a finite state machine. * * @param fsmContext - the object used as the action context for this FSM * @param transitions - the interface class used to define the transitions for * this FSM * @param transitionsCL - the class loader to be used to load the transitions * interface class * @param initialState - the initial state of the FSM * @param sync - true if this FSM is to synchronize state transitions. * This is required for multi-threaded use of the FSM * @return the Fsm instance */ public static <Context, Transitions> Fsm<Context, Transitions> construct(Context fsmContext, Class<Transitions> transitions, ClassLoader transitionsCL, Enum<?> initialState, boolean sync) { if (!transitions.isAssignableFrom(initialState.getClass())) { throw new IllegalArgumentException( String.format("Supplied initial state '%s' does not implement the transitions interface '%s'", initialState, transitions)); } Fsm<Context, Transitions> fsm = new Fsm<>(fsmContext, sync, transitions, transitionsCL); @SuppressWarnings("unchecked") Transitions initial = (Transitions) initialState; fsm.current = initial; return fsm; } /** * Construct a new instance of a finite state machine with a default * ClassLoader. */ public static <Context, Transitions> Fsm<Context, Transitions> construct(Context fsmContext, Class<Transitions> transitions, Enum<?> initialState, boolean sync) { return construct(fsmContext, transitions, fsmContext.getClass().getClassLoader(), initialState, sync); } /** * * @return the Context of the currently executing Fsm */ public static <Context> Context thisContext() { @SuppressWarnings("unchecked") Fsm<Context, ?> fsm = (Fsm<Context, ?>) thisFsm.get(); return fsm.getContext(); } /** * * @return the currrently executing Fsm */ public static <Context, Transitions> Fsm<Context, Transitions> thisFsm() { @SuppressWarnings("unchecked") Fsm<Context, Transitions> fsm = (Fsm<Context, Transitions>) thisFsm.get(); return fsm; } private final Context context; private volatile Transitions current; private volatile Logger log; private volatile String name = ""; private volatile boolean pendingPop = false; private volatile Transitions pendingPush; private volatile PendingTransition popTransition; private volatile Transitions previous; private final Transitions proxy; private final Deque<Transitions> stack = new ArrayDeque<>(); private final Lock sync; private volatile String transition; private final Class<Transitions> transitionsType; private volatile PendingTransition pushTransition; Fsm(Context context, boolean sync, Class<Transitions> transitionsType, ClassLoader transitionsCL) { this.context = context; this.sync = sync ? new ReentrantLock(true) : null; this.transitionsType = transitionsType; this.log = DEFAULT_LOG; @SuppressWarnings("unchecked") Transitions facade = (Transitions) Proxy.newProxyInstance(transitionsCL, new Class<?>[] { transitionsType }, transitionsHandler()); proxy = facade; } /** * Execute the initial state's entry action. Note that we do not guard against * multiple invocations. */ public void enterStartState() { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Entering start state %s", name, prettyPrint(current))); } executeEntryAction(); } /** * * @return the action context object of this Fsm */ public Context getContext() { return context; } /** * * @return the current state of the Fsm */ public Transitions getCurrentState() { return locked(() -> { Transitions transitions = current; return transitions; }); } /** * * @return the logger used by this Fsm */ public Logger getLog() { return locked(() -> { Logger c = log; return c; }); } public String getName() { return name; } /** * * @return the previous state of the Fsm, or null if no previous state */ public Transitions getPreviousState() { return locked(() -> { Transitions transitions = previous; return transitions; }); } /** * @return the invalid transition excepiton based current transition attempt */ public InvalidTransition invalidTransitionOn() { return new InvalidTransition(String.format("[%s] %s.%s", name, prettyPrint(current), transition)); } /** * * @return the String representation of the current transition */ public String getTransition() { return locked(() -> { final String c = transition; return c; }); } /** * * @return the Transitions object that drives this Fsm through its transitions */ public Transitions getTransitions() { return proxy; } /** * Pop the state off of the stack of pushed states. This state will become the * current state of the Fsm. Answer the Transitions object that may be used to * send a transition to the popped state. * * @return the Transitions object that may be used to send a transition to the * popped state. */ public Transitions pop() { if (pendingPop) { throw new IllegalStateException(String.format("[%s] State has already been popped", name)); } if (pendingPush != null) { throw new IllegalStateException(String.format("[%s] Cannot pop after pushing", name)); } if (stack.size() == 0) { throw new IllegalStateException(String.format("[%s] State stack is empty", name)); } pendingPop = true; popTransition = new PendingTransition(); @SuppressWarnings("unchecked") Transitions pendingTransition = (Transitions) Proxy.newProxyInstance(context.getClass().getClassLoader(), new Class<?>[] { transitionsType }, popTransition); return pendingTransition; } public String prettyPrint(Transitions state) { if (state == null) { return "null"; } Class<?> enclosingClass = state.getClass().getEnclosingClass(); return String.format("%s.%s", (enclosingClass != null ? enclosingClass : state.getClass()).getSimpleName(), ((Enum<?>) state).name()); } /** * Push the current state of the Fsm on the state stack. The supplied state * becomes the current state of the Fsm * * @param state - the new current state of the Fsm. */ public Transitions push(Transitions state) { if (state == null) { throw new IllegalStateException(String.format("[%s] Cannot push a null state", name)); } if (pendingPush != null) { throw new IllegalStateException(String.format("[%s] Cannot push state twice", name)); } if (pendingPop) { throw new IllegalStateException(String.format("[%s] Cannot push after pop", name)); } pushTransition = new PendingTransition(); pendingPush = state; @SuppressWarnings("unchecked") Transitions pendingTransition = (Transitions) Proxy.newProxyInstance(context.getClass().getClassLoader(), new Class<?>[] { transitionsType }, pushTransition); return pendingTransition; } /** * Set the Logger for this Fsm. * * @param log - the Logger of this Fsm */ public void setLog(Logger log) { this.log = log; } public void setName(String name) { this.name = name; } public <R> R synchonizeOnState(Callable<R> call) throws Exception { return locked(call); } public void synchonizeOnState(Runnable call) { locked(() -> { call.run(); return null; }); } @Override public String toString() { return String.format("Fsm [name = %s, current=%s, previous=%s, transition=%s]", name, prettyPrint(current), prettyPrint(previous), getTransition()); } private void executeEntryAction() { for (Method action : current.getClass().getDeclaredMethods()) { if (action.isAnnotationPresent(Entry.class)) { action.setAccessible(true); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Entry action: %s.%s", name, prettyPrint(current), prettyPrint(action))); } try { // For entry actions with parameters, inject the context if (action.getParameterTypes().length > 0) action.invoke(current, context); else action.invoke(current, new Object[] {}); return; } catch (IllegalAccessException | IllegalArgumentException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } throw new IllegalStateException(targetException); } } } } private void executeExitAction() { for (Method action : current.getClass().getDeclaredMethods()) { if (action.isAnnotationPresent(Exit.class)) { action.setAccessible(true); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Exit action: %s.%s", name, prettyPrint(current), prettyPrint(action))); } try { // For exit action with parameters, inject the context if (action.getParameterTypes().length > 0) action.invoke(current, context); else action.invoke(current, new Object[] {}); return; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException(e); } } } } /** * The Jesus Nut * * @param t - the transition to fire * @param arguments - the transition arguments * @return */ private Object fire(Method t, Object[] arguments) { if (t == null) { return null; } Fsm<?, ?> previousFsm = thisFsm.get(); thisFsm.set(this); previous = current; if (!transitionsType.isAssignableFrom(t.getReturnType())) { try { return t.invoke(current, arguments); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException(e); } } try { return locked(() -> { transition = prettyPrint(t); Transitions nextState; Transitions pinned = current; try { nextState = fireTransition(lookupTransition(t), arguments); } catch (InvalidTransition e) { nextState = fireTransition(lookupDefaultTransition(e, t), arguments); } if (pinned == current) { transitionTo(nextState); } else { if (nextState != null && log.isTraceEnabled()) { log.trace(String.format("[%s] Eliding Transition %s -> %s, pinned state: %s", name, prettyPrint(current), prettyPrint(nextState), prettyPrint(pinned))); } } return null; }); } finally { thisFsm.set(previousFsm); } } /** * Fire the concrete transition of the current state * * @param stateTransition - the transition method to execute * @param arguments - the arguments of the method * * @return the next state */ @SuppressWarnings("unchecked") private Transitions fireTransition(Method stateTransition, Object[] arguments) { if (stateTransition.isAnnotationPresent(Default.class)) { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Default transition: %s.%s", prettyPrint(current)), getTransition(), name); } try { return (Transitions) stateTransition.invoke(current, (Object[]) null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException(String.format("Unable to invoke transition %s,%s", prettyPrint(current), prettyPrint(stateTransition)), e); } } if (log.isTraceEnabled()) { log.trace(String.format("[%s] Transition: %s.%s", name, prettyPrint(current), getTransition())); } try { return (Transitions) stateTransition.invoke(current, arguments); } catch (IllegalAccessException | IllegalArgumentException e) { throw new IllegalStateException(String.format("Unable to invoke transition %s.%s", prettyPrint(current), prettyPrint(stateTransition)), e.getCause()); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof InvalidTransition) { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Invalid transition %s.%s", name, prettyPrint(current), getTransition())); } throw (InvalidTransition) e.getTargetException(); } if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } throw new IllegalStateException(String.format("[%s] Unable to invoke transition %s.%s", name, prettyPrint(current), prettyPrint(stateTransition)), e.getTargetException()); } } private <T> T locked(Callable<T> call) { final Lock lock = sync; if (lock != null) { lock.lock(); } try { return call.call(); } catch (RuntimeException e) { throw (RuntimeException) e; } catch (Exception e) { throw new IllegalStateException(e); } finally { if (lock != null) { lock.unlock(); } } } private Method lookupDefaultTransition(InvalidTransition previousException, Method t) { // look for a @Default transition for the state singleton for (Method defaultTransition : current.getClass().getDeclaredMethods()) { if (defaultTransition.isAnnotationPresent(Default.class)) { defaultTransition.setAccessible(true); return defaultTransition; } } // look for a @Default transition for the state on the enclosing enum class for (Method defaultTransition : current.getClass().getMethods()) { if (defaultTransition.isAnnotationPresent(Default.class)) { defaultTransition.setAccessible(true); return defaultTransition; } } if (previousException == null) { throw new InvalidTransition(String.format(prettyPrint(t))); } else { throw previousException; } } /** * Lookup the transition. * * @param t - the transition defined in the interface * @return the transition Method for the current state matching the interface * definition */ private Method lookupTransition(Method t) { Method stateTransition = null; try { // First we try declared methods on the state stateTransition = current.getClass().getMethod(t.getName(), t.getParameterTypes()); } catch (NoSuchMethodException | SecurityException e1) { throw new IllegalStateException( String.format("Inconcievable! The state %s does not implement the transition %s", prettyPrint(current), prettyPrint(t))); } stateTransition.setAccessible(true); return stateTransition; } /** * Ye olde tyme state transition * * @param nextState - the next state of the Fsm */ private void normalTransition(Transitions nextState) { if (nextState == null) { // internal loopback transition if (log.isTraceEnabled()) { log.trace(String.format("[%s] Internal loopback: %s", name, prettyPrint(current))); } return; } executeExitAction(); if (log.isTraceEnabled()) { log.trace(String.format("[%s] State transition: %s -> %s", name, prettyPrint(current), prettyPrint(nextState))); } current = nextState; executeEntryAction(); } /** * Execute the exit action of the current state. Set current state to popped * state of the stack. Execute any pending transition on the current state. */ private void popTransition() { pendingPop = false; previous = current; Transitions pop = stack.pop(); PendingTransition pendingTransition = popTransition; popTransition = null; executeExitAction(); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Popping(%s) from: %s to: %s", name, stack.size() + 1, prettyPrint(previous), prettyPrint(pop))); } current = pop; if (pendingTransition != null) { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Pop transition: %s.%s", name, prettyPrint(current), prettyPrint(pendingTransition.method))); } fire(pendingTransition.method, pendingTransition.args); } } private String prettyPrint(Method transition) { StringBuilder builder = new StringBuilder(); if (transition != null) { builder.append(transition.getName()); builder.append('('); Class<?>[] parameters = transition.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { builder.append(parameters[i].getSimpleName()); if (i != parameters.length - 1) { builder.append(", "); } } builder.append(')'); } else { builder.append("loopback"); } return builder.toString(); } /** * Push the current state of the Fsm to the stack. If non null, transition the * Fsm to the nextState, execute the entry action of that state. Set the current * state of the Fsm to the pending push state, executing the entry action on * that state * * @param nextState */ private void pushTransition(Transitions nextState) { Transitions pushed = pendingPush; pendingPush = null; normalTransition(nextState); stack.push(current); if (log.isTraceEnabled()) { log.trace(String.format("[%s] Pushing(%s) %s -> %s", name, stack.size(), prettyPrint(current), prettyPrint(pushed))); } current = pushed; Transitions pinned = current; PendingTransition pushTrns = pushTransition; pushTransition = null; executeEntryAction(); if (pushTrns != null) { if (current != pinned) { log.trace(String.format("[%s] Eliding push transition %s.%s pinned: %s", name, prettyPrint(current), prettyPrint(pushTrns.method), prettyPrint(pinned))); } else { if (log.isTraceEnabled()) { log.trace(String.format("[%s] Push transition: %s.%s", name, prettyPrint(current), prettyPrint(pushTrns.method))); } fire(pushTrns.method, pushTrns.args); } } } private InvocationHandler transitionsHandler() { return new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return fire(method, args); } }; } /** * Transition to the next state * * @param nextState */ private void transitionTo(Transitions nextState) { if (pendingPush != null) { pushTransition(nextState); } else if (pendingPop) { popTransition(); } else { normalTransition(nextState); } } }
do not use fair sync
framework/src/main/java/com/chiralbehaviors/tron/Fsm.java
do not use fair sync
<ide><path>ramework/src/main/java/com/chiralbehaviors/tron/Fsm.java <ide> <ide> Fsm(Context context, boolean sync, Class<Transitions> transitionsType, ClassLoader transitionsCL) { <ide> this.context = context; <del> this.sync = sync ? new ReentrantLock(true) : null; <add> this.sync = sync ? new ReentrantLock() : null; <ide> this.transitionsType = transitionsType; <ide> this.log = DEFAULT_LOG; <ide> @SuppressWarnings("unchecked")
Java
mit
74eb86ab93bef1c9f4f2ce10927a2e226926f0e3
0
chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster
package fi.csc.microarray.client.visualisation.methods; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import org.apache.log4j.Logger; import org.jfree.chart.BioChartFactory; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.HCTreeNodeEntity; import org.jfree.chart.entity.HeatMapBlockEntity; import org.jfree.chart.event.ClusteringTreeChangeEvent; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.PlotChangeListener; import org.jfree.chart.labels.StandardHCToolTipGenerator; import org.jfree.chart.plot.GradientColorPalette; import org.jfree.chart.plot.HCPlot; import org.jfree.chart.plot.HCPlot.Selection; import org.jfree.chart.title.TextTitle; import org.jfree.data.hc.DataRange; import org.jfree.data.hc.DataRangeMismatchException; import org.jfree.data.hc.HCDataset; import org.jfree.data.hc.HCTreeNode; import org.jfree.data.hc.HeatMap; import fi.csc.microarray.ErrorReportAsException; import fi.csc.microarray.MicroarrayException; import fi.csc.microarray.client.selection.RowChoiceEvent; import fi.csc.microarray.client.selection.RowSelectionManager; import fi.csc.microarray.client.visualisation.AnnotateListPanel; import fi.csc.microarray.client.visualisation.TableAnnotationProvider; import fi.csc.microarray.client.visualisation.Visualisation; import fi.csc.microarray.client.visualisation.VisualisationFrame; import fi.csc.microarray.client.visualisation.methods.SelectableChartPanel.SelectionChangeListener; import fi.csc.microarray.client.visualisation.methods.hc.OrderSuperviser; import fi.csc.microarray.cluster.ClusterBranchNode; import fi.csc.microarray.cluster.ClusterLeafNode; import fi.csc.microarray.cluster.ClusterNode; import fi.csc.microarray.cluster.ClusterParser; import fi.csc.microarray.databeans.DataBean; import fi.csc.microarray.databeans.DataBean.Link; import fi.csc.microarray.databeans.DataBean.Traversal; import fi.csc.microarray.databeans.features.QueryResult; import fi.csc.microarray.databeans.features.Table; public class HierarchicalClustering extends Visualisation implements PropertyChangeListener, SelectionChangeListener { public HierarchicalClustering(VisualisationFrame frame) { super(frame); } private SelectableChartPanel selectableChartPanel; private static final Logger logger = Logger.getLogger(HierarchicalClustering.class); OrderSuperviser orders; private JPanel paramPanel; private AnnotateListPanel list; //Selected indexes in the order of parent data bean private Set<Integer> selected = new HashSet<Integer>(); private DataBean selectionBean; private HCPlot hcPlot; private boolean reversed; private JPanel zoomChangerPanel; private JPanel spaceFiller; private JScrollPane scroller; private Dimension preferredSize; private JCheckBox zoomCheckBox; private class MicroarrayHCToolTipGenerator extends StandardHCToolTipGenerator { /** * Creates tooltip for Hierarchical clustering visualisation. The * tooltip includes chip and gene names and value. * * The code is mainly copied from StandardHCToolTipGenerator * * Note! The rows and columns are in different order than in original * version of this method. In the Viski library the rows and columns are * messed up. */ @Override public String generateToolTip(HeatMap heatmap, DataRange rowRange, DataRange columnRange) { int minRow; int maxRow; int minColumn; int maxColumn; int rowCounter; int columnCounter; int blockCount; double averageValue; try { minRow = rowRange.getLeftBound(); maxRow = rowRange.getRightBound(); minColumn = columnRange.getLeftBound(); maxColumn = columnRange.getRightBound(); } catch (Exception e) { return "This block contains no data."; } if ((minRow == maxRow) && (minColumn == maxColumn)) { return "(" + heatmap.getRowName(minRow) + "," + heatmap.getColumnName(minColumn) + ") = " + heatmap.get(minRow, minColumn); } for (averageValue = 0, blockCount = 0, rowCounter = minRow; rowCounter <= maxRow; rowCounter++) { for (columnCounter = minColumn; columnCounter <= maxColumn; columnCounter++, blockCount++) { averageValue += heatmap.get(rowCounter, columnCounter); } } averageValue = averageValue / blockCount; return "(" + heatmap.getRowName(minRow) + "," + heatmap.getColumnName(minColumn) + ") .. " + "(" + heatmap.getRowName(maxRow) + "," + heatmap.getColumnName(maxColumn) + ") = " + averageValue + " (contains " + (blockCount + 1) + " blocks)"; } } @Override public JPanel getParameterPanel() { if (paramPanel == null) { paramPanel = new JPanel(); paramPanel.setPreferredSize(Visualisation.PARAMETER_SIZE); paramPanel.setLayout(new BorderLayout()); JPanel settings = this.createSettingsPanel(); list = new AnnotateListPanel(); JTabbedPane tabPane = new JTabbedPane(); tabPane.addTab("Settings", settings); tabPane.addTab("Selected", list); paramPanel.add(tabPane, BorderLayout.CENTER); } return paramPanel; } public JPanel createSettingsPanel() { JPanel settingsPanel = new JPanel(); settingsPanel.setLayout(new GridBagLayout()); settingsPanel.setPreferredSize(Visualisation.PARAMETER_SIZE); zoomCheckBox = new JCheckBox("Fit to screen", false); zoomCheckBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { setScaledMode(zoomCheckBox.isSelected()); } }); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; c.insets.set(10, 10, 0, 10); c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.HORIZONTAL; c.weighty = 0; c.weightx = 1.0; settingsPanel.add(zoomCheckBox, c); c.gridy++; c.fill = GridBagConstraints.BOTH; c.weighty = 1.0; settingsPanel.add(new JPanel(), c); return settingsPanel; } /** * getVisualisation method has too modes. If the genes are clustered the * mode is normal and in reversed mode the chips are clustered. Both modes * are implemented in turns of couple rows which makes the structure very * ugly and vulnerable for mistakes. Maybe some day there is time to * restructure this method. * * @throws MicroarrayException * is parsing or visualisation generation fails */ @Override public JComponent getVisualisation(DataBean data) throws MicroarrayException { //There is no point to bind selections to HC data because it's not possible to visualise it //with other visualisation methods. It's parent is used instead. List<DataBean> selectionBeans = data.traverseLinks(new Link[] {Link.DERIVATION}, Traversal.DIRECT); //First one is hc data //TODO there is no point to find all ancestors if(selectionBeans.size() > 1){ selectionBean = selectionBeans.get(1); } if(selectionBean == null){ throw new ErrorReportAsException("Source dataset not found", "Hierarchical clustering " + "needs its source dataset.", " Select both HC and its source dataset by keeping \n" + "Ctrl key pressed and right click with mouse over one of them to create \n" + "derivation link from the original dataset to \n" + "clustered one."); } try { String hcTree = data.queryFeatures("/clusters/hierarchical/tree").asStrings().iterator().next(); // create heatmap QueryResult heatMapFeature = data.queryFeatures("/clusters/hierarchical/heatmap"); Table heatMapData = heatMapFeature.asTable(); TableAnnotationProvider annotationProvider = new TableAnnotationProvider(selectionBean); // count rows int rowCount = 0; while (heatMapData.nextRow()) { rowCount++; } LinkedList<String> columns = new LinkedList<String>(); for (String columnName : heatMapData.getColumnNames()) { if (columnName.startsWith("chip.")) { columns.add(columnName); } else { logger.debug("Column skipped in HC: " + columnName); } } int columnCount = columns.size(); // HC tree has to be done first to find out the order of rows and number of rows HCTreeNode root = null; ClusterParser parser = new ClusterParser(hcTree); ClusterBranchNode tree = parser.getTree(); // check which way we have clustered reversed = hcTree.contains("chip."); HeatMap heatMap = null; if (!reversed) { rowCount = tree.getLeafCount(); // heatmap has more genes than tree (sampling done), correct for it heatMap = new HeatMap("Heatmap", rowCount, columnCount); } else { heatMap = new HeatMap("Heatmap", columnCount, rowCount); } // go through the tree to find its biggest height (depth actually) int initialHeight = getTreeHeight(tree); List<String> treeToId = new ArrayList<String>(); treeToId.addAll(Collections.nCopies(rowCount, (String)null)); // read the tree and fill the treeToId map root = readTree(tree, 0, initialHeight, treeToId); orders = new OrderSuperviser(); orders.setTreeToId(treeToId); // set data to heatmap, reset the iterator heatMapData = data.queryFeatures("/clusters/hierarchical/heatmap").asTable(); List<Integer> treeToBean = new ArrayList<Integer>(); treeToBean.addAll(Collections.nCopies(rowCount, -1)); int row = -1; // This is increased to 0 in the beginning of the // loop int originalRow = 0; while (heatMapData.nextRow()) { if (!reversed) { // Find the row number in heatMap corresponding the name of // this row String key = translate(heatMapData.getStringValue(" ")); if (orders.idToTree(key) != -1) { //if the id is found row = orders.idToTree(key); treeToBean.set(row, originalRow); originalRow++; } else { continue; } logger.debug("Adding a new row to heatmap, name: " + heatMapData.getStringValue(" ") + "\tto row: " + row); } else { // reversed row is a column, just use the order from the // iteration row++; } String geneName = heatMapData.getStringValue(" "); geneName = annotationProvider.getAnnotatedRowname(geneName); if (!reversed) { heatMap.setRowName(row, geneName); } else { heatMap.setColumnName(row, geneName); } int i = -1; for (String columnName : columns) { if (!reversed) { // column index, just use the order from the iteration i++; } else { i = orders.idToTree(columnName); logger.debug("Adding a new row to heatmap (reversed), name: " + columnName + "\tto row: " + i); } if (!reversed) { heatMap.update(row, i, heatMapData.getFloatValue(columnName)); } else { heatMap.update(i, row, heatMapData.getFloatValue(columnName)); } } } orders.setTreeToBean(treeToBean); // Set column names (row names if reversed) int i = -1; // increased once before action for (String columnName : columns) { String sampleName = columnName.substring("chip.".length()); String realName = data.queryFeatures("/phenodata/linked/describe/" + sampleName).asString(); if (!reversed) { // column index, just use the order from the iteration i++; } else { i = orders.idToTree(columnName); logger.debug("Adding a new row to heatmap (reversed), name: " + columnName + "\tto row: " + i); } if (!reversed) { heatMap.setColumnName(i, realName); } else { heatMap.setRowName(i, realName); } } HCDataset dataset = new HCDataset(heatMap, root, null); // create the chart... boolean tooltips = true; JFreeChart chart = BioChartFactory.createHCChart("Hierarchical Clustering", // chart // title dataset, // data tooltips, // tooltips? false // URLs? ); // set special tooltips to hcChart if (chart.getPlot() instanceof HCPlot) { HCPlot hcPlot = (HCPlot) chart.getPlot(); this.hcPlot = hcPlot; orders.setPlot(hcPlot); this.hcPlot.addChangeListener(new PlotChangeListener(){ public void plotChanged(PlotChangeEvent event) { if(event instanceof ClusteringTreeChangeEvent){ HierarchicalClustering.this.orders.updateVisibleIndexes(); HierarchicalClustering.this.updateSelectionsFromApplication(false); } } }); // Set tooltips if (tooltips) { hcPlot.setToolTipGenerator(new MicroarrayHCToolTipGenerator()); } // Colors double min = getMinValue(dataset.getHeatMap()); double max = getMaxValue(dataset.getHeatMap()); GradientColorPalette colors = new GradientColorPalette( new double[] {min, max}, new Color[] {Color.GREEN, Color.BLACK, Color.RED}); hcPlot.setColoring(colors); } chart.setTitle((TextTitle)null); selectableChartPanel = new SelectableChartPanel(chart, this, false); selectableChartPanel.getChartPanel().addChartMouseListener((HCPlot)chart.getPlot()); updateSelectionsFromApplication(false); application.addPropertyChangeListener(this); int blockSize = 10; int width = (int)(heatMap.getColumnsCount() * blockSize + hcPlot.getRowTreeSize() + hcPlot.getRowNamesSize() + hcPlot.getLeftMarginSize() + hcPlot.getRightMarginSize()); //Column tree not visible int height = (int)(heatMap.getRowCount() * blockSize + hcPlot.getColumnNamesSize() + hcPlot.getTopMarginSize() + hcPlot.getBottomMarginSize()); preferredSize = new Dimension(width, height); zoomChangerPanel = new JPanel(new BorderLayout()); spaceFiller = new JPanel(); ((FlowLayout)spaceFiller.getLayout()).setAlignment(FlowLayout.LEFT); spaceFiller.setBackground(Color.white); scroller = new JScrollPane(spaceFiller); setScaledMode(false); return zoomChangerPanel; } catch (Exception e) { // these are very tricky, mostly caused by bad data logger.error(e); // log actual cause throw new ErrorReportAsException("Hierarchical clustering cannot be shown.", "The problem is probably caused by unsupported data, such as gene names that have illegal characters in them.", e); } } public void setScaledMode(boolean scaled){ /* Ugly way to change zoom level by changing containing panel layout and scroller * existence, but JFreeChart scaling is little bit problematic in this kind of * usage. */ if(scaled){ spaceFiller.remove(selectableChartPanel); zoomChangerPanel.remove(scroller); zoomChangerPanel.add(selectableChartPanel, BorderLayout.CENTER); selectableChartPanel.setPreferredSize(null); } else { spaceFiller.add(selectableChartPanel); zoomChangerPanel.remove(selectableChartPanel); zoomChangerPanel.add(scroller, BorderLayout.CENTER); selectableChartPanel.setPreferredSize(preferredSize); } zoomChangerPanel.validate(); zoomChangerPanel.repaint(); } /** * Translates name to parenthesis tree format. This translation is required * because R script does it. */ private String translate(String gene) { while(gene.startsWith(" ") || gene.startsWith("(")){ gene = gene.substring(1); } while(gene.endsWith(" ") || gene.endsWith(")")){ gene = gene.substring(0, gene.length() - 1); } gene = gene.replace("(", "-").replace(")", "-").replace(" ", "_"); while(gene.contains("--")){ gene = gene.replace("--", "-"); } return gene; } private int getTreeHeight(ClusterNode tree) { if (tree instanceof ClusterLeafNode) { return 0; } else { int left = getTreeHeight(((ClusterBranchNode) tree).getLeftBranch()) + 1; int right = getTreeHeight(((ClusterBranchNode) tree).getRightBranch()) + 1; return left > right ? left : right; } } private HCTreeNode readTree(ClusterNode tree, int index, int height, List<String> treeToId) throws DataRangeMismatchException { if (tree instanceof ClusterLeafNode) { String gene = ((ClusterLeafNode) tree).getGene(); treeToId.set(index, gene); logger.debug("LeafNode: " + ((ClusterLeafNode) tree).getGene() + "in index: " + index); return new HCTreeNode(0, index); // height is zero } else { HCTreeNode node = new HCTreeNode(height); HCTreeNode leftChild = readTree(((ClusterBranchNode) tree).getLeftBranch(), index, height - 1, treeToId); node.setLeftChild(leftChild); HCTreeNode rightChild = readTree(((ClusterBranchNode) tree).getRightBranch(), node.getDataRange().getRightBound() + 1, height - 1, treeToId); node.setRightChild(rightChild); return node; } } private static Double getMinValue(HeatMap heatmap) { Double min = null; for (int row = 0; row < heatmap.getRowCount(); row++) { for (int column = 0; column < heatmap.getColumnsCount(); column++) { Double value = heatmap.get(row, column); if (min == null || value < min) { min = value; } } } return min; } private static Double getMaxValue(HeatMap heatmap) { Double max = null; for (int row = 0; row < heatmap.getRowCount(); row++) { for (int column = 0; column < heatmap.getColumnsCount(); column++) { Double value = heatmap.get(row, column); if (max == null || value > max) { max = value; } } } return max; } @Override public boolean canVisualise(DataBean bean) throws MicroarrayException { return bean.isContentTypeCompatitible("application/x-treeview") && bean.queryFeatures("/clusters/hierarchical/tree").exists() && bean.queryFeatures("/clusters/hierarchical/heatmap").exists(); } public void selectionChanged(Rectangle2D.Double selectionRect) { if(selectionRect == null){ selected.clear(); } else { orders.updateVisibleIndexes(); ChartRenderingInfo info = selectableChartPanel.getChartPanel().getChartRenderingInfo(); EntityCollection entities = info.getEntityCollection(); Set<Integer> newSelection = new HashSet<Integer>(); for(Object obj: entities.getEntities()){ //Don't clear the selection if tree was clicked if(obj instanceof HCTreeNodeEntity){ HCTreeNodeEntity entity = (HCTreeNodeEntity)obj; if(entity.getArea().intersects(selectionRect)){ return; } } if(obj instanceof HeatMapBlockEntity){ HeatMapBlockEntity entity = (HeatMapBlockEntity)obj; if(entity.getArea().intersects(selectionRect)){ if(!reversed){ newSelection.addAll(orders.visibleToBean(entity.getRow())); } else { newSelection.add(entity.getColumn()); } } } } //New selections can't be put directly to selectedIndexes, because every other occurrence //of block (several in one line) inside selection rectangle would undo selection for(Integer row: newSelection){ if(selected.contains(row)){ selected.remove(row); } else { selected.add(row); } } showSelection(true); } } public void propertyChange(PropertyChangeEvent evt) { if (evt instanceof RowChoiceEvent && evt.getSource() != this && ((RowChoiceEvent) evt).getData() == selectionBean) { updateSelectionsFromApplication(false); } } protected void updateSelectionsFromApplication(boolean dispatchEvent) { RowSelectionManager manager = application.getSelectionManager().getRowSelectionManager(selectionBean); orders.updateVisibleIndexes(); selected.clear(); for (int i : manager.getSelectedRows()){ selected.add(i); } showSelection(dispatchEvent); } private void showSelection(boolean dispatchEvent){ Selection[] detailedSelection; if(!reversed){ detailedSelection = calculateRowSelectionDetails(); } else { detailedSelection = calculateColumnSelectionDetails(); } hcPlot.showSelection(detailedSelection, !reversed); list.setSelectedRows(selected, this, dispatchEvent, selectionBean); } private Selection[] calculateRowSelectionDetails(){ //Number of rows represented by each visible row int[] closedRows = orders.getCountOfVisibleReferences(); //Number of selected in each visible row int[] selectedRows = new int[closedRows.length]; //Is each visible row fully, partially or not at all selected Selection[] detailedSelection = new Selection[closedRows.length]; for(int selectedRow : selected){ selectedRows[orders.beanToVisible(selectedRow)]++; } for(int i = 0; i < selectedRows.length; i++){ if(selectedRows[i] == 0){ detailedSelection[i] = Selection.NO; } else if(selectedRows[i] == closedRows[i]){ detailedSelection[i] = Selection.YES; } else if(selectedRows[i] < closedRows[i]){ detailedSelection[i] = Selection.PARTIAL; } } return detailedSelection; } private Selection[] calculateColumnSelectionDetails(){ //Columns are already in right order, so just convert the selections to right format Selection[] detailedSelection = new Selection[hcPlot.getDataset().getHeatMap().getColumnsCount()]; for(int i = 0; i < detailedSelection.length; i++){ if(selected.contains(i)){ detailedSelection[i] = Selection.YES; } else { detailedSelection[i] = Selection.NO; } } return detailedSelection; } }
src/main/java/fi/csc/microarray/client/visualisation/methods/HierarchicalClustering.java
package fi.csc.microarray.client.visualisation.methods; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import org.apache.log4j.Logger; import org.jfree.chart.BioChartFactory; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.HCTreeNodeEntity; import org.jfree.chart.entity.HeatMapBlockEntity; import org.jfree.chart.event.ClusteringTreeChangeEvent; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.PlotChangeListener; import org.jfree.chart.labels.StandardHCToolTipGenerator; import org.jfree.chart.plot.GradientColorPalette; import org.jfree.chart.plot.HCPlot; import org.jfree.chart.plot.HCPlot.Selection; import org.jfree.chart.title.TextTitle; import org.jfree.data.hc.DataRange; import org.jfree.data.hc.DataRangeMismatchException; import org.jfree.data.hc.HCDataset; import org.jfree.data.hc.HCTreeNode; import org.jfree.data.hc.HeatMap; import fi.csc.microarray.ErrorReportAsException; import fi.csc.microarray.MicroarrayException; import fi.csc.microarray.client.selection.RowChoiceEvent; import fi.csc.microarray.client.selection.RowSelectionManager; import fi.csc.microarray.client.visualisation.AnnotateListPanel; import fi.csc.microarray.client.visualisation.TableAnnotationProvider; import fi.csc.microarray.client.visualisation.Visualisation; import fi.csc.microarray.client.visualisation.VisualisationFrame; import fi.csc.microarray.client.visualisation.methods.SelectableChartPanel.SelectionChangeListener; import fi.csc.microarray.client.visualisation.methods.hc.OrderSuperviser; import fi.csc.microarray.cluster.ClusterBranchNode; import fi.csc.microarray.cluster.ClusterLeafNode; import fi.csc.microarray.cluster.ClusterNode; import fi.csc.microarray.cluster.ClusterParser; import fi.csc.microarray.databeans.DataBean; import fi.csc.microarray.databeans.DataBean.Link; import fi.csc.microarray.databeans.DataBean.Traversal; import fi.csc.microarray.databeans.features.QueryResult; import fi.csc.microarray.databeans.features.Table; public class HierarchicalClustering extends Visualisation implements PropertyChangeListener, SelectionChangeListener { public HierarchicalClustering(VisualisationFrame frame) { super(frame); } private SelectableChartPanel selectableChartPanel; private static final Logger logger = Logger.getLogger(HierarchicalClustering.class); OrderSuperviser orders; private JPanel paramPanel; private AnnotateListPanel list; //Selected indexes in the order of parent data bean private Set<Integer> selected = new HashSet<Integer>(); private DataBean selectionBean; private HCPlot hcPlot; private boolean reversed; private JPanel zoomChangerPanel; private JPanel spaceFiller; private JScrollPane scroller; private Dimension preferredSize; private JCheckBox zoomCheckBox; private class MicroarrayHCToolTipGenerator extends StandardHCToolTipGenerator { /** * Creates tooltip for Hierarchical clustering visualisation. The * tooltip includes chip and gene names and value. * * The code is mainly copied from StandardHCToolTipGenerator * * Note! The rows and columns are in different order than in original * version of this method. In the Viski library the rows and columns are * messed up. */ @Override public String generateToolTip(HeatMap heatmap, DataRange rowRange, DataRange columnRange) { int minRow; int maxRow; int minColumn; int maxColumn; int rowCounter; int columnCounter; int blockCount; double averageValue; try { minRow = rowRange.getLeftBound(); maxRow = rowRange.getRightBound(); minColumn = columnRange.getLeftBound(); maxColumn = columnRange.getRightBound(); } catch (Exception e) { return "This block contains no data."; } if ((minRow == maxRow) && (minColumn == maxColumn)) { return "(" + heatmap.getRowName(minRow) + "," + heatmap.getColumnName(minColumn) + ") = " + heatmap.get(minRow, minColumn); } for (averageValue = 0, blockCount = 0, rowCounter = minRow; rowCounter <= maxRow; rowCounter++) { for (columnCounter = minColumn; columnCounter <= maxColumn; columnCounter++, blockCount++) { averageValue += heatmap.get(rowCounter, columnCounter); } } averageValue = averageValue / blockCount; return "(" + heatmap.getRowName(minRow) + "," + heatmap.getColumnName(minColumn) + ") .. " + "(" + heatmap.getRowName(maxRow) + "," + heatmap.getColumnName(maxColumn) + ") = " + averageValue + " (contains " + (blockCount + 1) + " blocks)"; } } @Override public JPanel getParameterPanel() { if (paramPanel == null) { paramPanel = new JPanel(); paramPanel.setPreferredSize(Visualisation.PARAMETER_SIZE); paramPanel.setLayout(new BorderLayout()); JPanel settings = this.createSettingsPanel(); list = new AnnotateListPanel(); JTabbedPane tabPane = new JTabbedPane(); tabPane.addTab("Settings", settings); tabPane.addTab("Selected", list); paramPanel.add(tabPane, BorderLayout.CENTER); } return paramPanel; } public JPanel createSettingsPanel() { JPanel settingsPanel = new JPanel(); settingsPanel.setLayout(new GridBagLayout()); settingsPanel.setPreferredSize(Visualisation.PARAMETER_SIZE); zoomCheckBox = new JCheckBox("Enable scroll bars", true); JTextArea scrollHelp = new JTextArea("(Recommended for \n big datasets)"); scrollHelp.setEditable(false); scrollHelp.setBackground(settingsPanel.getBackground()); zoomCheckBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { setScaledMode(zoomCheckBox.isSelected()); } }); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; c.insets.set(10, 10, 0, 10); c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.HORIZONTAL; c.weighty = 0; c.weightx = 1.0; settingsPanel.add(zoomCheckBox, c); c.gridy++; settingsPanel.add(scrollHelp, c); c.gridy++; c.fill = GridBagConstraints.BOTH; c.weighty = 1.0; settingsPanel.add(new JPanel(), c); return settingsPanel; } /** * getVisualisation method has too modes. If the genes are clustered the * mode is normal and in reversed mode the chips are clustered. Both modes * are implemented in turns of couple rows which makes the structure very * ugly and vulnerable for mistakes. Maybe some day there is time to * restructure this method. * * @throws MicroarrayException * is parsing or visualisation generation fails */ @Override public JComponent getVisualisation(DataBean data) throws MicroarrayException { //There is no point to bind selections to HC data because it's not possible to visualise it //with other visualisation methods. It's parent is used instead. List<DataBean> selectionBeans = data.traverseLinks(new Link[] {Link.DERIVATION}, Traversal.DIRECT); //First one is hc data //TODO there is no point to find all ancestors if(selectionBeans.size() > 1){ selectionBean = selectionBeans.get(1); } if(selectionBean == null){ throw new ErrorReportAsException("Source dataset not found", "Hierarchical clustering " + "needs its source dataset.", " Select both HC and its source dataset by keeping \n" + "Ctrl key pressed and right click with mouse over one of them to create \n" + "derivation link from the original dataset to \n" + "clustered one."); } try { String hcTree = data.queryFeatures("/clusters/hierarchical/tree").asStrings().iterator().next(); // create heatmap QueryResult heatMapFeature = data.queryFeatures("/clusters/hierarchical/heatmap"); Table heatMapData = heatMapFeature.asTable(); TableAnnotationProvider annotationProvider = new TableAnnotationProvider(selectionBean); // count rows int rowCount = 0; while (heatMapData.nextRow()) { rowCount++; } LinkedList<String> columns = new LinkedList<String>(); for (String columnName : heatMapData.getColumnNames()) { if (columnName.startsWith("chip.")) { columns.add(columnName); } else { logger.debug("Column skipped in HC: " + columnName); } } int columnCount = columns.size(); // HC tree has to be done first to find out the order of rows and number of rows HCTreeNode root = null; ClusterParser parser = new ClusterParser(hcTree); ClusterBranchNode tree = parser.getTree(); // check which way we have clustered reversed = hcTree.contains("chip."); HeatMap heatMap = null; if (!reversed) { rowCount = tree.getLeafCount(); // heatmap has more genes than tree (sampling done), correct for it heatMap = new HeatMap("Heatmap", rowCount, columnCount); } else { heatMap = new HeatMap("Heatmap", columnCount, rowCount); } // go through the tree to find its biggest height (depth actually) int initialHeight = getTreeHeight(tree); List<String> treeToId = new ArrayList<String>(); treeToId.addAll(Collections.nCopies(rowCount, (String)null)); // read the tree and fill the treeToId map root = readTree(tree, 0, initialHeight, treeToId); orders = new OrderSuperviser(); orders.setTreeToId(treeToId); // set data to heatmap, reset the iterator heatMapData = data.queryFeatures("/clusters/hierarchical/heatmap").asTable(); List<Integer> treeToBean = new ArrayList<Integer>(); treeToBean.addAll(Collections.nCopies(rowCount, -1)); int row = -1; // This is increased to 0 in the beginning of the // loop int originalRow = 0; while (heatMapData.nextRow()) { if (!reversed) { // Find the row number in heatMap corresponding the name of // this row String key = translate(heatMapData.getStringValue(" ")); if (orders.idToTree(key) != -1) { //if the id is found row = orders.idToTree(key); treeToBean.set(row, originalRow); originalRow++; } else { continue; } logger.debug("Adding a new row to heatmap, name: " + heatMapData.getStringValue(" ") + "\tto row: " + row); } else { // reversed row is a column, just use the order from the // iteration row++; } String geneName = heatMapData.getStringValue(" "); geneName = annotationProvider.getAnnotatedRowname(geneName); if (!reversed) { heatMap.setRowName(row, geneName); } else { heatMap.setColumnName(row, geneName); } int i = -1; for (String columnName : columns) { if (!reversed) { // column index, just use the order from the iteration i++; } else { i = orders.idToTree(columnName); logger.debug("Adding a new row to heatmap (reversed), name: " + columnName + "\tto row: " + i); } if (!reversed) { heatMap.update(row, i, heatMapData.getFloatValue(columnName)); } else { heatMap.update(i, row, heatMapData.getFloatValue(columnName)); } } } orders.setTreeToBean(treeToBean); // Set column names (row names if reversed) int i = -1; // increased once before action for (String columnName : columns) { String sampleName = columnName.substring("chip.".length()); String realName = data.queryFeatures("/phenodata/linked/describe/" + sampleName).asString(); if (!reversed) { // column index, just use the order from the iteration i++; } else { i = orders.idToTree(columnName); logger.debug("Adding a new row to heatmap (reversed), name: " + columnName + "\tto row: " + i); } if (!reversed) { heatMap.setColumnName(i, realName); } else { heatMap.setRowName(i, realName); } } HCDataset dataset = new HCDataset(heatMap, root, null); // create the chart... boolean tooltips = true; JFreeChart chart = BioChartFactory.createHCChart("Hierarchical Clustering", // chart // title dataset, // data tooltips, // tooltips? false // URLs? ); // set special tooltips to hcChart if (chart.getPlot() instanceof HCPlot) { HCPlot hcPlot = (HCPlot) chart.getPlot(); this.hcPlot = hcPlot; orders.setPlot(hcPlot); this.hcPlot.addChangeListener(new PlotChangeListener(){ public void plotChanged(PlotChangeEvent event) { if(event instanceof ClusteringTreeChangeEvent){ HierarchicalClustering.this.orders.updateVisibleIndexes(); HierarchicalClustering.this.updateSelectionsFromApplication(false); } } }); // Set tooltips if (tooltips) { hcPlot.setToolTipGenerator(new MicroarrayHCToolTipGenerator()); } // Colors double min = getMinValue(dataset.getHeatMap()); double max = getMaxValue(dataset.getHeatMap()); GradientColorPalette colors = new GradientColorPalette( new double[] {min, max}, new Color[] {Color.GREEN, Color.BLACK, Color.RED}); hcPlot.setColoring(colors); } chart.setTitle((TextTitle)null); selectableChartPanel = new SelectableChartPanel(chart, this, false); selectableChartPanel.getChartPanel().addChartMouseListener((HCPlot)chart.getPlot()); updateSelectionsFromApplication(false); application.addPropertyChangeListener(this); int blockSize = 10; int width = (int)(heatMap.getColumnsCount() * blockSize + hcPlot.getRowTreeSize() + hcPlot.getRowNamesSize() + hcPlot.getLeftMarginSize() + hcPlot.getRightMarginSize()); //Column tree not visible int height = (int)(heatMap.getRowCount() * blockSize + hcPlot.getColumnNamesSize() + hcPlot.getTopMarginSize() + hcPlot.getBottomMarginSize()); preferredSize = new Dimension(width, height); zoomChangerPanel = new JPanel(new BorderLayout()); spaceFiller = new JPanel(); ((FlowLayout)spaceFiller.getLayout()).setAlignment(FlowLayout.LEFT); spaceFiller.setBackground(Color.white); scroller = new JScrollPane(spaceFiller); setScaledMode(true); return zoomChangerPanel; } catch (Exception e) { // these are very tricky, mostly caused by bad data logger.error(e); // log actual cause throw new ErrorReportAsException("Hierarchical clustering cannot be shown.", "The problem is probably caused by unsupported data, such as gene names that have illegal characters in them.", e); } } public void setScaledMode(boolean scaled){ /* Ugly way to change zoom level by changing containing panel layout and scroller * existence, but JFreeChart scaling is little bit problematic in this kind of * usage. */ if(scaled){ spaceFiller.remove(selectableChartPanel); zoomChangerPanel.remove(scroller); zoomChangerPanel.add(selectableChartPanel, BorderLayout.CENTER); selectableChartPanel.setPreferredSize(null); } else { spaceFiller.add(selectableChartPanel); zoomChangerPanel.remove(selectableChartPanel); zoomChangerPanel.add(scroller, BorderLayout.CENTER); selectableChartPanel.setPreferredSize(preferredSize); } zoomChangerPanel.validate(); zoomChangerPanel.repaint(); } /** * Translates name to parenthesis tree format. This translation is required * because R script does it. */ private String translate(String gene) { while(gene.startsWith(" ") || gene.startsWith("(")){ gene = gene.substring(1); } while(gene.endsWith(" ") || gene.endsWith(")")){ gene = gene.substring(0, gene.length() - 1); } gene = gene.replace("(", "-").replace(")", "-").replace(" ", "_"); while(gene.contains("--")){ gene = gene.replace("--", "-"); } return gene; } private int getTreeHeight(ClusterNode tree) { if (tree instanceof ClusterLeafNode) { return 0; } else { int left = getTreeHeight(((ClusterBranchNode) tree).getLeftBranch()) + 1; int right = getTreeHeight(((ClusterBranchNode) tree).getRightBranch()) + 1; return left > right ? left : right; } } private HCTreeNode readTree(ClusterNode tree, int index, int height, List<String> treeToId) throws DataRangeMismatchException { if (tree instanceof ClusterLeafNode) { String gene = ((ClusterLeafNode) tree).getGene(); treeToId.set(index, gene); logger.debug("LeafNode: " + ((ClusterLeafNode) tree).getGene() + "in index: " + index); return new HCTreeNode(0, index); // height is zero } else { HCTreeNode node = new HCTreeNode(height); HCTreeNode leftChild = readTree(((ClusterBranchNode) tree).getLeftBranch(), index, height - 1, treeToId); node.setLeftChild(leftChild); HCTreeNode rightChild = readTree(((ClusterBranchNode) tree).getRightBranch(), node.getDataRange().getRightBound() + 1, height - 1, treeToId); node.setRightChild(rightChild); return node; } } private static Double getMinValue(HeatMap heatmap) { Double min = null; for (int row = 0; row < heatmap.getRowCount(); row++) { for (int column = 0; column < heatmap.getColumnsCount(); column++) { Double value = heatmap.get(row, column); if (min == null || value < min) { min = value; } } } return min; } private static Double getMaxValue(HeatMap heatmap) { Double max = null; for (int row = 0; row < heatmap.getRowCount(); row++) { for (int column = 0; column < heatmap.getColumnsCount(); column++) { Double value = heatmap.get(row, column); if (max == null || value > max) { max = value; } } } return max; } @Override public boolean canVisualise(DataBean bean) throws MicroarrayException { return bean.isContentTypeCompatitible("application/x-treeview") && bean.queryFeatures("/clusters/hierarchical/tree").exists() && bean.queryFeatures("/clusters/hierarchical/heatmap").exists(); } public void selectionChanged(Rectangle2D.Double selectionRect) { if(selectionRect == null){ selected.clear(); } else { orders.updateVisibleIndexes(); ChartRenderingInfo info = selectableChartPanel.getChartPanel().getChartRenderingInfo(); EntityCollection entities = info.getEntityCollection(); Set<Integer> newSelection = new HashSet<Integer>(); for(Object obj: entities.getEntities()){ //Don't clear the selection if tree was clicked if(obj instanceof HCTreeNodeEntity){ HCTreeNodeEntity entity = (HCTreeNodeEntity)obj; if(entity.getArea().intersects(selectionRect)){ return; } } if(obj instanceof HeatMapBlockEntity){ HeatMapBlockEntity entity = (HeatMapBlockEntity)obj; if(entity.getArea().intersects(selectionRect)){ if(!reversed){ newSelection.addAll(orders.visibleToBean(entity.getRow())); } else { newSelection.add(entity.getColumn()); } } } } //New selections can't be put directly to selectedIndexes, because every other occurrence //of block (several in one line) inside selection rectangle would undo selection for(Integer row: newSelection){ if(selected.contains(row)){ selected.remove(row); } else { selected.add(row); } } showSelection(true); } } public void propertyChange(PropertyChangeEvent evt) { if (evt instanceof RowChoiceEvent && evt.getSource() != this && ((RowChoiceEvent) evt).getData() == selectionBean) { updateSelectionsFromApplication(false); } } protected void updateSelectionsFromApplication(boolean dispatchEvent) { RowSelectionManager manager = application.getSelectionManager().getRowSelectionManager(selectionBean); orders.updateVisibleIndexes(); selected.clear(); for (int i : manager.getSelectedRows()){ selected.add(i); } showSelection(dispatchEvent); } private void showSelection(boolean dispatchEvent){ Selection[] detailedSelection; if(!reversed){ detailedSelection = calculateRowSelectionDetails(); } else { detailedSelection = calculateColumnSelectionDetails(); } hcPlot.showSelection(detailedSelection, !reversed); list.setSelectedRows(selected, this, dispatchEvent, selectionBean); } private Selection[] calculateRowSelectionDetails(){ //Number of rows represented by each visible row int[] closedRows = orders.getCountOfVisibleReferences(); //Number of selected in each visible row int[] selectedRows = new int[closedRows.length]; //Is each visible row fully, partially or not at all selected Selection[] detailedSelection = new Selection[closedRows.length]; for(int selectedRow : selected){ selectedRows[orders.beanToVisible(selectedRow)]++; } for(int i = 0; i < selectedRows.length; i++){ if(selectedRows[i] == 0){ detailedSelection[i] = Selection.NO; } else if(selectedRows[i] == closedRows[i]){ detailedSelection[i] = Selection.YES; } else if(selectedRows[i] < closedRows[i]){ detailedSelection[i] = Selection.PARTIAL; } } return detailedSelection; } private Selection[] calculateColumnSelectionDetails(){ //Columns are already in right order, so just convert the selections to right format Selection[] detailedSelection = new Selection[hcPlot.getDataset().getHeatMap().getColumnsCount()]; for(int i = 0; i < detailedSelection.length; i++){ if(selected.contains(i)){ detailedSelection[i] = Selection.YES; } else { detailedSelection[i] = Selection.NO; } } return detailedSelection; } }
fit to screen off by default
src/main/java/fi/csc/microarray/client/visualisation/methods/HierarchicalClustering.java
fit to screen off by default
<ide><path>rc/main/java/fi/csc/microarray/client/visualisation/methods/HierarchicalClustering.java <ide> import javax.swing.JPanel; <ide> import javax.swing.JScrollPane; <ide> import javax.swing.JTabbedPane; <del>import javax.swing.JTextArea; <ide> <ide> import org.apache.log4j.Logger; <ide> import org.jfree.chart.BioChartFactory; <ide> settingsPanel.setLayout(new GridBagLayout()); <ide> settingsPanel.setPreferredSize(Visualisation.PARAMETER_SIZE); <ide> <del> zoomCheckBox = new JCheckBox("Enable scroll bars", true); <del> JTextArea scrollHelp = new JTextArea("(Recommended for \n big datasets)"); <del> scrollHelp.setEditable(false); <del> scrollHelp.setBackground(settingsPanel.getBackground()); <add> zoomCheckBox = new JCheckBox("Fit to screen", false); <ide> <ide> zoomCheckBox.addActionListener(new ActionListener(){ <ide> <ide> c.fill = GridBagConstraints.HORIZONTAL; <ide> c.weighty = 0; <ide> c.weightx = 1.0; <del> settingsPanel.add(zoomCheckBox, c); <del> c.gridy++; <del> settingsPanel.add(scrollHelp, c); <add> settingsPanel.add(zoomCheckBox, c); <ide> c.gridy++; <ide> c.fill = GridBagConstraints.BOTH; <ide> c.weighty = 1.0; <ide> spaceFiller.setBackground(Color.white); <ide> scroller = new JScrollPane(spaceFiller); <ide> <del> setScaledMode(true); <add> setScaledMode(false); <ide> <ide> return zoomChangerPanel; <ide>
Java
apache-2.0
895cd07f1ebf13b6568f231c31b555f1d6cc679c
0
yuluo-ding/alluxio,bf8086/alluxio,calvinjia/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,jsimsa/alluxio,riversand963/alluxio,PasaLab/tachyon,madanadit/alluxio,bf8086/alluxio,jswudi/alluxio,PasaLab/tachyon,Alluxio/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,aaudiber/alluxio,PasaLab/tachyon,madanadit/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,bf8086/alluxio,maboelhassan/alluxio,jsimsa/alluxio,jswudi/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,apc999/alluxio,Reidddddd/alluxio,riversand963/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,jswudi/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,Reidddddd/alluxio,calvinjia/tachyon,maobaolong/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,maboelhassan/alluxio,uronce-cc/alluxio,ShailShah/alluxio,wwjiang007/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,ShailShah/alluxio,apc999/alluxio,wwjiang007/alluxio,Alluxio/alluxio,PasaLab/tachyon,maobaolong/alluxio,Alluxio/alluxio,apc999/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,jsimsa/alluxio,jswudi/alluxio,apc999/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,maboelhassan/alluxio,bf8086/alluxio,apc999/alluxio,wwjiang007/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,ChangerYoung/alluxio,madanadit/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,calvinjia/tachyon,madanadit/alluxio,riversand963/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,Reidddddd/alluxio,PasaLab/tachyon,uronce-cc/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,maobaolong/alluxio,riversand963/alluxio,bf8086/alluxio,Alluxio/alluxio,Reidddddd/alluxio,madanadit/alluxio,aaudiber/alluxio,maboelhassan/alluxio,madanadit/alluxio,riversand963/alluxio,Reidddddd/alluxio,PasaLab/tachyon,uronce-cc/alluxio,wwjiang007/alluxio,riversand963/alluxio,ShailShah/alluxio,maobaolong/alluxio,Reidddddd/alluxio,ShailShah/alluxio,yuluo-ding/alluxio,calvinjia/tachyon,bf8086/alluxio,aaudiber/alluxio,ShailShah/alluxio,Alluxio/alluxio,maobaolong/alluxio,maobaolong/alluxio,apc999/alluxio,aaudiber/alluxio,aaudiber/alluxio,madanadit/alluxio,maobaolong/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,aaudiber/alluxio,jsimsa/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,aaudiber/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,WilliamZapata/alluxio,uronce-cc/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,WilliamZapata/alluxio,calvinjia/tachyon
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.rest; import alluxio.LocalAlluxioClusterResource; import alluxio.PropertyKey; import alluxio.security.authentication.AuthType; import org.junit.Rule; import java.util.HashMap; import java.util.Map; public abstract class RestApiTest { protected static final Map<String, String> NO_PARAMS = new HashMap<>(); protected String mHostname; protected int mPort; protected String mServicePrefix; // TODO(chaomin): Rest API integration tests are only run in NOSASL mode now. Need to // fix the test setup in SIMPLE mode. @Rule public LocalAlluxioClusterResource mResource = new LocalAlluxioClusterResource.Builder() .setProperty(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "false") .setProperty(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()) .build(); protected String getEndpoint(String suffix) { return mServicePrefix + "/" + suffix; } }
tests/src/test/java/alluxio/rest/RestApiTest.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.rest; import alluxio.LocalAlluxioClusterResource; import alluxio.PropertyKey; import alluxio.security.authentication.AuthType; import org.junit.Rule; import java.util.HashMap; import java.util.Map; public abstract class RestApiTest { protected static final Map<String, String> NO_PARAMS = new HashMap<>(); protected String mHostname; protected int mPort; protected String mServicePrefix; // TODO(chaomin): Rest API integration tests are only run in NOSASL mode now. Need to re-evaluate // whether REST API still works in SIMPLE mode. @Rule public LocalAlluxioClusterResource mResource = new LocalAlluxioClusterResource.Builder() .setProperty(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "false") .setProperty(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()) .build(); protected String getEndpoint(String suffix) { return mServicePrefix + "/" + suffix; } }
Update a TODO.
tests/src/test/java/alluxio/rest/RestApiTest.java
Update a TODO.
<ide><path>ests/src/test/java/alluxio/rest/RestApiTest.java <ide> protected int mPort; <ide> protected String mServicePrefix; <ide> <del> // TODO(chaomin): Rest API integration tests are only run in NOSASL mode now. Need to re-evaluate <del> // whether REST API still works in SIMPLE mode. <add> // TODO(chaomin): Rest API integration tests are only run in NOSASL mode now. Need to <add> // fix the test setup in SIMPLE mode. <ide> @Rule <ide> public LocalAlluxioClusterResource mResource = new LocalAlluxioClusterResource.Builder() <ide> .setProperty(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "false")
Java
apache-2.0
6e7398e3d37a88c8c2efec3e2466e85f8fc6576b
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util; import com.intellij.execution.CommandLineUtil; import com.intellij.execution.process.UnixProcessManager; import com.intellij.execution.process.WinProcessManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.io.BaseOutputReader; import com.intellij.util.text.CaseInsensitiveStringHashingStrategy; import gnu.trove.THashMap; import org.jetbrains.annotations.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public final class EnvironmentUtil { private static final Logger LOG = Logger.getInstance(EnvironmentUtil.class); /** * The default time-out to read the environment, in milliseconds. */ private static final long DEFAULT_SHELL_ENV_READING_TIMEOUT_MILLIS = 20_000L; private static final String LANG = "LANG"; private static final String LC_ALL = "LC_ALL"; private static final String LC_CTYPE = "LC_CTYPE"; private static final String DESKTOP_STARTUP_ID = "DESKTOP_STARTUP_ID"; public static final @NonNls String BASH_EXECUTABLE_NAME = "bash"; public static final String SHELL_VARIABLE_NAME = "SHELL"; private static final String SHELL_INTERACTIVE_ARGUMENT = "-i"; public static final String SHELL_LOGIN_ARGUMENT = "-l"; public static final String SHELL_COMMAND_ARGUMENT = "-c"; public static final String SHELL_SOURCE_COMMAND = "source"; /** * Holds the number of shell levels the current shell is running on top of. * Tested with bash/zsh/fish/tcsh/csh/ksh. */ private static final String SHLVL = "SHLVL"; private static final AtomicReference<CompletableFuture<Map<String, String>>> ourEnvGetter = new AtomicReference<>(); private EnvironmentUtil() { } /** * <p>A wrapper layer around {@link System#getenv()}.</p> * * <p>On Windows, the returned map is case-insensitive (i.e. {@code map.get("Path") == map.get("PATH")} holds).</p> * * <p>On macOS, things are complicated.<br/> * An app launched by a GUI launcher (Finder, Dock, Spotlight etc.) receives a pretty empty and useless environment, * since standard Unix ways of setting variables via e.g. ~/.profile do not work. What's more important, there are no * sane alternatives. This causes a lot of user complaints about tools working in a terminal not working when launched * from the IDE. To ease their pain, the IDE loads a shell environment (see {@link #getShellEnv()} for gory details) * and returns it as the result.<br/> * And one more thing (c): locale variables on macOS are usually set by a terminal app - meaning they are missing * even from a shell environment above. This again causes user complaints about tools being unable to output anything * outside ASCII range when launched from the IDE. Resolved by adding LC_CTYPE variable to the map if it doesn't contain * explicitly set locale variables (LANG/LC_ALL/LC_CTYPE). See {@link #setCharsetVar(Map)} for details.</p> * * @return unmodifiable map of the process environment. */ public static @NotNull Map<String, String> getEnvironmentMap() { CompletableFuture<Map<String, String>> getter = ourEnvGetter.get(); if (getter == null) { getter = CompletableFuture.completedFuture(getSystemEnv()); if (!ourEnvGetter.compareAndSet(null, getter)) { getter = ourEnvGetter.get(); } } try { return getter.join(); } catch (Throwable t) { throw new AssertionError(t); // unknown state; is not expected to happen } } @ApiStatus.Internal public static void loadEnvironment(@NotNull Runnable callback) { if (shouldLoadShellEnv()) { ourEnvGetter.set(CompletableFuture.supplyAsync(() -> { try { Map<String, String> env = getShellEnv(); setCharsetVar(env); return Collections.unmodifiableMap(env); } catch (Throwable t) { LOG.warn("can't get shell environment", t); return getSystemEnv(); } finally { callback.run(); } }, AppExecutorUtil.getAppExecutorService())); } else { ourEnvGetter.set(CompletableFuture.completedFuture(getSystemEnv())); callback.run(); } } private static boolean shouldLoadShellEnv() { if (!SystemInfoRt.isMac) { return false; } // The method is called too early when the IDE starts up, at this point the registry values have not been loaded yet from the service. // Using a system property is a good alternative. if (!Boolean.parseBoolean(System.getProperty("ij.load.shell.env", "true"))) { LOG.info("loading shell env is turned off"); return false; } String value = System.getenv(SHLVL); // On macOS, login shell session is not run when a user logs in, thus "SHLVL > 0" likely means that IDE is run from a terminal. if (StringUtilRt.parseInt(value, 0) > 0) { LOG.info("loading shell env is skipped: IDE has been launched from a terminal (" + SHLVL + "=" + value + ")"); return false; } return true; } private static @NotNull Map<String, String> getSystemEnv() { if (SystemInfoRt.isWindows) { return Collections.unmodifiableMap(new THashMap<>(System.getenv(), CaseInsensitiveStringHashingStrategy.INSTANCE)); } else if (SystemInfoRt.isXWindow) { // DESKTOP_STARTUP_ID variable can be set by an application launcher in X Window environment. // It shouldn't be passed to child processes as per 'Startup notification protocol' // (https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt). // Ideally, JDK should clear this variable, and it actually does, but the snapshot of the environment variables, // returned by System.getenv(), is captured before the removal. Map<String, String> env = System.getenv(); if (env.containsKey(DESKTOP_STARTUP_ID)) { env = new HashMap<>(env); env.remove(DESKTOP_STARTUP_ID); env = Collections.unmodifiableMap(env); } return env; } else { return System.getenv(); } } /** * Same as {@code getEnvironmentMap().get(name)}. * Returns value for the passed environment variable name, or null if no such variable found. * * @see #getEnvironmentMap() */ public static @Nullable @NonNls String getValue(@NotNull @NonNls String name) { return getEnvironmentMap().get(name); } /** * Validates environment variable name in accordance to * {@code ProcessEnvironment#validateVariable} ({@code ProcessEnvironment#validateName} on Windows). * * @see #isValidValue(String) * @see <a href="http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html">Environment Variables in Unix</a> * @see <a href="https://docs.microsoft.com/en-us/windows/desktop/ProcThread/environment-variables">Environment Variables in Windows</a> */ @Contract(value = "null -> false", pure = true) public static boolean isValidName(@Nullable @NonNls String name) { return name != null && !name.isEmpty() && name.indexOf('\0') == -1 && name.indexOf('=', SystemInfoRt.isWindows ? 1 : 0) == -1; } /** * Validates environment variable value in accordance to {@code ProcessEnvironment#validateValue}. * * @see #isValidName(String) */ @Contract(value = "null -> false", pure = true) public static boolean isValidValue(@Nullable @NonNls String value) { return value != null && value.indexOf('\0') == -1; } private static final String DISABLE_OMZ_AUTO_UPDATE = "DISABLE_AUTO_UPDATE"; private static final String INTELLIJ_ENVIRONMENT_READER = "INTELLIJ_ENVIRONMENT_READER"; private static @NotNull Map<String, String> getShellEnv() throws IOException { return new ShellEnvReader().readShellEnv(null); } public static class ShellEnvReader { private final long myTimeoutMillis; /** * Creates an instance with the default time-out value of {@value #DEFAULT_SHELL_ENV_READING_TIMEOUT_MILLIS} milliseconds. * * @see #ShellEnvReader(long) */ public ShellEnvReader() { this(DEFAULT_SHELL_ENV_READING_TIMEOUT_MILLIS); } /** * @param timeoutMillis the time-out (in milliseconds) for reading environment variables. * @see #ShellEnvReader() */ public ShellEnvReader(long timeoutMillis) { myTimeoutMillis = timeoutMillis; } public final @NotNull Map<String, String> readShellEnv(@Nullable Path file, @Nullable Map<String, String> additionalEnvironment) throws IOException { Path reader = PathManager.findBinFileWithException("printenv.py"); Path envFile = Files.createTempFile("intellij-shell-env.", ".tmp"); StringBuilder readerCmd = new StringBuilder(); if (file != null) { if (!Files.exists(file)) { throw new NoSuchFileException(file.toString()); } readerCmd.append(SHELL_SOURCE_COMMAND).append(" \"").append(file).append("\" && "); } readerCmd.append("'").append(reader.toAbsolutePath()).append("' '").append(envFile.toAbsolutePath()).append("'"); try { List<String> command = getShellProcessCommand(); int idx = command.indexOf(SHELL_COMMAND_ARGUMENT); if (idx >= 0) { // if there is already a command append command to the end command.set(idx + 1, command.get(idx + 1) + ";" + readerCmd.toString()); } else { command.add(SHELL_COMMAND_ARGUMENT); command.add(readerCmd.toString()); } LOG.info("loading shell env: " + String.join(" ", command)); return runProcessAndReadOutputAndEnvs(command, null, additionalEnvironment, envFile).second; } finally { try { Files.delete(envFile); } catch (NoSuchFileException ignore) { } catch (IOException e) { LOG.warn("Cannot delete temporary file", e); } } } protected final @NotNull Map<String, String> readShellEnv(@Nullable Map<String, String> additionalEnvironment) throws IOException { return readShellEnv(null, additionalEnvironment); } public @NotNull Map<String, String> readBatEnv(@Nullable Path batchFile, List<String> args) throws IOException { return readBatOutputAndEnv(batchFile, args).second; } public @NotNull Pair<String, Map<String, String>> readBatOutputAndEnv(@Nullable Path batchFile, List<String> args) throws IOException { if (batchFile != null && !Files.exists(batchFile)) { throw new NoSuchFileException(batchFile.toString()); } Path envFile = Files.createTempFile("intellij-cmd-env.", ".tmp"); try { List<@NonNls String> callArgs = new ArrayList<>(); if (batchFile != null) { callArgs.add("call"); callArgs.add(batchFile.toString()); if (args != null) callArgs.addAll(args); callArgs.add("&&"); } callArgs.addAll(getReadEnvCommand()); callArgs.add(envFile.toString()); callArgs.addAll(Arrays.asList("||", "exit", "/B", "%ERRORLEVEL%")); List<@NonNls String> cl = new ArrayList<>(); cl.add(CommandLineUtil.getWinShellName()); cl.add("/c"); cl.add(prepareCallArgs(callArgs)); return runProcessAndReadOutputAndEnvs(cl, batchFile != null ? batchFile.getParent() : null, null, envFile); } finally { try { Files.delete(envFile); } catch (NoSuchFileException ignore) { } catch (IOException e) { LOG.warn("Cannot delete temporary file", e); } } } @NotNull private static String prepareCallArgs(@NotNull List<String> callArgs) { List<String> preparedCallArgs = CommandLineUtil.toCommandLine(callArgs); String firstArg = preparedCallArgs.remove(0); preparedCallArgs.add(0, CommandLineUtil.escapeParameterOnWindows(firstArg, false)); // for CMD we would like to add extra double quotes for the actual command in call // to mitigate possible JVM issue when argument contains spaces and the first word // starts with double quote and the last ends with double quote and JVM does not // wrap the argument with double quotes // Example: callArgs = ["\"C:\\New Folder\aa\"", "\"C:\\New Folder\aa\""] return StringUtil.wrapWithDoubleQuote(String.join(" ", preparedCallArgs)); } private static @NotNull List<String> getReadEnvCommand() { return Arrays.asList(FileUtilRt.toSystemDependentName(System.getProperty("java.home") + "/bin/java"), "-cp", PathManager.getJarPathForClass(ReadEnv.class), ReadEnv.class.getCanonicalName()); } protected final @NotNull Pair<String, Map<String, String>> runProcessAndReadOutputAndEnvs(@NotNull List<String> command, @Nullable Path workingDir, @Nullable Map<String, String> scriptEnvironment, @NotNull Path envFile) throws IOException { ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); if (scriptEnvironment != null) { // we might need default environment for the process to launch correctly builder.environment().putAll(scriptEnvironment); } if (workingDir != null) { builder.directory(workingDir.toFile()); } builder.environment().put(DISABLE_OMZ_AUTO_UPDATE, "true"); builder.environment().put(INTELLIJ_ENVIRONMENT_READER, "true"); Process process = builder.start(); StreamGobbler gobbler = new StreamGobbler(process.getInputStream()); final int exitCode = waitAndTerminateAfter(process, myTimeoutMillis); gobbler.stop(); String lines = new String(Files.readAllBytes(envFile), StandardCharsets.UTF_8); if (exitCode != 0 || lines.isEmpty()) { throw new RuntimeException("command " + command + "\n\texit code:" + exitCode + " text:" + lines.length() + " out:" + gobbler.getText().trim()); } return new Pair<>(gobbler.getText(), parseEnv(lines)); } protected @NotNull List<String> getShellProcessCommand() { String shellScript = getShell(); if (StringUtilRt.isEmptyOrSpaces(shellScript)) { throw new RuntimeException("empty $SHELL"); } if (!Files.isExecutable(Paths.get(shellScript))) { throw new RuntimeException("$SHELL points to a missing or non-executable file: " + shellScript); } return buildShellProcessCommand(shellScript, true, true, false); } protected @Nullable String getShell() { return System.getenv(SHELL_VARIABLE_NAME); } } /** * Builds a login shell command list from the {@code shellScript} path. * * @param shellScript path to the shell script, probably taken from environment variable {@code SHELL} * @param isLogin true iff it should be login shell, usually {@code -l} parameter * @param isInteractive true iff it should be interactive shell, usually {@code -i} parameter * @param isCommand true iff command should accept a command, instead of script name, usually {@code -c} parameter * @return list of commands for starting a process, e.g. {@code /bin/bash -l -i -c} */ @ApiStatus.Experimental public static @NotNull List<String> buildShellProcessCommand(@NotNull @NonNls String shellScript, boolean isLogin, boolean isInteractive, boolean isCommand) { List<String> commands = new ArrayList<>(); commands.add(shellScript); if (isLogin && !(shellScript.endsWith("/tcsh") || shellScript.endsWith("/csh"))) { // *csh do not allow to use -l with any other options commands.add(SHELL_LOGIN_ARGUMENT); } if (isInteractive && !shellScript.endsWith("/fish")) { // Fish uses a single config file with conditions commands.add(SHELL_INTERACTIVE_ARGUMENT); } if (isCommand) { commands.add(SHELL_COMMAND_ARGUMENT); } return commands; } @SuppressWarnings("SSBasedInspection") public static @NotNull Map<String, String> parseEnv(String @NotNull[] lines) { Set<String> toIgnore = new HashSet<>(Arrays.asList("_", "PWD", "SHLVL", DISABLE_OMZ_AUTO_UPDATE, INTELLIJ_ENVIRONMENT_READER)); Map<String, String> env = System.getenv(); Map<String, String> newEnv = new HashMap<>(); for (String line : lines) { int pos = line.indexOf('='); if (pos <= 0) { throw new RuntimeException("malformed:" + line); } String name = line.substring(0, pos); if (!toIgnore.contains(name)) { newEnv.put(name, line.substring(pos + 1)); } else if (env.containsKey(name)) { newEnv.put(name, env.get(name)); } } LOG.info("shell environment loaded (" + newEnv.size() + " vars)"); return newEnv; } private static @NotNull Map<String, String> parseEnv(@NotNull String text) { return parseEnv(text.split("\0")); } /** * @param timeoutMillis the time-out (in milliseconds) for {@code process} to terminate. */ private static int waitAndTerminateAfter(@NotNull Process process, final long timeoutMillis) { Integer exitCode = waitFor(process, timeoutMillis); if (exitCode != null) { return exitCode; } LOG.warn("shell env loader is timed out"); // First, try to interrupt 'softly' (we know how to do it only on *nix) if (!SystemInfoRt.isWindows) { UnixProcessManager.sendSigIntToProcessTree(process); exitCode = waitFor(process, 1000L); if (exitCode != null) { return exitCode; } LOG.warn("failed to terminate shell env loader process gracefully, terminating forcibly"); } if (SystemInfoRt.isWindows) { WinProcessManager.kill(process, true); } else { UnixProcessManager.sendSigKillToProcessTree(process); } exitCode = waitFor(process, 1000L); if (exitCode != null) { return exitCode; } LOG.warn("failed to kill shell env loader"); return -1; } /** * @param timeoutMillis the time-out (in milliseconds) for {@code process} to terminate. * @return the exit code of the process if it has already terminated, or it has terminated within the timeout; or {@code null} otherwise */ private static @Nullable Integer waitFor(@NotNull Process process, final long timeoutMillis) { try { if (process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS)) { return process.exitValue(); } } catch (InterruptedException e) { LOG.info("Interrupted while waiting for process", e); } return null; } private static void setCharsetVar(@NotNull Map<String, String> env) { if (!isCharsetVarDefined(env)) { String value = setLocaleEnv(env, CharsetToolkit.getDefaultSystemCharset()); LOG.info("LC_CTYPE=" + value); } } private static boolean checkIfLocaleAvailable(String candidateLanguageTerritory) { Locale[] available = Locale.getAvailableLocales(); for (Locale l : available) { if (StringUtilRt.equal(l.toString(), candidateLanguageTerritory, true)) { return true; } } return false; } public static @NotNull String setLocaleEnv(@NotNull Map<String, String> env, @NotNull Charset charset) { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); @NonNls String languageTerritory = "en_US"; if (!language.isEmpty() && !country.isEmpty()) { String languageTerritoryFromLocale = language + '_' + country; if (checkIfLocaleAvailable(languageTerritoryFromLocale)) { languageTerritory = languageTerritoryFromLocale ; } } String result = languageTerritory + '.' + charset.name(); env.put(LC_CTYPE, result); return result; } private static boolean isCharsetVarDefined(@NotNull Map<String, String> env) { return !env.isEmpty() && (env.containsKey(LANG) || env.containsKey(LC_ALL) || env.containsKey(LC_CTYPE)); } public static void inlineParentOccurrences(@NotNull Map<String, String> envs) { inlineParentOccurrences(envs, getEnvironmentMap()); } public static void inlineParentOccurrences(@NotNull Map<String, String> envs, @NotNull Map<String, String> parentEnv) { for (Map.Entry<String, String> entry : envs.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value != null) { String parentVal = parentEnv.get(key); if (parentVal != null && containsEnvKeySubstitution(key, value)) { envs.put(key, value.replace("$" + key + "$", parentVal)); } } } } private static boolean containsEnvKeySubstitution(final String envKey, final String val) { return ArrayUtil.find(val.split(File.pathSeparator), "$" + envKey + "$") != -1; } @TestOnly static Map<String, String> testLoader() { try { return getShellEnv(); } catch (Exception e) { throw new RuntimeException(e); } } @TestOnly static Map<String, String> testParser(@NotNull String lines) { try { return parseEnv(lines); } catch (Exception e) { throw new RuntimeException(e); } } private static class StreamGobbler extends BaseOutputReader { private static final Options OPTIONS = new Options() { @Override public SleepingPolicy policy() { return SleepingPolicy.BLOCKING; } @Override public boolean splitToLines() { return false; } }; private final StringBuffer myBuffer; StreamGobbler(@NotNull InputStream stream) { super(stream, CharsetToolkit.getDefaultSystemCharset(), OPTIONS); myBuffer = new StringBuffer(); start("stdout/stderr streams of shell env loading process"); } @Override protected @NotNull Future<?> executeOnPooledThread(@NotNull Runnable runnable) { return AppExecutorUtil.getAppExecutorService().submit(runnable); } @Override protected void onTextAvailable(@NotNull String text) { myBuffer.append(text); } public @NotNull String getText() { return myBuffer.toString(); } } }
platform/util/src/com/intellij/util/EnvironmentUtil.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util; import com.intellij.execution.CommandLineUtil; import com.intellij.execution.process.UnixProcessManager; import com.intellij.execution.process.WinProcessManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.io.BaseOutputReader; import com.intellij.util.text.CaseInsensitiveStringHashingStrategy; import gnu.trove.THashMap; import org.jetbrains.annotations.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public final class EnvironmentUtil { private static final Logger LOG = Logger.getInstance(EnvironmentUtil.class); /** * The default time-out to read the environment, in milliseconds. */ private static final long DEFAULT_SHELL_ENV_READING_TIMEOUT_MILLIS = 20_000L; private static final String LANG = "LANG"; private static final String LC_ALL = "LC_ALL"; private static final String LC_CTYPE = "LC_CTYPE"; private static final String DESKTOP_STARTUP_ID = "DESKTOP_STARTUP_ID"; public static final @NonNls String BASH_EXECUTABLE_NAME = "bash"; public static final String SHELL_VARIABLE_NAME = "SHELL"; private static final String SHELL_INTERACTIVE_ARGUMENT = "-i"; public static final String SHELL_LOGIN_ARGUMENT = "-l"; public static final String SHELL_COMMAND_ARGUMENT = "-c"; public static final String SHELL_SOURCE_COMMAND = "source"; /** * Holds the number of shell levels the current shell is running on top of. * Tested with bash/zsh/fish/tcsh/csh/ksh. */ private static final String SHLVL = "SHLVL"; private static final AtomicReference<CompletableFuture<Map<String, String>>> ourEnvGetter = new AtomicReference<>(); private EnvironmentUtil() { } /** * <p>A wrapper layer around {@link System#getenv()}.</p> * * <p>On Windows, the returned map is case-insensitive (i.e. {@code map.get("Path") == map.get("PATH")} holds).</p> * * <p>On macOS, things are complicated.<br/> * An app launched by a GUI launcher (Finder, Dock, Spotlight etc.) receives a pretty empty and useless environment, * since standard Unix ways of setting variables via e.g. ~/.profile do not work. What's more important, there are no * sane alternatives. This causes a lot of user complaints about tools working in a terminal not working when launched * from the IDE. To ease their pain, the IDE loads a shell environment (see {@link #getShellEnv()} for gory details) * and returns it as the result.<br/> * And one more thing (c): locale variables on macOS are usually set by a terminal app - meaning they are missing * even from a shell environment above. This again causes user complaints about tools being unable to output anything * outside ASCII range when launched from the IDE. Resolved by adding LC_CTYPE variable to the map if it doesn't contain * explicitly set locale variables (LANG/LC_ALL/LC_CTYPE). See {@link #setCharsetVar(Map)} for details.</p> * * @return unmodifiable map of the process environment. */ public static @NotNull Map<String, String> getEnvironmentMap() { CompletableFuture<Map<String, String>> getter = ourEnvGetter.get(); if (getter == null) { getter = CompletableFuture.completedFuture(getSystemEnv()); if (!ourEnvGetter.compareAndSet(null, getter)) { getter = ourEnvGetter.get(); } } try { return getter.join(); } catch (Throwable t) { throw new AssertionError(t); // unknown state; is not expected to happen } } @ApiStatus.Internal public static void loadEnvironment(@NotNull Runnable callback) { if (shouldLoadShellEnv()) { ourEnvGetter.set(CompletableFuture.supplyAsync(() -> { try { Map<String, String> env = getShellEnv(); setCharsetVar(env); return Collections.unmodifiableMap(env); } catch (Throwable t) { LOG.warn("can't get shell environment", t); return getSystemEnv(); } finally { callback.run(); } }, AppExecutorUtil.getAppExecutorService())); } else { ourEnvGetter.set(CompletableFuture.completedFuture(getSystemEnv())); callback.run(); } } private static boolean shouldLoadShellEnv() { if (!SystemInfoRt.isMac) { return false; } // The method is called too early when the IDE starts up, at this point the registry values have not been loaded yet from the service. // Using a system property is a good alternative. if (!Boolean.parseBoolean(System.getProperty("ij.load.shell.env", "true"))) { LOG.info("loading shell env is turned off"); return false; } String value = System.getenv(SHLVL); // On macOS, login shell session is not run when a user logs in, thus "SHLVL > 0" likely means that IDE is run from a terminal. if (StringUtilRt.parseInt(value, 0) > 0) { LOG.info("loading shell env is skipped: IDE has been launched from a terminal (" + SHLVL + "=" + value + ")"); return false; } return true; } private static @NotNull Map<String, String> getSystemEnv() { if (SystemInfoRt.isWindows) { return Collections.unmodifiableMap(new THashMap<>(System.getenv(), CaseInsensitiveStringHashingStrategy.INSTANCE)); } else if (SystemInfoRt.isXWindow) { // DESKTOP_STARTUP_ID variable can be set by an application launcher in X Window environment. // It shouldn't be passed to child processes as per 'Startup notification protocol' // (https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt). // Ideally, JDK should clear this variable, and it actually does, but the snapshot of the environment variables, // returned by System.getenv(), is captured before the removal. Map<String, String> env = System.getenv(); if (env.containsKey(DESKTOP_STARTUP_ID)) { env = new HashMap<>(env); env.remove(DESKTOP_STARTUP_ID); env = Collections.unmodifiableMap(env); } return env; } else { return System.getenv(); } } /** * Same as {@code getEnvironmentMap().get(name)}. * Returns value for the passed environment variable name, or null if no such variable found. * * @see #getEnvironmentMap() */ public static @Nullable @NonNls String getValue(@NotNull @NonNls String name) { return getEnvironmentMap().get(name); } /** * Validates environment variable name in accordance to * {@code ProcessEnvironment#validateVariable} ({@code ProcessEnvironment#validateName} on Windows). * * @see #isValidValue(String) * @see <a href="http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html">Environment Variables in Unix</a> * @see <a href="https://docs.microsoft.com/en-us/windows/desktop/ProcThread/environment-variables">Environment Variables in Windows</a> */ @Contract(value = "null -> false", pure = true) public static boolean isValidName(@Nullable @NonNls String name) { return name != null && !name.isEmpty() && name.indexOf('\0') == -1 && name.indexOf('=', SystemInfoRt.isWindows ? 1 : 0) == -1; } /** * Validates environment variable value in accordance to {@code ProcessEnvironment#validateValue}. * * @see #isValidName(String) */ @Contract(value = "null -> false", pure = true) public static boolean isValidValue(@Nullable @NonNls String value) { return value != null && value.indexOf('\0') == -1; } private static final String DISABLE_OMZ_AUTO_UPDATE = "DISABLE_AUTO_UPDATE"; private static final String INTELLIJ_ENVIRONMENT_READER = "INTELLIJ_ENVIRONMENT_READER"; private static @NotNull Map<String, String> getShellEnv() throws IOException { return new ShellEnvReader().readShellEnv(null); } public static class ShellEnvReader { private final long myTimeoutMillis; /** * Creates an instance with the default time-out value of {@value #DEFAULT_SHELL_ENV_READING_TIMEOUT_MILLIS} milliseconds. * * @see #ShellEnvReader(long) */ public ShellEnvReader() { this(DEFAULT_SHELL_ENV_READING_TIMEOUT_MILLIS); } /** * @param timeoutMillis the time-out (in milliseconds) for reading environment variables. * @see #ShellEnvReader() */ public ShellEnvReader(long timeoutMillis) { myTimeoutMillis = timeoutMillis; } public final @NotNull Map<String, String> readShellEnv(@Nullable Path file, @Nullable Map<String, String> additionalEnvironment) throws IOException { Path reader = PathManager.findBinFileWithException("printenv.py"); Path envFile = Files.createTempFile("intellij-shell-env.", ".tmp"); StringBuilder readerCmd = new StringBuilder(); if (file != null) { if (!Files.exists(file)) { throw new NoSuchFileException(file.toString()); } readerCmd.append(SHELL_SOURCE_COMMAND).append(" \"").append(file).append("\" && "); } readerCmd.append("'").append(reader.toAbsolutePath()).append("' '").append(envFile.toAbsolutePath()).append("'"); try { List<String> command = getShellProcessCommand(); int idx = command.indexOf(SHELL_COMMAND_ARGUMENT); if (idx >= 0) { // if there is already a command append command to the end command.set(idx + 1, command.get(idx + 1) + ";" + readerCmd.toString()); } else { command.add(SHELL_COMMAND_ARGUMENT); command.add(readerCmd.toString()); } LOG.info("loading shell env: " + String.join(" ", command)); return runProcessAndReadOutputAndEnvs(command, null, additionalEnvironment, envFile).second; } finally { try { Files.delete(envFile); } catch (NoSuchFileException ignore) { } catch (IOException e) { LOG.warn("Cannot delete temporary file", e); } } } protected final @NotNull Map<String, String> readShellEnv(@Nullable Map<String, String> additionalEnvironment) throws IOException { return readShellEnv(null, additionalEnvironment); } public @NotNull Map<String, String> readBatEnv(@Nullable Path batchFile, List<String> args) throws IOException { return readBatOutputAndEnv(batchFile, args).second; } public @NotNull Pair<String, Map<String, String>> readBatOutputAndEnv(@Nullable Path batchFile, List<String> args) throws IOException { if (batchFile != null && !Files.exists(batchFile)) { throw new NoSuchFileException(batchFile.toString()); } Path envFile = Files.createTempFile("intellij-cmd-env.", ".tmp"); try { List<@NonNls String> cl = new ArrayList<>(); cl.add(CommandLineUtil.getWinShellName()); cl.add("/c"); if (batchFile != null) { cl.add("call"); cl.add(batchFile.toString()); if (args != null) cl.addAll(args); cl.add("&&"); } cl.addAll(getReadEnvCommand()); cl.add(envFile.toString()); cl.addAll(Arrays.asList("||", "exit", "/B", "%ERRORLEVEL%")); return runProcessAndReadOutputAndEnvs(cl, batchFile != null ? batchFile.getParent() : null, null, envFile); } finally { try { Files.delete(envFile); } catch (NoSuchFileException ignore) { } catch (IOException e) { LOG.warn("Cannot delete temporary file", e); } } } private static @NotNull List<String> getReadEnvCommand() { return Arrays.asList(FileUtilRt.toSystemDependentName(System.getProperty("java.home") + "/bin/java"), "-cp", PathManager.getJarPathForClass(ReadEnv.class), ReadEnv.class.getCanonicalName()); } protected final @NotNull Pair<String, Map<String, String>> runProcessAndReadOutputAndEnvs(@NotNull List<String> command, @Nullable Path workingDir, @Nullable Map<String, String> scriptEnvironment, @NotNull Path envFile) throws IOException { ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); if (scriptEnvironment != null) { // we might need default environment for the process to launch correctly builder.environment().putAll(scriptEnvironment); } if (workingDir != null) { builder.directory(workingDir.toFile()); } builder.environment().put(DISABLE_OMZ_AUTO_UPDATE, "true"); builder.environment().put(INTELLIJ_ENVIRONMENT_READER, "true"); Process process = builder.start(); StreamGobbler gobbler = new StreamGobbler(process.getInputStream()); final int exitCode = waitAndTerminateAfter(process, myTimeoutMillis); gobbler.stop(); String lines = new String(Files.readAllBytes(envFile), StandardCharsets.UTF_8); if (exitCode != 0 || lines.isEmpty()) { throw new RuntimeException("command " + command + "\n\texit code:" + exitCode + " text:" + lines.length() + " out:" + gobbler.getText().trim()); } return new Pair<>(gobbler.getText(), parseEnv(lines)); } protected @NotNull List<String> getShellProcessCommand() { String shellScript = getShell(); if (StringUtilRt.isEmptyOrSpaces(shellScript)) { throw new RuntimeException("empty $SHELL"); } if (!Files.isExecutable(Paths.get(shellScript))) { throw new RuntimeException("$SHELL points to a missing or non-executable file: " + shellScript); } return buildShellProcessCommand(shellScript, true, true, false); } protected @Nullable String getShell() { return System.getenv(SHELL_VARIABLE_NAME); } } /** * Builds a login shell command list from the {@code shellScript} path. * * @param shellScript path to the shell script, probably taken from environment variable {@code SHELL} * @param isLogin true iff it should be login shell, usually {@code -l} parameter * @param isInteractive true iff it should be interactive shell, usually {@code -i} parameter * @param isCommand true iff command should accept a command, instead of script name, usually {@code -c} parameter * @return list of commands for starting a process, e.g. {@code /bin/bash -l -i -c} */ @ApiStatus.Experimental public static @NotNull List<String> buildShellProcessCommand(@NotNull @NonNls String shellScript, boolean isLogin, boolean isInteractive, boolean isCommand) { List<String> commands = new ArrayList<>(); commands.add(shellScript); if (isLogin && !(shellScript.endsWith("/tcsh") || shellScript.endsWith("/csh"))) { // *csh do not allow to use -l with any other options commands.add(SHELL_LOGIN_ARGUMENT); } if (isInteractive && !shellScript.endsWith("/fish")) { // Fish uses a single config file with conditions commands.add(SHELL_INTERACTIVE_ARGUMENT); } if (isCommand) { commands.add(SHELL_COMMAND_ARGUMENT); } return commands; } @SuppressWarnings("SSBasedInspection") public static @NotNull Map<String, String> parseEnv(String @NotNull[] lines) { Set<String> toIgnore = new HashSet<>(Arrays.asList("_", "PWD", "SHLVL", DISABLE_OMZ_AUTO_UPDATE, INTELLIJ_ENVIRONMENT_READER)); Map<String, String> env = System.getenv(); Map<String, String> newEnv = new HashMap<>(); for (String line : lines) { int pos = line.indexOf('='); if (pos <= 0) { throw new RuntimeException("malformed:" + line); } String name = line.substring(0, pos); if (!toIgnore.contains(name)) { newEnv.put(name, line.substring(pos + 1)); } else if (env.containsKey(name)) { newEnv.put(name, env.get(name)); } } LOG.info("shell environment loaded (" + newEnv.size() + " vars)"); return newEnv; } private static @NotNull Map<String, String> parseEnv(@NotNull String text) { return parseEnv(text.split("\0")); } /** * @param timeoutMillis the time-out (in milliseconds) for {@code process} to terminate. */ private static int waitAndTerminateAfter(@NotNull Process process, final long timeoutMillis) { Integer exitCode = waitFor(process, timeoutMillis); if (exitCode != null) { return exitCode; } LOG.warn("shell env loader is timed out"); // First, try to interrupt 'softly' (we know how to do it only on *nix) if (!SystemInfoRt.isWindows) { UnixProcessManager.sendSigIntToProcessTree(process); exitCode = waitFor(process, 1000L); if (exitCode != null) { return exitCode; } LOG.warn("failed to terminate shell env loader process gracefully, terminating forcibly"); } if (SystemInfoRt.isWindows) { WinProcessManager.kill(process, true); } else { UnixProcessManager.sendSigKillToProcessTree(process); } exitCode = waitFor(process, 1000L); if (exitCode != null) { return exitCode; } LOG.warn("failed to kill shell env loader"); return -1; } /** * @param timeoutMillis the time-out (in milliseconds) for {@code process} to terminate. * @return the exit code of the process if it has already terminated, or it has terminated within the timeout; or {@code null} otherwise */ private static @Nullable Integer waitFor(@NotNull Process process, final long timeoutMillis) { try { if (process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS)) { return process.exitValue(); } } catch (InterruptedException e) { LOG.info("Interrupted while waiting for process", e); } return null; } private static void setCharsetVar(@NotNull Map<String, String> env) { if (!isCharsetVarDefined(env)) { String value = setLocaleEnv(env, CharsetToolkit.getDefaultSystemCharset()); LOG.info("LC_CTYPE=" + value); } } private static boolean checkIfLocaleAvailable(String candidateLanguageTerritory) { Locale[] available = Locale.getAvailableLocales(); for (Locale l : available) { if (StringUtilRt.equal(l.toString(), candidateLanguageTerritory, true)) { return true; } } return false; } public static @NotNull String setLocaleEnv(@NotNull Map<String, String> env, @NotNull Charset charset) { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); @NonNls String languageTerritory = "en_US"; if (!language.isEmpty() && !country.isEmpty()) { String languageTerritoryFromLocale = language + '_' + country; if (checkIfLocaleAvailable(languageTerritoryFromLocale)) { languageTerritory = languageTerritoryFromLocale ; } } String result = languageTerritory + '.' + charset.name(); env.put(LC_CTYPE, result); return result; } private static boolean isCharsetVarDefined(@NotNull Map<String, String> env) { return !env.isEmpty() && (env.containsKey(LANG) || env.containsKey(LC_ALL) || env.containsKey(LC_CTYPE)); } public static void inlineParentOccurrences(@NotNull Map<String, String> envs) { inlineParentOccurrences(envs, getEnvironmentMap()); } public static void inlineParentOccurrences(@NotNull Map<String, String> envs, @NotNull Map<String, String> parentEnv) { for (Map.Entry<String, String> entry : envs.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value != null) { String parentVal = parentEnv.get(key); if (parentVal != null && containsEnvKeySubstitution(key, value)) { envs.put(key, value.replace("$" + key + "$", parentVal)); } } } } private static boolean containsEnvKeySubstitution(final String envKey, final String val) { return ArrayUtil.find(val.split(File.pathSeparator), "$" + envKey + "$") != -1; } @TestOnly static Map<String, String> testLoader() { try { return getShellEnv(); } catch (Exception e) { throw new RuntimeException(e); } } @TestOnly static Map<String, String> testParser(@NotNull String lines) { try { return parseEnv(lines); } catch (Exception e) { throw new RuntimeException(e); } } private static class StreamGobbler extends BaseOutputReader { private static final Options OPTIONS = new Options() { @Override public SleepingPolicy policy() { return SleepingPolicy.BLOCKING; } @Override public boolean splitToLines() { return false; } }; private final StringBuffer myBuffer; StreamGobbler(@NotNull InputStream stream) { super(stream, CharsetToolkit.getDefaultSystemCharset(), OPTIONS); myBuffer = new StringBuffer(); start("stdout/stderr streams of shell env loading process"); } @Override protected @NotNull Future<?> executeOnPooledThread(@NotNull Runnable runnable) { return AppExecutorUtil.getAppExecutorService().submit(runnable); } @Override protected void onTextAvailable(@NotNull String text) { myBuffer.append(text); } public @NotNull String getText() { return myBuffer.toString(); } } }
CPP-22596: fix reading environment from file if paths contains spaces GitOrigin-RevId: 12e102e83268f12f6f5a961b19101bfb4e0436f1
platform/util/src/com/intellij/util/EnvironmentUtil.java
CPP-22596: fix reading environment from file if paths contains spaces
<ide><path>latform/util/src/com/intellij/util/EnvironmentUtil.java <ide> import com.intellij.openapi.util.Pair; <ide> import com.intellij.openapi.util.SystemInfoRt; <ide> import com.intellij.openapi.util.io.FileUtilRt; <add>import com.intellij.openapi.util.text.StringUtil; <ide> import com.intellij.openapi.util.text.StringUtilRt; <ide> import com.intellij.openapi.vfs.CharsetToolkit; <ide> import com.intellij.util.concurrency.AppExecutorUtil; <ide> <ide> Path envFile = Files.createTempFile("intellij-cmd-env.", ".tmp"); <ide> try { <add> List<@NonNls String> callArgs = new ArrayList<>(); <add> if (batchFile != null) { <add> callArgs.add("call"); <add> callArgs.add(batchFile.toString()); <add> if (args != null) <add> callArgs.addAll(args); <add> callArgs.add("&&"); <add> } <add> callArgs.addAll(getReadEnvCommand()); <add> callArgs.add(envFile.toString()); <add> callArgs.addAll(Arrays.asList("||", "exit", "/B", "%ERRORLEVEL%")); <add> <ide> List<@NonNls String> cl = new ArrayList<>(); <ide> cl.add(CommandLineUtil.getWinShellName()); <ide> cl.add("/c"); <del> if (batchFile != null) { <del> cl.add("call"); <del> cl.add(batchFile.toString()); <del> if (args != null) <del> cl.addAll(args); <del> cl.add("&&"); <del> } <del> cl.addAll(getReadEnvCommand()); <del> cl.add(envFile.toString()); <del> cl.addAll(Arrays.asList("||", "exit", "/B", "%ERRORLEVEL%")); <add> cl.add(prepareCallArgs(callArgs)); <ide> return runProcessAndReadOutputAndEnvs(cl, batchFile != null ? batchFile.getParent() : null, null, envFile); <ide> } <ide> finally { <ide> LOG.warn("Cannot delete temporary file", e); <ide> } <ide> } <add> } <add> <add> @NotNull <add> private static String prepareCallArgs(@NotNull List<String> callArgs) { <add> List<String> preparedCallArgs = CommandLineUtil.toCommandLine(callArgs); <add> String firstArg = preparedCallArgs.remove(0); <add> preparedCallArgs.add(0, CommandLineUtil.escapeParameterOnWindows(firstArg, false)); <add> // for CMD we would like to add extra double quotes for the actual command in call <add> // to mitigate possible JVM issue when argument contains spaces and the first word <add> // starts with double quote and the last ends with double quote and JVM does not <add> // wrap the argument with double quotes <add> // Example: callArgs = ["\"C:\\New Folder\aa\"", "\"C:\\New Folder\aa\""] <add> return StringUtil.wrapWithDoubleQuote(String.join(" ", preparedCallArgs)); <ide> } <ide> <ide> private static @NotNull List<String> getReadEnvCommand() {
Java
mit
df5657495215629724f0cf548bac8a60b6339ddc
0
sdl/Testy,sdl/Testy,sdl/Testy,sdl/Testy
package com.sdl.selenium.utils.config; import com.sdl.selenium.utils.browsers.AbstractBrowserConfigReader; import com.sdl.selenium.utils.browsers.ChromeConfigReader; import com.sdl.selenium.utils.browsers.FirefoxConfigReader; import com.sdl.selenium.utils.browsers.IExplorerConfigReader; import com.sdl.selenium.web.Browser; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.utils.PropertiesReader; import com.sdl.selenium.web.utils.RetryUtils; import com.sdl.selenium.web.utils.Utils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.SystemUtils; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.service.DriverService; import org.openqa.selenium.safari.SafariDriver; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; @Slf4j public class WebDriverConfig { private static WebDriver driver; private static boolean isIE; private static boolean isOpera; private static boolean isSafari; private static boolean isChrome; private static boolean isFireFox; private static boolean isSilentDownload; private static boolean isHeadless; private static DriverService driverService; private static String downloadPath; /** * @return last created driver (current one) */ public static WebDriver getDriver() { return driver; } public static boolean isIE() { return isIE; } public static boolean isOpera() { return isOpera; } public static boolean isSafari() { return isSafari; } public static boolean isChrome() { return isChrome; } public static boolean isFireFox() { return isFireFox; } public static void init(WebDriver driver) { if (driver != null) { log.info("==============================================================="); log.info("| Open Selenium Web Driver "); log.info("===============================================================\n"); WebDriverConfig.driver = driver; WebLocator.setDriverExecutor(driver); if (driver instanceof InternetExplorerDriver) { isIE = true; } else if (driver instanceof ChromeDriver) { isChrome = true; } else if (driver instanceof FirefoxDriver) { isFireFox = true; } else if (driver instanceof SafariDriver) { isSafari = true; } if (!SystemUtils.IS_OS_LINUX) { driver.manage().window().maximize(); } driver.manage().timeouts().implicitlyWait(WebLocatorConfig.getInt("driver.implicitlyWait"), TimeUnit.MILLISECONDS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (WebLocatorConfig.getBoolean("driver.autoClose")) { initSeleniumEnd(); } } }); } } private static void initSeleniumEnd() { log.info("==============================================================="); log.info("| Stopping driver (closing browser) |"); log.info("==============================================================="); driver.quit(); String user = System.getProperty("user.home"); try { org.apache.commons.io.FileUtils.cleanDirectory(new File(user + "\\AppData\\Local\\Temp")); } catch (IOException e) { log.debug("{}", e.getMessage()); } log.debug("==============================================================="); log.debug("| Driver stopped (browser closed) |"); log.debug("===============================================================\n"); } public static boolean isSilentDownload() { return isSilentDownload; } private static void setSilentDownload(boolean isSalientDownload) { WebDriverConfig.isSilentDownload = isSalientDownload; } public static boolean isHeadless() { return isHeadless; } public static void setHeadless(boolean isHeadless) { WebDriverConfig.isHeadless = isHeadless; } public static DriverService getDriverService() { return driverService; } public static void setDriverService(DriverService driverService) { WebDriverConfig.driverService = driverService; } public static String getDownloadPath() { return downloadPath; } public static void setDownloadPath(String downloadPath) { WebDriverConfig.downloadPath = downloadPath; } /** * Create and return new WebDriver * * @param browserProperties path to browser.properties * @return WebDriver * @throws IOException exception */ public static WebDriver getWebDriver(String browserProperties) throws IOException { return getWebDriver(browserProperties, null); } /** * Create and return new WebDriver or RemoteWebDriver based on properties file * * @param browserProperties path to browser.properties * @param remoteUrl url * @return WebDriver * @throws IOException exception */ public static WebDriver getWebDriver(String browserProperties, URL remoteUrl) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(browserProperties); log.debug("File: {} " + (resource != null ? "exists" : "does not exist"), browserProperties); if (resource != null) { Browser browser = findBrowser(resource.openStream()); return getDriver(browser, resource.openStream(), remoteUrl); } return null; } /** * Create and return new WebDriver * * @param browser see details {@link com.sdl.selenium.web.Browser} * @return WebDriver * @throws IOException exception */ public static WebDriver getWebDriver(Browser browser) throws IOException { return getDriver(browser, null); } public static WebDriver getWebDriver(URL remoteUrl, DesiredCapabilities capabilities) { driver = new RemoteWebDriver(remoteUrl, capabilities); ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector()); init(driver); return driver; } private static WebDriver getDriver(Browser browser, InputStream inputStream, URL remoteUrl) throws IOException { AbstractBrowserConfigReader properties = null; if (browser == Browser.FIREFOX) { properties = new FirefoxConfigReader(); } else if (browser == Browser.IEXPLORE) { properties = new IExplorerConfigReader(); } else if (browser == Browser.CHROME) { properties = new ChromeConfigReader(); } else { log.error("Browser not supported {}", browser); driver = null; } if (properties != null) { if (inputStream != null) { properties.load(inputStream); } log.debug(properties.toString()); if (System.getProperty("RUNNER_NAME") != null) { String userData = "user-data-dir=" + System.getProperty("user.home") + "\\AppData\\Local\\Temp\\" + System.getProperty("RUNNER_NAME"); properties.setProperty("options.arguments", properties.getProperty("options.arguments") + userData); } driver = properties.createDriver(remoteUrl); WebDriverConfig.setDownloadPath(properties.getDownloadPath()); WebDriverConfig.setSilentDownload(properties.isSilentDownload()); WebDriverConfig.setHeadless(properties.getProperty("options.arguments").contains("headless")); WebDriverConfig.setDriverService(properties.getDriveService()); } init(driver); return driver; } private static WebDriver getDriver(Browser browser, InputStream inputStream) throws IOException { return getDriver(browser, inputStream, null); } public static Browser getBrowser(String browserKey) { browserKey = browserKey.toUpperCase(); Browser browser = null; try { browser = Browser.valueOf(browserKey); } catch (IllegalArgumentException e) { log.error("BROWSER not supported : {}. Supported browsers: {}", browserKey, Arrays.asList(Browser.values())); } return browser; } private static Browser findBrowser(InputStream inputStream) { PropertiesReader properties = new PropertiesReader(null, inputStream); String browserKey = properties.getProperty("browser"); WebLocatorConfig.setBrowserProperties(properties); log.info("Browser is: {}", browserKey); return getBrowser(browserKey); } /** * Switch driver to last browser tab * * @return oldTabName */ public static String switchToLastTab() { int totalTabs; int time = 0; do { Utils.sleep(100L); totalTabs = getCountTabs(); time++; } while (totalTabs <= 1 && time < 10); return switchToTab(totalTabs - 1); } public static int getCountTabs() { return driver.getWindowHandles().size(); } /** * Switch driver to first browser tab * Tab is not visible but we can interact with it, TODO see how to make it active * * @return oldTabName */ public static String switchToFirstTab() { return switchToTab(0); } public static String switchToTab(int index) { String oldTabName = null; try { Utils.sleep(100); // to make sure tab has been created try { oldTabName = driver.getWindowHandle(); log.debug("Preview tab id: {}, title {}", oldTabName, driver.getTitle()); } catch (NoSuchWindowException e) { log.info("Preview tab already closed"); } List<String> winList = new ArrayList<>(driver.getWindowHandles()); String tabID = winList.get(index); String title = RetryUtils.retry(3, () -> { driver.switchTo().window(tabID); Utils.sleep(100); return driver.getTitle(); }); log.info("Current tab id: {}, title: {}", tabID, title); } catch (NoSuchWindowException e) { log.error("NoSuchWindowException", e); } return oldTabName; } /** * @param tabCount : this is webdriver * @param millis : time you define to wait the tab open * @return true if tab open in the time, false if tab not open in the time. */ public static boolean waitForNewTab(int tabCount, long millis) { boolean hasExpectedTabs = false; while (!hasExpectedTabs && millis > 0) { if (getCountTabs() >= tabCount) { hasExpectedTabs = true; } else { log.info("Waiting {} ms for new tab...", millis); Utils.sleep(100); } millis -= 100; } return hasExpectedTabs; } }
src/main/java/com/sdl/selenium/utils/config/WebDriverConfig.java
package com.sdl.selenium.utils.config; import com.sdl.selenium.utils.browsers.AbstractBrowserConfigReader; import com.sdl.selenium.utils.browsers.ChromeConfigReader; import com.sdl.selenium.utils.browsers.FirefoxConfigReader; import com.sdl.selenium.utils.browsers.IExplorerConfigReader; import com.sdl.selenium.web.Browser; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.utils.PropertiesReader; import com.sdl.selenium.web.utils.RetryUtils; import com.sdl.selenium.web.utils.Utils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.SystemUtils; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.service.DriverService; import org.openqa.selenium.safari.SafariDriver; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; @Slf4j public class WebDriverConfig { private static WebDriver driver; private static boolean isIE; private static boolean isOpera; private static boolean isSafari; private static boolean isChrome; private static boolean isFireFox; private static boolean isSilentDownload; private static boolean isHeadless; private static DriverService driverService; private static String downloadPath; /** * @return last created driver (current one) */ public static WebDriver getDriver() { return driver; } public static boolean isIE() { return isIE; } public static boolean isOpera() { return isOpera; } public static boolean isSafari() { return isSafari; } public static boolean isChrome() { return isChrome; } public static boolean isFireFox() { return isFireFox; } public static void init(WebDriver driver) { if (driver != null) { log.info("==============================================================="); log.info("| Open Selenium Web Driver "); log.info("===============================================================\n"); WebDriverConfig.driver = driver; WebLocator.setDriverExecutor(driver); if (driver instanceof InternetExplorerDriver) { isIE = true; } else if (driver instanceof ChromeDriver) { isChrome = true; } else if (driver instanceof FirefoxDriver) { isFireFox = true; } else if (driver instanceof SafariDriver) { isSafari = true; } if (!SystemUtils.IS_OS_LINUX) { driver.manage().window().maximize(); } driver.manage().timeouts().implicitlyWait(WebLocatorConfig.getInt("driver.implicitlyWait"), TimeUnit.MILLISECONDS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (WebLocatorConfig.getBoolean("driver.autoClose")) { initSeleniumEnd(); } } }); } } private static void initSeleniumEnd() { log.info("==============================================================="); log.info("| Stopping driver (closing browser) |"); log.info("==============================================================="); driver.quit(); String user = System.getProperty("user.home"); try { org.apache.commons.io.FileUtils.cleanDirectory(new File(user + "\\AppData\\Local\\Temp")); } catch (IOException e) { log.debug("{}", e.getMessage()); } log.debug("==============================================================="); log.debug("| Driver stopped (browser closed) |"); log.debug("===============================================================\n"); } public static boolean isSilentDownload() { return isSilentDownload; } private static void setSilentDownload(boolean isSalientDownload) { WebDriverConfig.isSilentDownload = isSalientDownload; } public static boolean isHeadless() { return isHeadless; } public static void setHeadless(boolean isHeadless) { WebDriverConfig.isHeadless = isHeadless; } public static DriverService getDriverService() { return driverService; } public static void setDriverService(DriverService driverService) { WebDriverConfig.driverService = driverService; } public static String getDownloadPath() { return downloadPath; } public static void setDownloadPath(String downloadPath) { WebDriverConfig.downloadPath = downloadPath; } /** * Create and return new WebDriver * * @param browserProperties path to browser.properties * @return WebDriver * @throws IOException exception */ public static WebDriver getWebDriver(String browserProperties) throws IOException { return getWebDriver(browserProperties, null); } /** * Create and return new WebDriver or RemoteWebDriver based on properties file * * @param browserProperties path to browser.properties * @param remoteUrl url * @return WebDriver * @throws IOException exception */ public static WebDriver getWebDriver(String browserProperties, URL remoteUrl) throws IOException { URL resource = Thread.currentThread().getContextClassLoader().getResource(browserProperties); log.debug("File: {} " + (resource != null ? "exists" : "does not exist"), browserProperties); if (resource != null) { Browser browser = findBrowser(resource.openStream()); return getDriver(browser, resource.openStream(), remoteUrl); } return null; } /** * Create and return new WebDriver * * @param browser see details {@link com.sdl.selenium.web.Browser} * @return WebDriver * @throws IOException exception */ public static WebDriver getWebDriver(Browser browser) throws IOException { return getDriver(browser, null); } public static WebDriver getWebDriver(URL remoteUrl, DesiredCapabilities capabilities) { driver = new RemoteWebDriver(remoteUrl, capabilities); ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector()); init(driver); return driver; } private static WebDriver getDriver(Browser browser, InputStream inputStream, URL remoteUrl) throws IOException { AbstractBrowserConfigReader properties = null; if (browser == Browser.FIREFOX) { properties = new FirefoxConfigReader(); } else if (browser == Browser.IEXPLORE) { properties = new IExplorerConfigReader(); } else if (browser == Browser.CHROME) { properties = new ChromeConfigReader(); } else { log.error("Browser not supported {}", browser); driver = null; } if (properties != null) { if (inputStream != null) { properties.load(inputStream); } log.debug(properties.toString()); if (System.getProperty("RUNNER_NAME") != null) { String userData = "user-data-dir=" + System.getProperty("user.home") + "\\AppData\\Local\\Google\\Chrome\\" + System.getProperty("RUNNER_NAME"); properties.setProperty("options.arguments", properties.getProperty("options.arguments") + userData); } driver = properties.createDriver(remoteUrl); WebDriverConfig.setDownloadPath(properties.getDownloadPath()); WebDriverConfig.setSilentDownload(properties.isSilentDownload()); WebDriverConfig.setHeadless(properties.getProperty("options.arguments").contains("headless")); WebDriverConfig.setDriverService(properties.getDriveService()); } init(driver); return driver; } private static WebDriver getDriver(Browser browser, InputStream inputStream) throws IOException { return getDriver(browser, inputStream, null); } public static Browser getBrowser(String browserKey) { browserKey = browserKey.toUpperCase(); Browser browser = null; try { browser = Browser.valueOf(browserKey); } catch (IllegalArgumentException e) { log.error("BROWSER not supported : {}. Supported browsers: {}", browserKey, Arrays.asList(Browser.values())); } return browser; } private static Browser findBrowser(InputStream inputStream) { PropertiesReader properties = new PropertiesReader(null, inputStream); String browserKey = properties.getProperty("browser"); WebLocatorConfig.setBrowserProperties(properties); log.info("Browser is: {}", browserKey); return getBrowser(browserKey); } /** * Switch driver to last browser tab * * @return oldTabName */ public static String switchToLastTab() { int totalTabs; int time = 0; do { Utils.sleep(100L); totalTabs = getCountTabs(); time++; } while (totalTabs <= 1 && time < 10); return switchToTab(totalTabs - 1); } public static int getCountTabs() { return driver.getWindowHandles().size(); } /** * Switch driver to first browser tab * Tab is not visible but we can interact with it, TODO see how to make it active * * @return oldTabName */ public static String switchToFirstTab() { return switchToTab(0); } public static String switchToTab(int index) { String oldTabName = null; try { Utils.sleep(100); // to make sure tab has been created try { oldTabName = driver.getWindowHandle(); log.debug("Preview tab id: {}, title {}", oldTabName, driver.getTitle()); } catch (NoSuchWindowException e) { log.info("Preview tab already closed"); } List<String> winList = new ArrayList<>(driver.getWindowHandles()); String tabID = winList.get(index); String title = RetryUtils.retry(3, () -> { driver.switchTo().window(tabID); Utils.sleep(100); return driver.getTitle(); }); log.info("Current tab id: {}, title: {}", tabID, title); } catch (NoSuchWindowException e) { log.error("NoSuchWindowException", e); } return oldTabName; } /** * @param tabCount : this is webdriver * @param millis : time you define to wait the tab open * @return true if tab open in the time, false if tab not open in the time. */ public static boolean waitForNewTab(int tabCount, long millis) { boolean hasExpectedTabs = false; while (!hasExpectedTabs && millis > 0) { if (getCountTabs() >= tabCount) { hasExpectedTabs = true; } else { log.info("Waiting {} ms for new tab...", millis); Utils.sleep(100); } millis -= 100; } return hasExpectedTabs; } }
LTLC-44413 Fixing chrome profile cache problems
src/main/java/com/sdl/selenium/utils/config/WebDriverConfig.java
LTLC-44413 Fixing chrome profile cache problems
<ide><path>rc/main/java/com/sdl/selenium/utils/config/WebDriverConfig.java <ide> log.debug(properties.toString()); <ide> <ide> if (System.getProperty("RUNNER_NAME") != null) { <del> String userData = "user-data-dir=" + System.getProperty("user.home") + "\\AppData\\Local\\Google\\Chrome\\" + System.getProperty("RUNNER_NAME"); <add> String userData = "user-data-dir=" + System.getProperty("user.home") + "\\AppData\\Local\\Temp\\" + System.getProperty("RUNNER_NAME"); <ide> properties.setProperty("options.arguments", properties.getProperty("options.arguments") + userData); <ide> } <ide>
JavaScript
mit
7d1e22f25f2245b84d936f5df91f63d80bb5a51b
0
AHIOS/my-badgesBE,AHIOS/my-badgesBE
/** * Module dependencies. */ const express = require('express'); const compression = require('compression'); const session = require('express-session'); const bodyParser = require('body-parser'); const logger = require('morgan'); const chalk = require('chalk'); const errorHandler = require('errorhandler'); const lusca = require('lusca'); const MongoStore = require('connect-mongo')(session); const flash = require('express-flash'); const path = require('path'); const mongoose = require('mongoose'); const passport = require('passport'); const expressValidator = require('express-validator'); const expressStatusMonitor = require('express-status-monitor'); const sass = require('node-sass-middleware'); const multer = require('multer'); const router = require('./routes'); const upload = multer({ dest: path.join(__dirname, 'uploads') }); /** * Create Express server. */ const app = express(); /** * Connect to MongoDB. */ mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI); mongoose.connection.on('error', (err) => { console.error(err); console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗')); process.exit(); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(expressStatusMonitor()); app.use(compression()); app.use(sass({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public') })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressValidator()); app.use(session({ resave: true, saveUninitialized: true, secret: process.env.SESSION_SECRET, store: new MongoStore({ url: process.env.MONGODB_URI || process.env.MONGOLAB_URI, autoReconnect: true, clear_interval: 3600 }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.use((req, res, next) => { if (req.path === '/providers/upload' || req.path.startsWith('/api')) { next(); } else { lusca.csrf()(req, res, next); } }); app.use(lusca.xframe('SAMEORIGIN')); app.use(lusca.xssProtection(true)); app.use((req, res, next) => { res.locals.user = req.user; next(); }); app.use((req, res, next) => { // After successful login, redirect back to the intended page if (!req.user && req.path !== '/login' && req.path !== '/signup' && !req.path.match(/^\/auth/) && !req.path.match(/\./)) { req.session.returnTo = req.path; } else if (req.user && req.path == '/account') { req.session.returnTo = req.path; } next(); }); app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); /** * Error Handler. */ app.use(errorHandler()); /** * Start Express server. */ app.listen(app.get('port'), () => { console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
 console.log(' Press CTRL-C to stop\n'); }); app.use('/', router); app.get('/REACT/*', function(req, res) { res.sendFile(path.resolve(__dirname, 'clients/react/build/my-badgesREACT/index.html')); }); module.exports = app;
app.js
/** * Module dependencies. */ const express = require('express'); const compression = require('compression'); const session = require('express-session'); const bodyParser = require('body-parser'); const logger = require('morgan'); const chalk = require('chalk'); const errorHandler = require('errorhandler'); const lusca = require('lusca'); const MongoStore = require('connect-mongo')(session); const flash = require('express-flash'); const path = require('path'); const mongoose = require('mongoose'); const passport = require('passport'); const expressValidator = require('express-validator'); const expressStatusMonitor = require('express-status-monitor'); const sass = require('node-sass-middleware'); const multer = require('multer'); const router = require('./routes'); const upload = multer({ dest: path.join(__dirname, 'uploads') }); /** * Create Express server. */ const app = express(); /** * Connect to MongoDB. */ mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI); mongoose.connection.on('error', (err) => { console.error(err); console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗')); process.exit(); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(expressStatusMonitor()); app.use(compression()); app.use(sass({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public') })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressValidator()); app.use(session({ resave: true, saveUninitialized: true, secret: process.env.SESSION_SECRET, store: new MongoStore({ url: process.env.MONGODB_URI || process.env.MONGOLAB_URI, autoReconnect: true, clear_interval: 3600 }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.use((req, res, next) => { if (req.path === '/providers/upload' || req.path.startsWith('/api')) { next(); } else { lusca.csrf()(req, res, next); } }); app.use(lusca.xframe('SAMEORIGIN')); app.use(lusca.xssProtection(true)); app.use((req, res, next) => { res.locals.user = req.user; next(); }); app.use((req, res, next) => { // After successful login, redirect back to the intended page if (!req.user && req.path !== '/login' && req.path !== '/signup' && !req.path.match(/^\/auth/) && !req.path.match(/\./)) { req.session.returnTo = req.path; } else if (req.user && req.path == '/account') { req.session.returnTo = req.path; } next(); }); app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); /** * Error Handler. */ app.use(errorHandler()); /** * Start Express server. */ app.listen(app.get('port'), () => { console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
 console.log(' Press CTRL-C to stop\n'); }); app.use('/', router); module.exports = app;
* path for react client
app.js
* path for react client
<ide><path>pp.js <ide> <ide> app.use('/', router); <ide> <add>app.get('/REACT/*', function(req, res) { <add> res.sendFile(path.resolve(__dirname, 'clients/react/build/my-badgesREACT/index.html')); <add>}); <add> <ide> module.exports = app;
Java
apache-2.0
90a9dcb28e47007d3d283eb28adcb71000e1924e
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.memory.agent; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.engine.DebugProcessAdapterImpl; import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.SuspendContextImpl; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.jdi.StackFrameProxyImpl; import com.intellij.debugger.memory.agent.extractor.AgentExtractor; import com.intellij.debugger.memory.ui.JavaReferenceInfo; import com.intellij.debugger.memory.ui.SizedReferenceInfo; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.debugger.ui.JavaDebuggerSupport; import com.intellij.execution.ExecutionListener; import com.intellij.execution.ExecutionManager; import com.intellij.execution.JavaExecutionUtil; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import one.util.streamex.IntStreamEx; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.io.File; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.jar.Attributes; public class MemoryAgentUtil { private static final Logger LOG = Logger.getInstance(MemoryAgentUtil.class); private static final Key<Boolean> LISTEN_MEMORY_AGENT_STARTUP_FAILED = Key.create("LISTEN_MEMORY_AGENT_STARTUP_FAILED"); private static final int ESTIMATE_OBJECTS_SIZE_LIMIT = 2000; public static void addMemoryAgent(@NotNull JavaParameters parameters) { if (!DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT) { return; } if (isIbmJdk(parameters)) { LOG.info("Do not attach memory agent for IBM jdk"); return; } ParametersList parametersList = parameters.getVMParametersList(); if (parametersList.getParameters().stream().anyMatch(x -> x.contains("memory_agent"))) return; boolean isInDebugMode = Registry.is("debugger.memory.agent.debug"); File agentFile = null; String errorMessage = null; long start = System.currentTimeMillis(); try { agentFile = getAgentFile(isInDebugMode); } catch (InterruptedException e) { errorMessage = "Interrupted"; } catch (ExecutionException e) { LOG.warn(e.getCause()); errorMessage = "Exception thrown (see logs for details)"; } catch (TimeoutException e) { errorMessage = "Timeout"; } if (errorMessage != null || agentFile == null) { LOG.warn("Could not extract agent: " + errorMessage); return; } LOG.info("Memory agent extracting took " + (System.currentTimeMillis() - start) + " ms"); String path = JavaExecutionUtil.handleSpacesInAgentPath(agentFile.getAbsolutePath(), "debugger-memory-agent", null); if (path == null) { LOG.error("Could not use memory agent file. Spaces are found."); return; } String args = ""; if (isInDebugMode) { args = "5";// Enable debug messages } path += "=" + args; parametersList.add("-agentpath:" + path); listenIfStartupFailed(); } public static List<JavaReferenceInfo> tryCalculateSizes(@NotNull List<JavaReferenceInfo> objects, @Nullable MemoryAgent agent) { if (agent == null || !agent.canEvaluateObjectsSizes()) return objects; if (objects.size() > ESTIMATE_OBJECTS_SIZE_LIMIT) { LOG.info("Too many objects to estimate their sizes"); return objects; } try { long[] sizes = agent.evaluateObjectsSizes(ContainerUtil.map(objects, x -> x.getObjectReference())); return IntStreamEx.range(0, objects.size()) .mapToObj(i -> new SizedReferenceInfo(objects.get(i).getObjectReference(), sizes[i])) .reverseSorted(Comparator.comparing(x -> x.size())) .map(x -> (JavaReferenceInfo)x) .toList(); } catch (EvaluateException e) { LOG.error("Could not estimate objects sizes", e); } return objects; } public static void loadAgentProxy(@NotNull DebugProcessImpl debugProcess, @NotNull Consumer<MemoryAgent> agentLoaded) { debugProcess.addDebugProcessListener(new DebugProcessAdapterImpl() { private final AtomicBoolean isInitializing = new AtomicBoolean(false); @Override public void paused(SuspendContextImpl suspendContext) { if (isInitializing.compareAndSet(false, true)) { try { MemoryAgent memoryAgent = initMemoryAgent(suspendContext); if (memoryAgent == null) { LOG.warn("Could not initialize memory agent."); return; } agentLoaded.accept(memoryAgent); debugProcess.removeDebugProcessListener(this); } finally { isInitializing.set(false); } } } @Nullable private MemoryAgent initMemoryAgent(@NotNull SuspendContextImpl suspendContext) { if (!DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT) { LOG.info("Memory agent disabled"); return AgentLoader.DEFAULT_PROXY; } StackFrameProxyImpl frameProxy = suspendContext.getFrameProxy(); if (frameProxy == null) { LOG.warn("frame proxy is not available"); return null; } long start = System.currentTimeMillis(); EvaluationContextImpl evaluationContext = new EvaluationContextImpl(suspendContext, frameProxy); MemoryAgent agent = new AgentLoader().load(evaluationContext, debugProcess.getVirtualMachineProxy()); LOG.info("Memory agent loading took " + (System.currentTimeMillis() - start) + " ms"); return agent; } }); } private static boolean isIbmJdk(@NotNull JavaParameters parameters) { Sdk jdk = parameters.getJdk(); String vendor = jdk == null ? null : JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VENDOR); return vendor != null && StringUtil.containsIgnoreCase(vendor, "ibm"); } private static File getAgentFile(boolean isInDebugMode) throws InterruptedException, ExecutionException, TimeoutException { if (isInDebugMode) { String debugAgentPath = Registry.get("debugger.memory.agent.debug.path").asString(); if (!debugAgentPath.isEmpty()) { LOG.info("Local memory agent will be used: " + debugAgentPath); return new File(debugAgentPath); } } return ApplicationManager.getApplication() .executeOnPooledThread(() -> new AgentExtractor().extract()).get(1, TimeUnit.SECONDS); } private static void listenIfStartupFailed() { Project project = JavaDebuggerSupport.getContextProjectForEditorFieldsInDebuggerConfigurables(); if (project == null || Boolean.TRUE.equals(project.getUserData(LISTEN_MEMORY_AGENT_STARTUP_FAILED))) return; project.getMessageBus().connect().subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() { @Override public void processTerminated(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler, int exitCode) { if (executorId != DefaultDebugExecutor.EXECUTOR_ID || exitCode == 0) return; RunContentDescriptor content = env.getContentToReuse(); if (content == null) return; ExecutionConsole console = content.getExecutionConsole(); if (!(console instanceof ConsoleViewImpl)) return; ConsoleViewImpl consoleView = (ConsoleViewImpl)console; ApplicationManager.getApplication().invokeLater(() -> { if (consoleView.hasDeferredOutput()) { consoleView.flushDeferredText(); } Editor editor = consoleView.getEditor(); if (editor == null) return; String[] outputLines = StringUtil.splitByLines(editor.getDocument().getText()); List<String> mentions = StreamEx.of(outputLines).skip(1).filter(x -> x.contains("memory_agent")).limit(10).toList(); if (outputLines.length >= 1 && outputLines[0].contains("memory_agent") && !mentions.isEmpty()) { Project project = env.getProject(); String name = env.getRunProfile().getName(); String windowId = ExecutionManager.getInstance(project).getContentManager().getToolWindowIdByEnvironment(env); Attachment[] mentionsInOutput = StreamEx.of(mentions).map(x -> new Attachment("agent_mention.txt", x)) .toArray(new Attachment[0]); RuntimeExceptionWithAttachments exception = new RuntimeExceptionWithAttachments("Could not start debug process with memory agent", mentionsInOutput); String checkboxName = DebuggerBundle.message("label.debugger.general.configurable.enable.memory.agent"); String description = "Memory agent could not be loaded. <a href=\"Disable\">Disable</a> the agent. To enable it back use \"" + checkboxName + "\" option in File | Settings | Build, Execution, Deployment | Debugger"; ExecutionUtil.handleExecutionError(project, windowId, name, exception, description, new DisablingMemoryAgentListener()); LOG.error(exception); } }, project.getDisposed()); } }); project.putUserData(LISTEN_MEMORY_AGENT_STARTUP_FAILED, true); } private static class DisablingMemoryAgentListener implements HyperlinkListener { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) { DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT = false; } } } }
java/debugger/impl/src/com/intellij/debugger/memory/agent/MemoryAgentUtil.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.memory.agent; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.engine.DebugProcessAdapterImpl; import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.SuspendContextImpl; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.jdi.StackFrameProxyImpl; import com.intellij.debugger.memory.agent.extractor.AgentExtractor; import com.intellij.debugger.memory.ui.JavaReferenceInfo; import com.intellij.debugger.memory.ui.SizedReferenceInfo; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.debugger.ui.JavaDebuggerSupport; import com.intellij.execution.ExecutionListener; import com.intellij.execution.ExecutionManager; import com.intellij.execution.JavaExecutionUtil; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import one.util.streamex.IntStreamEx; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.io.File; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.jar.Attributes; public class MemoryAgentUtil { private static final Logger LOG = Logger.getInstance(MemoryAgentUtil.class); private static final Key<Boolean> LISTEN_MEMORY_AGENT_STARTUP_FAILED = Key.create("LISTEN_MEMORY_AGENT_STARTUP_FAILED"); private static final int ESTIMATE_OBJECTS_SIZE_LIMIT = 2000; private static final AtomicBoolean LISTENER_ADDED = new AtomicBoolean(false); public static void addMemoryAgent(@NotNull JavaParameters parameters) { if (!DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT) { return; } if (isIbmJdk(parameters)) { LOG.info("Do not attach memory agent for IBM jdk"); return; } ParametersList parametersList = parameters.getVMParametersList(); if (parametersList.getParameters().stream().anyMatch(x -> x.contains("memory_agent"))) return; boolean isInDebugMode = Registry.is("debugger.memory.agent.debug"); File agentFile = null; String errorMessage = null; long start = System.currentTimeMillis(); try { agentFile = getAgentFile(isInDebugMode); } catch (InterruptedException e) { errorMessage = "Interrupted"; } catch (ExecutionException e) { LOG.warn(e.getCause()); errorMessage = "Exception thrown (see logs for details)"; } catch (TimeoutException e) { errorMessage = "Timeout"; } if (errorMessage != null || agentFile == null) { LOG.warn("Could not extract agent: " + errorMessage); return; } LOG.info("Memory agent extracting took " + (System.currentTimeMillis() - start) + " ms"); String path = JavaExecutionUtil.handleSpacesInAgentPath(agentFile.getAbsolutePath(), "debugger-memory-agent", null); if (path == null) { LOG.error("Could not use memory agent file. Spaces are found."); return; } String args = ""; if (isInDebugMode) { args = "5";// Enable debug messages } path += "=" + args; parametersList.add("-agentpath:" + path); listenIfStartupFailed(); } public static List<JavaReferenceInfo> tryCalculateSizes(@NotNull List<JavaReferenceInfo> objects, @Nullable MemoryAgent agent) { if (agent == null || !agent.canEvaluateObjectsSizes()) return objects; if (objects.size() > ESTIMATE_OBJECTS_SIZE_LIMIT) { LOG.info("Too many objects to estimate their sizes"); return objects; } try { long[] sizes = agent.evaluateObjectsSizes(ContainerUtil.map(objects, x -> x.getObjectReference())); return IntStreamEx.range(0, objects.size()) .mapToObj(i -> new SizedReferenceInfo(objects.get(i).getObjectReference(), sizes[i])) .reverseSorted(Comparator.comparing(x -> x.size())) .map(x -> (JavaReferenceInfo)x) .toList(); } catch (EvaluateException e) { LOG.error("Could not estimate objects sizes", e); } return objects; } public static void loadAgentProxy(@NotNull DebugProcessImpl debugProcess, @NotNull Consumer<MemoryAgent> agentLoaded) { debugProcess.addDebugProcessListener(new DebugProcessAdapterImpl() { private final AtomicBoolean isInitializing = new AtomicBoolean(false); @Override public void paused(SuspendContextImpl suspendContext) { if (isInitializing.compareAndSet(false, true)) { try { MemoryAgent memoryAgent = initMemoryAgent(suspendContext); if (memoryAgent == null) { LOG.warn("Could not initialize memory agent."); return; } agentLoaded.accept(memoryAgent); debugProcess.removeDebugProcessListener(this); } finally { isInitializing.set(false); } } } @Nullable private MemoryAgent initMemoryAgent(@NotNull SuspendContextImpl suspendContext) { if (!DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT) { LOG.info("Memory agent disabled"); return AgentLoader.DEFAULT_PROXY; } StackFrameProxyImpl frameProxy = suspendContext.getFrameProxy(); if (frameProxy == null) { LOG.warn("frame proxy is not available"); return null; } long start = System.currentTimeMillis(); EvaluationContextImpl evaluationContext = new EvaluationContextImpl(suspendContext, frameProxy); MemoryAgent agent = new AgentLoader().load(evaluationContext, debugProcess.getVirtualMachineProxy()); LOG.info("Memory agent loading took " + (System.currentTimeMillis() - start) + " ms"); return agent; } }); } private static boolean isIbmJdk(@NotNull JavaParameters parameters) { Sdk jdk = parameters.getJdk(); String vendor = jdk == null ? null : JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VENDOR); return vendor != null && StringUtil.containsIgnoreCase(vendor, "ibm"); } private static File getAgentFile(boolean isInDebugMode) throws InterruptedException, ExecutionException, TimeoutException { if (isInDebugMode) { String debugAgentPath = Registry.get("debugger.memory.agent.debug.path").asString(); if (!debugAgentPath.isEmpty()) { LOG.info("Local memory agent will be used: " + debugAgentPath); return new File(debugAgentPath); } } return ApplicationManager.getApplication() .executeOnPooledThread(() -> new AgentExtractor().extract()).get(1, TimeUnit.SECONDS); } private static void listenIfStartupFailed() { Project project = JavaDebuggerSupport.getContextProjectForEditorFieldsInDebuggerConfigurables(); if (project == null || Boolean.TRUE.equals(project.getUserData(LISTEN_MEMORY_AGENT_STARTUP_FAILED))) return; project.getMessageBus().connect().subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() { @Override public void processTerminated(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler, int exitCode) { if (executorId != DefaultDebugExecutor.EXECUTOR_ID || exitCode == 0) return; RunContentDescriptor content = env.getContentToReuse(); if (content == null) return; ExecutionConsole console = content.getExecutionConsole(); if (!(console instanceof ConsoleViewImpl)) return; ConsoleViewImpl consoleView = (ConsoleViewImpl)console; ApplicationManager.getApplication().invokeLater(() -> { if (consoleView.hasDeferredOutput()) { consoleView.flushDeferredText(); } Editor editor = consoleView.getEditor(); if (editor == null) return; String[] outputLines = StringUtil.splitByLines(editor.getDocument().getText()); List<String> mentions = StreamEx.of(outputLines).skip(1).filter(x -> x.contains("memory_agent")).limit(10).toList(); if (outputLines.length >= 1 && outputLines[0].contains("memory_agent") && !mentions.isEmpty()) { Project project = env.getProject(); String name = env.getRunProfile().getName(); String windowId = ExecutionManager.getInstance(project).getContentManager().getToolWindowIdByEnvironment(env); Attachment[] mentionsInOutput = StreamEx.of(mentions).map(x -> new Attachment("agent_mention.txt", x)) .toArray(new Attachment[0]); RuntimeExceptionWithAttachments exception = new RuntimeExceptionWithAttachments("Could not start debug process with memory agent", mentionsInOutput); String checkboxName = DebuggerBundle.message("label.debugger.general.configurable.enable.memory.agent"); String description = "Memory agent could not be loaded. <a href=\"Disable\">Disable</a> the agent. To enable it back use \"" + checkboxName + "\" option in File | Settings | Build, Execution, Deployment | Debugger"; ExecutionUtil.handleExecutionError(project, windowId, name, exception, description, new DisablingMemoryAgentListener()); LOG.error(exception); } }, o -> project.isDisposed()); } }); project.putUserData(LISTEN_MEMORY_AGENT_STARTUP_FAILED, true); } private static class DisablingMemoryAgentListener implements HyperlinkListener { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) { DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT = false; } } } }
[memory-agent] EA-138182 - NPE: ConsoleViewImpl.getText (fix IDEA-CR-44212)
java/debugger/impl/src/com/intellij/debugger/memory/agent/MemoryAgentUtil.java
[memory-agent] EA-138182 - NPE: ConsoleViewImpl.getText (fix IDEA-CR-44212)
<ide><path>ava/debugger/impl/src/com/intellij/debugger/memory/agent/MemoryAgentUtil.java <ide> private static final Logger LOG = Logger.getInstance(MemoryAgentUtil.class); <ide> private static final Key<Boolean> LISTEN_MEMORY_AGENT_STARTUP_FAILED = Key.create("LISTEN_MEMORY_AGENT_STARTUP_FAILED"); <ide> private static final int ESTIMATE_OBJECTS_SIZE_LIMIT = 2000; <del> private static final AtomicBoolean LISTENER_ADDED = new AtomicBoolean(false); <ide> <ide> public static void addMemoryAgent(@NotNull JavaParameters parameters) { <ide> if (!DebuggerSettings.getInstance().ENABLE_MEMORY_AGENT) { <ide> ExecutionUtil.handleExecutionError(project, windowId, name, exception, description, new DisablingMemoryAgentListener()); <ide> LOG.error(exception); <ide> } <del> }, o -> project.isDisposed()); <add> }, project.getDisposed()); <ide> } <ide> }); <ide>
Java
apache-2.0
eadba9f2e75b105791e5a9ef210c034504077d3c
0
freiheit-com/wicket,selckin/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,mafulafunk/wicket,martin-g/wicket-osgi,klopfdreh/wicket,astrapi69/wicket,aldaris/wicket,aldaris/wicket,dashorst/wicket,klopfdreh/wicket,aldaris/wicket,apache/wicket,mosoft521/wicket,astrapi69/wicket,mafulafunk/wicket,dashorst/wicket,mafulafunk/wicket,AlienQueen/wicket,astrapi69/wicket,zwsong/wicket,selckin/wicket,AlienQueen/wicket,bitstorm/wicket,bitstorm/wicket,bitstorm/wicket,selckin/wicket,mosoft521/wicket,klopfdreh/wicket,selckin/wicket,mosoft521/wicket,zwsong/wicket,apache/wicket,astrapi69/wicket,freiheit-com/wicket,topicusonderwijs/wicket,dashorst/wicket,topicusonderwijs/wicket,zwsong/wicket,aldaris/wicket,mosoft521/wicket,klopfdreh/wicket,apache/wicket,aldaris/wicket,AlienQueen/wicket,bitstorm/wicket,mosoft521/wicket,bitstorm/wicket,apache/wicket,klopfdreh/wicket,dashorst/wicket,topicusonderwijs/wicket,zwsong/wicket,apache/wicket,freiheit-com/wicket,AlienQueen/wicket,dashorst/wicket,AlienQueen/wicket,selckin/wicket,freiheit-com/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,freiheit-com/wicket
/* * 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.wicket.util.tester; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.wicket.Application; import org.apache.wicket.Component; import org.apache.wicket.IPageManagerProvider; import org.apache.wicket.IPageRendererProvider; import org.apache.wicket.IRequestCycleProvider; import org.apache.wicket.MarkupContainer; import org.apache.wicket.Page; import org.apache.wicket.RequestListenerInterface; import org.apache.wicket.Session; import org.apache.wicket.ThreadContext; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.behavior.AbstractAjaxBehavior; import org.apache.wicket.behavior.IBehavior; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.feedback.FeedbackMessages; import org.apache.wicket.feedback.IFeedbackMessageFilter; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.IFormSubmitListener; import org.apache.wicket.markup.html.form.SubmitLink; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.ILinkListener; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.mock.MockApplication; import org.apache.wicket.mock.MockPageManager; import org.apache.wicket.mock.MockRequestParameters; import org.apache.wicket.mock.MockSessionStore; import org.apache.wicket.page.IPageManager; import org.apache.wicket.page.IPageManagerContext; import org.apache.wicket.protocol.http.IMetaDataBufferingWebResponse; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.protocol.http.WicketFilter; import org.apache.wicket.protocol.http.mock.MockHttpServletRequest; import org.apache.wicket.protocol.http.mock.MockHttpServletResponse; import org.apache.wicket.protocol.http.mock.MockHttpSession; import org.apache.wicket.protocol.http.servlet.ServletWebRequest; import org.apache.wicket.protocol.http.servlet.ServletWebResponse; import org.apache.wicket.request.IExceptionMapper; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.cycle.RequestCycleContext; import org.apache.wicket.request.handler.BookmarkablePageRequestHandler; import org.apache.wicket.request.handler.IPageProvider; import org.apache.wicket.request.handler.ListenerInterfaceRequestHandler; import org.apache.wicket.request.handler.PageAndComponentProvider; import org.apache.wicket.request.handler.PageProvider; import org.apache.wicket.request.handler.RenderPageRequestHandler; import org.apache.wicket.request.handler.render.PageRenderer; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.session.ISessionStore; import org.apache.wicket.settings.IRequestCycleSettings.RenderStrategy; import org.apache.wicket.util.IProvider; import org.apache.wicket.util.lang.Classes; import org.apache.wicket.util.string.Strings; import org.apache.wicket.util.visit.IVisit; import org.apache.wicket.util.visit.IVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A helper class to ease unit testing of Wicket applications without the need for a servlet * container. See javadoc of <code>WicketTester</code> for example usage. This class can be used as * is, but JUnit users should use derived class <code>WicketTester</code>. * * @see WicketTester * * @author Ingram Chen * @author Juergen Donnerstag * @author Frank Bille * @author Igor Vaynberg * * @since 1.2.6 */ public class BaseWicketTester { /** log. */ private static final Logger log = LoggerFactory.getLogger(BaseWicketTester.class); /** * @author jcompagner */ private static final class TestPageSource implements ITestPageSource { private final Page page; private static final long serialVersionUID = 1L; /** * Constructor. * * @param page */ private TestPageSource(Page page) { this.page = page; } public Page getTestPage() { return page; } } private org.apache.wicket.protocol.http.mock.MockServletContext servletContext; private MockHttpSession hsession; private final WebApplication application; private boolean followRedirects = true; private int redirectCount; private MockHttpServletRequest lastRequest; private MockHttpServletResponse lastResponse; private final List<MockHttpServletRequest> previousRequests = new ArrayList<MockHttpServletRequest>(); private final List<MockHttpServletResponse> previousResponses = new ArrayList<MockHttpServletResponse>(); private final ThreadContext oldThreadContext; /** current request */ private MockHttpServletRequest request; /** current response */ private MockHttpServletResponse response; /** current session */ private Session session; /** current request cycle */ private RequestCycle requestCycle; private Page lastRenderedPage; private boolean exposeExceptions = true; private IRequestHandler forcedHandler; // Simulates the cookies maintained by the browser private final List<Cookie> browserCookies = new ArrayList<Cookie>(); // The root component used for the start. Usually the Page, but can also be a Panel // see https://issues.apache.org/jira/browse/WICKET-1214 private MarkupContainer startComponent; /** * Creates <code>WicketTester</code> and automatically create a <code>WebApplication</code>, but * the tester will have no home page. */ public BaseWicketTester() { this(new MockApplication()); } /** * Creates <code>WicketTester</code> and automatically creates a <code>WebApplication</code>. * * @param <C> * * @param homePage * a home page <code>Class</code> */ public <C extends Page> BaseWicketTester(final Class<C> homePage) { this(new MockApplication() { /** * @see org.apache.wicket.Application#getHomePage() */ @Override public Class<? extends Page> getHomePage() { return homePage; } }); } /** * Creates a <code>WicketTester</code>. * * @param application * a <code>WicketTester</code> <code>WebApplication</code> object */ public BaseWicketTester(final WebApplication application) { this(application, null); } /** * Creates a <code>WicketTester</code>. * * @param application * a <code>WicketTester</code> <code>WebApplication</code> object * * @param servletContextBasePath * the absolute path on disk to the web application's contents (e.g. war root) - may * be <code>null</code> */ public BaseWicketTester(final WebApplication application, String servletContextBasePath) { servletContext = new org.apache.wicket.protocol.http.mock.MockServletContext(application, servletContextBasePath); final FilterConfig filterConfig = new TestFilterConfig(); WicketFilter filter = new WicketFilter() { @Override public FilterConfig getFilterConfig() { return filterConfig; } }; application.setWicketFilter(filter); hsession = new MockHttpSession(servletContext); oldThreadContext = ThreadContext.detach(); this.application = application; // FIXME some tests are leaking applications by not calling destroy on them or overriding // teardown() without calling super, for now we work around by making each name unique this.application.setName("WicketTesterApplication-" + UUID.randomUUID()); ThreadContext.setApplication(application); application.setServletContext(servletContext); // initialize the application this.application.initApplication(); // reconfigure application for the test environment application.setPageRendererProvider(new LastPageRecordingPageRendererProvider( application.getPageRendererProvider())); application.setRequestCycleProvider(new TestRequestCycleProvider( application.getRequestCycleProvider())); application.setSessionStoreProvider(new TestSessionStoreProvider()); application.setPageManagerProvider(newTestPageManagerProvider()); // prepare session setupNextRequestCycle(); } protected IPageManagerProvider newTestPageManagerProvider() { return new TestPageManagerProvider(); } /** * @return last rendered page */ public Page getLastRenderedPage() { return lastRenderedPage; } /** * */ private void setupNextRequestCycle() { request = new MockHttpServletRequest(application, hsession, servletContext); request.setURL(request.getContextPath() + request.getServletPath() + "/"); response = new MockHttpServletResponse(request); ServletWebRequest servletWebRequest = createServletWebRequest(); requestCycle = application.createRequestCycle(servletWebRequest, createServletWebResponse(servletWebRequest)); requestCycle.setCleanupFeedbackMessagesOnDetach(false); ThreadContext.setRequestCycle(requestCycle); if (session == null) { createNewSession(); } } /** * @return */ private ServletWebResponse createServletWebResponse(ServletWebRequest servletWebRequest) { return new WicketTesterServletWebResponse(servletWebRequest, response); } /** * @return */ private ServletWebRequest createServletWebRequest() { return new ServletWebRequest(request, request.getFilterPrefix()); } /** * */ private void createNewSession() { session = Session.get(); ThreadContext.setSession(session); } /** * * @return */ public MockHttpServletRequest getRequest() { return request; } /** * * @param request */ public void setRequest(MockHttpServletRequest request) { this.request = request; applyRequest(); } /** * * @return session */ public Session getSession() { return session; } /** * Returns {@link HttpSession} for this environment * * @return session */ public MockHttpSession getHttpSession() { return hsession; } /** * Returns the {@link Application} for this environment. * * @return application */ public WebApplication getApplication() { return application; } /** * Returns the {@link ServletContext} for this environment * * @return servlet context */ public org.apache.wicket.protocol.http.mock.MockServletContext getServletContext() { return servletContext; } /** * Destroys the tester. Restores {@link ThreadContext} to state before instance of * {@link WicketTester} was created. */ public void destroy() { application.internalDestroy(); ThreadContext.detach(); } /** * * @return */ public boolean processRequest() { return processRequest(null, null); } /** * Processes the request in mocked Wicket environment. * * @param request * request to process * */ public void processRequest(MockHttpServletRequest request) { processRequest(request, null); } /** * Processes the request in mocked Wicket environment. * * @param request * request to process * * @param forcedRequestHandler * optional parameter to override parsing the request URL and force * {@link IRequestHandler} */ public boolean processRequest(MockHttpServletRequest request, IRequestHandler forcedRequestHandler) { return processRequest(request, forcedRequestHandler, false); } /** * * @param forcedRequestHandler * @return */ public boolean processRequest(IRequestHandler forcedRequestHandler) { return processRequest(null, forcedRequestHandler, false); } /** * * @param forcedRequest * @param forcedRequestHandler * @param redirect * @return */ private boolean processRequest(MockHttpServletRequest forcedRequest, IRequestHandler forcedRequestHandler, boolean redirect) { if (forcedRequest != null) { request = forcedRequest; } forcedHandler = forcedRequestHandler; if (!redirect && getRequest().getHeader("Wicket-Ajax") == null) { lastRenderedPage = null; } try { if (!redirect) { /* * we do not reset the session during redirect processing because we want to * preserve the state before the redirect, eg any error messages reported */ session.cleanupFeedbackMessages(); } if (getLastResponse() != null) { // transfer cookies from previous response to this request, quirky but how old stuff // worked... for (Cookie cookie : getLastResponse().getCookies()) { request.addCookie(cookie); } } applyRequest(); requestCycle.scheduleRequestHandlerAfterCurrent(null); if (!requestCycle.processRequestAndDetach()) { return false; } recordRequestResponse(); setupNextRequestCycle(); if (followRedirects && lastResponse.isRedirect()) { if (redirectCount++ >= 100) { throw new IllegalStateException( "Possible infinite redirect detected. Bailing out."); } Url newUrl = Url.parse(lastResponse.getRedirectLocation(), Charset.forName(request.getCharacterEncoding())); if (newUrl.isAbsolute()) { throw new WicketRuntimeException("Can not follow absolute redirect URL."); } // append redirect URL to current URL (what browser would do) Url mergedURL = new Url(lastRequest.getUrl().getSegments(), newUrl.getQueryParameters()); mergedURL.concatSegments(newUrl.getSegments()); request.setUrl(mergedURL); processRequest(null, null, true); --redirectCount; } return true; } finally { redirectCount = 0; } } /** * */ private void recordRequestResponse() { lastRequest = request; lastResponse = response; previousRequests.add(request); previousResponses.add(response); // transfer cookies from previous request to previous response, quirky but how old stuff // worked... if (lastRequest.getCookies() != null) { for (Cookie cookie : lastRequest.getCookies()) { lastResponse.addCookie(cookie); } } } /** * Renders the page specified by given {@link IPageProvider}. After render the page instance can * be retreived using {@link #getLastRenderedPage()} and the rendered document will be available * in {@link #getLastResponse()}. * * Depending on {@link RenderStrategy} invoking this method can mean that a redirect will happen * before the actual render. * * @param pageProvider * @return last rendered page */ public Page startPage(IPageProvider pageProvider) { startComponent = null; request = new MockHttpServletRequest(application, hsession, servletContext); request.setURL(request.getContextPath() + request.getServletPath() + "/"); IRequestHandler handler = new RenderPageRequestHandler(pageProvider); processRequest(request, handler); return getLastRenderedPage(); } /** * Renders the page. * * @see #startPage(IPageProvider) * * @param page */ public Page startPage(Page page) { return startPage(new PageProvider(page)); } /** * @return last response or <code>null</code>> if no response has been produced yet. */ public MockHttpServletResponse getLastResponse() { return lastResponse; } public String getLastResponseAsString() { return lastResponse.getDocument(); } /** * @return list of prior requests */ public List<MockHttpServletRequest> getPreviousRequests() { return Collections.unmodifiableList(previousRequests); } /** * @return list of prior responses */ public List<MockHttpServletResponse> getPreviousResponses() { return Collections.unmodifiableList(previousResponses); } /** * Sets whether responses with redirects will be followed automatically. * * @param followRedirects */ public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } /** * @return <code>true</code> if redirect responses will be followed automatically, * <code>false</code> otherwise. */ public boolean isFollowRedirects() { return followRedirects; } /** * Encodes the {@link IRequestHandler} to {@link Url}. It should be safe to call this method * outside request thread as log as no registered {@link IRequestMapper} requires a * {@link RequestCycle}. * * @param handler * @return {@link Url} for handler. */ public Url urlFor(IRequestHandler handler) { Url url = application.getRootRequestMapper().mapHandler(handler); transform(url); return url; } public String urlFor(Link link) { return link.urlFor(ILinkListener.INTERFACE).toString(); } /** * Renders a <code>Page</code> defined in <code>TestPageSource</code>. This is usually used when * a page does not have default constructor. For example, a <code>ViewBook</code> page requires * a <code>Book</code> instance: * * <pre> * tester.startPage(new TestPageSource() * { * public Page getTestPage() * { * Book mockBook = new Book(&quot;myBookName&quot;); * return new ViewBook(mockBook); * } * }); * </pre> * * @param testPageSource * a <code>Page</code> factory that creates a test page instance * @return the rendered Page */ public final Page startPage(final ITestPageSource testPageSource) { return startPage(testPageSource.getTestPage()); } /** * Simulates processing URL that invokes specified {@link RequestListenerInterface} on * component. * * After the listener interface is invoked the page containing the component will be rendered * (with an optional redirect - depending on {@link RenderStrategy}). * * @param component * @param listener */ public void executeListener(Component component, RequestListenerInterface listener) { // there are two ways to do this. RequestCycle could be forced to call the handler // directly but constructing and parsing the URL increases the chance of triggering bugs IRequestHandler handler = new ListenerInterfaceRequestHandler(new PageAndComponentProvider( component.getPage(), component), listener); Url url = urlFor(handler); MockHttpServletRequest request = new MockHttpServletRequest(application, hsession, servletContext); request.setUrl(url); processRequest(request, null); } /** * Builds and processes a request suitable for invoking a listener. The <code>Component</code> * must implement any of the known <code>IListener</code> interfaces. * * @param component * the listener to invoke */ public void executeListener(Component component) { for (RequestListenerInterface iface : RequestListenerInterface.getRegisteredInterfaces()) { if (iface.getListenerInterfaceClass().isAssignableFrom(component.getClass())) { executeListener(component, iface); } } } /** * Builds and processes a request suitable for executing an <code>AbstractAjaxBehavior</code>. * * @param behavior * an <code>AbstractAjaxBehavior</code> to execute */ public void executeBehavior(final AbstractAjaxBehavior behavior) { Url url = Url.parse(behavior.getCallbackUrl().toString(), Charset.forName(request.getCharacterEncoding())); transform(url); request.setUrl(url); request.addHeader("Wicket-Ajax-BaseURL", url.toString()); request.addHeader("Wicket-Ajax", "true"); processRequest(); } /** * * @param link * @return */ public Url urlFor(AjaxLink<?> link) { AbstractAjaxBehavior behavior = WicketTesterHelper.findAjaxEventBehavior(link, "onclick"); Url url = Url.parse(behavior.getCallbackUrl().toString(), Charset.forName(request.getCharacterEncoding())); transform(url); return url; } /** * * @param url */ public void executeAjaxUrl(Url url) { transform(url); request.setUrl(url); request.addHeader("Wicket-Ajax-BaseURL", url.toString()); request.addHeader("Wicket-Ajax", "true"); processRequest(); } /** * Renders a <code>Page</code> from its default constructor. * * @param <C> * * @param pageClass * a test <code>Page</code> class with default constructor * @return the rendered <code>Page</code> */ public final <C extends Page> Page startPage(Class<C> pageClass) { startComponent = null; request.setUrl(application.getRootRequestMapper().mapHandler( new BookmarkablePageRequestHandler(new PageProvider(pageClass)))); processRequest(); return getLastRenderedPage(); } /** * Renders a <code>Page</code> from its default constructor. * * @param <C> * * @param pageClass * a test <code>Page</code> class with default constructor * @param parameters * the parameters to use for the class. * @return the rendered <code>Page</code> */ public final <C extends Page> Page startPage(Class<C> pageClass, PageParameters parameters) { startComponent = null; request.setUrl(application.getRootRequestMapper().mapHandler( new BookmarkablePageRequestHandler(new PageProvider(pageClass, parameters)))); processRequest(); return getLastRenderedPage(); } /** * Creates a {@link FormTester} for the <code>Form</code> at a given path, and fills all child * {@link org.apache.wicket.markup.html.form.FormComponent}s with blank <code>String</code>s. * * @param path * path to <code>FormComponent</code> * @return a <code>FormTester</code> instance for testing the <code>Form</code> * @see #newFormTester(String, boolean) */ public FormTester newFormTester(String path) { return newFormTester(path, true); } /** * Creates a {@link FormTester} for the <code>Form</code> at a given path. * * @param path * path to <code>FormComponent</code> * @param fillBlankString * specifies whether to fill all child <code>FormComponent</code>s with blank * <code>String</code>s * @return a <code>FormTester</code> instance for testing the <code>Form</code> * @see FormTester */ public FormTester newFormTester(String path, boolean fillBlankString) { return new FormTester(path, (Form<?>)getComponentFromLastRenderedPage(path), this, fillBlankString); } /** * Renders a <code>Panel</code> defined in <code>TestPanelSource</code>. The usage is similar to * {@link #startPage(ITestPageSource)}. Please note that testing <code>Panel</code> must use the * supplied <code>panelId<code> as a <code>Component</code> id. * * <pre> * tester.startPanel(new TestPanelSource() * { * public Panel getTestPanel(String panelId) * { * MyData mockMyData = new MyData(); * return new MyPanel(panelId, mockMyData); * } * }); * </pre> * * @param testPanelSource * a <code>Panel</code> factory that creates test <code>Panel</code> instances * @return a rendered <code>Panel</code> */ public final Panel startPanel(final TestPanelSource testPanelSource) { Panel panel = (Panel)startPage(new ITestPageSource() { private static final long serialVersionUID = 1L; public Page getTestPage() { return new DummyPanelPage(testPanelSource); } }).get(DummyPanelPage.TEST_PANEL_ID); startComponent = panel; return panel; } /** * Renders a <code>Panel</code> from a <code>Panel(String id)</code> constructor. * * @param <C> * * @param panelClass * a test <code>Panel</code> class with <code>Panel(String id)</code> constructor * @return a rendered <code>Panel</code> */ public final <C extends Panel> Panel startPanel(final Class<C> panelClass) { Panel panel = (Panel)startPage(new ITestPageSource() { private static final long serialVersionUID = 1L; public Page getTestPage() { return new DummyPanelPage(new TestPanelSource() { private static final long serialVersionUID = 1L; public Panel getTestPanel(String panelId) { try { Constructor<? extends Panel> c = panelClass.getConstructor(String.class); return c.newInstance(panelId); } catch (Exception e) { throw convertoUnexpect(e); } } }); } }).get(DummyPanelPage.TEST_PANEL_ID); startComponent = panel; return panel; } /** * A helper method for starting a component for a test without attaching it to a Page. * * Components which are somehow dependent on the page structure can not be currently tested with * this method. * * Example: * * UserDataView view = new UserDataView("view", new ListDataProvider(userList)); * tester.startComponent(view); assertEquals(4, view.size()); * * @param component */ public void startComponent(Component component) { if (component instanceof FormComponent) { ((FormComponent<?>)component).processInput(); } component.beforeRender(); } /** * Throw "standard" WicketRuntimeException * * @param e * @return RuntimeException */ private RuntimeException convertoUnexpect(Exception e) { return new WicketRuntimeException("tester: unexpected", e); } /** * Gets the component with the given path from last rendered page. This method fails in case the * component couldn't be found, and it will return null if the component was found, but is not * visible. * * @param path * Path to component * @return The component at the path * @see org.apache.wicket.MarkupContainer#get(String) */ public Component getComponentFromLastRenderedPage(String path) { if (startComponent != null) { path = startComponent.getId() + ":" + path; } Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does not exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); return component; } if (component.isVisibleInHierarchy()) { return component; } return null; } /** * assert the text of <code>Label</code> component. * * @param path * path to <code>Label</code> component * @param expectedLabelText * expected label text * @return a <code>Result</code> */ public Result hasLabel(String path, String expectedLabelText) { Label label = (Label)getComponentFromLastRenderedPage(path); return isEqual(expectedLabelText, label.getDefaultModelObjectAsString()); } /** * assert component class * * @param <C> * * @param path * path to component * @param expectedComponentClass * expected component class * @return a <code>Result</code> */ public <C extends Component> Result isComponent(String path, Class<C> expectedComponentClass) { Component component = getComponentFromLastRenderedPage(path); if (component == null) { return Result.fail("Component not found: " + path); } return isTrue("component '" + Classes.simpleName(component.getClass()) + "' is not type:" + Classes.simpleName(expectedComponentClass), expectedComponentClass.isAssignableFrom(component.getClass())); } /** * assert component visible. * * @param path * path to component * @return a <code>Result</code> */ public Result isVisible(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } return isTrue("component '" + path + "' is not visible", component.isVisibleInHierarchy()); } /** * assert component invisible. * * @param path * path to component * @return a <code>Result</code> */ public Result isInvisible(String path) { return isNull("component '" + path + "' is visible", getComponentFromLastRenderedPage(path)); } /** * assert component enabled. * * @param path * path to component * @return a <code>Result</code> */ public Result isEnabled(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } return isTrue("component '" + path + "' is disabled", component.isEnabledInHierarchy()); } /** * assert component disabled. * * @param path * path to component * @return a <code>Result</code> */ public Result isDisabled(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } return isFalse("component '" + path + "' is enabled", component.isEnabledInHierarchy()); } /** * assert component required. * * @param path * path to component * @return a <code>Result</code> */ public Result isRequired(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } else if (component instanceof FormComponent == false) { fail("path: '" + path + "' is not a form component"); } return isRequired((FormComponent<?>)component); } /** * assert component required. * * @param component * a form component * @return a <code>Result</code> */ public Result isRequired(FormComponent<?> component) { return isTrue("component '" + component + "' is not required", component.isRequired()); } /** * assert the content of last rendered page contains(matches) regex pattern. * * @param pattern * reqex pattern to match * @return a <code>Result</code> */ public Result ifContains(String pattern) { return isTrue("pattern '" + pattern + "' not found in:\n" + getLastResponseAsString(), getLastResponseAsString().toString().matches("(?s).*" + pattern + ".*")); } /** * assert the model of {@link ListView} use expectedList * * @param path * path to {@link ListView} component * @param expectedList * expected list in the model of {@link ListView} */ public void assertListView(String path, List<?> expectedList) { ListView<?> listView = (ListView<?>)getComponentFromLastRenderedPage(path); WicketTesterHelper.assertEquals(expectedList, listView.getList()); } /** * Click the {@link Link} in the last rendered Page. * <p> * Simulate that AJAX is enabled. * * @see WicketTester#clickLink(String, boolean) * @param path * Click the <code>Link</code> in the last rendered Page. */ public void clickLink(String path) { clickLink(path, true); } /** * Click the {@link Link} in the last rendered Page. * <p> * This method also works for {@link AjaxLink}, {@link AjaxFallbackLink} and * {@link AjaxSubmitLink}. * <p> * On AjaxLinks and AjaxFallbackLinks the onClick method is invoked with a valid * AjaxRequestTarget. In that way you can test the flow of your application when using AJAX. * <p> * When clicking an AjaxSubmitLink the form, which the AjaxSubmitLink is attached to is first * submitted, and then the onSubmit method on AjaxSubmitLink is invoked. If you have changed * some values in the form during your test, these will also be submitted. This should not be * used as a replacement for the {@link FormTester} to test your forms. It should be used to * test that the code in your onSubmit method in AjaxSubmitLink actually works. * <p> * This method is also able to simulate that AJAX (javascript) is disabled on the client. This * is done by setting the isAjax parameter to false. If you have an AjaxFallbackLink you can * then check that it doesn't fail when invoked as a normal link. * * @param path * path to <code>Link</code> component * @param isAjax * Whether to simulate that AJAX (javascript) is enabled or not. If it's false then * AjaxLink and AjaxSubmitLink will fail, since it wouldn't work in real life. * AjaxFallbackLink will be invoked with null as the AjaxRequestTarget parameter. */ public void clickLink(String path, boolean isAjax) { Component linkComponent = getComponentFromLastRenderedPage(path); checkUsability(linkComponent); // if the link is an AjaxLink, we process it differently // than a normal link if (linkComponent instanceof AjaxLink) { // If it's not ajax we fail if (isAjax == false) { fail("Link " + path + "is an AjaxLink and will " + "not be invoked when AJAX (javascript) is disabled."); } executeBehavior(WicketTesterHelper.findAjaxEventBehavior(linkComponent, "onclick")); } // AjaxFallbackLinks is processed like an AjaxLink if isAjax is true // If it's not handling of the linkComponent is passed through to the // Link. else if (linkComponent instanceof AjaxFallbackLink && isAjax) { executeBehavior(WicketTesterHelper.findAjaxEventBehavior(linkComponent, "onclick")); } // if the link is an AjaxSubmitLink, we need to find the form // from it using reflection so we know what to submit. else if (linkComponent instanceof AjaxSubmitLink) { // If it's not ajax we fail if (isAjax == false) { fail("Link " + path + " is an AjaxSubmitLink and " + "will not be invoked when AJAX (javascript) is disabled."); } AjaxSubmitLink link = (AjaxSubmitLink)linkComponent; String pageRelativePath = link.getInputName(); request.getPostParameters().setParameterValue(pageRelativePath, "x"); submitAjaxFormSubmitBehavior(link, (AjaxFormSubmitBehavior)WicketTesterHelper.findAjaxEventBehavior(link, "onclick")); } /* * If the link is a submitlink then we pretend to have clicked it */ else if (linkComponent instanceof SubmitLink) { SubmitLink submitLink = (SubmitLink)linkComponent; String pageRelativePath = submitLink.getInputName(); request.getPostParameters().setParameterValue(pageRelativePath, "x"); submitForm(submitLink.getForm().getPageRelativePath()); } // if the link is a normal link (or ResourceLink) else if (linkComponent instanceof AbstractLink) { AbstractLink link = (AbstractLink)linkComponent; /* * If the link is a bookmarkable link, then we need to transfer the parameters to the * next request. */ if (link instanceof BookmarkablePageLink) { BookmarkablePageLink<?> bookmarkablePageLink = (BookmarkablePageLink<?>)link; try { BookmarkablePageLink.class.getDeclaredField("parameters"); Method getParametersMethod = BookmarkablePageLink.class.getDeclaredMethod( "getPageParameters", (Class<?>[])null); getParametersMethod.setAccessible(true); PageParameters parameters = (PageParameters)getParametersMethod.invoke( bookmarkablePageLink, (Object[])null); startPage(bookmarkablePageLink.getPageClass(), parameters); return; } catch (Exception e) { fail("Internal error in WicketTester. " + "Please report this in Wickets Issue Tracker."); } } executeListener(link, ILinkListener.INTERFACE); } else { fail("Link " + path + " is not a Link, AjaxLink, AjaxFallbackLink or AjaxSubmitLink"); } } /** * * @param form */ public void submitForm(Form form) { submitForm(form.getPageRelativePath()); } /** * Submits the <code>Form</code> in the last rendered <code>Page</code>. * * @param path * path to <code>Form</code> component */ public void submitForm(String path) { Form<?> form = (Form<?>)getComponentFromLastRenderedPage(path); Url url = Url.parse(form.urlFor(IFormSubmitListener.INTERFACE).toString(), Charset.forName(request.getCharacterEncoding())); // make url absolute transform(url); request.setUrl(url); processRequest(); } /** * make url suitable for wicket tester use. usually this involves stripping any leading .. * segments to make the url absolute * * @param url */ private void transform(Url url) { while (url.getSegments().size() > 0 && url.getSegments().get(0).equals("..")) { url.getSegments().remove(0); } } /** * Asserts the last rendered <code>Page</code> class. * * FIXME explain why the code is so complicated to compare two classes, or simplify * * @param <C> * * @param expectedRenderedPageClass * expected class of last rendered page * @return a <code>Result</code> */ public <C extends Page> Result isRenderedPage(Class<C> expectedRenderedPageClass) { Page page = getLastRenderedPage(); if (page == null) { return Result.fail("page was null"); } if (!page.getClass().isAssignableFrom(expectedRenderedPageClass)) { return isEqual(Classes.simpleName(expectedRenderedPageClass), Classes.simpleName(page.getClass())); } return Result.pass(); } /** * Asserts last rendered <code>Page</code> against an expected HTML document. * <p> * Use <code>-Dwicket.replace.expected.results=true</code> to automatically replace the expected * output file. * </p> * * @param pageClass * used to load the <code>File</code> (relative to <code>clazz</code> package) * @param filename * expected output <code>File</code> name * @throws Exception */ public void assertResultPage(final Class<?> pageClass, final String filename) throws Exception { // Validate the document String document = getLastResponseAsString(); DiffUtil.validatePage(document, pageClass, filename, true); } /** * Asserts last rendered <code>Page</code> against an expected HTML document as a * <code>String</code>. * * @param expectedDocument * expected output * @return a <code>Result</code> * @throws Exception */ public Result isResultPage(final String expectedDocument) throws Exception { // Validate the document String document = getLastResponseAsString(); return isTrue("expected rendered page equals", document.equals(expectedDocument)); } /** * Asserts no error-level feedback messages. * * @return a <code>Result</code> */ public Result hasNoErrorMessage() { List<Serializable> messages = getMessages(FeedbackMessage.ERROR); return isTrue( "expect no error message, but contains\n" + WicketTesterHelper.asLined(messages), messages.isEmpty()); } /** * Asserts no info-level feedback messages. * * @return a <code>Result</code> */ public Result hasNoInfoMessage() { List<Serializable> messages = getMessages(FeedbackMessage.INFO); return isTrue( "expect no info message, but contains\n" + WicketTesterHelper.asLined(messages), messages.isEmpty()); } /** * Retrieves <code>FeedbackMessages</code>. * * @param level * level of feedback message, for example: * <code>FeedbackMessage.DEBUG or FeedbackMessage.INFO.. etc</code> * @return <code>List</code> of messages (as <code>String</code>s) * @see FeedbackMessage */ public List<Serializable> getMessages(final int level) { FeedbackMessages feedbackMessages = Session.get().getFeedbackMessages(); List<FeedbackMessage> allMessages = feedbackMessages.messages(new IFeedbackMessageFilter() { private static final long serialVersionUID = 1L; public boolean accept(FeedbackMessage message) { return message.getLevel() == level; } }); List<Serializable> actualMessages = new ArrayList<Serializable>(); for (FeedbackMessage message : allMessages) { actualMessages.add(message.getMessage()); } return actualMessages; } /** * Dumps the source of last rendered <code>Page</code>. */ public void dumpPage() { log.info(getLastResponseAsString()); } /** * Dumps the <code>Component</code> trees. */ public void debugComponentTrees() { debugComponentTrees(""); } /** * Dumps the <code>Component</code> trees to log. Show only the <code>Component</code>s whose * paths contain the filter <code>String</code>. * * @param filter * a filter <code>String</code> */ public void debugComponentTrees(String filter) { log.info("debugging ----------------------------------------------"); for (WicketTesterHelper.ComponentData obj : WicketTesterHelper.getComponentData(getLastRenderedPage())) { if (obj.path.matches(".*" + filter + ".*")) { log.info("path\t" + obj.path + " \t" + obj.type + " \t[" + obj.value + "]"); } } } /** * Tests that a <code>Component</code> has been added to a <code>AjaxRequestTarget</code>, using * {@link AjaxRequestTarget#add(Component)}. This method actually tests that a * <code>Component</code> is on the Ajax response sent back to the client. * <p> * PLEASE NOTE! This method doesn't actually insert the <code>Component</code> in the client DOM * tree, using JavaScript. But it shouldn't be needed because you have to trust that the Wicket * Ajax JavaScript just works. * * @param component * the <code>Component</code> to test * @return a <code>Result</code> */ public Result isComponentOnAjaxResponse(Component component) { String failMessage = "A component which is null could not have been added to the AJAX response"; notNull(failMessage, component); Result result; // test that the component renders the placeholder tag if it's not visible if (!component.isVisible()) { failMessage = "A component which is invisible and doesn't render a placeholder tag" + " will not be rendered at all and thus won't be accessible for subsequent AJAX interaction"; result = isTrue(failMessage, component.getOutputMarkupPlaceholderTag()); if (result.wasFailed()) { return result; } } // Get the AJAX response String ajaxResponse = getLastResponseAsString(); // Test that the previous response was actually a AJAX response failMessage = "The Previous response was not an AJAX response. " + "You need to execute an AJAX event, using clickLink, before using this assert"; boolean isAjaxResponse = Pattern.compile( "^<\\?xml version=\"1.0\" encoding=\".*?\"\\?><ajax-response>") .matcher(ajaxResponse) .find(); result = isTrue(failMessage, isAjaxResponse); if (result.wasFailed()) { return result; } // See if the component has a markup id String markupId = component.getMarkupId(); failMessage = "The component doesn't have a markup id, " + "which means that it can't have been added to the AJAX response"; result = isTrue(failMessage, !Strings.isEmpty(markupId)); if (result.wasFailed()) { return result; } // Look for that the component is on the response, using the markup id boolean isComponentInAjaxResponse = ajaxResponse.matches("(?s).*<component id=\"" + markupId + "\"[^>]*?>.*"); failMessage = "Component wasn't found in the AJAX response"; return isTrue(failMessage, isComponentInAjaxResponse); } /** * Simulates the firing of an Ajax event. * * @see #executeAjaxEvent(Component, String) * * @since 1.2.3 * @param componentPath * the <code>Component</code> path * @param event * the event which we simulate being fired. If <code>event</code> is * <code>null</code>, the test will fail. */ public void executeAjaxEvent(String componentPath, String event) { Component component = getComponentFromLastRenderedPage(componentPath); executeAjaxEvent(component, event); } /** * Simulates the firing of all ajax timer behaviors on the page * * @param wt * @param container */ public void executeAllTimerBehaviors(MarkupContainer container) { container.visitChildren(MarkupContainer.class, new IVisitor<MarkupContainer, Void>() { public void component(final MarkupContainer component, final IVisit<Void> visit) { // get the AbstractAjaxBehaviour which is responsible for // getting the contents of the lazy panel List<AbstractAjaxTimerBehavior> behaviors = component.getBehaviors(AbstractAjaxTimerBehavior.class); for (IBehavior b : behaviors) { checkUsability(component); log.debug("Triggering AjaxSelfUpdatingTimerBehavior: " + component.getClassRelativePath()); AbstractAjaxTimerBehavior timer = (AbstractAjaxTimerBehavior)b; if (!timer.isStopped()) { executeBehavior(timer); } } } }); } /** * Simulates the firing of an Ajax event. You add an Ajax event to a <code>Component</code> by * using: * * <pre> * ... * component.add(new AjaxEventBehavior(&quot;ondblclick&quot;) { * public void onEvent(AjaxRequestTarget) {} * }); * ... * </pre> * * You can then test that the code inside <code>onEvent</code> actually does what it's supposed * to, using the <code>WicketTester</code>: * * <pre> * ... * tester.executeAjaxEvent(component, &quot;ondblclick&quot;); * // Test that the code inside onEvent is correct. * ... * </pre> * * This also works with <code>AjaxFormSubmitBehavior</code>, where it will "submit" the * <code>Form</code> before executing the command. * <p> * PLEASE NOTE! This method doesn't actually insert the <code>Component</code> in the client DOM * tree, using JavaScript. * * @param component * the <code>Component</code> that has the <code>AjaxEventBehavior</code> we want to * test. If the <code>Component</code> is <code>null</code>, the test will fail. * @param event * the event to simulate being fired. If <code>event</code> is <code>null</code>, the * test will fail. */ public void executeAjaxEvent(final Component component, final String event) { String failMessage = "Can't execute event on a component which is null."; notNull(failMessage, component); failMessage = "event must not be null"; notNull(failMessage, event); checkUsability(component); AjaxEventBehavior ajaxEventBehavior = WicketTesterHelper.findAjaxEventBehavior(component, event); executeBehavior(ajaxEventBehavior); } /** * Retrieves a <code>TagTester</code> based on a <code>wicket:id</code>. If more * <code>Component</code>s exist with the same <code>wicket:id</code> in the markup, only the * first one is returned. * * @param wicketId * the <code>wicket:id</code> to search for * @return the <code>TagTester</code> for the tag which has the given <code>wicket:id</code> */ public TagTester getTagByWicketId(String wicketId) { return TagTester.createTagByAttribute(getLastResponseAsString(), "wicket:id", wicketId); } /** * Modified version of BaseWicketTester#getTagByWicketId(String) that returns all matching tags * instead of just the first. * * @see BaseWicketTester#getTagByWicketId(String) */ public List<TagTester> getTagsByWicketId(String wicketId) { return TagTester.createTagsByAttribute(getLastResponseAsString(), "wicket:id", wicketId, false); } /** * Retrieves a <code>TagTester</code> based on an DOM id. If more <code>Component</code>s exist * with the same id in the markup, only the first one is returned. * * @param id * the DOM id to search for. * @return the <code>TagTester</code> for the tag which has the given DOM id */ public TagTester getTagById(String id) { return TagTester.createTagByAttribute(getLastResponseAsString(), "id", id); } /** * Helper method for all the places where an Ajax call should submit an associated * <code>Form</code>. * * @param component * The component the behavior is attached to * @param behavior * The <code>AjaxFormSubmitBehavior</code> with the <code>Form</code> to "submit" */ private void submitAjaxFormSubmitBehavior(final Component component, AjaxFormSubmitBehavior behavior) { // The form that needs to be "submitted". Form<?> form = behavior.getForm(); String failMessage = "No form attached to the submitlink."; notNull(failMessage, form); checkUsability(form); serializeFormToRequest(form); executeBehavior(behavior); } /** * Puts all not already scheduled (e.g. via {@link FormTester#setValue(String, String)}) form * component values in the post parameters for the next form submit * * @param form * the {@link Form} which components should be submitted */ private void serializeFormToRequest(final Form<?> form) { final MockRequestParameters postParameters = request.getPostParameters(); final Set<String> currentParameterNamesSet = postParameters.getParameterNames(); form.visitFormComponents(new IVisitor<FormComponent<?>, Void>() { public void component(final FormComponent<?> formComponent, final IVisit<Void> visit) { final String inputName = formComponent.getInputName(); if (!currentParameterNamesSet.contains(inputName)) { final Object modelObject = formComponent.getModelObject(); if (modelObject instanceof Collection<?>) { final Collection<?> collectionModelObject = (Collection<?>)modelObject; for (Object value : collectionModelObject) { postParameters.addParameterValue(inputName, value.toString()); } } else { postParameters.addParameterValue(inputName, formComponent.getValue()); } } } }); } /** * Retrieves the content type from the response header. * * @return the content type from the response header */ public String getContentTypeFromResponseHeader() { String contentType = getLastResponse().getContentType(); if (contentType == null) { throw new WicketRuntimeException("No Content-Type header found"); } return contentType; } /** * Retrieves the content length from the response header. * * @return the content length from the response header */ public int getContentLengthFromResponseHeader() { String contentLength = getLastResponse().getHeader("Content-Length"); if (contentLength == null) { throw new WicketRuntimeException("No Content-Length header found"); } return Integer.parseInt(contentLength); } /** * Retrieves the last-modified value from the response header. * * @return the last-modified value from the response header */ public String getLastModifiedFromResponseHeader() { return getLastResponse().getHeader("Last-Modified"); } /** * Retrieves the content disposition from the response header. * * @return the content disposition from the response header */ public String getContentDispositionFromResponseHeader() { return getLastResponse().getHeader("Content-Disposition"); } /** * Rebuilds {@link ServletWebRequest} used by wicket from the mock request used to build * requests. Sometimes this method is useful when changes need to be checked without processing * a request. */ public void applyRequest() { ServletWebRequest req = createServletWebRequest(); requestCycle.setRequest(req); requestCycle.getUrlRenderer().setBaseUrl(req.getUrl()); } /** * * @param message * @param condition * @return */ private Result isTrue(String message, boolean condition) { if (condition) { return Result.pass(); } return Result.fail(message); } /** * * @param message * @param condition * @return */ private Result isFalse(String message, boolean condition) { if (!condition) { return Result.pass(); } return Result.fail(message); } /** * * @param expected * @param actual * @return */ protected final Result isEqual(Object expected, Object actual) { if (expected == null && actual == null) { return Result.pass(); } if (expected != null && expected.equals(actual)) { return Result.pass(); } String message = "expected:<" + expected + "> but was:<" + actual + ">"; return Result.fail(message); } /** * * @param message * @param object */ private void notNull(String message, Object object) { if (object == null) { fail(message); } } /** * * @param message * @param object * @return */ private Result isNull(String message, Object object) { if (object != null) { return Result.fail(message); } return Result.pass(); } /** * Checks whether a component is visible and/or enabled before usage * * @param component */ private void checkUsability(final Component component) { if (component.isVisibleInHierarchy() == false) { fail("The component is currently not visible in the hierarchy and thus you can not be used." + " Component: " + component); } if (component.isEnabledInHierarchy() == false) { fail("The component is currently not enabled in the hierarchy and thus you can not be used." + " Component: " + component); } } /** * * @param message */ protected final void fail(String message) { throw new WicketRuntimeException(message); } /** * * @return */ public RequestCycle getRequestCycle() { return requestCycle; } /** * * @return */ public MockHttpServletResponse getResponse() { return response; } /** * * @return */ public MockHttpServletRequest getLastRequest() { return lastRequest; } /** * * @return */ public boolean isExposeExceptions() { return exposeExceptions; } /** * * @param exposeExceptions */ public void setExposeExceptions(boolean exposeExceptions) { this.exposeExceptions = exposeExceptions; } /** * * @param _url */ public void executeUrl(String _url) { Url url = Url.parse(_url, Charset.forName(request.getCharacterEncoding())); transform(url); getRequest().setUrl(url); processRequest(); } /** * */ private class LastPageRecordingPageRendererProvider implements IPageRendererProvider { private final IPageRendererProvider delegate; public LastPageRecordingPageRendererProvider(IPageRendererProvider delegate) { this.delegate = delegate; } public PageRenderer get(RenderPageRequestHandler handler) { lastRenderedPage = (Page)handler.getPageProvider().getPageInstance(); return delegate.get(handler); } } /** * */ private class TestExceptionMapper implements IExceptionMapper { private final IExceptionMapper delegate; public TestExceptionMapper(IExceptionMapper delegate) { this.delegate = delegate; } public IRequestHandler map(Exception e) { if (exposeExceptions) { if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new WicketRuntimeException(e); } } else { return delegate.map(e); } } } /** * */ private class TestRequestCycleProvider implements IRequestCycleProvider { private final IRequestCycleProvider delegate; public TestRequestCycleProvider(IRequestCycleProvider delegate) { this.delegate = delegate; } public RequestCycle get(RequestCycleContext context) { context.setRequestMapper(new TestRequestMapper(context.getRequestMapper())); forcedHandler = null; context.setExceptionMapper(new TestExceptionMapper(context.getExceptionMapper())); return delegate.get(context); } } /** * */ private class TestRequestMapper implements IRequestMapper { private final IRequestMapper delegate; public TestRequestMapper(IRequestMapper delegate) { this.delegate = delegate; } public int getCompatibilityScore(Request request) { return delegate.getCompatibilityScore(request); } public Url mapHandler(IRequestHandler requestHandler) { return delegate.mapHandler(requestHandler); } public IRequestHandler mapRequest(Request request) { if (forcedHandler != null) { IRequestHandler handler = forcedHandler; forcedHandler = null; return handler; } else { return delegate.mapRequest(request); } } } /** * */ private class TestSessionStore extends MockSessionStore { @Override public void invalidate(Request request) { super.invalidate(request); createNewSession(); } } /** * */ private class TestSessionStoreProvider implements IProvider<ISessionStore> { public ISessionStore get() { return new TestSessionStore(); } } /** * */ private class TestPageManagerProvider implements IPageManagerProvider { public IPageManager get(IPageManagerContext pageManagerContext) { return new MockPageManager(); } } /** * */ private class TestFilterConfig implements FilterConfig { private final Map<String, String> initParameters = new HashMap<String, String>(); public TestFilterConfig() { initParameters.put(WicketFilter.FILTER_MAPPING_PARAM, "/servlet/*"); } public String getFilterName() { return getClass().getName(); } public ServletContext getServletContext() { return servletContext; } public String getInitParameter(String s) { return initParameters.get(s); } public Enumeration<String> getInitParameterNames() { throw new UnsupportedOperationException("Not implemented"); } } private class WicketTesterServletWebResponse extends ServletWebResponse implements IMetaDataBufferingWebResponse { private List<Cookie> cookies = new ArrayList<Cookie>(); public WicketTesterServletWebResponse(ServletWebRequest request, MockHttpServletResponse response) { super(request, response); } @Override public void addCookie(Cookie cookie) { super.addCookie(cookie); cookies.add(cookie); } @Override public void clearCookie(Cookie cookie) { super.clearCookie(cookie); cookies.add(cookie); } public void writeMetaData(WebResponse webResponse) { for (Cookie cookie : cookies) { webResponse.addCookie(cookie); } } @Override public void sendRedirect(String url) { super.sendRedirect(url); try { getHttpServletResponse().sendRedirect(url); } catch (IOException e) { throw new RuntimeException(e); } } } }
wicket/src/main/java/org/apache/wicket/util/tester/BaseWicketTester.java
/* * 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.wicket.util.tester; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.wicket.Application; import org.apache.wicket.Component; import org.apache.wicket.IPageManagerProvider; import org.apache.wicket.IPageRendererProvider; import org.apache.wicket.IRequestCycleProvider; import org.apache.wicket.MarkupContainer; import org.apache.wicket.Page; import org.apache.wicket.RequestListenerInterface; import org.apache.wicket.Session; import org.apache.wicket.ThreadContext; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.behavior.AbstractAjaxBehavior; import org.apache.wicket.behavior.IBehavior; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.feedback.FeedbackMessages; import org.apache.wicket.feedback.IFeedbackMessageFilter; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.IFormSubmitListener; import org.apache.wicket.markup.html.form.SubmitLink; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.ILinkListener; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.mock.MockApplication; import org.apache.wicket.mock.MockPageManager; import org.apache.wicket.mock.MockRequestParameters; import org.apache.wicket.mock.MockSessionStore; import org.apache.wicket.page.IPageManager; import org.apache.wicket.page.IPageManagerContext; import org.apache.wicket.protocol.http.IMetaDataBufferingWebResponse; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.protocol.http.WicketFilter; import org.apache.wicket.protocol.http.mock.MockHttpServletRequest; import org.apache.wicket.protocol.http.mock.MockHttpServletResponse; import org.apache.wicket.protocol.http.mock.MockHttpSession; import org.apache.wicket.protocol.http.servlet.ServletWebRequest; import org.apache.wicket.protocol.http.servlet.ServletWebResponse; import org.apache.wicket.request.IExceptionMapper; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.cycle.RequestCycleContext; import org.apache.wicket.request.handler.BookmarkablePageRequestHandler; import org.apache.wicket.request.handler.IPageProvider; import org.apache.wicket.request.handler.ListenerInterfaceRequestHandler; import org.apache.wicket.request.handler.PageAndComponentProvider; import org.apache.wicket.request.handler.PageProvider; import org.apache.wicket.request.handler.RenderPageRequestHandler; import org.apache.wicket.request.handler.render.PageRenderer; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.session.ISessionStore; import org.apache.wicket.settings.IRequestCycleSettings.RenderStrategy; import org.apache.wicket.util.IProvider; import org.apache.wicket.util.lang.Classes; import org.apache.wicket.util.string.Strings; import org.apache.wicket.util.visit.IVisit; import org.apache.wicket.util.visit.IVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A helper class to ease unit testing of Wicket applications without the need for a servlet * container. See javadoc of <code>WicketTester</code> for example usage. This class can be used as * is, but JUnit users should use derived class <code>WicketTester</code>. * * @see WicketTester * * @author Ingram Chen * @author Juergen Donnerstag * @author Frank Bille * @author Igor Vaynberg * * @since 1.2.6 */ public class BaseWicketTester { /** log. */ private static final Logger log = LoggerFactory.getLogger(BaseWicketTester.class); /** * @author jcompagner */ private static final class TestPageSource implements ITestPageSource { private final Page page; private static final long serialVersionUID = 1L; /** * Constructor. * * @param page */ private TestPageSource(Page page) { this.page = page; } public Page getTestPage() { return page; } } private org.apache.wicket.protocol.http.mock.MockServletContext servletContext; private MockHttpSession hsession; private final WebApplication application; private boolean followRedirects = true; private int redirectCount; private MockHttpServletRequest lastRequest; private MockHttpServletResponse lastResponse; private final List<MockHttpServletRequest> previousRequests = new ArrayList<MockHttpServletRequest>(); private final List<MockHttpServletResponse> previousResponses = new ArrayList<MockHttpServletResponse>(); private final ThreadContext oldThreadContext; /** current request */ private MockHttpServletRequest request; /** current response */ private MockHttpServletResponse response; /** current session */ private Session session; /** current request cycle */ private RequestCycle requestCycle; private Page lastRenderedPage; private boolean exposeExceptions = true; private IRequestHandler forcedHandler; // Simulates the cookies maintained by the browser private final List<Cookie> browserCookies = new ArrayList<Cookie>(); /** * Creates <code>WicketTester</code> and automatically create a <code>WebApplication</code>, but * the tester will have no home page. */ public BaseWicketTester() { this(new MockApplication()); } /** * Creates <code>WicketTester</code> and automatically creates a <code>WebApplication</code>. * * @param <C> * * @param homePage * a home page <code>Class</code> */ public <C extends Page> BaseWicketTester(final Class<C> homePage) { this(new MockApplication() { /** * @see org.apache.wicket.Application#getHomePage() */ @Override public Class<? extends Page> getHomePage() { return homePage; } }); } /** * Creates a <code>WicketTester</code>. * * @param application * a <code>WicketTester</code> <code>WebApplication</code> object */ public BaseWicketTester(final WebApplication application) { this(application, null); } /** * Creates a <code>WicketTester</code>. * * @param application * a <code>WicketTester</code> <code>WebApplication</code> object * * @param servletContextBasePath * the absolute path on disk to the web application's contents (e.g. war root) - may * be <code>null</code> */ public BaseWicketTester(final WebApplication application, String servletContextBasePath) { servletContext = new org.apache.wicket.protocol.http.mock.MockServletContext(application, servletContextBasePath); final FilterConfig filterConfig = new TestFilterConfig(); WicketFilter filter = new WicketFilter() { @Override public FilterConfig getFilterConfig() { return filterConfig; } }; application.setWicketFilter(filter); hsession = new MockHttpSession(servletContext); oldThreadContext = ThreadContext.detach(); this.application = application; // FIXME some tests are leaking applications by not calling destroy on them or overriding // teardown() without calling super, for now we work around by making each name unique this.application.setName("WicketTesterApplication-" + UUID.randomUUID()); ThreadContext.setApplication(application); application.setServletContext(servletContext); // initialize the application this.application.initApplication(); // reconfigure application for the test environment application.setPageRendererProvider(new LastPageRecordingPageRendererProvider( application.getPageRendererProvider())); application.setRequestCycleProvider(new TestRequestCycleProvider( application.getRequestCycleProvider())); application.setSessionStoreProvider(new TestSessionStoreProvider()); application.setPageManagerProvider(newTestPageManagerProvider()); // prepare session setupNextRequestCycle(); } protected IPageManagerProvider newTestPageManagerProvider() { return new TestPageManagerProvider(); } /** * @return last rendered page */ public Page getLastRenderedPage() { return lastRenderedPage; } /** * */ private void setupNextRequestCycle() { request = new MockHttpServletRequest(application, hsession, servletContext); request.setURL(request.getContextPath() + request.getServletPath() + "/"); response = new MockHttpServletResponse(request); ServletWebRequest servletWebRequest = createServletWebRequest(); requestCycle = application.createRequestCycle(servletWebRequest, createServletWebResponse(servletWebRequest)); requestCycle.setCleanupFeedbackMessagesOnDetach(false); ThreadContext.setRequestCycle(requestCycle); if (session == null) { createNewSession(); } } /** * @return */ private ServletWebResponse createServletWebResponse(ServletWebRequest servletWebRequest) { return new WicketTesterServletWebResponse(servletWebRequest, response); } /** * @return */ private ServletWebRequest createServletWebRequest() { return new ServletWebRequest(request, request.getFilterPrefix()); } /** * */ private void createNewSession() { session = Session.get(); ThreadContext.setSession(session); } /** * * @return */ public MockHttpServletRequest getRequest() { return request; } /** * * @param request */ public void setRequest(MockHttpServletRequest request) { this.request = request; applyRequest(); } /** * * @return session */ public Session getSession() { return session; } /** * Returns {@link HttpSession} for this environment * * @return session */ public MockHttpSession getHttpSession() { return hsession; } /** * Returns the {@link Application} for this environment. * * @return application */ public WebApplication getApplication() { return application; } /** * Returns the {@link ServletContext} for this environment * * @return servlet context */ public org.apache.wicket.protocol.http.mock.MockServletContext getServletContext() { return servletContext; } /** * Destroys the tester. Restores {@link ThreadContext} to state before instance of * {@link WicketTester} was created. */ public void destroy() { application.internalDestroy(); ThreadContext.detach(); } /** * * @return */ public boolean processRequest() { return processRequest(null, null); } /** * Processes the request in mocked Wicket environment. * * @param request * request to process * */ public void processRequest(MockHttpServletRequest request) { processRequest(request, null); } /** * Processes the request in mocked Wicket environment. * * @param request * request to process * * @param forcedRequestHandler * optional parameter to override parsing the request URL and force * {@link IRequestHandler} */ public boolean processRequest(MockHttpServletRequest request, IRequestHandler forcedRequestHandler) { return processRequest(request, forcedRequestHandler, false); } /** * * @param forcedRequestHandler * @return */ public boolean processRequest(IRequestHandler forcedRequestHandler) { return processRequest(null, forcedRequestHandler, false); } /** * * @param forcedRequest * @param forcedRequestHandler * @param redirect * @return */ private boolean processRequest(MockHttpServletRequest forcedRequest, IRequestHandler forcedRequestHandler, boolean redirect) { if (forcedRequest != null) { request = forcedRequest; } forcedHandler = forcedRequestHandler; if (!redirect && getRequest().getHeader("Wicket-Ajax") == null) { lastRenderedPage = null; } try { if (!redirect) { /* * we do not reset the session during redirect processing because we want to * preserve the state before the redirect, eg any error messages reported */ session.cleanupFeedbackMessages(); } if (getLastResponse() != null) { // transfer cookies from previous response to this request, quirky but how old stuff // worked... for (Cookie cookie : getLastResponse().getCookies()) { request.addCookie(cookie); } } applyRequest(); requestCycle.scheduleRequestHandlerAfterCurrent(null); if (!requestCycle.processRequestAndDetach()) { return false; } recordRequestResponse(); setupNextRequestCycle(); if (followRedirects && lastResponse.isRedirect()) { if (redirectCount++ >= 100) { throw new IllegalStateException( "Possible infinite redirect detected. Bailing out."); } Url newUrl = Url.parse(lastResponse.getRedirectLocation(), Charset.forName(request.getCharacterEncoding())); if (newUrl.isAbsolute()) { throw new WicketRuntimeException("Can not follow absolute redirect URL."); } // append redirect URL to current URL (what browser would do) Url mergedURL = new Url(lastRequest.getUrl().getSegments(), newUrl.getQueryParameters()); mergedURL.concatSegments(newUrl.getSegments()); request.setUrl(mergedURL); processRequest(null, null, true); --redirectCount; } return true; } finally { redirectCount = 0; } } /** * */ private void recordRequestResponse() { lastRequest = request; lastResponse = response; previousRequests.add(request); previousResponses.add(response); // transfer cookies from previous request to previous response, quirky but how old stuff // worked... if (lastRequest.getCookies() != null) { for (Cookie cookie : lastRequest.getCookies()) { lastResponse.addCookie(cookie); } } } /** * Renders the page specified by given {@link IPageProvider}. After render the page instance can * be retreived using {@link #getLastRenderedPage()} and the rendered document will be available * in {@link #getLastResponse()}. * * Depending on {@link RenderStrategy} invoking this method can mean that a redirect will happen * before the actual render. * * @param pageProvider * @return last rendered page */ public Page startPage(IPageProvider pageProvider) { request = new MockHttpServletRequest(application, hsession, servletContext); request.setURL(request.getContextPath() + request.getServletPath() + "/"); IRequestHandler handler = new RenderPageRequestHandler(pageProvider); processRequest(request, handler); return getLastRenderedPage(); } /** * Renders the page. * * @see #startPage(IPageProvider) * * @param page */ public Page startPage(Page page) { return startPage(new PageProvider(page)); } /** * @return last response or <code>null</code>> if no response has been produced yet. */ public MockHttpServletResponse getLastResponse() { return lastResponse; } public String getLastResponseAsString() { return lastResponse.getDocument(); } /** * @return list of prior requests */ public List<MockHttpServletRequest> getPreviousRequests() { return Collections.unmodifiableList(previousRequests); } /** * @return list of prior responses */ public List<MockHttpServletResponse> getPreviousResponses() { return Collections.unmodifiableList(previousResponses); } /** * Sets whether responses with redirects will be followed automatically. * * @param followRedirects */ public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } /** * @return <code>true</code> if redirect responses will be followed automatically, * <code>false</code> otherwise. */ public boolean isFollowRedirects() { return followRedirects; } /** * Encodes the {@link IRequestHandler} to {@link Url}. It should be safe to call this method * outside request thread as log as no registered {@link IRequestMapper} requires a * {@link RequestCycle}. * * @param handler * @return {@link Url} for handler. */ public Url urlFor(IRequestHandler handler) { Url url = application.getRootRequestMapper().mapHandler(handler); transform(url); return url; } public String urlFor(Link link) { return link.urlFor(ILinkListener.INTERFACE).toString(); } /** * Renders a <code>Page</code> defined in <code>TestPageSource</code>. This is usually used when * a page does not have default constructor. For example, a <code>ViewBook</code> page requires * a <code>Book</code> instance: * * <pre> * tester.startPage(new TestPageSource() * { * public Page getTestPage() * { * Book mockBook = new Book(&quot;myBookName&quot;); * return new ViewBook(mockBook); * } * }); * </pre> * * @param testPageSource * a <code>Page</code> factory that creates a test page instance * @return the rendered Page */ public final Page startPage(final ITestPageSource testPageSource) { return startPage(testPageSource.getTestPage()); } /** * Simulates processing URL that invokes specified {@link RequestListenerInterface} on * component. * * After the listener interface is invoked the page containing the component will be rendered * (with an optional redirect - depending on {@link RenderStrategy}). * * @param component * @param listener */ public void executeListener(Component component, RequestListenerInterface listener) { // there are two ways to do this. RequestCycle could be forced to call the handler // directly but constructing and parsing the URL increases the chance of triggering bugs IRequestHandler handler = new ListenerInterfaceRequestHandler(new PageAndComponentProvider( component.getPage(), component), listener); Url url = urlFor(handler); MockHttpServletRequest request = new MockHttpServletRequest(application, hsession, servletContext); request.setUrl(url); processRequest(request, null); } /** * Builds and processes a request suitable for invoking a listener. The <code>Component</code> * must implement any of the known <code>IListener</code> interfaces. * * @param component * the listener to invoke */ public void executeListener(Component component) { for (RequestListenerInterface iface : RequestListenerInterface.getRegisteredInterfaces()) { if (iface.getListenerInterfaceClass().isAssignableFrom(component.getClass())) { executeListener(component, iface); } } } /** * Builds and processes a request suitable for executing an <code>AbstractAjaxBehavior</code>. * * @param behavior * an <code>AbstractAjaxBehavior</code> to execute */ public void executeBehavior(final AbstractAjaxBehavior behavior) { Url url = Url.parse(behavior.getCallbackUrl().toString(), Charset.forName(request.getCharacterEncoding())); transform(url); request.setUrl(url); request.addHeader("Wicket-Ajax-BaseURL", url.toString()); request.addHeader("Wicket-Ajax", "true"); processRequest(); } /** * * @param link * @return */ public Url urlFor(AjaxLink<?> link) { AbstractAjaxBehavior behavior = WicketTesterHelper.findAjaxEventBehavior(link, "onclick"); Url url = Url.parse(behavior.getCallbackUrl().toString(), Charset.forName(request.getCharacterEncoding())); transform(url); return url; } /** * * @param url */ public void executeAjaxUrl(Url url) { transform(url); request.setUrl(url); request.addHeader("Wicket-Ajax-BaseURL", url.toString()); request.addHeader("Wicket-Ajax", "true"); processRequest(); } /** * Renders a <code>Page</code> from its default constructor. * * @param <C> * * @param pageClass * a test <code>Page</code> class with default constructor * @return the rendered <code>Page</code> */ public final <C extends Page> Page startPage(Class<C> pageClass) { request.setUrl(application.getRootRequestMapper().mapHandler( new BookmarkablePageRequestHandler(new PageProvider(pageClass)))); processRequest(); return getLastRenderedPage(); } /** * Renders a <code>Page</code> from its default constructor. * * @param <C> * * @param pageClass * a test <code>Page</code> class with default constructor * @param parameters * the parameters to use for the class. * @return the rendered <code>Page</code> */ public final <C extends Page> Page startPage(Class<C> pageClass, PageParameters parameters) { request.setUrl(application.getRootRequestMapper().mapHandler( new BookmarkablePageRequestHandler(new PageProvider(pageClass, parameters)))); processRequest(); return getLastRenderedPage(); } /** * Creates a {@link FormTester} for the <code>Form</code> at a given path, and fills all child * {@link org.apache.wicket.markup.html.form.FormComponent}s with blank <code>String</code>s. * * @param path * path to <code>FormComponent</code> * @return a <code>FormTester</code> instance for testing the <code>Form</code> * @see #newFormTester(String, boolean) */ public FormTester newFormTester(String path) { return newFormTester(path, true); } /** * Creates a {@link FormTester} for the <code>Form</code> at a given path. * * @param path * path to <code>FormComponent</code> * @param fillBlankString * specifies whether to fill all child <code>FormComponent</code>s with blank * <code>String</code>s * @return a <code>FormTester</code> instance for testing the <code>Form</code> * @see FormTester */ public FormTester newFormTester(String path, boolean fillBlankString) { return new FormTester(path, (Form<?>)getComponentFromLastRenderedPage(path), this, fillBlankString); } /** * Renders a <code>Panel</code> defined in <code>TestPanelSource</code>. The usage is similar to * {@link #startPage(ITestPageSource)}. Please note that testing <code>Panel</code> must use the * supplied <code>panelId<code> as a <code>Component</code> id. * * <pre> * tester.startPanel(new TestPanelSource() * { * public Panel getTestPanel(String panelId) * { * MyData mockMyData = new MyData(); * return new MyPanel(panelId, mockMyData); * } * }); * </pre> * * @param testPanelSource * a <code>Panel</code> factory that creates test <code>Panel</code> instances * @return a rendered <code>Panel</code> */ public final Panel startPanel(final TestPanelSource testPanelSource) { return (Panel)startPage(new ITestPageSource() { private static final long serialVersionUID = 1L; public Page getTestPage() { return new DummyPanelPage(testPanelSource); } }).get(DummyPanelPage.TEST_PANEL_ID); } /** * Renders a <code>Panel</code> from a <code>Panel(String id)</code> constructor. * * @param <C> * * @param panelClass * a test <code>Panel</code> class with <code>Panel(String id)</code> constructor * @return a rendered <code>Panel</code> */ public final <C extends Panel> Panel startPanel(final Class<C> panelClass) { return (Panel)startPage(new ITestPageSource() { private static final long serialVersionUID = 1L; public Page getTestPage() { return new DummyPanelPage(new TestPanelSource() { private static final long serialVersionUID = 1L; public Panel getTestPanel(String panelId) { try { Constructor<? extends Panel> c = panelClass.getConstructor(String.class); return c.newInstance(panelId); } catch (Exception e) { throw convertoUnexpect(e); } } }); } }).get(DummyPanelPage.TEST_PANEL_ID); } /** * A helper method for starting a component for a test without attaching it to a Page. * * Components which are somehow dependent on the page structure can not be currently tested with * this method. * * Example: * * UserDataView view = new UserDataView("view", new ListDataProvider(userList)); * tester.startComponent(view); assertEquals(4, view.size()); * * @param component */ public void startComponent(Component component) { if (component instanceof FormComponent) { ((FormComponent<?>)component).processInput(); } component.beforeRender(); } /** * Throw "standard" WicketRuntimeException * * @param e * @return RuntimeException */ private RuntimeException convertoUnexpect(Exception e) { return new WicketRuntimeException("tester: unexpected", e); } /** * Gets the component with the given path from last rendered page. This method fails in case the * component couldn't be found, and it will return null if the component was found, but is not * visible. * * @param path * Path to component * @return The component at the path * @see org.apache.wicket.MarkupContainer#get(String) */ public Component getComponentFromLastRenderedPage(String path) { MarkupContainer root = getLastRenderedPage(); if (root instanceof DummyPanelPage) { root = (MarkupContainer)root.get(DummyPanelPage.TEST_PANEL_ID); } Component component = root.get(path); if (component == null) { fail("path: '" + path + "' does not exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); return component; } if (component.isVisibleInHierarchy()) { return component; } return null; } /** * assert the text of <code>Label</code> component. * * @param path * path to <code>Label</code> component * @param expectedLabelText * expected label text * @return a <code>Result</code> */ public Result hasLabel(String path, String expectedLabelText) { Label label = (Label)getComponentFromLastRenderedPage(path); return isEqual(expectedLabelText, label.getDefaultModelObjectAsString()); } /** * assert component class * * @param <C> * * @param path * path to component * @param expectedComponentClass * expected component class * @return a <code>Result</code> */ public <C extends Component> Result isComponent(String path, Class<C> expectedComponentClass) { Component component = getComponentFromLastRenderedPage(path); if (component == null) { return Result.fail("Component not found: " + path); } return isTrue("component '" + Classes.simpleName(component.getClass()) + "' is not type:" + Classes.simpleName(expectedComponentClass), expectedComponentClass.isAssignableFrom(component.getClass())); } /** * assert component visible. * * @param path * path to component * @return a <code>Result</code> */ public Result isVisible(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } return isTrue("component '" + path + "' is not visible", component.isVisibleInHierarchy()); } /** * assert component invisible. * * @param path * path to component * @return a <code>Result</code> */ public Result isInvisible(String path) { return isNull("component '" + path + "' is visible", getComponentFromLastRenderedPage(path)); } /** * assert component enabled. * * @param path * path to component * @return a <code>Result</code> */ public Result isEnabled(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } return isTrue("component '" + path + "' is disabled", component.isEnabledInHierarchy()); } /** * assert component disabled. * * @param path * path to component * @return a <code>Result</code> */ public Result isDisabled(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } return isFalse("component '" + path + "' is enabled", component.isEnabledInHierarchy()); } /** * assert component required. * * @param path * path to component * @return a <code>Result</code> */ public Result isRequired(String path) { Component component = getLastRenderedPage().get(path); if (component == null) { fail("path: '" + path + "' does no exist for page: " + Classes.simpleName(getLastRenderedPage().getClass())); } else if (component instanceof FormComponent == false) { fail("path: '" + path + "' is not a form component"); } return isRequired((FormComponent<?>)component); } /** * assert component required. * * @param component * a form component * @return a <code>Result</code> */ public Result isRequired(FormComponent<?> component) { return isTrue("component '" + component + "' is not required", component.isRequired()); } /** * assert the content of last rendered page contains(matches) regex pattern. * * @param pattern * reqex pattern to match * @return a <code>Result</code> */ public Result ifContains(String pattern) { return isTrue("pattern '" + pattern + "' not found in:\n" + getLastResponseAsString(), getLastResponseAsString().toString().matches("(?s).*" + pattern + ".*")); } /** * assert the model of {@link ListView} use expectedList * * @param path * path to {@link ListView} component * @param expectedList * expected list in the model of {@link ListView} */ public void assertListView(String path, List<?> expectedList) { ListView<?> listView = (ListView<?>)getComponentFromLastRenderedPage(path); WicketTesterHelper.assertEquals(expectedList, listView.getList()); } /** * Click the {@link Link} in the last rendered Page. * <p> * Simulate that AJAX is enabled. * * @see WicketTester#clickLink(String, boolean) * @param path * Click the <code>Link</code> in the last rendered Page. */ public void clickLink(String path) { clickLink(path, true); } /** * Click the {@link Link} in the last rendered Page. * <p> * This method also works for {@link AjaxLink}, {@link AjaxFallbackLink} and * {@link AjaxSubmitLink}. * <p> * On AjaxLinks and AjaxFallbackLinks the onClick method is invoked with a valid * AjaxRequestTarget. In that way you can test the flow of your application when using AJAX. * <p> * When clicking an AjaxSubmitLink the form, which the AjaxSubmitLink is attached to is first * submitted, and then the onSubmit method on AjaxSubmitLink is invoked. If you have changed * some values in the form during your test, these will also be submitted. This should not be * used as a replacement for the {@link FormTester} to test your forms. It should be used to * test that the code in your onSubmit method in AjaxSubmitLink actually works. * <p> * This method is also able to simulate that AJAX (javascript) is disabled on the client. This * is done by setting the isAjax parameter to false. If you have an AjaxFallbackLink you can * then check that it doesn't fail when invoked as a normal link. * * @param path * path to <code>Link</code> component * @param isAjax * Whether to simulate that AJAX (javascript) is enabled or not. If it's false then * AjaxLink and AjaxSubmitLink will fail, since it wouldn't work in real life. * AjaxFallbackLink will be invoked with null as the AjaxRequestTarget parameter. */ public void clickLink(String path, boolean isAjax) { Component linkComponent = getComponentFromLastRenderedPage(path); checkUsability(linkComponent); // if the link is an AjaxLink, we process it differently // than a normal link if (linkComponent instanceof AjaxLink) { // If it's not ajax we fail if (isAjax == false) { fail("Link " + path + "is an AjaxLink and will " + "not be invoked when AJAX (javascript) is disabled."); } executeBehavior(WicketTesterHelper.findAjaxEventBehavior(linkComponent, "onclick")); } // AjaxFallbackLinks is processed like an AjaxLink if isAjax is true // If it's not handling of the linkComponent is passed through to the // Link. else if (linkComponent instanceof AjaxFallbackLink && isAjax) { executeBehavior(WicketTesterHelper.findAjaxEventBehavior(linkComponent, "onclick")); } // if the link is an AjaxSubmitLink, we need to find the form // from it using reflection so we know what to submit. else if (linkComponent instanceof AjaxSubmitLink) { // If it's not ajax we fail if (isAjax == false) { fail("Link " + path + " is an AjaxSubmitLink and " + "will not be invoked when AJAX (javascript) is disabled."); } AjaxSubmitLink link = (AjaxSubmitLink)linkComponent; String pageRelativePath = link.getInputName(); request.getPostParameters().setParameterValue(pageRelativePath, "x"); submitAjaxFormSubmitBehavior(link, (AjaxFormSubmitBehavior)WicketTesterHelper.findAjaxEventBehavior(link, "onclick")); } /* * If the link is a submitlink then we pretend to have clicked it */ else if (linkComponent instanceof SubmitLink) { SubmitLink submitLink = (SubmitLink)linkComponent; String pageRelativePath = submitLink.getInputName(); request.getPostParameters().setParameterValue(pageRelativePath, "x"); submitForm(submitLink.getForm().getPageRelativePath()); } // if the link is a normal link (or ResourceLink) else if (linkComponent instanceof AbstractLink) { AbstractLink link = (AbstractLink)linkComponent; /* * If the link is a bookmarkable link, then we need to transfer the parameters to the * next request. */ if (link instanceof BookmarkablePageLink) { BookmarkablePageLink<?> bookmarkablePageLink = (BookmarkablePageLink<?>)link; try { BookmarkablePageLink.class.getDeclaredField("parameters"); Method getParametersMethod = BookmarkablePageLink.class.getDeclaredMethod( "getPageParameters", (Class<?>[])null); getParametersMethod.setAccessible(true); PageParameters parameters = (PageParameters)getParametersMethod.invoke( bookmarkablePageLink, (Object[])null); startPage(bookmarkablePageLink.getPageClass(), parameters); return; } catch (Exception e) { fail("Internal error in WicketTester. " + "Please report this in Wickets Issue Tracker."); } } executeListener(link, ILinkListener.INTERFACE); } else { fail("Link " + path + " is not a Link, AjaxLink, AjaxFallbackLink or AjaxSubmitLink"); } } /** * * @param form */ public void submitForm(Form form) { submitForm(form.getPageRelativePath()); } /** * Submits the <code>Form</code> in the last rendered <code>Page</code>. * * @param path * path to <code>Form</code> component */ public void submitForm(String path) { Form<?> form = (Form<?>)getComponentFromLastRenderedPage(path); Url url = Url.parse(form.urlFor(IFormSubmitListener.INTERFACE).toString(), Charset.forName(request.getCharacterEncoding())); // make url absolute transform(url); request.setUrl(url); processRequest(); } /** * make url suitable for wicket tester use. usually this involves stripping any leading .. * segments to make the url absolute * * @param url */ private void transform(Url url) { while (url.getSegments().size() > 0 && url.getSegments().get(0).equals("..")) { url.getSegments().remove(0); } } /** * Asserts the last rendered <code>Page</code> class. * * FIXME explain why the code is so complicated to compare two classes, or simplify * * @param <C> * * @param expectedRenderedPageClass * expected class of last rendered page * @return a <code>Result</code> */ public <C extends Page> Result isRenderedPage(Class<C> expectedRenderedPageClass) { Page page = getLastRenderedPage(); if (page == null) { return Result.fail("page was null"); } if (!page.getClass().isAssignableFrom(expectedRenderedPageClass)) { return isEqual(Classes.simpleName(expectedRenderedPageClass), Classes.simpleName(page.getClass())); } return Result.pass(); } /** * Asserts last rendered <code>Page</code> against an expected HTML document. * <p> * Use <code>-Dwicket.replace.expected.results=true</code> to automatically replace the expected * output file. * </p> * * @param pageClass * used to load the <code>File</code> (relative to <code>clazz</code> package) * @param filename * expected output <code>File</code> name * @throws Exception */ public void assertResultPage(final Class<?> pageClass, final String filename) throws Exception { // Validate the document String document = getLastResponseAsString(); DiffUtil.validatePage(document, pageClass, filename, true); } /** * Asserts last rendered <code>Page</code> against an expected HTML document as a * <code>String</code>. * * @param expectedDocument * expected output * @return a <code>Result</code> * @throws Exception */ public Result isResultPage(final String expectedDocument) throws Exception { // Validate the document String document = getLastResponseAsString(); return isTrue("expected rendered page equals", document.equals(expectedDocument)); } /** * Asserts no error-level feedback messages. * * @return a <code>Result</code> */ public Result hasNoErrorMessage() { List<Serializable> messages = getMessages(FeedbackMessage.ERROR); return isTrue( "expect no error message, but contains\n" + WicketTesterHelper.asLined(messages), messages.isEmpty()); } /** * Asserts no info-level feedback messages. * * @return a <code>Result</code> */ public Result hasNoInfoMessage() { List<Serializable> messages = getMessages(FeedbackMessage.INFO); return isTrue( "expect no info message, but contains\n" + WicketTesterHelper.asLined(messages), messages.isEmpty()); } /** * Retrieves <code>FeedbackMessages</code>. * * @param level * level of feedback message, for example: * <code>FeedbackMessage.DEBUG or FeedbackMessage.INFO.. etc</code> * @return <code>List</code> of messages (as <code>String</code>s) * @see FeedbackMessage */ public List<Serializable> getMessages(final int level) { FeedbackMessages feedbackMessages = Session.get().getFeedbackMessages(); List<FeedbackMessage> allMessages = feedbackMessages.messages(new IFeedbackMessageFilter() { private static final long serialVersionUID = 1L; public boolean accept(FeedbackMessage message) { return message.getLevel() == level; } }); List<Serializable> actualMessages = new ArrayList<Serializable>(); for (FeedbackMessage message : allMessages) { actualMessages.add(message.getMessage()); } return actualMessages; } /** * Dumps the source of last rendered <code>Page</code>. */ public void dumpPage() { log.info(getLastResponseAsString()); } /** * Dumps the <code>Component</code> trees. */ public void debugComponentTrees() { debugComponentTrees(""); } /** * Dumps the <code>Component</code> trees to log. Show only the <code>Component</code>s whose * paths contain the filter <code>String</code>. * * @param filter * a filter <code>String</code> */ public void debugComponentTrees(String filter) { log.info("debugging ----------------------------------------------"); for (WicketTesterHelper.ComponentData obj : WicketTesterHelper.getComponentData(getLastRenderedPage())) { if (obj.path.matches(".*" + filter + ".*")) { log.info("path\t" + obj.path + " \t" + obj.type + " \t[" + obj.value + "]"); } } } /** * Tests that a <code>Component</code> has been added to a <code>AjaxRequestTarget</code>, using * {@link AjaxRequestTarget#add(Component)}. This method actually tests that a * <code>Component</code> is on the Ajax response sent back to the client. * <p> * PLEASE NOTE! This method doesn't actually insert the <code>Component</code> in the client DOM * tree, using Javascript. But it shouldn't be needed because you have to trust that the Wicket * Ajax Javascript just works. * * @param component * the <code>Component</code> to test * @return a <code>Result</code> */ public Result isComponentOnAjaxResponse(Component component) { String failMessage = "A component which is null could not have been added to the AJAX response"; notNull(failMessage, component); Result result; // test that the component renders the placeholder tag if it's not visible if (!component.isVisible()) { failMessage = "A component which is invisible and doesn't render a placeholder tag" + " will not be rendered at all and thus won't be accessible for subsequent AJAX interaction"; result = isTrue(failMessage, component.getOutputMarkupPlaceholderTag()); if (result.wasFailed()) { return result; } } // Get the AJAX response String ajaxResponse = getLastResponseAsString(); // Test that the previous response was actually a AJAX response failMessage = "The Previous response was not an AJAX response. " + "You need to execute an AJAX event, using clickLink, before using this assert"; boolean isAjaxResponse = Pattern.compile( "^<\\?xml version=\"1.0\" encoding=\".*?\"\\?><ajax-response>") .matcher(ajaxResponse) .find(); result = isTrue(failMessage, isAjaxResponse); if (result.wasFailed()) { return result; } // See if the component has a markup id String markupId = component.getMarkupId(); failMessage = "The component doesn't have a markup id, " + "which means that it can't have been added to the AJAX response"; result = isTrue(failMessage, !Strings.isEmpty(markupId)); if (result.wasFailed()) { return result; } // Look for that the component is on the response, using the markup id boolean isComponentInAjaxResponse = ajaxResponse.matches("(?s).*<component id=\"" + markupId + "\"[^>]*?>.*"); failMessage = "Component wasn't found in the AJAX response"; return isTrue(failMessage, isComponentInAjaxResponse); } /** * Simulates the firing of an Ajax event. * * @see #executeAjaxEvent(Component, String) * * @since 1.2.3 * @param componentPath * the <code>Component</code> path * @param event * the event which we simulate being fired. If <code>event</code> is * <code>null</code>, the test will fail. */ public void executeAjaxEvent(String componentPath, String event) { Component component = getComponentFromLastRenderedPage(componentPath); executeAjaxEvent(component, event); } /** * Simulates the firing of all ajax timer behaviors on the page * * @param wt * @param container */ public void executeAllTimerBehaviors(MarkupContainer container) { container.visitChildren(MarkupContainer.class, new IVisitor<MarkupContainer, Void>() { public void component(final MarkupContainer component, final IVisit<Void> visit) { // get the AbstractAjaxBehaviour which is responsible for // getting the contents of the lazy panel List<AbstractAjaxTimerBehavior> behaviors = component.getBehaviors(AbstractAjaxTimerBehavior.class); for (IBehavior b : behaviors) { checkUsability(component); log.debug("Triggering AjaxSelfUpdatingTimerBehavior: " + component.getClassRelativePath()); AbstractAjaxTimerBehavior timer = (AbstractAjaxTimerBehavior)b; if (!timer.isStopped()) { executeBehavior(timer); } } } }); } /** * Simulates the firing of an Ajax event. You add an Ajax event to a <code>Component</code> by * using: * * <pre> * ... * component.add(new AjaxEventBehavior(&quot;ondblclick&quot;) { * public void onEvent(AjaxRequestTarget) {} * }); * ... * </pre> * * You can then test that the code inside <code>onEvent</code> actually does what it's supposed * to, using the <code>WicketTester</code>: * * <pre> * ... * tester.executeAjaxEvent(component, &quot;ondblclick&quot;); * // Test that the code inside onEvent is correct. * ... * </pre> * * This also works with <code>AjaxFormSubmitBehavior</code>, where it will "submit" the * <code>Form</code> before executing the command. * <p> * PLEASE NOTE! This method doesn't actually insert the <code>Component</code> in the client DOM * tree, using Javascript. * * @param component * the <code>Component</code> that has the <code>AjaxEventBehavior</code> we want to * test. If the <code>Component</code> is <code>null</code>, the test will fail. * @param event * the event to simulate being fired. If <code>event</code> is <code>null</code>, the * test will fail. */ public void executeAjaxEvent(final Component component, final String event) { String failMessage = "Can't execute event on a component which is null."; notNull(failMessage, component); failMessage = "event must not be null"; notNull(failMessage, event); checkUsability(component); AjaxEventBehavior ajaxEventBehavior = WicketTesterHelper.findAjaxEventBehavior(component, event); executeBehavior(ajaxEventBehavior); } /** * Retrieves a <code>TagTester</code> based on a <code>wicket:id</code>. If more * <code>Component</code>s exist with the same <code>wicket:id</code> in the markup, only the * first one is returned. * * @param wicketId * the <code>wicket:id</code> to search for * @return the <code>TagTester</code> for the tag which has the given <code>wicket:id</code> */ public TagTester getTagByWicketId(String wicketId) { return TagTester.createTagByAttribute(getLastResponseAsString(), "wicket:id", wicketId); } /** * Modified version of BaseWicketTester#getTagByWicketId(String) that returns all matching tags * instead of just the first. * * @see BaseWicketTester#getTagByWicketId(String) */ public List<TagTester> getTagsByWicketId(String wicketId) { return TagTester.createTagsByAttribute(getLastResponseAsString(), "wicket:id", wicketId, false); } /** * Retrieves a <code>TagTester</code> based on an DOM id. If more <code>Component</code>s exist * with the same id in the markup, only the first one is returned. * * @param id * the DOM id to search for. * @return the <code>TagTester</code> for the tag which has the given DOM id */ public TagTester getTagById(String id) { return TagTester.createTagByAttribute(getLastResponseAsString(), "id", id); } /** * Helper method for all the places where an Ajax call should submit an associated * <code>Form</code>. * * @param component * The component the behavior is attached to * @param behavior * The <code>AjaxFormSubmitBehavior</code> with the <code>Form</code> to "submit" */ private void submitAjaxFormSubmitBehavior(final Component component, AjaxFormSubmitBehavior behavior) { // The form that needs to be "submitted". Form<?> form = behavior.getForm(); String failMessage = "No form attached to the submitlink."; notNull(failMessage, form); checkUsability(form); serializeFormToRequest(form); executeBehavior(behavior); } /** * Puts all not already scheduled (e.g. via {@link FormTester#setValue(String, String)}) form * component values in the post parameters for the next form submit * * @param form * the {@link Form} which components should be submitted */ private void serializeFormToRequest(final Form<?> form) { final MockRequestParameters postParameters = request.getPostParameters(); final Set<String> currentParameterNamesSet = postParameters.getParameterNames(); form.visitFormComponents(new IVisitor<FormComponent<?>, Void>() { public void component(final FormComponent<?> formComponent, final IVisit<Void> visit) { final String inputName = formComponent.getInputName(); if (!currentParameterNamesSet.contains(inputName)) { final Object modelObject = formComponent.getModelObject(); if (modelObject instanceof Collection<?>) { final Collection<?> collectionModelObject = (Collection<?>)modelObject; for (Object value : collectionModelObject) { postParameters.addParameterValue(inputName, value.toString()); } } else { postParameters.addParameterValue(inputName, formComponent.getValue()); } } } }); } /** * Retrieves the content type from the response header. * * @return the content type from the response header */ public String getContentTypeFromResponseHeader() { String contentType = getLastResponse().getContentType(); if (contentType == null) { throw new WicketRuntimeException("No Content-Type header found"); } return contentType; } /** * Retrieves the content length from the response header. * * @return the content length from the response header */ public int getContentLengthFromResponseHeader() { String contentLength = getLastResponse().getHeader("Content-Length"); if (contentLength == null) { throw new WicketRuntimeException("No Content-Length header found"); } return Integer.parseInt(contentLength); } /** * Retrieves the last-modified value from the response header. * * @return the last-modified value from the response header */ public String getLastModifiedFromResponseHeader() { return getLastResponse().getHeader("Last-Modified"); } /** * Retrieves the content disposition from the response header. * * @return the content disposition from the response header */ public String getContentDispositionFromResponseHeader() { return getLastResponse().getHeader("Content-Disposition"); } /** * Rebuilds {@link ServletWebRequest} used by wicket from the mock request used to build * requests. Sometimes this method is useful when changes need to be checked without processing * a request. */ public void applyRequest() { ServletWebRequest req = createServletWebRequest(); requestCycle.setRequest(req); requestCycle.getUrlRenderer().setBaseUrl(req.getUrl()); } /** * * @param message * @param condition * @return */ private Result isTrue(String message, boolean condition) { if (condition) { return Result.pass(); } return Result.fail(message); } /** * * @param message * @param condition * @return */ private Result isFalse(String message, boolean condition) { if (!condition) { return Result.pass(); } return Result.fail(message); } /** * * @param expected * @param actual * @return */ protected final Result isEqual(Object expected, Object actual) { if (expected == null && actual == null) { return Result.pass(); } if (expected != null && expected.equals(actual)) { return Result.pass(); } String message = "expected:<" + expected + "> but was:<" + actual + ">"; return Result.fail(message); } /** * * @param message * @param object */ private void notNull(String message, Object object) { if (object == null) { fail(message); } } /** * * @param message * @param object * @return */ private Result isNull(String message, Object object) { if (object != null) { return Result.fail(message); } return Result.pass(); } /** * Checks whether a component is visible and/or enabled before usage * * @param component */ private void checkUsability(final Component component) { if (component.isVisibleInHierarchy() == false) { fail("The component is currently not visible in the hierarchy and thus you can not be used." + " Component: " + component); } if (component.isEnabledInHierarchy() == false) { fail("The component is currently not enabled in the hierarchy and thus you can not be used." + " Component: " + component); } } /** * * @param message */ protected final void fail(String message) { throw new WicketRuntimeException(message); } /** * * @return */ public RequestCycle getRequestCycle() { return requestCycle; } /** * * @return */ public MockHttpServletResponse getResponse() { return response; } /** * * @return */ public MockHttpServletRequest getLastRequest() { return lastRequest; } /** * * @return */ public boolean isExposeExceptions() { return exposeExceptions; } /** * * @param exposeExceptions */ public void setExposeExceptions(boolean exposeExceptions) { this.exposeExceptions = exposeExceptions; } /** * * @param _url */ public void executeUrl(String _url) { Url url = Url.parse(_url, Charset.forName(request.getCharacterEncoding())); transform(url); getRequest().setUrl(url); processRequest(); } /** * */ private class LastPageRecordingPageRendererProvider implements IPageRendererProvider { private final IPageRendererProvider delegate; public LastPageRecordingPageRendererProvider(IPageRendererProvider delegate) { this.delegate = delegate; } public PageRenderer get(RenderPageRequestHandler handler) { lastRenderedPage = (Page)handler.getPageProvider().getPageInstance(); return delegate.get(handler); } } /** * */ private class TestExceptionMapper implements IExceptionMapper { private final IExceptionMapper delegate; public TestExceptionMapper(IExceptionMapper delegate) { this.delegate = delegate; } public IRequestHandler map(Exception e) { if (exposeExceptions) { if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new WicketRuntimeException(e); } } else { return delegate.map(e); } } } /** * */ private class TestRequestCycleProvider implements IRequestCycleProvider { private final IRequestCycleProvider delegate; public TestRequestCycleProvider(IRequestCycleProvider delegate) { this.delegate = delegate; } public RequestCycle get(RequestCycleContext context) { context.setRequestMapper(new TestRequestMapper(context.getRequestMapper())); forcedHandler = null; context.setExceptionMapper(new TestExceptionMapper(context.getExceptionMapper())); return delegate.get(context); } } /** * */ private class TestRequestMapper implements IRequestMapper { private final IRequestMapper delegate; public TestRequestMapper(IRequestMapper delegate) { this.delegate = delegate; } public int getCompatibilityScore(Request request) { return delegate.getCompatibilityScore(request); } public Url mapHandler(IRequestHandler requestHandler) { return delegate.mapHandler(requestHandler); } public IRequestHandler mapRequest(Request request) { if (forcedHandler != null) { IRequestHandler handler = forcedHandler; forcedHandler = null; return handler; } else { return delegate.mapRequest(request); } } } /** * */ private class TestSessionStore extends MockSessionStore { @Override public void invalidate(Request request) { super.invalidate(request); createNewSession(); } } /** * */ private class TestSessionStoreProvider implements IProvider<ISessionStore> { public ISessionStore get() { return new TestSessionStore(); } } /** * */ private class TestPageManagerProvider implements IPageManagerProvider { public IPageManager get(IPageManagerContext pageManagerContext) { return new MockPageManager(); } } /** * */ private class TestFilterConfig implements FilterConfig { private final Map<String, String> initParameters = new HashMap<String, String>(); public TestFilterConfig() { initParameters.put(WicketFilter.FILTER_MAPPING_PARAM, "/servlet/*"); } public String getFilterName() { return getClass().getName(); } public ServletContext getServletContext() { return servletContext; } public String getInitParameter(String s) { return initParameters.get(s); } public Enumeration<String> getInitParameterNames() { throw new UnsupportedOperationException("Not implemented"); } } private class WicketTesterServletWebResponse extends ServletWebResponse implements IMetaDataBufferingWebResponse { private List<Cookie> cookies = new ArrayList<Cookie>(); public WicketTesterServletWebResponse(ServletWebRequest request, MockHttpServletResponse response) { super(request, response); } @Override public void addCookie(Cookie cookie) { super.addCookie(cookie); cookies.add(cookie); } @Override public void clearCookie(Cookie cookie) { super.clearCookie(cookie); cookies.add(cookie); } public void writeMetaData(WebResponse webResponse) { for (Cookie cookie : cookies) { webResponse.addCookie(cookie); } } @Override public void sendRedirect(String url) { super.sendRedirect(url); try { getHttpServletResponse().sendRedirect(url); } catch (IOException e) { throw new RuntimeException(e); } } } }
changes the fix to be more safe Issue: WICKET-1214 git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@1039700 13f79535-47bb-0310-9956-ffa450edef68
wicket/src/main/java/org/apache/wicket/util/tester/BaseWicketTester.java
changes the fix to be more safe Issue: WICKET-1214
<ide><path>icket/src/main/java/org/apache/wicket/util/tester/BaseWicketTester.java <ide> // Simulates the cookies maintained by the browser <ide> private final List<Cookie> browserCookies = new ArrayList<Cookie>(); <ide> <add> // The root component used for the start. Usually the Page, but can also be a Panel <add> // see https://issues.apache.org/jira/browse/WICKET-1214 <add> private MarkupContainer startComponent; <add> <ide> /** <ide> * Creates <code>WicketTester</code> and automatically create a <code>WebApplication</code>, but <ide> * the tester will have no home page. <ide> */ <ide> public Page startPage(IPageProvider pageProvider) <ide> { <add> startComponent = null; <ide> request = new MockHttpServletRequest(application, hsession, servletContext); <ide> request.setURL(request.getContextPath() + request.getServletPath() + "/"); <ide> IRequestHandler handler = new RenderPageRequestHandler(pageProvider); <ide> */ <ide> public final <C extends Page> Page startPage(Class<C> pageClass) <ide> { <add> startComponent = null; <ide> request.setUrl(application.getRootRequestMapper().mapHandler( <ide> new BookmarkablePageRequestHandler(new PageProvider(pageClass)))); <ide> processRequest(); <ide> */ <ide> public final <C extends Page> Page startPage(Class<C> pageClass, PageParameters parameters) <ide> { <add> startComponent = null; <ide> request.setUrl(application.getRootRequestMapper().mapHandler( <ide> new BookmarkablePageRequestHandler(new PageProvider(pageClass, parameters)))); <ide> processRequest(); <ide> */ <ide> public final Panel startPanel(final TestPanelSource testPanelSource) <ide> { <del> return (Panel)startPage(new ITestPageSource() <add> Panel panel = (Panel)startPage(new ITestPageSource() <ide> { <ide> private static final long serialVersionUID = 1L; <ide> <ide> return new DummyPanelPage(testPanelSource); <ide> } <ide> }).get(DummyPanelPage.TEST_PANEL_ID); <add> startComponent = panel; <add> return panel; <ide> } <ide> <ide> /** <ide> */ <ide> public final <C extends Panel> Panel startPanel(final Class<C> panelClass) <ide> { <del> return (Panel)startPage(new ITestPageSource() <add> Panel panel = (Panel)startPage(new ITestPageSource() <ide> { <ide> private static final long serialVersionUID = 1L; <ide> <ide> }); <ide> } <ide> }).get(DummyPanelPage.TEST_PANEL_ID); <add> startComponent = panel; <add> return panel; <ide> } <ide> <ide> /** <ide> */ <ide> public Component getComponentFromLastRenderedPage(String path) <ide> { <del> MarkupContainer root = getLastRenderedPage(); <del> if (root instanceof DummyPanelPage) <del> { <del> root = (MarkupContainer)root.get(DummyPanelPage.TEST_PANEL_ID); <del> } <del> <del> Component component = root.get(path); <add> if (startComponent != null) <add> { <add> path = startComponent.getId() + ":" + path; <add> } <add> Component component = getLastRenderedPage().get(path); <ide> if (component == null) <ide> { <ide> fail("path: '" + path + "' does not exist for page: " + <ide> * <code>Component</code> is on the Ajax response sent back to the client. <ide> * <p> <ide> * PLEASE NOTE! This method doesn't actually insert the <code>Component</code> in the client DOM <del> * tree, using Javascript. But it shouldn't be needed because you have to trust that the Wicket <del> * Ajax Javascript just works. <add> * tree, using JavaScript. But it shouldn't be needed because you have to trust that the Wicket <add> * Ajax JavaScript just works. <ide> * <ide> * @param component <ide> * the <code>Component</code> to test <ide> * <code>Form</code> before executing the command. <ide> * <p> <ide> * PLEASE NOTE! This method doesn't actually insert the <code>Component</code> in the client DOM <del> * tree, using Javascript. <add> * tree, using JavaScript. <ide> * <ide> * @param component <ide> * the <code>Component</code> that has the <code>AjaxEventBehavior</code> we want to
Java
apache-2.0
2146634270ffd8d6960249302cb29b47c5d79cb7
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag ROOT_CHAIN_GRAPH = defineFeatureFlag( "root-chain-graph", true, List.of("hakonhall"), "2022-10-05", "2022-11-04", "Whether to run all tasks in the root task chain up to the one failing to converge (false), or " + "run all tasks in the root task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the root chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag QUERY_DISPATCH_POLICY = defineStringFlag( "query-dispatch-policy", "adaptive", List.of("baldersheim"), "2022-08-20", "2023-01-01", "Select query dispatch policy, valid values are adaptive, round-robin, best-of-random-2," + " latency-amortized-over-requests, latency-amortized-over-time", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-11-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-11-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-12-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-11-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2023-01-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-12-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-11-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-11-01", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-11-01", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-11-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2022-11-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag( "tls-capabilities-enforcement-mode", "disable", List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01", "Configure Vespa TLS capability enforcement mode", "Takes effect on restart of Docker container", APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION ); public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag( "cleanup-tenant-roles", false, List.of("olaa"), "2022-08-10", "2023-01-01", "Determines whether old tenant roles should be deleted", "Takes effect next maintenance run" ); public static final UnboundBooleanFlag USE_TWO_PHASE_DOCUMENT_GC = defineFeatureFlag( "use-two-phase-document-gc", false, List.of("vekterli"), "2022-08-24", "2022-11-01", "Use two-phase document GC in content clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag RESTRICT_DATA_PLANE_BINDINGS = defineFeatureFlag( "restrict-data-plane-bindings", false, List.of("mortent"), "2022-09-08", "2022-11-01", "Use restricted data plane bindings", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundStringFlag CSRF_MODE = defineStringFlag( "csrf-mode", "disabled", List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "Set mode for CSRF filter ('disabled', 'log_only', 'enabled')", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag SOFT_REBUILD = defineFeatureFlag( "soft-rebuild", false, List.of("mpolden"), "2022-09-27", "2022-12-01", "Whether soft rebuild can be used to rebuild hosts with remote disk", "Takes effect on next run of OsUpgradeActivator" ); public static final UnboundListFlag<String> CSRF_USERS = defineListFlag( "csrf-users", List.of(), String.class, List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "List of users to enable CSRF filter for. Use empty list for everyone.", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag ENABLE_OTELCOL = defineFeatureFlag( "enable-otel-collector", false, List.of("olaa"), "2022-09-23", "2023-01-01", "Whether an OpenTelemetry collector should be enabled", "Takes effect at next tick", APPLICATION_ID); public static final UnboundBooleanFlag CONSOLE_CSRF = defineFeatureFlag( "console-csrf", false, List.of("bjorncs", "tokle"), "2022-09-26", "2023-06-01", "Enable CSRF token in console", "Takes effect immediately", CONSOLE_USER_EMAIL); public static final UnboundBooleanFlag USE_WIREGUARD_ON_CONFIGSERVERS = defineFeatureFlag( "use-wireguard-on-configservers", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on config servers", "Takes effect on configserver restart", HOSTNAME); public static final UnboundBooleanFlag USE_WIREGUARD_ON_TENANT_HOSTS = defineFeatureFlag( "use-wireguard-on-tenant-hosts", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on tenant hosts", "Takes effect on host admin restart", HOSTNAME); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return defineStringFlag(flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, value -> true, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Predicate<String> validator, FetchVector.Dimension... dimensions) { return define((i, d, v) -> new UnboundStringFlag(i, d, v, validator), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultValue, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
flags/src/main/java/com/yahoo/vespa/flags/Flags.java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag ROOT_CHAIN_GRAPH = defineFeatureFlag( "root-chain-graph", true, List.of("hakonhall"), "2022-10-05", "2022-11-04", "Whether to run all tasks in the root task chain up to the one failing to converge (false), or " + "run all tasks in the root task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the root chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag QUERY_DISPATCH_POLICY = defineStringFlag( "query-dispatch-policy", "adaptive", List.of("baldersheim"), "2022-08-20", "2023-01-01", "Select query dispatch policy, valid values are adaptive, round-robin, best-of-random-2," + " latency-amortized-over-requests, latency-amortized-over-time", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-11-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-11-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-12-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-11-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2023-01-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-12-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-11-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-11-01", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-11-01", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-11-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2022-11-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag( "tls-capabilities-enforcement-mode", "disable", List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01", "Configure Vespa TLS capability enforcement mode", "Takes effect on restart of Docker container", APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION ); public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag( "cleanup-tenant-roles", false, List.of("olaa"), "2022-08-10", "2023-01-01", "Determines whether old tenant roles should be deleted", "Takes effect next maintenance run" ); public static final UnboundBooleanFlag USE_TWO_PHASE_DOCUMENT_GC = defineFeatureFlag( "use-two-phase-document-gc", false, List.of("vekterli"), "2022-08-24", "2022-11-01", "Use two-phase document GC in content clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag RESTRICT_DATA_PLANE_BINDINGS = defineFeatureFlag( "restrict-data-plane-bindings", false, List.of("mortent"), "2022-09-08", "2022-11-01", "Use restricted data plane bindings", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundStringFlag CSRF_MODE = defineStringFlag( "csrf-mode", "disabled", List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "Set mode for CSRF filter ('disabled', 'log_only', 'enabled')", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag SOFT_REBUILD = defineFeatureFlag( "soft-rebuild", false, List.of("mpolden"), "2022-09-27", "2022-12-01", "Whether soft rebuild can be used to rebuild hosts with remote disk", "Takes effect on next run of OsUpgradeActivator" ); public static final UnboundListFlag<String> CSRF_USERS = defineListFlag( "csrf-users", List.of(), String.class, List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "List of users to enable CSRF filter for. Use empty list for everyone.", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag ENABLE_OTELCOL = defineFeatureFlag( "enable-otel-collector", false, List.of("olaa"), "2022-09-23", "2023-01-01", "Whether an OpenTelemetry collector should be enabled", "Takes effect at next tick", APPLICATION_ID); public static final UnboundBooleanFlag CONSOLE_CSRF = defineFeatureFlag( "console-csrf", false, List.of("bjorncs", "tokle"), "2022-09-26", "2023-06-01", "Enable CSRF token in console", "Takes effect immediately", CONSOLE_USER_EMAIL); public static final UnboundBooleanFlag USE_WIREGUARD_ON_CONFIGSERVERS = defineFeatureFlag( "use-wireguard-on-configservers", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on config servers", "Takes effect on configserver restart", ZONE_ID, NODE_TYPE); public static final UnboundBooleanFlag USE_WIREGUARD_ON_TENANT_HOSTS = defineFeatureFlag( "use-wireguard-on-tenant-hosts", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on tenant hosts", "Takes effect on host admin restart", HOSTNAME); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return defineStringFlag(flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, value -> true, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Predicate<String> validator, FetchVector.Dimension... dimensions) { return define((i, d, v) -> new UnboundStringFlag(i, d, v, validator), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultValue, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
Use only hostname as dimension for USE_WIREGUARD_ON_TENANT_HOSTS (#24445) Co-authored-by: gjoranv <[email protected]>
flags/src/main/java/com/yahoo/vespa/flags/Flags.java
Use only hostname as dimension for USE_WIREGUARD_ON_TENANT_HOSTS (#24445)
<ide><path>lags/src/main/java/com/yahoo/vespa/flags/Flags.java <ide> List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", <ide> "Set up a WireGuard endpoint on config servers", <ide> "Takes effect on configserver restart", <del> ZONE_ID, NODE_TYPE); <add> HOSTNAME); <ide> <ide> public static final UnboundBooleanFlag USE_WIREGUARD_ON_TENANT_HOSTS = defineFeatureFlag( <ide> "use-wireguard-on-tenant-hosts", false,
Java
agpl-3.0
1a4e0fde67fe206e70645b3e158c8fa1c652a5fc
0
TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil
package nl.mpi.arbil.importexport; import nl.mpi.arbil.*; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.tree.DefaultMutableTreeNode; import nl.mpi.arbil.MetadataFile.MetadataUtils; import nl.mpi.arbil.data.ImdiLoader; /** * Document : ImportExportDialog * Created on : * @author [email protected] */ public class ImportExportDialog { private JDialog searchDialog; private JPanel searchPanel; private JPanel inputNodePanel; private JPanel outputNodePanel; private JCheckBox copyFilesCheckBox; private JCheckBox renameFileToNodeName; private JCheckBox renameFileToLamusFriendlyName; private JCheckBox detailsCheckBox; private JCheckBox overwriteCheckBox; private JCheckBox shibbolethCheckBox; private JPanel shibbolethPanel; // private JProgressBar resourceProgressBar; private JLabel resourceProgressLabel; private JProgressBar progressBar; private JLabel diskSpaceLabel; JPanel detailsPanel; JPanel bottomPanel; private JLabel progressFoundLabel; private JLabel progressProcessedLabel; private JLabel progressAlreadyInCacheLabel; private JLabel progressFailedLabel; private JLabel progressXmlErrorsLabel; private JLabel resourceCopyErrorsLabel; private JButton showInTableButton; String progressFoundLabelText = "Total Metadata Files Found: "; String progressProcessedLabelText = "Total Metadata Files Processed: "; String progressAlreadyInCacheLabelText = "Metadata Files already in Local Corpus: "; String progressFailedLabelText = "Metadata File Copy Errors: "; String progressXmlErrorsLabelText = "Metadata File Validation Errors: "; String resourceCopyErrorsLabelText = "Resource File Copy Errors: "; String diskFreeLabelText = "Total Disk Free: "; private JButton stopButton; private JButton startButton; private JTabbedPane detailsTabPane; private JTextArea taskOutput; private JTextArea xmlOutput; private JTextArea resourceCopyOutput; // variables used but the search thread // variables used by the copy thread // variables used by all threads private boolean stopSearch = false; private Vector selectedNodes; ImdiTreeObject destinationNode = null; File exportDestinationDirectory = null; DownloadAbortFlag downloadAbortFlag = new DownloadAbortFlag(); ShibbolethNegotiator shibbolethNegotiator = null; Vector<URI> validationErrors = new Vector<URI>(); Vector<URI> metaDataCopyErrors = new Vector<URI>(); Vector<URI> fileCopyErrors = new Vector<URI>(); private void setNodesPanel(ImdiTreeObject selectedNode, JPanel nodePanel) { JLabel currentLabel = new JLabel(selectedNode.toString(), selectedNode.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } private void setNodesPanel(Vector selectedNodes, JPanel nodePanel) { // setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS)); // nodePanel.setLayout(new java.awt.GridLayout()); // add(nodePanel); for (Enumeration<ImdiTreeObject> selectedNodesEnum = selectedNodes.elements(); selectedNodesEnum.hasMoreElements();) { ImdiTreeObject currentNode = selectedNodesEnum.nextElement(); JLabel currentLabel = new JLabel(currentNode.toString(), currentNode.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } } private void setLocalCacheToNodesPanel(JPanel nodePanel) { DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) TreeHelper.getSingleInstance().localCorpusTreeModel.getRoot(); JLabel rootNodeLabel = (JLabel) rootNode.getUserObject(); JLabel currentLabel = new JLabel(rootNodeLabel.getText(), rootNodeLabel.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } private void setLocalFileToNodesPanel(JPanel nodePanel, File destinationDirectory) { DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) TreeHelper.getSingleInstance().localDirectoryTreeModel.getRoot(); JLabel rootNodeLabel = (JLabel) rootNode.getUserObject(); JLabel currentLabel = new JLabel(destinationDirectory.getPath(), rootNodeLabel.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } public void importImdiBranch() { File[] selectedFiles = LinorgWindowManager.getSingleInstance().showFileSelectBox("Import", false, true, true); if (selectedFiles != null) { Vector importNodeVector = new Vector(); for (File currentFile : selectedFiles) { ImdiTreeObject imdiToImport = ImdiLoader.getSingleInstance().getImdiObject(null, currentFile.toURI()); importNodeVector.add(imdiToImport); } copyToCache(importNodeVector); } } public void selectExportDirectoryAndExport(ImdiTreeObject[] localCorpusSelectedNodes) { // make sure the chosen directory is empty // export the tree, maybe adjusting resource links so that resource files do not need to be copied searchDialog.setTitle("Export Branch"); File destinationDirectory = LinorgWindowManager.getSingleInstance().showEmptyExportDirectoryDialogue(searchDialog.getTitle()); if (destinationDirectory != null) { exportFromCache(new Vector(Arrays.asList(localCorpusSelectedNodes)), destinationDirectory); } } private void exportFromCache(Vector localSelectedNodes, File destinationDirectory) { selectedNodes = localSelectedNodes; // searchDialog.setTitle("Export Branch"); if (!selectedNodesContainImdi()) { JOptionPane.showMessageDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "No relevant nodes are selected", searchDialog.getTitle(), JOptionPane.PLAIN_MESSAGE); return; } setNodesPanel(selectedNodes, inputNodePanel); setLocalFileToNodesPanel(outputNodePanel, destinationDirectory); //String mirrorNameString = JOptionPane.showInputDialog(destinationComp, "Enter a tile for the local mirror"); exportDestinationDirectory = destinationDirectory; searchDialog.setVisible(true); } public void copyToCache(ImdiTreeObject[] localSelectedNodes) { copyToCache(new Vector(Arrays.asList(localSelectedNodes))); } // sets the destination branch for the imported nodes public void setDestinationNode(ImdiTreeObject localDestinationNode) { destinationNode = localDestinationNode; setNodesPanel(destinationNode, outputNodePanel); } public void copyToCache(Vector localSelectedNodes) { selectedNodes = localSelectedNodes; searchDialog.setTitle("Import Branch"); if (!selectedNodesContainImdi()) { JOptionPane.showMessageDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "No relevant nodes are selected", searchDialog.getTitle(), JOptionPane.PLAIN_MESSAGE); return; } setNodesPanel(selectedNodes, inputNodePanel); if (destinationNode == null) { setLocalCacheToNodesPanel(outputNodePanel); } searchDialog.setVisible(true); } private boolean selectedNodesContainImdi() { Enumeration selectedNodesEnum = selectedNodes.elements(); while (selectedNodesEnum.hasMoreElements()) { if (selectedNodesEnum.nextElement() instanceof ImdiTreeObject) { return true; } } return false; } private void showDetails(boolean showFlag) { // showFlag is false the first time this is called when the dialog is initialised so we need to make sure that pack gets called in this case // otherwise try to prevent chenging the window size when not required if (!showFlag || detailsTabPane.isVisible() != showFlag) { detailsTabPane.setVisible(showFlag); bottomPanel.setVisible(showFlag); copyFilesCheckBox.setVisible(showFlag); renameFileToNodeName.setVisible(showFlag && exportDestinationDirectory != null); renameFileToLamusFriendlyName.setVisible(showFlag && exportDestinationDirectory != null); overwriteCheckBox.setVisible(showFlag && exportDestinationDirectory == null); //shibbolethCheckBox.setVisible(showFlag && exportDestinationDirectory == null); shibbolethPanel.setVisible(showFlag/* && shibbolethCheckBox.isSelected()*/); outputNodePanel.setVisible(false); inputNodePanel.setVisible(false); // searchDialog.pack(); outputNodePanel.setVisible(true); inputNodePanel.setVisible(true); } } // the targetComponent is used to place the import dialog public ImportExportDialog(Component targetComponent) throws Exception { LinorgWindowManager.getSingleInstance().offerUserToSaveChanges(); searchDialog = new JDialog(JOptionPane.getFrameForComponent(LinorgWindowManager.getSingleInstance().linorgFrame), true); searchDialog.addWindowStateListener(new WindowAdapter() { @Override public void windowStateChanged(WindowEvent e) { if ((e.getNewState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) { detailsCheckBox.setSelected(true); showDetails(true); } else { searchDialog.pack(); } } }); //searchDialog.setUndecorated(true); searchDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stopSearch = true; downloadAbortFlag.abortDownload = true; // while (threadARunning || threadBRunning) { // try { // Thread.sleep(100); // } catch (InterruptedException ignore) { // GuiHelper.linorgBugCatcher.logError(ignore); // } // } // GuiHelper.linorgWindowManager.linorgFrame.requestFocusInWindow(); } }); searchPanel = new JPanel(); searchPanel.setLayout(new BorderLayout()); //searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.PAGE_AXIS)); searchDialog.getContentPane().setLayout(new BorderLayout()); searchDialog.add(searchPanel, BorderLayout.CENTER); JPanel inOutNodePanel = new JPanel(); inOutNodePanel.setLayout(new BoxLayout(inOutNodePanel, BoxLayout.PAGE_AXIS)); JPanel inputNodeLabelPanel = new JPanel(); inputNodeLabelPanel.setLayout(new BorderLayout()); inputNodePanel = new JPanel(); inputNodePanel.setLayout(new java.awt.GridLayout()); inputNodeLabelPanel.add(new JLabel("From: "), BorderLayout.LINE_START); inputNodeLabelPanel.add(inputNodePanel, BorderLayout.CENTER); inOutNodePanel.add(inputNodeLabelPanel); JPanel outputNodeLabelPanel = new JPanel(); outputNodeLabelPanel.setLayout(new BorderLayout()); outputNodePanel = new JPanel(); outputNodePanel.setLayout(new java.awt.GridLayout()); outputNodeLabelPanel.add(new JLabel("To: "), BorderLayout.LINE_START); outputNodeLabelPanel.add(outputNodePanel, BorderLayout.CENTER); inOutNodePanel.add(outputNodeLabelPanel); detailsCheckBox = new JCheckBox("Show Details", false); detailsCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { showDetails(detailsCheckBox.isSelected()); searchDialog.pack(); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); JPanel detailsCheckBoxPanel = new JPanel(); detailsCheckBoxPanel.setLayout(new java.awt.GridLayout()); detailsCheckBoxPanel.add(detailsCheckBox); inOutNodePanel.add(detailsCheckBoxPanel); searchPanel.add(inOutNodePanel, BorderLayout.NORTH); detailsPanel = new JPanel(); detailsPanel.setLayout(new BoxLayout(detailsPanel, BoxLayout.PAGE_AXIS)); copyFilesCheckBox = new JCheckBox("Copy Resource Files (if available)", false); renameFileToNodeName = new JCheckBox("Rename Metadata Files (to match local corpus tree names)", true); renameFileToLamusFriendlyName = new JCheckBox("Limit Characters in File Names (LAMUS friendly format)", true); overwriteCheckBox = new JCheckBox("Overwrite Local Changes", false); shibbolethCheckBox = new JCheckBox("Shibboleth authentication via the SURFnet method", false); shibbolethPanel = new JPanel(); shibbolethCheckBox.setVisible(false); shibbolethPanel.setVisible(false); shibbolethCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (shibbolethCheckBox.isSelected()) { if (shibbolethNegotiator == null) { shibbolethNegotiator = new ShibbolethNegotiator(); } shibbolethPanel.add(shibbolethNegotiator.getControlls()); } else { shibbolethPanel.removeAll(); shibbolethNegotiator = null; } searchDialog.pack(); } }); copyFilesCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { shibbolethCheckBox.setVisible(copyFilesCheckBox.isSelected()); shibbolethPanel.setVisible(copyFilesCheckBox.isSelected()); searchDialog.pack(); } }); // JPanel copyFilesCheckBoxPanel = new JPanel(); // copyFilesCheckBoxPanel.setLayout(new BoxLayout(copyFilesCheckBoxPanel, BoxLayout.X_AXIS)); // copyFilesCheckBoxPanel.add(copyFilesCheckBox); // copyFilesCheckBoxPanel.add(new JPanel()); // detailsPanel.add(copyFilesCheckBoxPanel, BorderLayout.NORTH); detailsPanel.add(renameFileToNodeName, BorderLayout.NORTH); detailsPanel.add(renameFileToLamusFriendlyName, BorderLayout.NORTH); detailsPanel.add(overwriteCheckBox, BorderLayout.NORTH); detailsPanel.add(copyFilesCheckBox, BorderLayout.NORTH); detailsPanel.add(shibbolethCheckBox, BorderLayout.NORTH); detailsPanel.add(shibbolethPanel, BorderLayout.NORTH); // detailsPanel.add(new JPanel()); detailsTabPane = new JTabbedPane(); taskOutput = new JTextArea(5, 20); taskOutput.setMargin(new Insets(5, 5, 5, 5)); taskOutput.setEditable(false); detailsTabPane.add("Process Details", new JScrollPane(taskOutput)); xmlOutput = new JTextArea(5, 20); xmlOutput.setMargin(new Insets(5, 5, 5, 5)); xmlOutput.setEditable(false); detailsTabPane.add("Validation Errors", new JScrollPane(xmlOutput)); resourceCopyOutput = new JTextArea(5, 20); resourceCopyOutput.setMargin(new Insets(5, 5, 5, 5)); resourceCopyOutput.setEditable(false); detailsTabPane.add("Resource Copy Errors", new JScrollPane(resourceCopyOutput)); detailsPanel.add(detailsTabPane, BorderLayout.CENTER); bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS)); progressFoundLabel = new JLabel(progressFoundLabelText); progressProcessedLabel = new JLabel(progressProcessedLabelText); progressAlreadyInCacheLabel = new JLabel(progressAlreadyInCacheLabelText); progressFailedLabel = new JLabel(progressFailedLabelText); progressXmlErrorsLabel = new JLabel(progressXmlErrorsLabelText); resourceCopyErrorsLabel = new JLabel(resourceCopyErrorsLabelText); showInTableButton = new JButton("Show errors in table"); diskSpaceLabel = new JLabel(diskFreeLabelText); progressAlreadyInCacheLabel.setForeground(Color.darkGray); progressFailedLabel.setForeground(Color.red); progressXmlErrorsLabel.setForeground(Color.red); resourceCopyErrorsLabel.setForeground(Color.red); bottomPanel.add(progressFoundLabel); bottomPanel.add(progressProcessedLabel); bottomPanel.add(progressAlreadyInCacheLabel); bottomPanel.add(progressFailedLabel); bottomPanel.add(progressXmlErrorsLabel); bottomPanel.add(resourceCopyErrorsLabel); bottomPanel.add(showInTableButton); bottomPanel.add(diskSpaceLabel); resourceProgressLabel = new JLabel(" "); bottomPanel.add(resourceProgressLabel); // bottomPanel = new JPanel(); // bottomPanel.setLayout(new java.awt.GridLayout()); // bottomPanel.add(bottomInnerPanel); // detailsPanel.add(bottomPanel, BorderLayout.SOUTH); detailsPanel.add(bottomPanel, BorderLayout.SOUTH); searchPanel.add(detailsPanel, BorderLayout.CENTER); JPanel buttonsPanel = new JPanel(new FlowLayout()); stopButton = new JButton("Stop"); startButton = new JButton("Start"); stopButton.setEnabled(false); buttonsPanel.add(stopButton); progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setStringPainted(true); progressBar.setString(""); buttonsPanel.add(progressBar); // resourceProgressBar = new JProgressBar(0, 100); // resourceProgressBar.setValue(0); // resourceProgressBar.setStringPainted(true); // resourceProgressBar.setString(""); // buttonsPanel.add(resourceProgressBar); buttonsPanel.add(startButton); searchPanel.add(buttonsPanel, BorderLayout.SOUTH); searchDialog.setLocationRelativeTo(targetComponent); showInTableButton.setEnabled(false); showInTableButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (metaDataCopyErrors.size() > 0) { LinorgWindowManager.getSingleInstance().openFloatingTableOnce(metaDataCopyErrors.toArray(new URI[]{}), progressFailedLabelText); } if (validationErrors.size() > 0) { LinorgWindowManager.getSingleInstance().openAllChildNodesInFloatingTableOnce(validationErrors.toArray(new URI[]{}), progressXmlErrorsLabelText); } if (fileCopyErrors.size() > 0) { ImdiTableModel resourceFileErrorsTable = LinorgWindowManager.getSingleInstance().openFloatingTableOnce(fileCopyErrors.toArray(new URI[]{}), resourceCopyErrorsLabelText); //resourceFileErrorsTable.getFieldView(). resourceFileErrorsTable.addChildTypeToDisplay("MediaFiles"); resourceFileErrorsTable.addChildTypeToDisplay("WrittenResources"); } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { performCopy(); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { stopSearch = true; downloadAbortFlag.abortDownload = true; stopButton.setEnabled(false); startButton.setEnabled(false); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); taskOutput.append("The details of the import / export process will be displayed here.\n"); xmlOutput.append("When the metadata files are imported or exported they will be validated (for XML schema conformance) and any errors will be reported here.\n"); resourceCopyOutput.append("If copying of resource files is selected, any file copy errors will be reported here.\n"); //searchDialog.pack(); showDetails(detailsCheckBox.isSelected()); // showDetails no longer calls pack() searchDialog.pack(); } private void appendToTaskOutput(String lineOfText) { taskOutput.append(lineOfText + "\n"); taskOutput.setCaretPosition(taskOutput.getText().length()); } private void setUItoRunningState() { stopButton.setEnabled(true); startButton.setEnabled(false); showInTableButton.setEnabled(false); taskOutput.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); searchDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } private void setUItoStoppedState() { Toolkit.getDefaultToolkit().beep(); taskOutput.setCursor(null); searchDialog.setCursor(null); //turn off the wait cursor //appendToTaskOutput("Done!"); progressBar.setIndeterminate(false); // resourceProgressBar.setIndeterminate(false); resourceProgressLabel.setText(" "); // progressLabel.setText(""); stopButton.setEnabled(false); startButton.setEnabled(selectedNodes.size() > 0); showInTableButton.setEnabled(validationErrors.size() > 0 || metaDataCopyErrors.size() > 0 || fileCopyErrors.size() > 0); // TODO: add a close button? stopSearch = false; downloadAbortFlag.abortDownload = false; } ///////////////////////////////////// // functions called by the threads // ///////////////////////////////////// private void waitTillVisible() { // this is to prevent deadlocks between the thread starting before the dialog is showing which causes the JTextArea to appear without the frame while (!searchDialog.isVisible()) { try { Thread.sleep(100); } catch (InterruptedException ignore) { GuiHelper.linorgBugCatcher.logError(ignore); } } } private void removeEmptyDirectoryPaths(File currentDirectory, File[] destinationFile) { File[] childDirectories = currentDirectory.listFiles(); if (childDirectories != null && childDirectories.length == 1) { removeEmptyDirectoryPaths(childDirectories[0], destinationFile); if (childDirectories[0].isDirectory()) { childDirectories[0].delete(); } } else { try { File tempFile = destinationFile[0] = File.createTempFile("tmp-" + currentDirectory.getName(), "", exportDestinationDirectory); destinationFile[1] = new File(exportDestinationDirectory, currentDirectory.getName()); tempFile.delete(); if (!currentDirectory.renameTo(tempFile)) { // appendToTaskOutput("failed to tidy directory stucture"); } else { // appendToTaskOutput("tidy directory stucture done"); } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } } // private String getShallowestDirectory() { // int childrenToLoad = 0, loadedChildren = 0; // Enumeration selectedNodesEnum = selectedNodes.elements(); // while (selectedNodesEnum.hasMoreElements()) { // Object currentElement = selectedNodesEnum.nextElement(); // if (currentElement instanceof ImdiTreeObject) { // int[] tempChildCountArray = ((ImdiTreeObject) currentElement).getRecursiveChildCount(); // childrenToLoad += tempChildCountArray[0]; // loadedChildren += tempChildCountArray[1]; // } // } // return (new int[]{childrenToLoad, loadedChildren}); // } ///////////////////////////////////////// // end functions called by the threads // ///////////////////////////////////////// /////////////////////////////////////// // functions that create the threads // /////////////////////////////////////// private void performCopy() { // appendToTaskOutput("performCopy"); setUItoRunningState(); // // Set the connection timeout // System.getProperties().setProperty("sun.net.client.defaultConnectTimeout", "2000"); // System.getProperties().setProperty("sun.net.client.defaultReadTimeout", "2000"); // searchPanel.setVisible(false); new Thread("performCopy") { public void run() { // setPriority(Thread.NORM_PRIORITY - 1); boolean testFreeSpace = true; String javaVersionString = System.getProperty("java.version"); if (javaVersionString.startsWith("1.4.") || javaVersionString.startsWith("1.5.")) { testFreeSpace = false; } int freeGbWarningPoint = 3; int xsdErrors = 0; int totalLoaded = 0; int totalErrors = 0; int totalExisting = 0; int resourceCopyErrors = 0; String finalMessageString = ""; File directoryForSizeTest; if (exportDestinationDirectory != null) { directoryForSizeTest = exportDestinationDirectory; } else { directoryForSizeTest = LinorgSessionStorage.getSingleInstance().getCacheDirectory(); } if (copyFilesCheckBox.isSelected()) { resourceCopyOutput.append("'Copy Resource Files' is selected: Resource files will be downloaded where appropriate permission are granted." + "\n"); } else { resourceCopyOutput.append("'Copy Resource Files' is not selected: No resource files will be downloaded, however they will be still accessible via the web server." + "\n"); } try { // boolean saveToCache = true; // File tempFileForValidator = File.createTempFile("linorg", ".imdi"); // tempFileForValidator.deleteOnExit(); XsdChecker xsdChecker = new XsdChecker(); waitTillVisible(); // appendToTaskOutput("copying: "); progressBar.setIndeterminate(true); // resourceProgressBar.setIndeterminate(true); // int[] childCount = countChildern(); // appendToTaskOutput("corpus to load: " + childCount[0] + "corpus loaded: " + childCount[1]); class RetrievableFile { public RetrievableFile(URI sourceURILocal, File destinationDirectoryLocal) { sourceURI = sourceURILocal; destinationDirectory = destinationDirectoryLocal; } private String makeFileNameLamusFriendly(String fileNameString) { // as requested by Eric: x = x.replaceAll("[^A-Za-z0-9._-]", "_"); // keep only "nice" chars return fileNameString.replaceAll("[^A-Za-z0-9-]", "_"); // this will only be passed the file name without suffix so "." should not be allowed, also there is no point replacing "_" with "_". } public void calculateUriFileName() { if (destinationDirectory != null) { destinationFile = LinorgSessionStorage.getSingleInstance().getExportPath(sourceURI.toString(), destinationDirectory.getPath()); } else { destinationFile = LinorgSessionStorage.getSingleInstance().getSaveLocation(sourceURI.toString()); } childDestinationDirectory = destinationDirectory; } public void calculateTreeFileName(boolean lamusFriendly) { fileSuffix = sourceURI.toString().substring(sourceURI.toString().lastIndexOf(".")); ImdiTreeObject currentNode = ImdiLoader.getSingleInstance().getImdiObject(null, sourceURI); // rather than use ImdiLoader this metadata could be loaded directly and then garbaged to save memory currentNode.waitTillLoaded(); String fileNameString; if (currentNode.isMetaDataNode()) { fileNameString = currentNode.toString(); } else { String urlString = sourceURI.toString(); try { urlString = URLDecoder.decode(urlString, "UTF-8"); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(urlString, ex); appendToTaskOutput("unable to decode the file name for: " + urlString); System.out.println("unable to decode the file name for: " + urlString); } fileNameString = urlString.substring(urlString.lastIndexOf("/") + 1, urlString.lastIndexOf(".")); } fileNameString = fileNameString.replace("\\", "_"); fileNameString = fileNameString.replace("/", "_"); // other potential problem chars can be removed with the lamus friendly option, if it was done always then all non asc11 languages will be destroyed and non english like languages would be unreadable if (lamusFriendly) { fileNameString = makeFileNameLamusFriendly(fileNameString); } if (fileNameString.length() < 1) { fileNameString = "unnamed"; } destinationFile = new File(destinationDirectory, fileNameString + fileSuffix); childDestinationDirectory = new File(destinationDirectory, fileNameString); int fileCounter = 1; while (destinationFile.exists()) { if (lamusFriendly) { destinationFile = new File(destinationDirectory, fileNameString + "_" + fileCounter + fileSuffix); childDestinationDirectory = new File(destinationDirectory, fileNameString + "_" + fileCounter); } else { destinationFile = new File(destinationDirectory, fileNameString + "(" + fileCounter + ")" + fileSuffix); childDestinationDirectory = new File(destinationDirectory, fileNameString + "(" + fileCounter + ")"); } fileCounter++; } } URI sourceURI; File destinationDirectory; // if null then getSaveLocation in LinorgSessionStorage will be used File childDestinationDirectory; File destinationFile; String fileSuffix; } Enumeration selectedNodesEnum = selectedNodes.elements(); ArrayList<ImdiTreeObject> finishedTopNodes = new ArrayList<ImdiTreeObject>(); Hashtable<URI, RetrievableFile> seenFiles = new Hashtable<URI, RetrievableFile>(); ArrayList<URI> getList = new ArrayList<URI>(); // TODO: make this global so files do not get redone ArrayList<URI> doneList = new ArrayList<URI>(); while (selectedNodesEnum.hasMoreElements() && !stopSearch) { // todo: test for export keeping file names // todo: test for export when there are nodes imported from the local file system // todo: test all the options for a unusal sotrage directory // todo: and test on windows Object currentElement = selectedNodesEnum.nextElement(); if (currentElement instanceof ImdiTreeObject) { URI currentGettableUri = ((ImdiTreeObject) currentElement).getParentDomNode().getURI(); getList.add(currentGettableUri); if (!seenFiles.containsKey(currentGettableUri)) { seenFiles.put(currentGettableUri, new RetrievableFile(((ImdiTreeObject) currentElement).getParentDomNode().getURI(), exportDestinationDirectory)); } while (!stopSearch && getList.size() > 0) { RetrievableFile currentRetrievableFile = seenFiles.get(getList.remove(0)); // appendToTaskOutput(currentTarget); try { if (!doneList.contains(currentRetrievableFile.sourceURI)) { // File destinationFile; // appendToTaskOutput("connecting..."); //OurURL inUrlLocal = new OurURL(currentTarget.toURL()); // String destinationPath; // File destinationFile;// = new File(destinationPath); String journalActionString; if (exportDestinationDirectory == null) { currentRetrievableFile.calculateUriFileName(); journalActionString = "import"; } else { if (renameFileToNodeName.isSelected() && exportDestinationDirectory != null) { currentRetrievableFile.calculateTreeFileName(renameFileToLamusFriendlyName.isSelected()); } else { currentRetrievableFile.calculateUriFileName(); } journalActionString = "export"; } MetadataUtils currentMetdataUtil = ImdiTreeObject.getMetadataUtils(currentRetrievableFile.sourceURI.toString()); ArrayList<URI[]> uncopiedLinks = new ArrayList<URI[]>(); URI[] linksUriArray = currentMetdataUtil.getCorpusLinks(currentRetrievableFile.sourceURI); // appendToTaskOutput("destination path: " + destinationFile.getAbsolutePath()); // appendToTaskOutput("getting links..."); // links = ImdiTreeObject.api.getIMDILinks(nodDom, inUrlLocal, WSNodeType.CORPUS); if (linksUriArray != null) { for (int linkCount = 0; linkCount < linksUriArray.length && !stopSearch; linkCount++) { System.out.println("Link: " + linksUriArray[linkCount].toString()); String currentLink = linksUriArray[linkCount].toString(); // URI gettableLinkUri = ImdiTreeObject.conformStringToUrl(currentLink); URI gettableLinkUri = linksUriArray[linkCount].normalize(); if (!seenFiles.containsKey(gettableLinkUri)) { seenFiles.put(gettableLinkUri, new RetrievableFile(gettableLinkUri, currentRetrievableFile.childDestinationDirectory)); } RetrievableFile retrievableLink = seenFiles.get(gettableLinkUri); if (ImdiTreeObject.isPathMetadata(currentLink)) { getList.add(gettableLinkUri); if (renameFileToNodeName.isSelected() && exportDestinationDirectory != null) { retrievableLink.calculateTreeFileName(renameFileToLamusFriendlyName.isSelected()); } else { retrievableLink.calculateUriFileName(); } uncopiedLinks.add(new URI[]{linksUriArray[linkCount], retrievableLink.destinationFile.toURI()}); } else /*if (links[linkCount].getType() != null) this null also exists when a resource is local *//* filter out non resources */ { if (!copyFilesCheckBox.isSelected()) { // retrievableLink.setFileNotCopied(); uncopiedLinks.add(new URI[]{linksUriArray[linkCount], linksUriArray[linkCount]}); } else { // appendToTaskOutput("getting resource file: " + links[linkCount].getType()); // resourceCopyOutput.append("Type: " + links[linkCount].getType() + "\n"); // resourceCopyOutput.append(currentLink + "\n"); File downloadFileLocation; // todo: warning! this appears to beable to create a directory called "file:" if (exportDestinationDirectory == null) { downloadFileLocation = LinorgSessionStorage.getSingleInstance().updateCache(currentLink, shibbolethNegotiator, false, downloadAbortFlag, resourceProgressLabel); } else { if (renameFileToNodeName.isSelected() && exportDestinationDirectory != null) { retrievableLink.calculateTreeFileName(renameFileToLamusFriendlyName.isSelected()); } else { retrievableLink.calculateUriFileName(); } if (!retrievableLink.destinationFile.getParentFile().exists()) { retrievableLink.destinationFile.getParentFile().mkdirs(); } downloadFileLocation = retrievableLink.destinationFile; // System.out.println("downloadLocation: " + downloadLocation); // resourceProgressBar.setIndeterminate(false); resourceProgressLabel.setText(" "); LinorgSessionStorage.getSingleInstance().saveRemoteResource(new URL(currentLink), downloadFileLocation, shibbolethNegotiator, true, downloadAbortFlag, resourceProgressLabel); // resourceProgressBar.setIndeterminate(true); resourceProgressLabel.setText(" "); } //resourceCopyOutput.append(downloadFileLocation + "\n"); if (downloadFileLocation.exists()) { appendToTaskOutput("Downloaded resource: " + downloadFileLocation.getAbsolutePath()); //resourceCopyOutput.append("Copied " + downloadFileLocation.length() + "b\n"); uncopiedLinks.add(new URI[]{linksUriArray[linkCount], downloadFileLocation.toURI()}); } else { resourceCopyOutput.append("Download failed: " + currentLink + " \n"); //resourceCopyOutput.append("path: " + destinationFile.getAbsolutePath()); //resourceCopyOutput.append("Failed" + "\n"); fileCopyErrors.add(currentRetrievableFile.sourceURI); uncopiedLinks.add(new URI[]{linksUriArray[linkCount], linksUriArray[linkCount]}); resourceCopyErrors++; } resourceCopyOutput.setCaretPosition(resourceCopyOutput.getText().length() - 1); } // if (!resourceFileCopied) { // currentMetdataUtil.updateSingleLink(currentTarget, curr) //// ImdiTreeObject.api.changeIMDILink(nodDom, destinationUrl, links[linkCount]); // } } // System.out.println("getIMDILinks.getRawURL: " + links[linkCount].getRawURL().toString()); // SystecurrentTree.m.out.println("getIMDILinks.getURL: " + links[linkCount].getURL().toString()); } } boolean replacingExitingFile = currentRetrievableFile.destinationFile.exists() && overwriteCheckBox.isSelected(); if (currentRetrievableFile.destinationFile.exists()) { totalExisting++; } if (currentRetrievableFile.destinationFile.exists() && !overwriteCheckBox.isSelected()) { appendToTaskOutput(currentRetrievableFile.sourceURI.toString()); appendToTaskOutput("Destination already exists, skipping file: " + currentRetrievableFile.destinationFile.getAbsolutePath()); // appendToTaskOutput("this destination file already exists, skipping file"); } else { if (replacingExitingFile) { //appendToTaskOutput(currentTarget); appendToTaskOutput("Replaced: " + currentRetrievableFile.destinationFile.getAbsolutePath()); //appendToTaskOutput("replacing existing file..."); } else { // appendToTaskOutput("saving to disk..."); } // this function of the imdi.api will modify the imdi file as it saves it "(will be normalized and possibly de-domId-ed)" // this will make it dificult to determin if changes are from this function of by the user deliberatly making a chage // boolean removeIdAttributes = exportDestinationDirectory != null; ImdiTreeObject destinationNode = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(currentRetrievableFile.destinationFile.toURI()); if (destinationNode.getNeedsSaveToDisk()) { destinationNode.saveChangesToCache(true); } if (destinationNode.hasHistory()) { destinationNode.bumpHistory(); } // todo: this has been observed to download a corpus branch that links to the sub nodes on the server instead of to the disk // todo: this appears to be adding too many ../../../../../../../ and must be checked // todo: the ../../../../../ issue is caused by the imdi api, but also there are issues with the way the imdi api 'corrects' links and the use of that method must be replaced if (!currentRetrievableFile.destinationFile.getParentFile().exists()) { currentRetrievableFile.destinationFile.getParentFile().mkdir(); } currentMetdataUtil.copyMetadataFile(currentRetrievableFile.sourceURI, currentRetrievableFile.destinationFile, uncopiedLinks.toArray(new URI[][]{}), true); // ImdiTreeObject.api.writeDOM(nodDom, destinationFile, removeIdAttributes); LinorgJournal.getSingleInstance().saveJournalEntry(currentRetrievableFile.destinationFile.getAbsolutePath(), "", currentRetrievableFile.sourceURI.toString(), "", journalActionString); // validate the imdi file // appendToTaskOutput("validating"); String checkerResult; checkerResult = xsdChecker.simpleCheck(currentRetrievableFile.destinationFile, currentRetrievableFile.sourceURI); if (checkerResult != null) { xmlOutput.append(currentRetrievableFile.sourceURI.toString() + "\n"); xmlOutput.append("destination path: " + currentRetrievableFile.destinationFile.getAbsolutePath()); System.out.println("checkerResult: " + checkerResult); xmlOutput.append(checkerResult + "\n"); xmlOutput.setCaretPosition(xmlOutput.getText().length() - 1); // appendToTaskOutput(checkerResult); validationErrors.add(currentRetrievableFile.sourceURI); xsdErrors++; } // at this point the file should exist and not have been modified by the user // create hash index with server url but basedon the saved file // note that if the imdi.api has changed this file then it will not be detected // TODO: it will be best to change this to use the server api get mb5 sum when it is written // TODO: there needs to be some mechanism to check for changes on the server and update the local copy //getHash(tempFile, this.getUrl()); if (replacingExitingFile) { // appendToTaskOutput("reloading existing data"); ImdiLoader.getSingleInstance().requestReloadOnlyIfLoaded(currentRetrievableFile.destinationFile.toURI()); } // appendToTaskOutput("done"); } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(currentRetrievableFile.sourceURI.toString(), ex); totalErrors++; metaDataCopyErrors.add(currentRetrievableFile.sourceURI); appendToTaskOutput("unable to process the file: " + currentRetrievableFile.sourceURI); System.out.println("Error getting links from: " + currentRetrievableFile.sourceURI); } totalLoaded++; progressFoundLabel.setText(progressFoundLabelText + (getList.size() + totalLoaded)); progressProcessedLabel.setText(progressProcessedLabelText + totalLoaded); progressAlreadyInCacheLabel.setText(progressAlreadyInCacheLabelText + totalExisting); progressFailedLabel.setText(progressFailedLabelText + totalErrors); progressXmlErrorsLabel.setText(progressXmlErrorsLabelText + xsdErrors); resourceCopyErrorsLabel.setText(resourceCopyErrorsLabelText + resourceCopyErrors); progressBar.setString(totalLoaded + "/" + (getList.size() + totalLoaded) + " (" + (totalErrors + xsdErrors + resourceCopyErrors) + " errors)"); if (testFreeSpace) { try { int diskFreePercent = (int) (directoryForSizeTest.getFreeSpace() / directoryForSizeTest.getTotalSpace() * 100); int freeGBytes = (int) (directoryForSizeTest.getFreeSpace() / 1073741824); //diskSpaceLabel.setText("Total Disk Use: " + diskFreePercent + "%"); diskSpaceLabel.setText(diskFreeLabelText + freeGBytes + "GB"); if (freeGbWarningPoint > freeGBytes) { progressBar.setIndeterminate(false); if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "There is only " + freeGBytes + "GB free space left on the disk.\nTo you still want to continue?", searchDialog.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE)) { freeGbWarningPoint = freeGBytes - 1; } else { stopSearch = true; } progressBar.setIndeterminate(true); } } catch (Exception ex) { diskSpaceLabel.setText(diskFreeLabelText + "N/A"); testFreeSpace = false; } } // System.out.println("progressFound"+ (getList.size() + totalLoaded)); // System.out.println("progressProcessed"+ totalLoaded); // System.out.println("progressAlreadyInCache" + totalExisting); // System.out.println("progressFailed"+totalErrors); // System.out.println("progressXmlErrors" + xsdErrors); // System.out.println("resourceCopyErrors" + resourceCopyErrors); } if (exportDestinationDirectory == null) { // add the completed node to the done list File newNodeLocation = LinorgSessionStorage.getSingleInstance().getSaveLocation(((ImdiTreeObject) currentElement).getParentDomNode().getUrlString()); finishedTopNodes.add(ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(newNodeLocation.toURI())); } } } finalMessageString = finalMessageString + "Processed " + totalLoaded + " Metadata Files.\n"; if (exportDestinationDirectory == null) { // String newNodeLocation = GuiHelper.linorgSessionStorage.getSaveLocation(((ImdiTreeObject) currentElement).getUrlString()); // String newNodeLocation = ((ImdiTreeObject) currentElement).loadImdiDom(); // save the first node which will not be saved by loadSomeChildren if (!stopSearch) { // make sure we dont add an incomplete location //appendToTaskOutput("would save location when done: " + newNodeLocation); //guiHelper.addLocation("file://" + newNodeLocation); // TODO: create an imdinode to contain the name and point to the location for (ImdiTreeObject currentFinishedNode : finishedTopNodes) { if (destinationNode != null) { if (!destinationNode.getURI().equals(currentFinishedNode.getURI())) { // do not try to link a node to itself (itself is passed as the lead selection node when reimporting from the context menu) // add the nodes to their parent here destinationNode.addCorpusLink(currentFinishedNode); } } else { // add the nodes to the local corpus root node here if (!TreeHelper.getSingleInstance().addLocation(currentFinishedNode.getURI())) { // alert the user when the node already exists and cannot be added again finalMessageString = finalMessageString + "The location:\n" + currentFinishedNode + "\nalready exists and need not be added again\n"; } } // make sure that any changes are reflected in the tree currentFinishedNode.reloadNode(); } } if (destinationNode == null) { // update the tree and reload the ui // TreeHelper.getSingleInstance().reloadLocalCorpusTree(); TreeHelper.getSingleInstance().applyRootLocations(); } } // progressLabel.setText(""); progressBar.setIndeterminate(false); if (totalErrors != 0) { finalMessageString = finalMessageString + "There were " + totalErrors + " errors, some files may not have been copied.\n"; } if (xsdErrors != 0) { finalMessageString = finalMessageString + "There were " + xsdErrors + " files that failed to validate and have xml errors.\n"; } if (stopSearch) { appendToTaskOutput("copy canceled"); System.out.println("copy canceled"); finalMessageString = finalMessageString + "The process was canceled, some files may not have been copied.\n"; } else { // prevent restart selectedNodes.removeAllElements(); //TODO: prevent restart and probably make sure that done files are not redone if stopped if (exportDestinationDirectory != null) { File[] destinationFile = new File[2]; removeEmptyDirectoryPaths(exportDestinationDirectory, destinationFile); destinationFile[0].renameTo(destinationFile[1]); } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); finalMessageString = finalMessageString + "There was a critical error."; } // finalMessageString = finalMessageString + totalLoaded + " files have been copied.\n"; setUItoStoppedState(); System.out.println("finalMessageString: " + finalMessageString); Object[] options = {"Close", "Details"}; int detailsOption = JOptionPane.showOptionDialog(LinorgWindowManager.getSingleInstance().linorgFrame, finalMessageString, searchDialog.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (detailsOption == 0) { searchDialog.setVisible(false); } else { if (!detailsCheckBox.isSelected()) { detailsCheckBox.setSelected(true); showDetails(true); searchDialog.pack(); } } if (exportDestinationDirectory != null) { GuiHelper.getSingleInstance().openFileInExternalApplication(exportDestinationDirectory.toURI()); } } }.start(); } /////////////////////////////////////////// // end functions that create the threads // /////////////////////////////////////////// }
src/nl/mpi/arbil/importexport/ImportExportDialog.java
package nl.mpi.arbil.importexport; import nl.mpi.arbil.*; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.tree.DefaultMutableTreeNode; import nl.mpi.arbil.MetadataFile.MetadataUtils; import nl.mpi.arbil.data.ImdiLoader; /** * Document : ImportExportDialog * Created on : * @author [email protected] */ public class ImportExportDialog { private JDialog searchDialog; private JPanel searchPanel; private JPanel inputNodePanel; private JPanel outputNodePanel; private JCheckBox copyFilesCheckBox; private JCheckBox renameFileToNodeName; private JCheckBox renameFileToLamusFriendlyName; private JCheckBox detailsCheckBox; private JCheckBox overwriteCheckBox; private JCheckBox shibbolethCheckBox; private JPanel shibbolethPanel; // private JProgressBar resourceProgressBar; private JLabel resourceProgressLabel; private JProgressBar progressBar; private JLabel diskSpaceLabel; JPanel detailsPanel; JPanel bottomPanel; private JLabel progressFoundLabel; private JLabel progressProcessedLabel; private JLabel progressAlreadyInCacheLabel; private JLabel progressFailedLabel; private JLabel progressXmlErrorsLabel; private JLabel resourceCopyErrorsLabel; private JButton showInTableButton; String progressFoundLabelText = "Total Metadata Files Found: "; String progressProcessedLabelText = "Total Metadata Files Processed: "; String progressAlreadyInCacheLabelText = "Metadata Files already in Local Corpus: "; String progressFailedLabelText = "Metadata File Copy Errors: "; String progressXmlErrorsLabelText = "Metadata File Validation Errors: "; String resourceCopyErrorsLabelText = "Resource File Copy Errors: "; String diskFreeLabelText = "Total Disk Free: "; private JButton stopButton; private JButton startButton; private JTabbedPane detailsTabPane; private JTextArea taskOutput; private JTextArea xmlOutput; private JTextArea resourceCopyOutput; // variables used but the search thread // variables used by the copy thread // variables used by all threads private boolean stopSearch = false; private Vector selectedNodes; ImdiTreeObject destinationNode = null; File exportDestinationDirectory = null; DownloadAbortFlag downloadAbortFlag = new DownloadAbortFlag(); ShibbolethNegotiator shibbolethNegotiator = null; Vector<URI> validationErrors = new Vector<URI>(); Vector<URI> metaDataCopyErrors = new Vector<URI>(); Vector<URI> fileCopyErrors = new Vector<URI>(); private void setNodesPanel(ImdiTreeObject selectedNode, JPanel nodePanel) { JLabel currentLabel = new JLabel(selectedNode.toString(), selectedNode.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } private void setNodesPanel(Vector selectedNodes, JPanel nodePanel) { // setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS)); // nodePanel.setLayout(new java.awt.GridLayout()); // add(nodePanel); for (Enumeration<ImdiTreeObject> selectedNodesEnum = selectedNodes.elements(); selectedNodesEnum.hasMoreElements();) { ImdiTreeObject currentNode = selectedNodesEnum.nextElement(); JLabel currentLabel = new JLabel(currentNode.toString(), currentNode.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } } private void setLocalCacheToNodesPanel(JPanel nodePanel) { DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) TreeHelper.getSingleInstance().localCorpusTreeModel.getRoot(); JLabel rootNodeLabel = (JLabel) rootNode.getUserObject(); JLabel currentLabel = new JLabel(rootNodeLabel.getText(), rootNodeLabel.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } private void setLocalFileToNodesPanel(JPanel nodePanel, File destinationDirectory) { DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) TreeHelper.getSingleInstance().localDirectoryTreeModel.getRoot(); JLabel rootNodeLabel = (JLabel) rootNode.getUserObject(); JLabel currentLabel = new JLabel(destinationDirectory.getPath(), rootNodeLabel.getIcon(), JLabel.CENTER); nodePanel.add(currentLabel); } public void importImdiBranch() { File[] selectedFiles = LinorgWindowManager.getSingleInstance().showFileSelectBox("Import", false, true, true); if (selectedFiles != null) { Vector importNodeVector = new Vector(); for (File currentFile : selectedFiles) { ImdiTreeObject imdiToImport = ImdiLoader.getSingleInstance().getImdiObject(null, currentFile.toURI()); importNodeVector.add(imdiToImport); } copyToCache(importNodeVector); } } public void selectExportDirectoryAndExport(ImdiTreeObject[] localCorpusSelectedNodes) { // make sure the chosen directory is empty // export the tree, maybe adjusting resource links so that resource files do not need to be copied searchDialog.setTitle("Export Branch"); File destinationDirectory = LinorgWindowManager.getSingleInstance().showEmptyExportDirectoryDialogue(searchDialog.getTitle()); if (destinationDirectory != null) { exportFromCache(new Vector(Arrays.asList(localCorpusSelectedNodes)), destinationDirectory); } } private void exportFromCache(Vector localSelectedNodes, File destinationDirectory) { selectedNodes = localSelectedNodes; // searchDialog.setTitle("Export Branch"); if (!selectedNodesContainImdi()) { JOptionPane.showMessageDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "No relevant nodes are selected", searchDialog.getTitle(), JOptionPane.PLAIN_MESSAGE); return; } setNodesPanel(selectedNodes, inputNodePanel); setLocalFileToNodesPanel(outputNodePanel, destinationDirectory); //String mirrorNameString = JOptionPane.showInputDialog(destinationComp, "Enter a tile for the local mirror"); exportDestinationDirectory = destinationDirectory; searchDialog.setVisible(true); } public void copyToCache(ImdiTreeObject[] localSelectedNodes) { copyToCache(new Vector(Arrays.asList(localSelectedNodes))); } // sets the destination branch for the imported nodes public void setDestinationNode(ImdiTreeObject localDestinationNode) { destinationNode = localDestinationNode; setNodesPanel(destinationNode, outputNodePanel); } public void copyToCache(Vector localSelectedNodes) { selectedNodes = localSelectedNodes; searchDialog.setTitle("Import Branch"); if (!selectedNodesContainImdi()) { JOptionPane.showMessageDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "No relevant nodes are selected", searchDialog.getTitle(), JOptionPane.PLAIN_MESSAGE); return; } setNodesPanel(selectedNodes, inputNodePanel); if (destinationNode == null) { setLocalCacheToNodesPanel(outputNodePanel); } searchDialog.setVisible(true); } private boolean selectedNodesContainImdi() { Enumeration selectedNodesEnum = selectedNodes.elements(); while (selectedNodesEnum.hasMoreElements()) { if (selectedNodesEnum.nextElement() instanceof ImdiTreeObject) { return true; } } return false; } private void showDetails(boolean showFlag) { // showFlag is false the first time this is called when the dialog is initialised so we need to make sure that pack gets called in this case // otherwise try to prevent chenging the window size when not required if (!showFlag || detailsTabPane.isVisible() != showFlag) { detailsTabPane.setVisible(showFlag); bottomPanel.setVisible(showFlag); copyFilesCheckBox.setVisible(showFlag); renameFileToNodeName.setVisible(showFlag && exportDestinationDirectory != null); renameFileToLamusFriendlyName.setVisible(showFlag && exportDestinationDirectory != null); overwriteCheckBox.setVisible(showFlag && exportDestinationDirectory == null); //shibbolethCheckBox.setVisible(showFlag && exportDestinationDirectory == null); shibbolethPanel.setVisible(showFlag/* && shibbolethCheckBox.isSelected()*/); outputNodePanel.setVisible(false); inputNodePanel.setVisible(false); // searchDialog.pack(); outputNodePanel.setVisible(true); inputNodePanel.setVisible(true); } } // the targetComponent is used to place the import dialog public ImportExportDialog(Component targetComponent) throws Exception { LinorgWindowManager.getSingleInstance().offerUserToSaveChanges(); searchDialog = new JDialog(JOptionPane.getFrameForComponent(LinorgWindowManager.getSingleInstance().linorgFrame), true); searchDialog.addWindowStateListener(new WindowAdapter() { @Override public void windowStateChanged(WindowEvent e) { if ((e.getNewState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) { detailsCheckBox.setSelected(true); showDetails(true); } else { searchDialog.pack(); } } }); //searchDialog.setUndecorated(true); searchDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stopSearch = true; downloadAbortFlag.abortDownload = true; // while (threadARunning || threadBRunning) { // try { // Thread.sleep(100); // } catch (InterruptedException ignore) { // GuiHelper.linorgBugCatcher.logError(ignore); // } // } // GuiHelper.linorgWindowManager.linorgFrame.requestFocusInWindow(); } }); searchPanel = new JPanel(); searchPanel.setLayout(new BorderLayout()); //searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.PAGE_AXIS)); searchDialog.getContentPane().setLayout(new BorderLayout()); searchDialog.add(searchPanel, BorderLayout.CENTER); JPanel inOutNodePanel = new JPanel(); inOutNodePanel.setLayout(new BoxLayout(inOutNodePanel, BoxLayout.PAGE_AXIS)); JPanel inputNodeLabelPanel = new JPanel(); inputNodeLabelPanel.setLayout(new BorderLayout()); inputNodePanel = new JPanel(); inputNodePanel.setLayout(new java.awt.GridLayout()); inputNodeLabelPanel.add(new JLabel("From: "), BorderLayout.LINE_START); inputNodeLabelPanel.add(inputNodePanel, BorderLayout.CENTER); inOutNodePanel.add(inputNodeLabelPanel); JPanel outputNodeLabelPanel = new JPanel(); outputNodeLabelPanel.setLayout(new BorderLayout()); outputNodePanel = new JPanel(); outputNodePanel.setLayout(new java.awt.GridLayout()); outputNodeLabelPanel.add(new JLabel("To: "), BorderLayout.LINE_START); outputNodeLabelPanel.add(outputNodePanel, BorderLayout.CENTER); inOutNodePanel.add(outputNodeLabelPanel); detailsCheckBox = new JCheckBox("Show Details", false); detailsCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { showDetails(detailsCheckBox.isSelected()); searchDialog.pack(); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); JPanel detailsCheckBoxPanel = new JPanel(); detailsCheckBoxPanel.setLayout(new java.awt.GridLayout()); detailsCheckBoxPanel.add(detailsCheckBox); inOutNodePanel.add(detailsCheckBoxPanel); searchPanel.add(inOutNodePanel, BorderLayout.NORTH); detailsPanel = new JPanel(); detailsPanel.setLayout(new BoxLayout(detailsPanel, BoxLayout.PAGE_AXIS)); copyFilesCheckBox = new JCheckBox("Copy Resource Files (if available)", false); renameFileToNodeName = new JCheckBox("Rename Metadata Files (to match local corpus tree names)", true); renameFileToLamusFriendlyName = new JCheckBox("Limit Characters in File Names (LAMUS friendly format)", false); overwriteCheckBox = new JCheckBox("Overwrite Local Changes", false); shibbolethCheckBox = new JCheckBox("Shibboleth authentication via the SURFnet method", false); shibbolethPanel = new JPanel(); shibbolethCheckBox.setVisible(false); shibbolethPanel.setVisible(false); shibbolethCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (shibbolethCheckBox.isSelected()) { if (shibbolethNegotiator == null) { shibbolethNegotiator = new ShibbolethNegotiator(); } shibbolethPanel.add(shibbolethNegotiator.getControlls()); } else { shibbolethPanel.removeAll(); shibbolethNegotiator = null; } searchDialog.pack(); } }); copyFilesCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { shibbolethCheckBox.setVisible(copyFilesCheckBox.isSelected()); shibbolethPanel.setVisible(copyFilesCheckBox.isSelected()); searchDialog.pack(); } }); // JPanel copyFilesCheckBoxPanel = new JPanel(); // copyFilesCheckBoxPanel.setLayout(new BoxLayout(copyFilesCheckBoxPanel, BoxLayout.X_AXIS)); // copyFilesCheckBoxPanel.add(copyFilesCheckBox); // copyFilesCheckBoxPanel.add(new JPanel()); // detailsPanel.add(copyFilesCheckBoxPanel, BorderLayout.NORTH); detailsPanel.add(renameFileToNodeName, BorderLayout.NORTH); detailsPanel.add(renameFileToLamusFriendlyName, BorderLayout.NORTH); detailsPanel.add(overwriteCheckBox, BorderLayout.NORTH); detailsPanel.add(copyFilesCheckBox, BorderLayout.NORTH); detailsPanel.add(shibbolethCheckBox, BorderLayout.NORTH); detailsPanel.add(shibbolethPanel, BorderLayout.NORTH); // detailsPanel.add(new JPanel()); detailsTabPane = new JTabbedPane(); taskOutput = new JTextArea(5, 20); taskOutput.setMargin(new Insets(5, 5, 5, 5)); taskOutput.setEditable(false); detailsTabPane.add("Process Details", new JScrollPane(taskOutput)); xmlOutput = new JTextArea(5, 20); xmlOutput.setMargin(new Insets(5, 5, 5, 5)); xmlOutput.setEditable(false); detailsTabPane.add("Validation Errors", new JScrollPane(xmlOutput)); resourceCopyOutput = new JTextArea(5, 20); resourceCopyOutput.setMargin(new Insets(5, 5, 5, 5)); resourceCopyOutput.setEditable(false); detailsTabPane.add("Resource Copy Errors", new JScrollPane(resourceCopyOutput)); detailsPanel.add(detailsTabPane, BorderLayout.CENTER); bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS)); progressFoundLabel = new JLabel(progressFoundLabelText); progressProcessedLabel = new JLabel(progressProcessedLabelText); progressAlreadyInCacheLabel = new JLabel(progressAlreadyInCacheLabelText); progressFailedLabel = new JLabel(progressFailedLabelText); progressXmlErrorsLabel = new JLabel(progressXmlErrorsLabelText); resourceCopyErrorsLabel = new JLabel(resourceCopyErrorsLabelText); showInTableButton = new JButton("Show errors in table"); diskSpaceLabel = new JLabel(diskFreeLabelText); progressAlreadyInCacheLabel.setForeground(Color.darkGray); progressFailedLabel.setForeground(Color.red); progressXmlErrorsLabel.setForeground(Color.red); resourceCopyErrorsLabel.setForeground(Color.red); bottomPanel.add(progressFoundLabel); bottomPanel.add(progressProcessedLabel); bottomPanel.add(progressAlreadyInCacheLabel); bottomPanel.add(progressFailedLabel); bottomPanel.add(progressXmlErrorsLabel); bottomPanel.add(resourceCopyErrorsLabel); bottomPanel.add(showInTableButton); bottomPanel.add(diskSpaceLabel); resourceProgressLabel = new JLabel(" "); bottomPanel.add(resourceProgressLabel); // bottomPanel = new JPanel(); // bottomPanel.setLayout(new java.awt.GridLayout()); // bottomPanel.add(bottomInnerPanel); // detailsPanel.add(bottomPanel, BorderLayout.SOUTH); detailsPanel.add(bottomPanel, BorderLayout.SOUTH); searchPanel.add(detailsPanel, BorderLayout.CENTER); JPanel buttonsPanel = new JPanel(new FlowLayout()); stopButton = new JButton("Stop"); startButton = new JButton("Start"); stopButton.setEnabled(false); buttonsPanel.add(stopButton); progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setStringPainted(true); progressBar.setString(""); buttonsPanel.add(progressBar); // resourceProgressBar = new JProgressBar(0, 100); // resourceProgressBar.setValue(0); // resourceProgressBar.setStringPainted(true); // resourceProgressBar.setString(""); // buttonsPanel.add(resourceProgressBar); buttonsPanel.add(startButton); searchPanel.add(buttonsPanel, BorderLayout.SOUTH); searchDialog.setLocationRelativeTo(targetComponent); showInTableButton.setEnabled(false); showInTableButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (metaDataCopyErrors.size() > 0) { LinorgWindowManager.getSingleInstance().openFloatingTableOnce(metaDataCopyErrors.toArray(new URI[]{}), progressFailedLabelText); } if (validationErrors.size() > 0) { LinorgWindowManager.getSingleInstance().openAllChildNodesInFloatingTableOnce(validationErrors.toArray(new URI[]{}), progressXmlErrorsLabelText); } if (fileCopyErrors.size() > 0) { ImdiTableModel resourceFileErrorsTable = LinorgWindowManager.getSingleInstance().openFloatingTableOnce(fileCopyErrors.toArray(new URI[]{}), resourceCopyErrorsLabelText); //resourceFileErrorsTable.getFieldView(). resourceFileErrorsTable.addChildTypeToDisplay("MediaFiles"); resourceFileErrorsTable.addChildTypeToDisplay("WrittenResources"); } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { performCopy(); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { stopSearch = true; downloadAbortFlag.abortDownload = true; stopButton.setEnabled(false); startButton.setEnabled(false); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); taskOutput.append("The details of the import / export process will be displayed here.\n"); xmlOutput.append("When the metadata files are imported or exported they will be validated (for XML schema conformance) and any errors will be reported here.\n"); resourceCopyOutput.append("If copying of resource files is selected, any file copy errors will be reported here.\n"); //searchDialog.pack(); showDetails(detailsCheckBox.isSelected()); // showDetails no longer calls pack() searchDialog.pack(); } private void appendToTaskOutput(String lineOfText) { taskOutput.append(lineOfText + "\n"); taskOutput.setCaretPosition(taskOutput.getText().length()); } private void setUItoRunningState() { stopButton.setEnabled(true); startButton.setEnabled(false); showInTableButton.setEnabled(false); taskOutput.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); searchDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } private void setUItoStoppedState() { Toolkit.getDefaultToolkit().beep(); taskOutput.setCursor(null); searchDialog.setCursor(null); //turn off the wait cursor //appendToTaskOutput("Done!"); progressBar.setIndeterminate(false); // resourceProgressBar.setIndeterminate(false); resourceProgressLabel.setText(" "); // progressLabel.setText(""); stopButton.setEnabled(false); startButton.setEnabled(selectedNodes.size() > 0); showInTableButton.setEnabled(validationErrors.size() > 0 || metaDataCopyErrors.size() > 0 || fileCopyErrors.size() > 0); // TODO: add a close button? stopSearch = false; downloadAbortFlag.abortDownload = false; } ///////////////////////////////////// // functions called by the threads // ///////////////////////////////////// private void waitTillVisible() { // this is to prevent deadlocks between the thread starting before the dialog is showing which causes the JTextArea to appear without the frame while (!searchDialog.isVisible()) { try { Thread.sleep(100); } catch (InterruptedException ignore) { GuiHelper.linorgBugCatcher.logError(ignore); } } } private void removeEmptyDirectoryPaths(File currentDirectory, File[] destinationFile) { File[] childDirectories = currentDirectory.listFiles(); if (childDirectories != null && childDirectories.length == 1) { removeEmptyDirectoryPaths(childDirectories[0], destinationFile); if (childDirectories[0].isDirectory()) { childDirectories[0].delete(); } } else { try { File tempFile = destinationFile[0] = File.createTempFile("tmp-" + currentDirectory.getName(), "", exportDestinationDirectory); destinationFile[1] = new File(exportDestinationDirectory, currentDirectory.getName()); tempFile.delete(); if (!currentDirectory.renameTo(tempFile)) { // appendToTaskOutput("failed to tidy directory stucture"); } else { // appendToTaskOutput("tidy directory stucture done"); } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } } // private String getShallowestDirectory() { // int childrenToLoad = 0, loadedChildren = 0; // Enumeration selectedNodesEnum = selectedNodes.elements(); // while (selectedNodesEnum.hasMoreElements()) { // Object currentElement = selectedNodesEnum.nextElement(); // if (currentElement instanceof ImdiTreeObject) { // int[] tempChildCountArray = ((ImdiTreeObject) currentElement).getRecursiveChildCount(); // childrenToLoad += tempChildCountArray[0]; // loadedChildren += tempChildCountArray[1]; // } // } // return (new int[]{childrenToLoad, loadedChildren}); // } ///////////////////////////////////////// // end functions called by the threads // ///////////////////////////////////////// /////////////////////////////////////// // functions that create the threads // /////////////////////////////////////// private void performCopy() { // appendToTaskOutput("performCopy"); setUItoRunningState(); // // Set the connection timeout // System.getProperties().setProperty("sun.net.client.defaultConnectTimeout", "2000"); // System.getProperties().setProperty("sun.net.client.defaultReadTimeout", "2000"); // searchPanel.setVisible(false); new Thread("performCopy") { public void run() { // setPriority(Thread.NORM_PRIORITY - 1); boolean testFreeSpace = true; String javaVersionString = System.getProperty("java.version"); if (javaVersionString.startsWith("1.4.") || javaVersionString.startsWith("1.5.")) { testFreeSpace = false; } int freeGbWarningPoint = 3; int xsdErrors = 0; int totalLoaded = 0; int totalErrors = 0; int totalExisting = 0; int resourceCopyErrors = 0; String finalMessageString = ""; File directoryForSizeTest; if (exportDestinationDirectory != null) { directoryForSizeTest = exportDestinationDirectory; } else { directoryForSizeTest = LinorgSessionStorage.getSingleInstance().getCacheDirectory(); } if (copyFilesCheckBox.isSelected()) { resourceCopyOutput.append("'Copy Resource Files' is selected: Resource files will be downloaded where appropriate permission are granted." + "\n"); } else { resourceCopyOutput.append("'Copy Resource Files' is not selected: No resource files will be downloaded, however they will be still accessible via the web server." + "\n"); } try { // boolean saveToCache = true; // File tempFileForValidator = File.createTempFile("linorg", ".imdi"); // tempFileForValidator.deleteOnExit(); XsdChecker xsdChecker = new XsdChecker(); waitTillVisible(); // appendToTaskOutput("copying: "); progressBar.setIndeterminate(true); // resourceProgressBar.setIndeterminate(true); // int[] childCount = countChildern(); // appendToTaskOutput("corpus to load: " + childCount[0] + "corpus loaded: " + childCount[1]); class RetrievableFile { public RetrievableFile(URI sourceURILocal, File destinationDirectoryLocal) { sourceURI = sourceURILocal; destinationDirectory = destinationDirectoryLocal; } private String makeFileNameLamusFriendly(String fileNameString) { // as requested by Eric: x = x.replaceAll("[^A-Za-z0-9._-]", "_"); // keep only "nice" chars return fileNameString.replaceAll("[^A-Za-z0-9-]", "_"); // this will only be passed the file name without suffix so "." should not be allowed, also there is no point replacing "_" with "_". } public void calculateUriFileName() { if (destinationDirectory != null) { destinationFile = LinorgSessionStorage.getSingleInstance().getExportPath(sourceURI.toString(), destinationDirectory.getPath()); } else { destinationFile = LinorgSessionStorage.getSingleInstance().getSaveLocation(sourceURI.toString()); } childDestinationDirectory = destinationDirectory; } public void calculateTreeFileName(boolean lamusFriendly) { fileSuffix = sourceURI.toString().substring(sourceURI.toString().lastIndexOf(".")); ImdiTreeObject currentNode = ImdiLoader.getSingleInstance().getImdiObject(null, sourceURI); // rather than use ImdiLoader this metadata could be loaded directly and then garbaged to save memory currentNode.waitTillLoaded(); String fileNameString; if (currentNode.isMetaDataNode()) { fileNameString = currentNode.toString(); } else { String urlString = sourceURI.toString(); try { urlString = URLDecoder.decode(urlString, "UTF-8"); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(urlString, ex); appendToTaskOutput("unable to decode the file name for: " + urlString); System.out.println("unable to decode the file name for: " + urlString); } fileNameString = urlString.substring(urlString.lastIndexOf("/") + 1, urlString.lastIndexOf(".")); } fileNameString = fileNameString.replace("\\", "_"); fileNameString = fileNameString.replace("/", "_"); // other potential problem chars can be removed with the lamus friendly option, if it was done always then all non asc11 languages will be destroyed and non english like languages would be unreadable if (lamusFriendly) { fileNameString = makeFileNameLamusFriendly(fileNameString); } if (fileNameString.length() < 1) { fileNameString = "unnamed"; } destinationFile = new File(destinationDirectory, fileNameString + fileSuffix); childDestinationDirectory = new File(destinationDirectory, fileNameString); int fileCounter = 1; while (destinationFile.exists()) { if (lamusFriendly) { destinationFile = new File(destinationDirectory, fileNameString + "_" + fileCounter + fileSuffix); childDestinationDirectory = new File(destinationDirectory, fileNameString + "_" + fileCounter); } else { destinationFile = new File(destinationDirectory, fileNameString + "(" + fileCounter + ")" + fileSuffix); childDestinationDirectory = new File(destinationDirectory, fileNameString + "(" + fileCounter + ")"); } fileCounter++; } } URI sourceURI; File destinationDirectory; // if null then getSaveLocation in LinorgSessionStorage will be used File childDestinationDirectory; File destinationFile; String fileSuffix; } Enumeration selectedNodesEnum = selectedNodes.elements(); ArrayList<ImdiTreeObject> finishedTopNodes = new ArrayList<ImdiTreeObject>(); Hashtable<URI, RetrievableFile> seenFiles = new Hashtable<URI, RetrievableFile>(); ArrayList<URI> getList = new ArrayList<URI>(); // TODO: make this global so files do not get redone ArrayList<URI> doneList = new ArrayList<URI>(); while (selectedNodesEnum.hasMoreElements() && !stopSearch) { // todo: test for export keeping file names // todo: test for export when there are nodes imported from the local file system // todo: test all the options for a unusal sotrage directory // todo: and test on windows Object currentElement = selectedNodesEnum.nextElement(); if (currentElement instanceof ImdiTreeObject) { URI currentGettableUri = ((ImdiTreeObject) currentElement).getParentDomNode().getURI(); getList.add(currentGettableUri); if (!seenFiles.containsKey(currentGettableUri)) { seenFiles.put(currentGettableUri, new RetrievableFile(((ImdiTreeObject) currentElement).getParentDomNode().getURI(), exportDestinationDirectory)); } while (!stopSearch && getList.size() > 0) { RetrievableFile currentRetrievableFile = seenFiles.get(getList.remove(0)); // appendToTaskOutput(currentTarget); try { if (!doneList.contains(currentRetrievableFile.sourceURI)) { // File destinationFile; // appendToTaskOutput("connecting..."); //OurURL inUrlLocal = new OurURL(currentTarget.toURL()); // String destinationPath; // File destinationFile;// = new File(destinationPath); String journalActionString; if (exportDestinationDirectory == null) { currentRetrievableFile.calculateUriFileName(); journalActionString = "import"; } else { if (renameFileToNodeName.isSelected() && exportDestinationDirectory != null) { currentRetrievableFile.calculateTreeFileName(renameFileToLamusFriendlyName.isSelected()); } else { currentRetrievableFile.calculateUriFileName(); } journalActionString = "export"; } MetadataUtils currentMetdataUtil = ImdiTreeObject.getMetadataUtils(currentRetrievableFile.sourceURI.toString()); ArrayList<URI[]> uncopiedLinks = new ArrayList<URI[]>(); URI[] linksUriArray = currentMetdataUtil.getCorpusLinks(currentRetrievableFile.sourceURI); // appendToTaskOutput("destination path: " + destinationFile.getAbsolutePath()); // appendToTaskOutput("getting links..."); // links = ImdiTreeObject.api.getIMDILinks(nodDom, inUrlLocal, WSNodeType.CORPUS); if (linksUriArray != null) { for (int linkCount = 0; linkCount < linksUriArray.length && !stopSearch; linkCount++) { System.out.println("Link: " + linksUriArray[linkCount].toString()); String currentLink = linksUriArray[linkCount].toString(); // URI gettableLinkUri = ImdiTreeObject.conformStringToUrl(currentLink); URI gettableLinkUri = linksUriArray[linkCount].normalize(); if (!seenFiles.containsKey(gettableLinkUri)) { seenFiles.put(gettableLinkUri, new RetrievableFile(gettableLinkUri, currentRetrievableFile.childDestinationDirectory)); } RetrievableFile retrievableLink = seenFiles.get(gettableLinkUri); if (ImdiTreeObject.isPathMetadata(currentLink)) { getList.add(gettableLinkUri); if (renameFileToNodeName.isSelected() && exportDestinationDirectory != null) { retrievableLink.calculateTreeFileName(renameFileToLamusFriendlyName.isSelected()); } else { retrievableLink.calculateUriFileName(); } uncopiedLinks.add(new URI[]{linksUriArray[linkCount], retrievableLink.destinationFile.toURI()}); } else /*if (links[linkCount].getType() != null) this null also exists when a resource is local *//* filter out non resources */ { if (!copyFilesCheckBox.isSelected()) { // retrievableLink.setFileNotCopied(); uncopiedLinks.add(new URI[]{linksUriArray[linkCount], linksUriArray[linkCount]}); } else { // appendToTaskOutput("getting resource file: " + links[linkCount].getType()); // resourceCopyOutput.append("Type: " + links[linkCount].getType() + "\n"); // resourceCopyOutput.append(currentLink + "\n"); File downloadFileLocation; // todo: warning! this appears to beable to create a directory called "file:" if (exportDestinationDirectory == null) { downloadFileLocation = LinorgSessionStorage.getSingleInstance().updateCache(currentLink, shibbolethNegotiator, false, downloadAbortFlag, resourceProgressLabel); } else { if (renameFileToNodeName.isSelected() && exportDestinationDirectory != null) { retrievableLink.calculateTreeFileName(renameFileToLamusFriendlyName.isSelected()); } else { retrievableLink.calculateUriFileName(); } if (!retrievableLink.destinationFile.getParentFile().exists()) { retrievableLink.destinationFile.getParentFile().mkdirs(); } downloadFileLocation = retrievableLink.destinationFile; // System.out.println("downloadLocation: " + downloadLocation); // resourceProgressBar.setIndeterminate(false); resourceProgressLabel.setText(" "); LinorgSessionStorage.getSingleInstance().saveRemoteResource(new URL(currentLink), downloadFileLocation, shibbolethNegotiator, true, downloadAbortFlag, resourceProgressLabel); // resourceProgressBar.setIndeterminate(true); resourceProgressLabel.setText(" "); } //resourceCopyOutput.append(downloadFileLocation + "\n"); if (downloadFileLocation.exists()) { appendToTaskOutput("Downloaded resource: " + downloadFileLocation.getAbsolutePath()); //resourceCopyOutput.append("Copied " + downloadFileLocation.length() + "b\n"); uncopiedLinks.add(new URI[]{linksUriArray[linkCount], downloadFileLocation.toURI()}); } else { resourceCopyOutput.append("Download failed: " + currentLink + " \n"); //resourceCopyOutput.append("path: " + destinationFile.getAbsolutePath()); //resourceCopyOutput.append("Failed" + "\n"); fileCopyErrors.add(currentRetrievableFile.sourceURI); uncopiedLinks.add(new URI[]{linksUriArray[linkCount], linksUriArray[linkCount]}); resourceCopyErrors++; } resourceCopyOutput.setCaretPosition(resourceCopyOutput.getText().length() - 1); } // if (!resourceFileCopied) { // currentMetdataUtil.updateSingleLink(currentTarget, curr) //// ImdiTreeObject.api.changeIMDILink(nodDom, destinationUrl, links[linkCount]); // } } // System.out.println("getIMDILinks.getRawURL: " + links[linkCount].getRawURL().toString()); // SystecurrentTree.m.out.println("getIMDILinks.getURL: " + links[linkCount].getURL().toString()); } } boolean replacingExitingFile = currentRetrievableFile.destinationFile.exists() && overwriteCheckBox.isSelected(); if (currentRetrievableFile.destinationFile.exists()) { totalExisting++; } if (currentRetrievableFile.destinationFile.exists() && !overwriteCheckBox.isSelected()) { appendToTaskOutput(currentRetrievableFile.sourceURI.toString()); appendToTaskOutput("Destination already exists, skipping file: " + currentRetrievableFile.destinationFile.getAbsolutePath()); // appendToTaskOutput("this destination file already exists, skipping file"); } else { if (replacingExitingFile) { //appendToTaskOutput(currentTarget); appendToTaskOutput("Replaced: " + currentRetrievableFile.destinationFile.getAbsolutePath()); //appendToTaskOutput("replacing existing file..."); } else { // appendToTaskOutput("saving to disk..."); } // this function of the imdi.api will modify the imdi file as it saves it "(will be normalized and possibly de-domId-ed)" // this will make it dificult to determin if changes are from this function of by the user deliberatly making a chage // boolean removeIdAttributes = exportDestinationDirectory != null; ImdiTreeObject destinationNode = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(currentRetrievableFile.destinationFile.toURI()); if (destinationNode.getNeedsSaveToDisk()) { destinationNode.saveChangesToCache(true); } if (destinationNode.hasHistory()) { destinationNode.bumpHistory(); } // todo: this has been observed to download a corpus branch that links to the sub nodes on the server instead of to the disk // todo: this appears to be adding too many ../../../../../../../ and must be checked // todo: the ../../../../../ issue is caused by the imdi api, but also there are issues with the way the imdi api 'corrects' links and the use of that method must be replaced if (!currentRetrievableFile.destinationFile.getParentFile().exists()) { currentRetrievableFile.destinationFile.getParentFile().mkdir(); } currentMetdataUtil.copyMetadataFile(currentRetrievableFile.sourceURI, currentRetrievableFile.destinationFile, uncopiedLinks.toArray(new URI[][]{}), true); // ImdiTreeObject.api.writeDOM(nodDom, destinationFile, removeIdAttributes); LinorgJournal.getSingleInstance().saveJournalEntry(currentRetrievableFile.destinationFile.getAbsolutePath(), "", currentRetrievableFile.sourceURI.toString(), "", journalActionString); // validate the imdi file // appendToTaskOutput("validating"); String checkerResult; checkerResult = xsdChecker.simpleCheck(currentRetrievableFile.destinationFile, currentRetrievableFile.sourceURI); if (checkerResult != null) { xmlOutput.append(currentRetrievableFile.sourceURI.toString() + "\n"); xmlOutput.append("destination path: " + currentRetrievableFile.destinationFile.getAbsolutePath()); System.out.println("checkerResult: " + checkerResult); xmlOutput.append(checkerResult + "\n"); xmlOutput.setCaretPosition(xmlOutput.getText().length() - 1); // appendToTaskOutput(checkerResult); validationErrors.add(currentRetrievableFile.sourceURI); xsdErrors++; } // at this point the file should exist and not have been modified by the user // create hash index with server url but basedon the saved file // note that if the imdi.api has changed this file then it will not be detected // TODO: it will be best to change this to use the server api get mb5 sum when it is written // TODO: there needs to be some mechanism to check for changes on the server and update the local copy //getHash(tempFile, this.getUrl()); if (replacingExitingFile) { // appendToTaskOutput("reloading existing data"); ImdiLoader.getSingleInstance().requestReloadOnlyIfLoaded(currentRetrievableFile.destinationFile.toURI()); } // appendToTaskOutput("done"); } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(currentRetrievableFile.sourceURI.toString(), ex); totalErrors++; metaDataCopyErrors.add(currentRetrievableFile.sourceURI); appendToTaskOutput("unable to process the file: " + currentRetrievableFile.sourceURI); System.out.println("Error getting links from: " + currentRetrievableFile.sourceURI); } totalLoaded++; progressFoundLabel.setText(progressFoundLabelText + (getList.size() + totalLoaded)); progressProcessedLabel.setText(progressProcessedLabelText + totalLoaded); progressAlreadyInCacheLabel.setText(progressAlreadyInCacheLabelText + totalExisting); progressFailedLabel.setText(progressFailedLabelText + totalErrors); progressXmlErrorsLabel.setText(progressXmlErrorsLabelText + xsdErrors); resourceCopyErrorsLabel.setText(resourceCopyErrorsLabelText + resourceCopyErrors); progressBar.setString(totalLoaded + "/" + (getList.size() + totalLoaded) + " (" + (totalErrors + xsdErrors + resourceCopyErrors) + " errors)"); if (testFreeSpace) { try { int diskFreePercent = (int) (directoryForSizeTest.getFreeSpace() / directoryForSizeTest.getTotalSpace() * 100); int freeGBytes = (int) (directoryForSizeTest.getFreeSpace() / 1073741824); //diskSpaceLabel.setText("Total Disk Use: " + diskFreePercent + "%"); diskSpaceLabel.setText(diskFreeLabelText + freeGBytes + "GB"); if (freeGbWarningPoint > freeGBytes) { progressBar.setIndeterminate(false); if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "There is only " + freeGBytes + "GB free space left on the disk.\nTo you still want to continue?", searchDialog.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE)) { freeGbWarningPoint = freeGBytes - 1; } else { stopSearch = true; } progressBar.setIndeterminate(true); } } catch (Exception ex) { diskSpaceLabel.setText(diskFreeLabelText + "N/A"); testFreeSpace = false; } } // System.out.println("progressFound"+ (getList.size() + totalLoaded)); // System.out.println("progressProcessed"+ totalLoaded); // System.out.println("progressAlreadyInCache" + totalExisting); // System.out.println("progressFailed"+totalErrors); // System.out.println("progressXmlErrors" + xsdErrors); // System.out.println("resourceCopyErrors" + resourceCopyErrors); } if (exportDestinationDirectory == null) { // add the completed node to the done list File newNodeLocation = LinorgSessionStorage.getSingleInstance().getSaveLocation(((ImdiTreeObject) currentElement).getParentDomNode().getUrlString()); finishedTopNodes.add(ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(newNodeLocation.toURI())); } } } finalMessageString = finalMessageString + "Processed " + totalLoaded + " Metadata Files.\n"; if (exportDestinationDirectory == null) { // String newNodeLocation = GuiHelper.linorgSessionStorage.getSaveLocation(((ImdiTreeObject) currentElement).getUrlString()); // String newNodeLocation = ((ImdiTreeObject) currentElement).loadImdiDom(); // save the first node which will not be saved by loadSomeChildren if (!stopSearch) { // make sure we dont add an incomplete location //appendToTaskOutput("would save location when done: " + newNodeLocation); //guiHelper.addLocation("file://" + newNodeLocation); // TODO: create an imdinode to contain the name and point to the location for (ImdiTreeObject currentFinishedNode : finishedTopNodes) { if (destinationNode != null) { if (!destinationNode.getURI().equals(currentFinishedNode.getURI())) { // do not try to link a node to itself (itself is passed as the lead selection node when reimporting from the context menu) // add the nodes to their parent here destinationNode.addCorpusLink(currentFinishedNode); } } else { // add the nodes to the local corpus root node here if (!TreeHelper.getSingleInstance().addLocation(currentFinishedNode.getURI())) { // alert the user when the node already exists and cannot be added again finalMessageString = finalMessageString + "The location:\n" + currentFinishedNode + "\nalready exists and need not be added again\n"; } } // make sure that any changes are reflected in the tree currentFinishedNode.reloadNode(); } } if (destinationNode == null) { // update the tree and reload the ui // TreeHelper.getSingleInstance().reloadLocalCorpusTree(); TreeHelper.getSingleInstance().applyRootLocations(); } } // progressLabel.setText(""); progressBar.setIndeterminate(false); if (totalErrors != 0) { finalMessageString = finalMessageString + "There were " + totalErrors + " errors, some files may not have been copied.\n"; } if (xsdErrors != 0) { finalMessageString = finalMessageString + "There were " + xsdErrors + " files that failed to validate and have xml errors.\n"; } if (stopSearch) { appendToTaskOutput("copy canceled"); System.out.println("copy canceled"); finalMessageString = finalMessageString + "The process was canceled, some files may not have been copied.\n"; } else { // prevent restart selectedNodes.removeAllElements(); //TODO: prevent restart and probably make sure that done files are not redone if stopped if (exportDestinationDirectory != null) { File[] destinationFile = new File[2]; removeEmptyDirectoryPaths(exportDestinationDirectory, destinationFile); destinationFile[0].renameTo(destinationFile[1]); } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); finalMessageString = finalMessageString + "There was a critical error."; } // finalMessageString = finalMessageString + totalLoaded + " files have been copied.\n"; setUItoStoppedState(); System.out.println("finalMessageString: " + finalMessageString); Object[] options = {"Close", "Details"}; int detailsOption = JOptionPane.showOptionDialog(LinorgWindowManager.getSingleInstance().linorgFrame, finalMessageString, searchDialog.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (detailsOption == 0) { searchDialog.setVisible(false); } else { if (!detailsCheckBox.isSelected()) { detailsCheckBox.setSelected(true); showDetails(true); searchDialog.pack(); } } if (exportDestinationDirectory != null) { GuiHelper.getSingleInstance().openFileInExternalApplication(exportDestinationDirectory.toURI()); } } }.start(); } /////////////////////////////////////////// // end functions that create the threads // /////////////////////////////////////////// }
Moved the table cell and long field editor and sub components into a separate package. Preserved the archive handles on import and export so that LAMUS knows which files are which. Added the field usage description as a heading in the long field editor. Added local caching and ability to use external xsd files for Clarin such as xml-lang. Added check for unnamed nodes when reading clarin profiles. Updated delete node to remove the deleted node from all tables when deleting from the root of the tree. Updated the delete node to also close the relevant long field editors. Added an indicator for individual file download progress (file name and bytes) to the import export dialogue. Corrected the removal of nodes and sub nodes from the tree, tables and long field editors when a node is deleted. Allowed cookies in the applet version, so that shibboleth logins will function (when not logged in the shibboleth cookies overrun the server headers hence they are normally disabled). When there is no type checker result any previous value is now kept rather than being removed. Prevented the test file that is used to test write access to the working directory being left when the application is abnormally terminated. Added function of closing any long field editors of a node when it is deleted. Corrected issue when saving from the long field editor where the freshly typed value was lost. Corrected issue when adding a description etc. where the long field editor could contain the wrong number of fields after reloading. When saving made sure that the currently edited table or long field editor stores its data first. Modified the lux17 applet page to be php and provided the logged in username to the applet. Prevented cookies being blocked when in the applet. Added a log out file menu item to the applet. Added logged in user name to the log out file menu item in the applet. Corrected typo in dialogue. Added remote corpus search. Corrected rendering issue in the search panel on Mac. Updated the required fields in the template. Added Session.References.Description as a separate template item. Added Anonyms as a separate template. Added Actors Description as a separate template. Changed Location Countries into an open vocabulary. Changed the export corpus option "LAMUS friendly format" to be set by default.
src/nl/mpi/arbil/importexport/ImportExportDialog.java
Moved the table cell and long field editor and sub components into a separate package. Preserved the archive handles on import and export so that LAMUS knows which files are which. Added the field usage description as a heading in the long field editor. Added local caching and ability to use external xsd files for Clarin such as xml-lang. Added check for unnamed nodes when reading clarin profiles. Updated delete node to remove the deleted node from all tables when deleting from the root of the tree. Updated the delete node to also close the relevant long field editors. Added an indicator for individual file download progress (file name and bytes) to the import export dialogue. Corrected the removal of nodes and sub nodes from the tree, tables and long field editors when a node is deleted. Allowed cookies in the applet version, so that shibboleth logins will function (when not logged in the shibboleth cookies overrun the server headers hence they are normally disabled). When there is no type checker result any previous value is now kept rather than being removed. Prevented the test file that is used to test write access to the working directory being left when the application is abnormally terminated. Added function of closing any long field editors of a node when it is deleted. Corrected issue when saving from the long field editor where the freshly typed value was lost. Corrected issue when adding a description etc. where the long field editor could contain the wrong number of fields after reloading. When saving made sure that the currently edited table or long field editor stores its data first. Modified the lux17 applet page to be php and provided the logged in username to the applet. Prevented cookies being blocked when in the applet. Added a log out file menu item to the applet. Added logged in user name to the log out file menu item in the applet. Corrected typo in dialogue. Added remote corpus search. Corrected rendering issue in the search panel on Mac. Updated the required fields in the template. Added Session.References.Description as a separate template item. Added Anonyms as a separate template. Added Actors Description as a separate template. Changed Location Countries into an open vocabulary. Changed the export corpus option "LAMUS friendly format" to be set by default.
<ide><path>rc/nl/mpi/arbil/importexport/ImportExportDialog.java <ide> <ide> copyFilesCheckBox = new JCheckBox("Copy Resource Files (if available)", false); <ide> renameFileToNodeName = new JCheckBox("Rename Metadata Files (to match local corpus tree names)", true); <del> renameFileToLamusFriendlyName = new JCheckBox("Limit Characters in File Names (LAMUS friendly format)", false); <add> renameFileToLamusFriendlyName = new JCheckBox("Limit Characters in File Names (LAMUS friendly format)", true); <ide> overwriteCheckBox = new JCheckBox("Overwrite Local Changes", false); <ide> shibbolethCheckBox = new JCheckBox("Shibboleth authentication via the SURFnet method", false); <ide> shibbolethPanel = new JPanel();
Java
mit
39b5efa9d073f666d2e4bb7a9ee751afaef26355
0
bugminer/bugminer,bugminer/bugminer,bugminer/bugminer,bugminer/bugminer
package de.unistuttgart.iste.rss.bugminer.scm.git; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import java.util.stream.StreamSupport; import de.unistuttgart.iste.rss.bugminer.computing.NodeConnection; import de.unistuttgart.iste.rss.bugminer.model.entities.LineChange; import de.unistuttgart.iste.rss.bugminer.model.entities.LineChangeKind; import de.unistuttgart.iste.rss.bugminer.scm.Commit; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.api.DiffCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.InvalidRemoteException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.errors.CorruptObjectException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.patch.FileHeader; import org.eclipse.jgit.patch.Patch; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.SshSessionFactory; import org.eclipse.jgit.transport.TransportGitSsh; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.PathFilter; import org.springframework.beans.factory.annotation.Autowired; import de.unistuttgart.iste.rss.bugminer.annotations.DataDirectory; import de.unistuttgart.iste.rss.bugminer.annotations.Strategy; import de.unistuttgart.iste.rss.bugminer.computing.SshConfig; import de.unistuttgart.iste.rss.bugminer.computing.SshConnection; import de.unistuttgart.iste.rss.bugminer.computing.SshConnector; import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRepo; import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRevision; import de.unistuttgart.iste.rss.bugminer.model.entities.Node; import de.unistuttgart.iste.rss.bugminer.scm.CodeRepoStrategy; import javax.sound.sampled.Line; @Strategy(type = CodeRepoStrategy.class, name = "git") public class GitStrategy implements CodeRepoStrategy { @Autowired private GitFactory gitFactory; @Autowired @DataDirectory private Path dataDir; @Autowired private SshConnector sshConnector; @Autowired private RemoteGitHelper remoteGit; protected GitStrategy() { // managed bean } @Override public void pushTo(CodeRepo repo, NodeConnection node, String remotePath, CodeRevision revision) throws IOException { initRepository(node, remotePath); Git git = open(repo); RefSpec refspec = new RefSpec() .setSource(revision.getCommitId()) .setDestination("refs/commits/" + revision.getCommitId()); SshConfig sshConfig = node.getConnection().getConfig(); // if remotePath is relative, it should be resolved against the home directory // if it is absolute, the last resolve() call removes the ~/ URI uri = sshConfig.toURIWithoutPassword().resolve("~/").resolve(remotePath); SshSessionFactory sshSessionFactory = new CustomSshConfigSessionFactory(sshConfig); CredentialsProvider credentialsProvider = null; // TODO implement password authentication try { git.push() .setRefSpecs(refspec) .setTransportConfigCallback(config -> ((TransportGitSsh) config).setSshSessionFactory(sshSessionFactory)) .setCredentialsProvider(credentialsProvider) .setRemote(uri.toString()) .call(); } catch (GitAPIException e) { throw new IOException(String.format("Unable to push %s at %s to %s", repo, revision, uri), e); } checkout(node, remotePath, revision); } private void checkout(NodeConnection node, String remotePath, CodeRevision revision) throws IOException { try (SshConnection connection = sshConnector.connect(node.getConnection().getConfig())) { remoteGit.checkoutHard(connection, remotePath, revision.getCommitId()); } } private Git open(CodeRepo repo) throws IOException { FileRepository repository = gitFactory.createFileRepository(getPath(repo).toFile()); return gitFactory.createGit(repository); } private Path getPath(CodeRepo repo) { return dataDir.resolve("scm").resolve(repo.getProject().getName()).resolve(repo.getName()); } /** * Makes sure that the repository is completely available and ready for pushTo * @param repo the repo to download */ public void download(CodeRepo repo) throws IOException { try { if (Files.exists(getPath(repo))) { open(repo).fetch().call(); return; } gitFactory.createCloneCommand() .setURI(repo.getUrl()) .setDirectory(getPath(repo).toFile()) .setBare(true) .call(); } catch (GitAPIException e) { throw new IOException(e); } } @Override public Stream<Commit> getCommits(CodeRepo repo) throws IOException { try { return StreamSupport.stream(open(repo).log().all().call().spliterator(), false) .map(c -> new Commit(c.getAuthorIdent().getName(), new CodeRevision(repo, c.getName()), c.getFullMessage(), c.getParentCount() > 1)); } catch (GitAPIException e) { throw new IOException(e); } } @Override public CodeRevision getParentRevision(CodeRevision rev) throws IOException { return new CodeRevision(rev.getCodeRepo(), open(rev.getCodeRepo()).getRepository().resolve(rev.getCommitId() + "^").getName()); } /** * Gets the line changes between two revisions in the repository * @param oldest * @param newest * @return * @throws IOException */ public List<LineChange> getDiff(CodeRevision oldest, CodeRevision newest) throws IOException { Git git = open(oldest.getCodeRepo()); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); StringBuffer buffer = new StringBuffer(); List<DiffEntry> diff = git.diff() .setOldTree(getTreeIterator(git, oldest)) .setNewTree(getTreeIterator(git, newest)) .setOutputStream(out) .call(); Patch patch = new Patch(); patch.parse(out.toByteArray(), 0, out.size()); List<LineChange> lineChanges = new ArrayList<>(); // prevent ConcurrentModificationExceptions List<FileHeader> files = new ArrayList<>(patch.getFiles()); for (FileHeader file : files) { Optional<String[]> oldFile = getBlob(git, file.getOldPath(), oldest); Optional<String[]> newFile = getBlob(git, file.getNewPath(), newest); String fileName = file.getOldPath(); if (file.getChangeType() == DiffEntry.ChangeType.ADD) { break; // for now, ignore additions because they generate huge diffs } for (Edit edit : file.toEditList()) { // deletions for (int line = edit.getBeginA(); line < edit.getEndA(); line++) { assert oldFile.isPresent() : "missing old file for " + file.getOldPath(); int deletedLine = line + 1; // line is 0-based LineChange change = new LineChange(); change.setCodeRepo(newest.getCodeRepo()); change.setFileName(fileName); change.setKind(LineChangeKind.DELETION); change.setOldLineNumber(deletedLine); if (deletedLine - 1 >= 0 && deletedLine - 1 < oldFile.get().length) { change.setLineText(oldFile.get()[deletedLine - 1]); } lineChanges.add(change); } // additions int additionBaseLine = edit.getBeginA() + 1; // beginA is 0-based for (int offset = 0; offset < edit.getLengthB(); offset++) { assert newFile.isPresent() : "missing new file for " + file.getNewPath(); LineChange change = new LineChange(); change.setCodeRepo(newest.getCodeRepo()); change.setFileName(fileName); change.setKind(LineChangeKind.ADDITION); change.setOldLineNumber(additionBaseLine); change.setNewLineNumberIndex(offset); int newFileNumber = edit.getBeginB() + offset; if (newFileNumber >= 0 && newFileNumber < newFile.get().length) { change.setLineText(newFile.get()[edit.getBeginB() + offset]); } lineChanges.add(change); } } } return lineChanges; } catch (GitAPIException e) { throw new IOException(e); } } private Optional<String[]> getBlob(Git git, String fileName, CodeRevision revision) throws IOException { TreeWalk treeWalk = new TreeWalk(git.getRepository()); treeWalk.addTree(getTreeIterator(git, revision)); treeWalk.setFilter(PathFilter.create(fileName)); treeWalk.setRecursive(true); if (!treeWalk.next()) { return Optional.empty(); } ObjectId blobId = treeWalk.getObjectId(0); String content = new String(git.getRepository().getObjectDatabase().open(blobId).getBytes(), Charset.forName("UTF-8")); String[] lines = content.split("\n"); return Optional.of(lines); } private AbstractTreeIterator getTreeIterator(Git git, CodeRevision rev) throws IOException { final CanonicalTreeParser p = new CanonicalTreeParser(); Repository db = git.getRepository(); final ObjectReader or = db.newObjectReader(); try { p.reset(or, new RevWalk(db).parseTree(ObjectId.fromString(rev.getCommitId()))); return p; } finally { or.release(); } } private void initRepository(NodeConnection node, String remotePath) throws IOException { try (SshConnection connection = sshConnector.connect(node.getConnection().getConfig())) { remoteGit.installGit(connection, node.getNode().getSystemSpecification()); remoteGit.initEmptyRepository(connection, remotePath); } } }
bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/scm/git/GitStrategy.java
package de.unistuttgart.iste.rss.bugminer.scm.git; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import java.util.stream.StreamSupport; import de.unistuttgart.iste.rss.bugminer.computing.NodeConnection; import de.unistuttgart.iste.rss.bugminer.model.entities.LineChange; import de.unistuttgart.iste.rss.bugminer.model.entities.LineChangeKind; import de.unistuttgart.iste.rss.bugminer.scm.Commit; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.api.DiffCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.InvalidRemoteException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.errors.CorruptObjectException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.patch.FileHeader; import org.eclipse.jgit.patch.Patch; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.SshSessionFactory; import org.eclipse.jgit.transport.TransportGitSsh; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.PathFilter; import org.springframework.beans.factory.annotation.Autowired; import de.unistuttgart.iste.rss.bugminer.annotations.DataDirectory; import de.unistuttgart.iste.rss.bugminer.annotations.Strategy; import de.unistuttgart.iste.rss.bugminer.computing.SshConfig; import de.unistuttgart.iste.rss.bugminer.computing.SshConnection; import de.unistuttgart.iste.rss.bugminer.computing.SshConnector; import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRepo; import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRevision; import de.unistuttgart.iste.rss.bugminer.model.entities.Node; import de.unistuttgart.iste.rss.bugminer.scm.CodeRepoStrategy; import javax.sound.sampled.Line; @Strategy(type = CodeRepoStrategy.class, name = "git") public class GitStrategy implements CodeRepoStrategy { @Autowired private GitFactory gitFactory; @Autowired @DataDirectory private Path dataDir; @Autowired private SshConnector sshConnector; @Autowired private RemoteGitHelper remoteGit; protected GitStrategy() { // managed bean } @Override public void pushTo(CodeRepo repo, NodeConnection node, String remotePath, CodeRevision revision) throws IOException { initRepository(node, remotePath); Git git = open(repo); RefSpec refspec = new RefSpec() .setSource(revision.getCommitId()) .setDestination("refs/commits/" + revision.getCommitId()); SshConfig sshConfig = node.getConnection().getConfig(); // if remotePath is relative, it should be resolved against the home directory // if it is absolute, the last resolve() call removes the ~/ URI uri = sshConfig.toURIWithoutPassword().resolve("~/").resolve(remotePath); SshSessionFactory sshSessionFactory = new CustomSshConfigSessionFactory(sshConfig); CredentialsProvider credentialsProvider = null; // TODO implement password authentication try { git.push() .setRefSpecs(refspec) .setTransportConfigCallback(config -> ((TransportGitSsh) config).setSshSessionFactory(sshSessionFactory)) .setCredentialsProvider(credentialsProvider) .setRemote(uri.toString()) .call(); } catch (GitAPIException e) { throw new IOException(String.format("Unable to push %s at %s to %s", repo, revision, uri), e); } checkout(node, remotePath, revision); } private void checkout(NodeConnection node, String remotePath, CodeRevision revision) throws IOException { try (SshConnection connection = sshConnector.connect(node.getConnection().getConfig())) { remoteGit.checkoutHard(connection, remotePath, revision.getCommitId()); } } private Git open(CodeRepo repo) throws IOException { FileRepository repository = gitFactory.createFileRepository(getPath(repo).toFile()); return gitFactory.createGit(repository); } private Path getPath(CodeRepo repo) { return dataDir.resolve("scm").resolve(repo.getProject().getName()).resolve(repo.getName()); } /** * Makes sure that the repository is completely available and ready for pushTo * @param repo the repo to download */ public void download(CodeRepo repo) throws IOException { try { if (Files.exists(getPath(repo))) { open(repo).fetch().call(); return; } gitFactory.createCloneCommand() .setURI(repo.getUrl()) .setDirectory(getPath(repo).toFile()) .setBare(true) .call(); } catch (GitAPIException e) { throw new IOException(e); } } @Override public Stream<Commit> getCommits(CodeRepo repo) throws IOException { try { return StreamSupport.stream(open(repo).log().all().call().spliterator(), false) .map(c -> new Commit(c.getAuthorIdent().getName(), new CodeRevision(repo, c.getName()), c.getFullMessage(), c.getParentCount() > 1)); } catch (GitAPIException e) { throw new IOException(e); } } @Override public CodeRevision getParentRevision(CodeRevision rev) throws IOException { return new CodeRevision(rev.getCodeRepo(), open(rev.getCodeRepo()).getRepository().resolve(rev.getCommitId() + "^").getName()); } /** * Gets the line changes between two revisions in the repository * @param oldest * @param newest * @return * @throws IOException */ public List<LineChange> getDiff(CodeRevision oldest, CodeRevision newest) throws IOException { Git git = open(oldest.getCodeRepo()); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); StringBuffer buffer = new StringBuffer(); List<DiffEntry> diff = git.diff() .setOldTree(getTreeIterator(git, oldest)) .setNewTree(getTreeIterator(git, newest)) .setOutputStream(out) .call(); Patch patch = new Patch(); patch.parse(out.toByteArray(), 0, out.size()); List<LineChange> lineChanges = new ArrayList<>(); // prevent ConcurrentModificationExceptions List<FileHeader> files = new ArrayList<>(patch.getFiles()); for (FileHeader file : files) { Optional<String[]> oldFile = getBlob(git, file.getOldPath(), oldest); Optional<String[]> newFile = getBlob(git, file.getNewPath(), newest); String fileName = file.getOldPath(); if (file.getChangeType() == DiffEntry.ChangeType.ADD) { fileName = file.getNewPath(); } for (Edit edit : file.toEditList()) { // deletions for (int line = edit.getBeginA(); line < edit.getEndA(); line++) { assert oldFile.isPresent() : "missing old file for " + file.getOldPath(); int deletedLine = line + 1; // line is 0-based LineChange change = new LineChange(); change.setCodeRepo(newest.getCodeRepo()); change.setFileName(fileName); change.setKind(LineChangeKind.DELETION); change.setOldLineNumber(deletedLine); if (deletedLine - 1 >= 0 && deletedLine - 1 < oldFile.get().length) { change.setLineText(oldFile.get()[deletedLine - 1]); } lineChanges.add(change); } // additions int additionBaseLine = edit.getBeginA() + 1; // beginA is 0-based for (int offset = 0; offset < edit.getLengthB(); offset++) { assert newFile.isPresent() : "missing new file for " + file.getNewPath(); LineChange change = new LineChange(); change.setCodeRepo(newest.getCodeRepo()); change.setFileName(fileName); change.setKind(LineChangeKind.ADDITION); change.setOldLineNumber(additionBaseLine); change.setNewLineNumberIndex(offset); int newFileNumber = edit.getBeginB() + offset; if (newFileNumber >= 0 && newFileNumber < newFile.get().length) { change.setLineText(newFile.get()[edit.getBeginB() + offset]); } lineChanges.add(change); } } } return lineChanges; } catch (GitAPIException e) { throw new IOException(e); } } private Optional<String[]> getBlob(Git git, String fileName, CodeRevision revision) throws IOException { TreeWalk treeWalk = new TreeWalk(git.getRepository()); treeWalk.addTree(getTreeIterator(git, revision)); treeWalk.setFilter(PathFilter.create(fileName)); treeWalk.setRecursive(true); if (!treeWalk.next()) { return Optional.empty(); } ObjectId blobId = treeWalk.getObjectId(0); String content = new String(git.getRepository().getObjectDatabase().open(blobId).getBytes(), Charset.forName("UTF-8")); String[] lines = content.split("\n"); return Optional.of(lines); } private AbstractTreeIterator getTreeIterator(Git git, CodeRevision rev) throws IOException { final CanonicalTreeParser p = new CanonicalTreeParser(); Repository db = git.getRepository(); final ObjectReader or = db.newObjectReader(); try { p.reset(or, new RevWalk(db).parseTree(ObjectId.fromString(rev.getCommitId()))); return p; } finally { or.release(); } } private void initRepository(NodeConnection node, String remotePath) throws IOException { try (SshConnection connection = sshConnector.connect(node.getConnection().getConfig())) { remoteGit.installGit(connection, node.getNode().getSystemSpecification()); remoteGit.initEmptyRepository(connection, remotePath); } } }
ignore added files in diffs
bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/scm/git/GitStrategy.java
ignore added files in diffs
<ide><path>ugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/scm/git/GitStrategy.java <ide> <ide> String fileName = file.getOldPath(); <ide> if (file.getChangeType() == DiffEntry.ChangeType.ADD) { <del> fileName = file.getNewPath(); <add> break; // for now, ignore additions because they generate huge diffs <ide> } <ide> for (Edit edit : file.toEditList()) { <ide> // deletions
Java
lgpl-2.1
2fd23571198932aa046358791e80102c48f058a8
0
cdauth/winstone,cdauth/winstone,cdauth/winstone
/* * Winstone Servlet Container * Copyright (C) 2003 Rick Knowles * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 as published by the Free Software Foundation. * * This program 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. * * You should have received a copy of the GNU General Public License * Version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package winstone; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionListener; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Models the web.xml file's details ... basically just a bunch of configuration * details, plus the actual instances of mounted servlets. * * @author <a href="mailto:[email protected]">Rick Knowles</a> * @version $Id$ */ public class WebAppConfiguration implements ServletContext, Comparator { private static final String ELEM_DESCRIPTION = "description"; private static final String ELEM_DISPLAY_NAME = "display-name"; private static final String ELEM_SERVLET = "servlet"; private static final String ELEM_SERVLET_MAPPING = "servlet-mapping"; private static final String ELEM_SERVLET_NAME = "servlet-name"; private static final String ELEM_FILTER = "filter"; private static final String ELEM_FILTER_MAPPING = "filter-mapping"; private static final String ELEM_FILTER_NAME = "filter-name"; private static final String ELEM_DISPATCHER = "dispatcher"; private static final String ELEM_URL_PATTERN = "url-pattern"; private static final String ELEM_WELCOME_FILES = "welcome-file-list"; private static final String ELEM_WELCOME_FILE = "welcome-file"; private static final String ELEM_SESSION_CONFIG = "session-config"; private static final String ELEM_SESSION_TIMEOUT = "session-timeout"; private static final String ELEM_MIME_MAPPING = "mime-mapping"; private static final String ELEM_MIME_EXTENSION = "extension"; private static final String ELEM_MIME_TYPE = "mime-type"; private static final String ELEM_CONTEXT_PARAM = "context-param"; private static final String ELEM_PARAM_NAME = "param-name"; private static final String ELEM_PARAM_VALUE = "param-value"; private static final String ELEM_LISTENER = "listener"; private static final String ELEM_LISTENER_CLASS = "listener-class"; private static final String ELEM_DISTRIBUTABLE = "distributable"; private static final String ELEM_ERROR_PAGE = "error-page"; private static final String ELEM_EXCEPTION_TYPE = "exception-type"; private static final String ELEM_ERROR_CODE = "error-code"; private static final String ELEM_ERROR_LOCATION = "location"; private static final String ELEM_SECURITY_CONSTRAINT = "security-constraint"; private static final String ELEM_LOGIN_CONFIG = "login-config"; private static final String ELEM_SECURITY_ROLE = "security-role"; private static final String ELEM_ROLE_NAME = "role-name"; private static final String ELEM_ENV_ENTRY = "env-entry"; private static final String ELEM_LOCALE_ENC_MAP_LIST = "locale-encoding-mapping-list"; private static final String ELEM_LOCALE_ENC_MAPPING = "locale-encoding-mapping"; private static final String ELEM_LOCALE = "locale"; private static final String ELEM_ENCODING = "encoding"; private static final String ELEM_JSP_CONFIG = "jsp-config"; private static final String ELEM_JSP_PROPERTY_GROUP = "jsp-property-group"; private static final String DISPATCHER_REQUEST = "REQUEST"; private static final String DISPATCHER_FORWARD = "FORWARD"; private static final String DISPATCHER_INCLUDE = "INCLUDE"; private static final String DISPATCHER_ERROR = "ERROR"; private static final String JSP_SERVLET_NAME = "JspServlet"; private static final String JSP_SERVLET_MAPPING = "*.jsp"; private static final String JSPX_SERVLET_MAPPING = "*.jspx"; private static final String JSP_SERVLET_LOG_LEVEL = "WARNING"; private static final String INVOKER_SERVLET_NAME = "invoker"; private static final String INVOKER_SERVLET_CLASS = "winstone.invoker.InvokerServlet"; private static final String DEFAULT_INVOKER_PREFIX = "/servlet/"; private static final String DEFAULT_SERVLET_NAME = "default"; private static final String DEFAULT_SERVLET_CLASS = "winstone.StaticResourceServlet"; private static final String DEFAULT_REALM_CLASS = "winstone.realm.ArgumentsRealm"; private static final String DEFAULT_JNDI_MGR_CLASS = "winstone.jndi.WebAppJNDIManager"; private static final String RELOADING_CL_CLASS = "winstone.classLoader.ReloadingClassLoader"; private static final String ERROR_SERVLET_NAME = "winstoneErrorServlet"; private static final String ERROR_SERVLET_CLASS = "winstone.ErrorServlet"; private static final String WEB_INF = "WEB-INF"; private static final String CLASSES = "classes/"; private static final String LIB = "lib"; static final String JSP_SERVLET_CLASS = "org.apache.jasper.servlet.JspServlet"; private HostConfiguration ownerHostConfig; private Cluster cluster; private String webRoot; private String prefix; private String contextName; private ClassLoader loader; private String displayName; private Map attributes; private Map initParameters; private Map sessions; private Map mimeTypes; private Map servletInstances; private Map filterInstances; private ServletContextAttributeListener contextAttributeListeners[]; private ServletContextListener contextListeners[]; private ServletRequestListener requestListeners[]; private ServletRequestAttributeListener requestAttributeListeners[]; private HttpSessionActivationListener sessionActivationListeners[]; private HttpSessionAttributeListener sessionAttributeListeners[]; private HttpSessionListener sessionListeners[]; private Throwable contextStartupError; private Map exactServletMatchMounts; private Mapping patternMatches[]; private Mapping filterPatternsRequest[]; private Mapping filterPatternsForward[]; private Mapping filterPatternsInclude[]; private Mapping filterPatternsError[]; private AuthenticationHandler authenticationHandler; private AuthenticationRealm authenticationRealm; private String welcomeFiles[]; private Integer sessionTimeout; private Class[] errorPagesByExceptionKeysSorted; private Map errorPagesByException; private Map errorPagesByCode; private Map localeEncodingMap; private String defaultServletName; private String errorServletName; private JNDIManager jndiManager; private AccessLogger accessLogger; private Map filterMatchCache; public static boolean booleanArg(Map args, String name, boolean defaultTrue) { String value = (String) args.get(name); if (defaultTrue) return (value == null) || (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); else return (value != null) && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); } public static String stringArg(Map args, String name, String defaultValue) { return (String) (args.get(name) == null ? defaultValue : args.get(name)); } public static int intArg(Map args, String name, int defaultValue) { return Integer.parseInt(stringArg(args, name, "" + defaultValue)); } public static String getTextFromNode(Node node) { if (node == null) { return null; } Node child = node.getFirstChild(); if (child == null) { return ""; } String textNode = child.getNodeValue(); if (textNode == null) { return ""; } else { return textNode.trim(); } } /** * Constructor. This parses the xml and sets up for basic routing */ public WebAppConfiguration(HostConfiguration ownerHostConfig, Cluster cluster, String webRoot, String prefix, ObjectPool objectPool, Map startupArgs, Node elm, ClassLoader parentClassLoader, File parentClassPaths[], String contextName) { this.ownerHostConfig = ownerHostConfig; this.webRoot = webRoot; this.prefix = prefix; this.contextName = contextName; List localLoaderClassPathFiles = new ArrayList(); this.loader = buildWebAppClassLoader(startupArgs, parentClassLoader, webRoot, localLoaderClassPathFiles); // Build switch values boolean useJasper = booleanArg(startupArgs, "useJasper", false); boolean useInvoker = booleanArg(startupArgs, "useInvoker", true); boolean useJNDI = booleanArg(startupArgs, "useJNDI", false); // Check jasper is available if (useJasper) { try { Class.forName(JSP_SERVLET_CLASS, false, this.loader); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.JasperNotFound"); Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.JasperLoadException", err); useJasper = false; } } if (useInvoker) { try { Class.forName(INVOKER_SERVLET_CLASS, false, this.loader); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvokerNotFound"); useInvoker = false; } } this.attributes = new Hashtable(); this.initParameters = new HashMap(); this.sessions = new Hashtable(); this.servletInstances = new HashMap(); this.filterInstances = new HashMap(); this.filterMatchCache = new HashMap(); List contextAttributeListeners = new ArrayList(); List contextListeners = new ArrayList(); List requestListeners = new ArrayList(); List requestAttributeListeners = new ArrayList(); List sessionActivationListeners = new ArrayList(); List sessionAttributeListeners = new ArrayList(); List sessionListeners = new ArrayList(); this.errorPagesByException = new HashMap(); this.errorPagesByCode = new HashMap(); boolean distributable = false; this.exactServletMatchMounts = new Hashtable(); List localFolderPatterns = new ArrayList(); List localExtensionPatterns = new ArrayList(); List lfpRequest = new ArrayList(); List lfpForward = new ArrayList(); List lfpInclude = new ArrayList(); List lfpError = new ArrayList(); List localWelcomeFiles = new ArrayList(); List startupServlets = new ArrayList(); Set rolesAllowed = new HashSet(); List constraintNodes = new ArrayList(); List envEntryNodes = new ArrayList(); List localErrorPagesByExceptionList = new ArrayList(); Node loginConfigNode = null; // Add the class loader as an implicit context listener if it implements the interface addListenerInstance(this.loader, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners); // init mimeTypes set this.mimeTypes = new Hashtable(); String allTypes = Launcher.RESOURCES.getString("WebAppConfig.DefaultMimeTypes"); StringTokenizer mappingST = new StringTokenizer(allTypes, ":", false); for (; mappingST.hasMoreTokens();) { String mapping = mappingST.nextToken(); int delimPos = mapping.indexOf('='); if (delimPos == -1) continue; String extension = mapping.substring(0, delimPos); String mimeType = mapping.substring(delimPos + 1); this.mimeTypes.put(extension.toLowerCase(), mimeType); } this.localeEncodingMap = new HashMap(); String encodingMapSet = Launcher.RESOURCES.getString("WebAppConfig.EncodingMap"); StringTokenizer st = new StringTokenizer(encodingMapSet, ";"); for (; st.hasMoreTokens();) { String token = st.nextToken(); int delimPos = token.indexOf("="); if (delimPos == -1) continue; this.localeEncodingMap.put(token.substring(0, delimPos), token .substring(delimPos + 1)); } // init jsp mappings set List jspMappings = new ArrayList(); jspMappings.add(JSP_SERVLET_MAPPING); jspMappings.add(JSPX_SERVLET_MAPPING); // Add required context atttributes File tmpDir = new File(new File(new File(System.getProperty("java.io.tmpdir"), "winstone.tmp"), ownerHostConfig.getHostname()), contextName); tmpDir.mkdirs(); this.attributes.put("javax.servlet.context.tempdir", tmpDir); // Parse the web.xml file if (elm != null) { NodeList children = elm.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node child = children.item(n); if (child.getNodeType() != Node.ELEMENT_NODE) continue; String nodeName = child.getNodeName(); if (nodeName.equals(ELEM_DISPLAY_NAME)) this.displayName = getTextFromNode(child); else if (nodeName.equals(ELEM_DISTRIBUTABLE)) distributable = true; else if (nodeName.equals(ELEM_SECURITY_CONSTRAINT)) constraintNodes.add(child); else if (nodeName.equals(ELEM_ENV_ENTRY)) envEntryNodes.add(child); else if (nodeName.equals(ELEM_LOGIN_CONFIG)) loginConfigNode = child; // Session config elements else if (nodeName.equals(ELEM_SESSION_CONFIG)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node timeoutElm = child.getChildNodes().item(m); if ((timeoutElm.getNodeType() == Node.ELEMENT_NODE) && (timeoutElm.getNodeName().equals(ELEM_SESSION_TIMEOUT))) { String timeoutStr = getTextFromNode(child); if (!timeoutStr.equals("")) { this.sessionTimeout = Integer.valueOf(timeoutStr); } } } } // Construct the security roles else if (child.getNodeName().equals(ELEM_SECURITY_ROLE)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node roleElm = child.getChildNodes().item(m); if ((roleElm.getNodeType() == Node.ELEMENT_NODE) && (roleElm.getNodeName() .equals(ELEM_ROLE_NAME))) rolesAllowed.add(getTextFromNode(roleElm)); } } // Construct the servlet instances else if (nodeName.equals(ELEM_SERVLET)) { ServletConfiguration instance = new ServletConfiguration( this, child); this.servletInstances.put(instance.getServletName(), instance); if (instance.getLoadOnStartup() >= 0) startupServlets.add(instance); } // Construct the servlet instances else if (nodeName.equals(ELEM_FILTER)) { FilterConfiguration instance = new FilterConfiguration( this, this.loader, child); this.filterInstances.put(instance.getFilterName(), instance); } // Construct the servlet instances else if (nodeName.equals(ELEM_LISTENER)) { String listenerClass = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node listenerElm = child.getChildNodes().item(m); if ((listenerElm.getNodeType() == Node.ELEMENT_NODE) && (listenerElm.getNodeName() .equals(ELEM_LISTENER_CLASS))) listenerClass = getTextFromNode(listenerElm); } if (listenerClass != null) try { Class listener = Class.forName(listenerClass, true, this.loader); Object listenerInstance = listener.newInstance(); addListenerInstance(listenerInstance, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners); Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.AddListener", listenerClass); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidListener", listenerClass); } } // Process the servlet mappings else if (nodeName.equals(ELEM_SERVLET_MAPPING)) { String name = null; String pattern = null; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node mapChild = child.getChildNodes().item(k); if (mapChild.getNodeType() != Node.ELEMENT_NODE) continue; String mapNodeName = mapChild.getNodeName(); if (mapNodeName.equals(ELEM_SERVLET_NAME)) name = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_URL_PATTERN)) pattern = getTextFromNode(mapChild); } processMapping(name, pattern, this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } // Process the filter mappings else if (nodeName.equals(ELEM_FILTER_MAPPING)) { String filterName = null; String servletName = null; String urlPattern = null; boolean onRequest = false; boolean onForward = false; boolean onInclude = false; boolean onError = false; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node mapChild = child.getChildNodes().item(k); if (mapChild.getNodeType() != Node.ELEMENT_NODE) continue; String mapNodeName = mapChild.getNodeName(); if (mapNodeName.equals(ELEM_FILTER_NAME)) filterName = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_SERVLET_NAME)) servletName = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_URL_PATTERN)) urlPattern = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_DISPATCHER)) { String dispatcherValue = getTextFromNode(mapChild); if (dispatcherValue.equals(DISPATCHER_REQUEST)) onRequest = true; else if (dispatcherValue.equals(DISPATCHER_FORWARD)) onForward = true; else if (dispatcherValue.equals(DISPATCHER_INCLUDE)) onInclude = true; else if (dispatcherValue.equals(DISPATCHER_ERROR)) onError = true; } } if (!onRequest && !onInclude && !onForward && !onError) onRequest = true; Mapping mapping = null; if (servletName != null) { mapping = Mapping.createFromLink(filterName, servletName); } else if (urlPattern != null) { mapping = Mapping.createFromURL(filterName, urlPattern); } else { throw new WinstoneException("Error in filter mapping - no pattern and no servlet name"); } if (onRequest) lfpRequest.add(mapping); if (onForward) lfpForward.add(mapping); if (onInclude) lfpInclude.add(mapping); if (onError) lfpError.add(mapping); } // Process the list of welcome files else if (nodeName.equals(ELEM_WELCOME_FILES)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node welcomeFile = child.getChildNodes().item(m); if ((welcomeFile.getNodeType() == Node.ELEMENT_NODE) && welcomeFile.getNodeName().equals(ELEM_WELCOME_FILE)) { String welcomeStr = getTextFromNode(welcomeFile); if (!welcomeStr.equals("")) { localWelcomeFiles.add(welcomeStr); } } } } // Process the error pages else if (nodeName.equals(ELEM_ERROR_PAGE)) { String code = null; String exception = null; String location = null; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node errorChild = child.getChildNodes().item(k); if (errorChild.getNodeType() != Node.ELEMENT_NODE) continue; String errorChildName = errorChild.getNodeName(); if (errorChildName.equals(ELEM_ERROR_CODE)) code = getTextFromNode(errorChild); else if (errorChildName.equals(ELEM_EXCEPTION_TYPE)) exception = getTextFromNode(errorChild); else if (errorChildName.equals(ELEM_ERROR_LOCATION)) location = getTextFromNode(errorChild); } if ((code != null) && (location != null)) this.errorPagesByCode.put(code.trim(), location.trim()); if ((exception != null) && (location != null)) try { Class exceptionClass = Class.forName(exception .trim(), false, this.loader); localErrorPagesByExceptionList.add(exceptionClass); this.errorPagesByException.put(exceptionClass, location.trim()); } catch (ClassNotFoundException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ExceptionNotFound", exception); } } // Process the list of welcome files else if (nodeName.equals(ELEM_MIME_MAPPING)) { String extension = null; String mimeType = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node mimeTypeNode = child.getChildNodes().item(m); if (mimeTypeNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mimeTypeNode.getNodeName().equals( ELEM_MIME_EXTENSION)) extension = getTextFromNode(mimeTypeNode); else if (mimeTypeNode.getNodeName().equals( ELEM_MIME_TYPE)) mimeType = getTextFromNode(mimeTypeNode); } if ((extension != null) && (mimeType != null)) this.mimeTypes.put(extension.toLowerCase(), mimeType); else Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidMimeMapping", new String[] { extension, mimeType }); } // Process the list of welcome files else if (nodeName.equals(ELEM_CONTEXT_PARAM)) { String name = null; String value = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node contextParamNode = child.getChildNodes().item(m); if (contextParamNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (contextParamNode.getNodeName().equals( ELEM_PARAM_NAME)) name = getTextFromNode(contextParamNode); else if (contextParamNode.getNodeName().equals( ELEM_PARAM_VALUE)) value = getTextFromNode(contextParamNode); } if ((name != null) && (value != null)) this.initParameters.put(name, value); else Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidInitParam", new String[] { name, value }); } // Process locale encoding mapping elements else if (nodeName.equals(ELEM_LOCALE_ENC_MAP_LIST)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node mappingNode = child.getChildNodes().item(m); if (mappingNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mappingNode.getNodeName().equals(ELEM_LOCALE_ENC_MAPPING)) { String localeName = ""; String encoding = ""; for (int l = 0; l < mappingNode.getChildNodes().getLength(); l++) { Node mappingChildNode = mappingNode.getChildNodes().item(l); if (mappingChildNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mappingChildNode.getNodeName().equals(ELEM_LOCALE)) localeName = getTextFromNode(mappingChildNode); else if (mappingChildNode.getNodeName().equals(ELEM_ENCODING)) encoding = getTextFromNode(mappingChildNode); } if (!encoding.equals("") && !localeName.equals("")) this.localeEncodingMap.put(localeName, encoding); } } } // Record the url mappings for jsp files if set else if (nodeName.equals(ELEM_JSP_CONFIG)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node propertyGroupNode = child.getChildNodes().item(m); if ((propertyGroupNode.getNodeType() == Node.ELEMENT_NODE) && propertyGroupNode.getNodeName().equals(ELEM_JSP_PROPERTY_GROUP)) { for (int l = 0; l < propertyGroupNode.getChildNodes().getLength(); l++) { Node urlPatternNode = propertyGroupNode.getChildNodes().item(l); if ((urlPatternNode.getNodeType() == Node.ELEMENT_NODE) && urlPatternNode.getNodeName().equals(ELEM_URL_PATTERN)) { String jm = getTextFromNode(urlPatternNode); if (!jm.equals("")) { jspMappings.add(jm); } } } } } } } } // If not distributable, remove the cluster reference if (!distributable && (cluster != null)) { Logger.log(Logger.INFO, Launcher.RESOURCES, "WebAppConfig.ClusterOffNotDistributable", this.contextName); } else { this.cluster = cluster; } // Build the login/security role instance if (!constraintNodes.isEmpty() && (loginConfigNode != null)) { String authMethod = null; for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++) if (loginConfigNode.getChildNodes().item(n).getNodeName().equals("auth-method")) authMethod = getTextFromNode(loginConfigNode.getChildNodes().item(n)); // Load the appropriate auth class if (authMethod == null) authMethod = "BASIC"; else authMethod = WinstoneResourceBundle.globalReplace(authMethod, "-", ""); String realmClassName = stringArg(startupArgs, "realmClassName", DEFAULT_REALM_CLASS).trim(); String authClassName = "winstone.auth." + authMethod.substring(0, 1).toUpperCase() + authMethod.substring(1).toLowerCase() + "AuthenticationHandler"; try { // Build the realm Class realmClass = Class.forName(realmClassName); Constructor realmConstr = realmClass .getConstructor(new Class[] {Set.class, Map.class }); this.authenticationRealm = (AuthenticationRealm) realmConstr .newInstance(new Object[] { rolesAllowed, startupArgs }); // Build the authentication handler Class authClass = Class.forName(authClassName); Constructor authConstr = authClass .getConstructor(new Class[] { Node.class, List.class, Set.class, AuthenticationRealm.class }); this.authenticationHandler = (AuthenticationHandler) authConstr .newInstance(new Object[] { loginConfigNode, constraintNodes, rolesAllowed, authenticationRealm }); } catch (ClassNotFoundException err) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.AuthDisabled", authMethod); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.AuthError", new String[] { authClassName, realmClassName }, err); } } // Instantiate the JNDI manager String jndiMgrClassName = stringArg(startupArgs, "webappJndiClassName", DEFAULT_JNDI_MGR_CLASS).trim(); if (useJNDI) { try { // Build the realm Class jndiMgrClass = Class.forName(jndiMgrClassName, true, this.loader); Constructor jndiMgrConstr = jndiMgrClass.getConstructor(new Class[] { Map.class, List.class, ClassLoader.class }); this.jndiManager = (JNDIManager) jndiMgrConstr.newInstance(new Object[] { null, envEntryNodes, this.loader }); if (this.jndiManager != null) this.jndiManager.setup(); } catch (ClassNotFoundException err) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.JNDIDisabled"); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.JNDIError", jndiMgrClassName, err); } } String loggerClassName = stringArg(startupArgs, "accessLoggerClassName", "").trim(); if (!loggerClassName.equals("")) { try { // Build the realm Class loggerClass = Class.forName(loggerClassName, true, this.loader); Constructor loggerConstr = loggerClass.getConstructor(new Class[] { WebAppConfiguration.class, Map.class }); this.accessLogger = (AccessLogger) loggerConstr.newInstance(new Object[] { this, startupArgs}); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.LoggerError", loggerClassName, err); } } else { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.LoggerDisabled"); } // Add the default index.html welcomeFile if none are supplied if (localWelcomeFiles.isEmpty()) { if (useJasper) { localWelcomeFiles.add("index.jsp"); } localWelcomeFiles.add("index.html"); } // Put the name filters after the url filters, then convert to string // arrays this.filterPatternsRequest = (Mapping[]) lfpRequest.toArray(new Mapping[0]); this.filterPatternsForward = (Mapping[]) lfpForward.toArray(new Mapping[0]); this.filterPatternsInclude = (Mapping[]) lfpInclude.toArray(new Mapping[0]); this.filterPatternsError = (Mapping[]) lfpError.toArray(new Mapping[0]); if (this.filterPatternsRequest.length > 0) Arrays.sort(this.filterPatternsRequest, this.filterPatternsRequest[0]); if (this.filterPatternsForward.length > 0) Arrays.sort(this.filterPatternsForward, this.filterPatternsForward[0]); if (this.filterPatternsInclude.length > 0) Arrays.sort(this.filterPatternsInclude, this.filterPatternsInclude[0]); if (this.filterPatternsError.length > 0) Arrays.sort(this.filterPatternsError, this.filterPatternsError[0]); this.welcomeFiles = (String[]) localWelcomeFiles.toArray(new String[0]); this.errorPagesByExceptionKeysSorted = (Class[]) localErrorPagesByExceptionList .toArray(new Class[0]); Arrays.sort(this.errorPagesByExceptionKeysSorted, this); // Put the listeners into their arrays this.contextAttributeListeners = (ServletContextAttributeListener[]) contextAttributeListeners .toArray(new ServletContextAttributeListener[0]); this.contextListeners = (ServletContextListener[]) contextListeners .toArray(new ServletContextListener[0]); this.requestListeners = (ServletRequestListener[]) requestListeners .toArray(new ServletRequestListener[0]); this.requestAttributeListeners = (ServletRequestAttributeListener[]) requestAttributeListeners .toArray(new ServletRequestAttributeListener[0]); this.sessionActivationListeners = (HttpSessionActivationListener[]) sessionActivationListeners .toArray(new HttpSessionActivationListener[0]); this.sessionAttributeListeners = (HttpSessionAttributeListener[]) sessionAttributeListeners .toArray(new HttpSessionAttributeListener[0]); this.sessionListeners = (HttpSessionListener[]) sessionListeners .toArray(new HttpSessionListener[0]); // If we haven't explicitly mapped the default servlet, map it here if (this.defaultServletName == null) this.defaultServletName = DEFAULT_SERVLET_NAME; if (this.errorServletName == null) this.errorServletName = ERROR_SERVLET_NAME; // If we don't have an instance of the default servlet, mount the inbuilt one if (this.servletInstances.get(this.defaultServletName) == null) { boolean useDirLists = booleanArg(startupArgs, "directoryListings", true); Map staticParams = new Hashtable(); staticParams.put("webRoot", webRoot); staticParams.put("prefix", this.prefix); staticParams.put("directoryList", "" + useDirLists); ServletConfiguration defaultServlet = new ServletConfiguration( this, this.defaultServletName, DEFAULT_SERVLET_CLASS, staticParams, 0); // commented cause it should be called during startup servlet // defaultServlet.getRequestDispatcher(this.filterInstances); this.servletInstances.put(this.defaultServletName, defaultServlet); startupServlets.add(defaultServlet); } // If we don't have an instance of the default servlet, mount the inbuilt one if (this.servletInstances.get(this.errorServletName) == null) { ServletConfiguration errorServlet = new ServletConfiguration( this, this.errorServletName, ERROR_SERVLET_CLASS, new HashMap(), 0); // commented cause it should be called during startup servlet // errorServlet.getRequestDispatcher(this.filterInstances); this.servletInstances.put(this.errorServletName, errorServlet); startupServlets.add(errorServlet); } // Initialise jasper servlet if requested if (useJasper) { setAttribute("org.apache.catalina.classloader", this.loader); // Logger.log(Logger.DEBUG, "Setting JSP classpath: " + // this.loader.getClasspath()); try { StringBuffer cp = new StringBuffer(); for (Iterator i = localLoaderClassPathFiles.iterator(); i.hasNext(); ) { cp.append(((File) i.next()).getCanonicalPath()).append( File.pathSeparatorChar); } for (int n = 0; n < parentClassPaths.length; n++) { cp.append(parentClassPaths[n].getCanonicalPath()).append( File.pathSeparatorChar); } setAttribute("org.apache.catalina.jsp_classpath", (cp.length() > 0 ? cp.substring(0, cp.length() - 1) : "")); } catch (IOException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ErrorSettingJSPPaths", err); } Map jspParams = new HashMap(); addJspServletParams(jspParams); ServletConfiguration sc = new ServletConfiguration(this, JSP_SERVLET_NAME, JSP_SERVLET_CLASS, jspParams, 3); this.servletInstances.put(JSP_SERVLET_NAME, sc); startupServlets.add(sc); for (Iterator mapIt = jspMappings.iterator(); mapIt.hasNext(); ) { processMapping(JSP_SERVLET_NAME, (String) mapIt.next(), this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } } // Initialise invoker servlet if requested if (useInvoker) { // Get generic options String invokerPrefix = stringArg(startupArgs, "invokerPrefix", DEFAULT_INVOKER_PREFIX); Map invokerParams = new HashMap(); invokerParams.put("prefix", this.prefix); invokerParams.put("invokerPrefix", invokerPrefix); ServletConfiguration sc = new ServletConfiguration(this, INVOKER_SERVLET_NAME, INVOKER_SERVLET_CLASS, invokerParams, 3); this.servletInstances.put(INVOKER_SERVLET_NAME, sc); processMapping(INVOKER_SERVLET_NAME, invokerPrefix + Mapping.STAR, this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } // Sort the folder patterns so the longest paths are first localFolderPatterns.addAll(localExtensionPatterns); this.patternMatches = (Mapping[]) localFolderPatterns.toArray(new Mapping[0]); if (this.patternMatches.length > 0) Arrays.sort(this.patternMatches, this.patternMatches[0]); // Send init notifies try { for (int n = 0; n < this.contextListeners.length; n++) this.contextListeners[n].contextInitialized(new ServletContextEvent(this)); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ContextStartupError", this.contextName, err); this.contextStartupError = err; } if (this.contextStartupError == null) { // Initialise all the filters for (Iterator i = this.filterInstances.values().iterator(); i.hasNext();) { FilterConfiguration config = (FilterConfiguration) i.next(); try { config.getFilter(); } catch (ServletException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.FilterStartupError", config.getFilterName(), err); } } // Initialise load on startup servlets Object autoStarters[] = startupServlets.toArray(); Arrays.sort(autoStarters); for (int n = 0; n < autoStarters.length; n++) { ((ServletConfiguration) autoStarters[n]).ensureInitialization(); } } } /** * Build the web-app classloader. This tries to load the preferred classloader first, * but if it fails, falls back to a simple URLClassLoader. */ private ClassLoader buildWebAppClassLoader(Map startupArgs, ClassLoader parentClassLoader, String webRoot, List classPathFileList) { List urlList = new ArrayList(); try { // Web-inf folder File webInfFolder = new File(webRoot, WEB_INF); // Classes folder File classesFolder = new File(webInfFolder, CLASSES); if (classesFolder.exists()) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WinstoneClassLoader.WebAppClasses"); urlList.add(new URL("file", "", classesFolder.getCanonicalPath() + "/")); classPathFileList.add(classesFolder); } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneClassLoader.NoWebAppClasses", classesFolder.toString()); } // Lib folder's jar files File libFolder = new File(webInfFolder, LIB); if (libFolder.exists()) { File jars[] = libFolder.listFiles(); for (int n = 0; n < jars.length; n++) { String jarName = jars[n].getCanonicalPath().toLowerCase(); if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WinstoneClassLoader.WebAppLib", jars[n].getName()); urlList.add(jars[n].toURL()); classPathFileList.add(jars[n]); } } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneClassLoader.NoWebAppLib", libFolder .toString()); } } catch (MalformedURLException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WinstoneClassLoader.BadURL"), err); } catch (IOException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WinstoneClassLoader.IOException"), err); } URL jarURLs[] = (URL []) urlList.toArray(new URL[0]); boolean useReloading = booleanArg(startupArgs, "useServletReloading", false); String preferredClassLoader = stringArg(startupArgs, "preferredClassLoader", ""); if (preferredClassLoader.equals("") && useReloading) { preferredClassLoader = RELOADING_CL_CLASS; } // Try to set up the preferred class loader, and if we fail, use the normal one ClassLoader outputCL = null; if (!preferredClassLoader.equals("")) { try { Class preferredCL = Class.forName(preferredClassLoader, true, parentClassLoader); Constructor reloadConstr = preferredCL.getConstructor(new Class[] { (new URL[0]).getClass(), ClassLoader.class}); outputCL = (ClassLoader) reloadConstr.newInstance(new Object[] { jarURLs, parentClassLoader}); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.CLError", err); } } if (outputCL == null) { outputCL = new URLClassLoader(jarURLs, parentClassLoader); } Logger.log(Logger.MAX, Launcher.RESOURCES, "WebAppConfig.WebInfClassLoader", outputCL.toString()); return outputCL; } private void addListenerInstance(Object listenerInstance, List contextAttributeListeners, List contextListeners, List requestAttributeListeners, List requestListeners, List sessionActivationListeners, List sessionAttributeListeners, List sessionListeners) { if (listenerInstance instanceof ServletContextAttributeListener) contextAttributeListeners.add(listenerInstance); if (listenerInstance instanceof ServletContextListener) contextListeners.add(listenerInstance); if (listenerInstance instanceof ServletRequestAttributeListener) requestAttributeListeners.add(listenerInstance); if (listenerInstance instanceof ServletRequestListener) requestListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionActivationListener) sessionActivationListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionAttributeListener) sessionAttributeListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionListener) sessionListeners.add(listenerInstance); } public String getPrefix() { return this.prefix; } public String getWebroot() { return this.webRoot; } public ClassLoader getLoader() { return this.loader; } public AccessLogger getAccessLogger() { return this.accessLogger; } public Map getFilters() { return this.filterInstances; } public String getContextName() { return this.contextName; } public Class[] getErrorPageExceptions() { return this.errorPagesByExceptionKeysSorted; } public Map getErrorPagesByException() { return this.errorPagesByException; } public Map getErrorPagesByCode() { return this.errorPagesByCode; } public Map getLocaleEncodingMap() { return this.localeEncodingMap; } public String[] getWelcomeFiles() { return this.welcomeFiles; } // public boolean isDistributable() { // return this.distributable; // } public Map getFilterMatchCache() { return this.filterMatchCache; } public String getOwnerHostname() { return this.ownerHostConfig.getHostname(); } public ServletRequestListener[] getRequestListeners() { return this.requestListeners; } public ServletRequestAttributeListener[] getRequestAttributeListeners() { return this.requestAttributeListeners; } public static void addJspServletParams(Map jspParams) { jspParams.put("logVerbosityLevel", JSP_SERVLET_LOG_LEVEL); jspParams.put("fork", "false"); } public int compare(Object one, Object two) { if (!(one instanceof Class) || !(two instanceof Class)) throw new IllegalArgumentException( "This comparator is only for sorting classes"); Class classOne = (Class) one; Class classTwo = (Class) two; if (classOne.isAssignableFrom(classTwo)) return 1; else if (classTwo.isAssignableFrom(classOne)) return -1; else return 0; } public String getServletURIFromRequestURI(String requestURI) { if (prefix.equals("")) { return requestURI; } else if (requestURI.startsWith(prefix)) { return requestURI.substring(prefix.length()); } else { throw new WinstoneException("This shouldn't happen, " + "since we aborted earlier if we didn't match"); } } /** * Iterates through each of the servlets/filters and calls destroy on them */ public void destroy() { synchronized (this.filterMatchCache) { this.filterMatchCache.clear(); } Collection filterInstances = new ArrayList(this.filterInstances.values()); for (Iterator i = filterInstances.iterator(); i.hasNext();) { try { ((FilterConfiguration) i.next()).destroy(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.filterInstances.clear(); Collection servletInstances = new ArrayList(this.servletInstances.values()); for (Iterator i = servletInstances.iterator(); i.hasNext();) { try { ((ServletConfiguration) i.next()).destroy(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.servletInstances.clear(); // Drop all sessions Collection sessions = new ArrayList(this.sessions.values()); for (Iterator i = sessions.iterator(); i.hasNext();) { try { ((WinstoneSession) i.next()).invalidate(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.sessions.clear(); // Send destroy notifies - backwards for (int n = this.contextListeners.length - 1; n >= 0; n--) { try { this.contextListeners[n].contextDestroyed(new ServletContextEvent(this)); this.contextListeners[n] = null; } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.contextListeners = null; // Terminate class loader reloading thread if running if (this.loader != null) { // already shutdown/handled by the servlet context listeners // try { // Method methDestroy = this.loader.getClass().getMethod("destroy", new Class[0]); // methDestroy.invoke(this.loader, new Object[0]); // } catch (Throwable err) { // Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); // } this.loader = null; } // Kill JNDI manager if we have one if (this.jndiManager != null) { this.jndiManager.tearDown(); this.jndiManager = null; } // Kill JNDI manager if we have one if (this.accessLogger != null) { this.accessLogger.destroy(); this.accessLogger = null; } } /** * Triggered by the admin thread on the reloading class loader. This will * cause a full shutdown and reinstantiation of the web app - not real * graceful, but you shouldn't have reloading turned on in high load * environments. */ public void resetClassLoader() throws IOException { this.ownerHostConfig.reloadWebApp(getPrefix()); } /** * Here we process url patterns into the exactMatch and patternMatch lists */ private void processMapping(String name, String pattern, Map exactPatterns, List folderPatterns, List extensionPatterns) { Mapping urlPattern = null; try { urlPattern = Mapping.createFromURL(name, pattern); } catch (WinstoneException err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.ErrorMapURL", err.getMessage()); return; } // put the pattern in the correct list if (urlPattern.getPatternType() == Mapping.EXACT_PATTERN) { exactPatterns.put(urlPattern.getUrlPattern(), name); } else if (urlPattern.getPatternType() == Mapping.FOLDER_PATTERN) { folderPatterns.add(urlPattern); } else if (urlPattern.getPatternType() == Mapping.EXTENSION_PATTERN) { extensionPatterns.add(urlPattern); } else if (urlPattern.getPatternType() == Mapping.DEFAULT_SERVLET) { this.defaultServletName = name; } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidMount", new String[] { name, pattern }); } } /** * Execute the pattern match, and try to return a servlet that matches this * URL */ private ServletConfiguration urlMatch(String path, StringBuffer servletPath, StringBuffer pathInfo) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.URLMatch", path); // Check exact matches first String exact = (String) this.exactServletMatchMounts.get(path); if (exact != null) { if (this.servletInstances.get(exact) != null) { servletPath.append(path); // pathInfo.append(""); // a hack - empty becomes null later return (ServletConfiguration) this.servletInstances.get(exact); } } // Inexact mount check for (int n = 0; n < this.patternMatches.length; n++) { Mapping urlPattern = this.patternMatches[n]; if (urlPattern.match(path, servletPath, pathInfo) && (this.servletInstances.get(urlPattern.getMappedTo()) != null)) { return (ServletConfiguration) this.servletInstances .get(urlPattern.getMappedTo()); } } // return default servlet // servletPath.append(""); // unneeded if (this.servletInstances.get(this.defaultServletName) == null) throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.MatchedNonExistServlet", this.defaultServletName)); // pathInfo.append(path); servletPath.append(path); return (ServletConfiguration) this.servletInstances.get(this.defaultServletName); } /** * Constructs a session instance with the given sessionId * * @param sessionId The sessionID for the new session * @return A valid session object */ public WinstoneSession makeNewSession(String sessionId) { WinstoneSession ws = new WinstoneSession(sessionId, this, (this.cluster != null)); setSessionListeners(ws); if ((this.sessionTimeout != null) && (this.sessionTimeout.intValue() > 0)) ws.setMaxInactiveInterval(this.sessionTimeout.intValue() * 60); else ws.setMaxInactiveInterval(-1); ws.setLastAccessedDate(System.currentTimeMillis()); ws.sendCreatedNotifies(); this.sessions.put(sessionId, ws); return ws; } /** * Retrieves the session by id. If the web app is distributable, it asks the * other members of the cluster if it doesn't have it itself. * * @param sessionId The id of the session we want * @return A valid session instance */ public WinstoneSession getSessionById(String sessionId, boolean localOnly) { if (sessionId == null) { return null; } WinstoneSession session = (WinstoneSession) this.sessions.get(sessionId); if (session != null) { return session; } // If I'm distributable ... check remotely if ((this.cluster != null) && !localOnly) { session = this.cluster.askClusterForSession(sessionId, this); if (session != null) { this.sessions.put(sessionId, session); } return session; } else { return null; } } /** * Remove the session from the collection */ public void removeSessionById(String sessionId) { this.sessions.remove(sessionId); } public void setSessionListeners(WinstoneSession session) { session.setSessionActivationListeners(this.sessionActivationListeners); session.setSessionAttributeListeners(this.sessionAttributeListeners); session.setSessionListeners(this.sessionListeners); } public void removeServletConfigurationAndMappings(ServletConfiguration config) { this.servletInstances.remove(config.getServletName()); // The urlMatch method will only match to non-null mappings, so we don't need // to remove anything here } /*************************************************************************** * * OK ... from here to the end is the interface implementation methods for * the servletContext interface. * **************************************************************************/ // Application level attributes public Object getAttribute(String name) { return this.attributes.get(name); } public Enumeration getAttributeNames() { return Collections.enumeration(this.attributes.keySet()); } public void removeAttribute(String name) { Object me = this.attributes.get(name); this.attributes.remove(name); if (me != null) for (int n = 0; n < this.contextAttributeListeners.length; n++) this.contextAttributeListeners[n] .attributeRemoved(new ServletContextAttributeEvent( this, name, me)); } public void setAttribute(String name, Object object) { if (object == null) { removeAttribute(name); } else { Object me = this.attributes.get(name); this.attributes.put(name, object); if (me != null) { for (int n = 0; n < this.contextAttributeListeners.length; n++) this.contextAttributeListeners[n] .attributeReplaced(new ServletContextAttributeEvent( this, name, me)); } else { for (int n = 0; n < this.contextAttributeListeners.length; n++) this.contextAttributeListeners[n] .attributeAdded(new ServletContextAttributeEvent(this, name, object)); } } } // Application level init parameters public String getInitParameter(String name) { return (String) this.initParameters.get(name); } public Enumeration getInitParameterNames() { return Collections.enumeration(this.initParameters.keySet()); } // Server info public String getServerInfo() { return Launcher.RESOURCES.getString("ServerVersion"); } public int getMajorVersion() { return 2; } public int getMinorVersion() { return 4; } // Weird mostly deprecated crap to do with getting servlet instances public javax.servlet.ServletContext getContext(String uri) { return this.ownerHostConfig.getWebAppByURI(uri); } public String getServletContextName() { return this.displayName; } /** * Look up the map of mimeType extensions, and return the type that matches */ public String getMimeType(String fileName) { int dotPos = fileName.lastIndexOf('.'); if ((dotPos != -1) && (dotPos != fileName.length() - 1)) { String extension = fileName.substring(dotPos + 1).toLowerCase(); String mimeType = (String) this.mimeTypes.get(extension); return mimeType; } else return null; } // Context level log statements public void log(String message) { Logger.logDirectMessage(Logger.INFO, this.contextName, message, null); } public void log(String message, Throwable throwable) { Logger.logDirectMessage(Logger.ERROR, this.contextName, message, throwable); } /** * Named dispatcher - this basically gets us a simple exact dispatcher (no * url matching, no request attributes and no security) */ public javax.servlet.RequestDispatcher getNamedDispatcher(String name) { ServletConfiguration servlet = (ServletConfiguration) this.servletInstances.get(name); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForNamedDispatcher(this.filterPatternsForward, this.filterPatternsInclude); return rd; } } return null; } /** * Gets a dispatcher, which sets the request attributes, etc on a * forward/include. Doesn't execute security though. */ public javax.servlet.RequestDispatcher getRequestDispatcher( String uriInsideWebapp) { if (uriInsideWebapp == null) { return null; } else if (!uriInsideWebapp.startsWith("/")) { return null; } // Parse the url for query string, etc String queryString = ""; int questionPos = uriInsideWebapp.indexOf('?'); if (questionPos != -1) { if (questionPos != uriInsideWebapp.length() - 1) queryString = uriInsideWebapp.substring(questionPos + 1); uriInsideWebapp = uriInsideWebapp.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForURLDispatcher(servletPath.toString(), pathInfo.toString() .equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, this.filterPatternsForward, this.filterPatternsInclude); return rd; } } return null; } /** * Creates the dispatcher that corresponds to a request level dispatch (ie * the initial entry point). The difference here is that we need to set up * the dispatcher so that on a forward, it executes the security checks and * the request filters, while not setting any of the request attributes for * a forward. Also, we can't return a null dispatcher in error case - instead * we have to return a dispatcher pre-init'd for showing an error page (eg 404). * A null dispatcher is interpreted to mean a successful 302 has occurred. */ public RequestDispatcher getInitialDispatcher(String uriInsideWebapp, WinstoneRequest request, WinstoneResponse response) throws IOException { if (!uriInsideWebapp.equals("") && !uriInsideWebapp.startsWith("/")) { return this.getErrorDispatcherByCode( HttpServletResponse.SC_BAD_REQUEST, Launcher.RESOURCES.getString("WebAppConfig.InvalidURI", uriInsideWebapp), null); } else if (this.contextStartupError != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); this.contextStartupError.printStackTrace(pw); return this.getErrorDispatcherByCode( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Launcher.RESOURCES.getString("WebAppConfig.ErrorDuringStartup", sw.toString()), this.contextStartupError); } // Parse the url for query string, etc String queryString = ""; int questionPos = uriInsideWebapp.indexOf('?'); if (questionPos != -1) { if (questionPos != uriInsideWebapp.length() - 1) queryString = uriInsideWebapp.substring(questionPos + 1); uriInsideWebapp = uriInsideWebapp.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo); if (servlet != null) { // If the default servlet was returned, we should check for welcome files if (servlet.getServletName().equals(this.defaultServletName)) { // Is path a directory ? String directoryPath = servletPath.toString(); if (directoryPath.endsWith("/")) { directoryPath = directoryPath.substring(0, directoryPath.length() - 1); } if (directoryPath.startsWith("/")) { directoryPath = directoryPath.substring(1); } File res = new File(webRoot, directoryPath); if (res.exists() && res.isDirectory() && (request.getMethod().equals("GET") || request.getMethod().equals("HEAD"))) { // Check for the send back with slash case if (!servletPath.toString().endsWith("/")) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.FoundNonSlashDirectory", servletPath.toString()); response.sendRedirect(this.prefix + servletPath.toString() + pathInfo.toString() + "/" + (queryString.equals("") ? "" : "?" + queryString)); return null; } // Check for welcome files Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.CheckWelcomeFile", servletPath.toString() + pathInfo.toString()); String welcomeFile = matchWelcomeFiles(servletPath.toString() + pathInfo.toString(), request); if (welcomeFile != null) { response.sendRedirect(this.prefix + servletPath.toString() + pathInfo.toString() + welcomeFile + (queryString.equals("") ? "" : "?" + queryString)); return null; } } } RequestDispatcher rd = new RequestDispatcher(this, servlet); rd.setForInitialDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, this.filterPatternsRequest, this.authenticationHandler); return rd; } // If we are here, return a 404 return this.getErrorDispatcherByCode(HttpServletResponse.SC_NOT_FOUND, Launcher.RESOURCES.getString("StaticResourceServlet.PathNotFound", uriInsideWebapp), null); } /** * Gets a dispatcher, set up for error dispatch. */ public RequestDispatcher getErrorDispatcherByClass( Throwable exception) { // Check for exception class match Class exceptionClasses[] = this.errorPagesByExceptionKeysSorted; Throwable errWrapper = new ServletException(exception); while (errWrapper instanceof ServletException) { errWrapper = ((ServletException) errWrapper).getRootCause(); if (errWrapper == null) { break; } for (int n = 0; n < exceptionClasses.length; n++) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WinstoneResponse.TestingException", new String[] {this.errorPagesByExceptionKeysSorted[n].getName(), errWrapper.getClass().getName()}); if (exceptionClasses[n].isInstance(errWrapper)) { String errorURI = (String) this.errorPagesByException.get(exceptionClasses[n]); if (errorURI != null) { RequestDispatcher rd = buildErrorDispatcher(errorURI, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errWrapper.getMessage(), errWrapper); if (rd != null) { return rd; } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.SkippingException", new String[] {exceptionClasses[n].getName(), (String) this.errorPagesByException.get(exceptionClasses[n]) }); } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.ExceptionNotMatched", exceptionClasses[n].getName()); } } } // Otherwise throw a code error Throwable errPassDown = exception; while ((errPassDown instanceof ServletException) && (((ServletException) errPassDown).getRootCause() != null)) { errPassDown = ((ServletException) errPassDown).getRootCause(); } return getErrorDispatcherByCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errPassDown.getMessage(), errPassDown); } public RequestDispatcher getErrorDispatcherByCode( int statusCode, String summaryMessage, Throwable exception) { // Check for status code match String errorURI = (String) getErrorPagesByCode().get("" + statusCode); if (errorURI != null) { RequestDispatcher rd = buildErrorDispatcher(errorURI, statusCode, summaryMessage, exception); if (rd != null) { return rd; } } // If no dispatcher available, return a dispatcher to the default error formatter ServletConfiguration errorServlet = (ServletConfiguration) this.servletInstances.get(this.errorServletName); if (errorServlet != null) { RequestDispatcher rd = new RequestDispatcher(this, errorServlet); if (rd != null) { rd.setForErrorDispatcher(null, null, null, statusCode, summaryMessage, exception, null, this.filterPatternsError); return rd; } } // Otherwise log and return null Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.NoErrorServlet", "" + statusCode, exception); return null; } /** * Build a dispatcher to the error handler if it's available. If it fails, return null. */ private RequestDispatcher buildErrorDispatcher(String errorURI, int statusCode, String summaryMessage, Throwable exception) { // Parse the url for query string, etc String queryString = ""; int questionPos = errorURI.indexOf('?'); if (questionPos != -1) { if (questionPos != errorURI.length() - 1) { queryString = errorURI.substring(questionPos + 1); } errorURI = errorURI.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForErrorDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, statusCode, summaryMessage, exception, errorURI, this.filterPatternsError); return rd; } } return null; } /** * Check if any of the welcome files under this path are available. Returns the * name of the file if found, null otherwise */ private String matchWelcomeFiles(String path, WinstoneRequest request) { Set subfiles = getResourcePaths(path); for (int n = 0; n < this.welcomeFiles.length; n++) { String exact = (String) this.exactServletMatchMounts.get(path); if (exact != null) return this.welcomeFiles[n]; // Inexact folder mount check - note folder mounts only for (int j = 0; j < this.patternMatches.length; j++) { Mapping urlPattern = this.patternMatches[j]; if ((urlPattern.getPatternType() == Mapping.FOLDER_PATTERN) && urlPattern.match(path + this.welcomeFiles[n], null, null)) return this.welcomeFiles[n]; } if (subfiles.contains(path + this.welcomeFiles[n])) return this.welcomeFiles[n]; } return null; } // Getting resources via the classloader public URL getResource(String path) throws MalformedURLException { if (path == null) { return null; } else if (!path.startsWith("/")) { throw new MalformedURLException(Launcher.RESOURCES.getString( "WebAppConfig.BadResourcePath", path)); } else if (!path.equals("/") && path.endsWith("/")) { path = path.substring(0, path.length() - 1); } File res = new File(webRoot, path.substring(1)); return (res != null) && res.exists() ? res.toURL() : null; } public InputStream getResourceAsStream(String path) { try { URL res = getResource(path); return res == null ? null : res.openStream(); } catch (IOException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WebAppConfig.ErrorOpeningStream"), err); } } public String getRealPath(String path) { // Trim the prefix if (path == null) return null; else { try { File res = new File(this.webRoot, path); if (res.isDirectory()) return res.getCanonicalPath() + "/"; else return res.getCanonicalPath(); } catch (IOException err) { return null; } } } public Set getResourcePaths(String path) { // Trim the prefix if (path == null) return null; else if (!path.startsWith("/")) throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.BadResourcePath", path)); else { String workingPath = null; if (path.equals("/")) workingPath = ""; else { boolean lastCharIsSlash = path.charAt(path.length() - 1) == '/'; workingPath = path.substring(1, path.length() - (lastCharIsSlash ? 1 : 0)); } File inPath = new File(this.webRoot, workingPath.equals("") ? "." : workingPath); if (!inPath.exists()) return null; else if (!inPath.isDirectory()) return null; // Find all the files in this folder File children[] = inPath.listFiles(); Set out = new HashSet(); for (int n = 0; n < children.length; n++) { // Write the entry as subpath + child element String entry = //this.prefix + "/" + (workingPath.length() != 0 ? workingPath + "/" : "") + children[n].getName() + (children[n].isDirectory() ? "/" : ""); out.add(entry); } return out; } } /** * @deprecated */ public javax.servlet.Servlet getServlet(String name) { return null; } /** * @deprecated */ public Enumeration getServletNames() { return Collections.enumeration(new ArrayList()); } /** * @deprecated */ public Enumeration getServlets() { return Collections.enumeration(new ArrayList()); } /** * @deprecated */ public void log(Exception exception, String msg) { this.log(msg, exception); } }
src/java/winstone/WebAppConfiguration.java
/* * Winstone Servlet Container * Copyright (C) 2003 Rick Knowles * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 as published by the Free Software Foundation. * * This program 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. * * You should have received a copy of the GNU General Public License * Version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package winstone; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionListener; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Models the web.xml file's details ... basically just a bunch of configuration * details, plus the actual instances of mounted servlets. * * @author <a href="mailto:[email protected]">Rick Knowles</a> * @version $Id$ */ public class WebAppConfiguration implements ServletContext, Comparator { private static final String ELEM_DESCRIPTION = "description"; private static final String ELEM_DISPLAY_NAME = "display-name"; private static final String ELEM_SERVLET = "servlet"; private static final String ELEM_SERVLET_MAPPING = "servlet-mapping"; private static final String ELEM_SERVLET_NAME = "servlet-name"; private static final String ELEM_FILTER = "filter"; private static final String ELEM_FILTER_MAPPING = "filter-mapping"; private static final String ELEM_FILTER_NAME = "filter-name"; private static final String ELEM_DISPATCHER = "dispatcher"; private static final String ELEM_URL_PATTERN = "url-pattern"; private static final String ELEM_WELCOME_FILES = "welcome-file-list"; private static final String ELEM_WELCOME_FILE = "welcome-file"; private static final String ELEM_SESSION_CONFIG = "session-config"; private static final String ELEM_SESSION_TIMEOUT = "session-timeout"; private static final String ELEM_MIME_MAPPING = "mime-mapping"; private static final String ELEM_MIME_EXTENSION = "extension"; private static final String ELEM_MIME_TYPE = "mime-type"; private static final String ELEM_CONTEXT_PARAM = "context-param"; private static final String ELEM_PARAM_NAME = "param-name"; private static final String ELEM_PARAM_VALUE = "param-value"; private static final String ELEM_LISTENER = "listener"; private static final String ELEM_LISTENER_CLASS = "listener-class"; private static final String ELEM_DISTRIBUTABLE = "distributable"; private static final String ELEM_ERROR_PAGE = "error-page"; private static final String ELEM_EXCEPTION_TYPE = "exception-type"; private static final String ELEM_ERROR_CODE = "error-code"; private static final String ELEM_ERROR_LOCATION = "location"; private static final String ELEM_SECURITY_CONSTRAINT = "security-constraint"; private static final String ELEM_LOGIN_CONFIG = "login-config"; private static final String ELEM_SECURITY_ROLE = "security-role"; private static final String ELEM_ROLE_NAME = "role-name"; private static final String ELEM_ENV_ENTRY = "env-entry"; private static final String ELEM_LOCALE_ENC_MAP_LIST = "locale-encoding-mapping-list"; private static final String ELEM_LOCALE_ENC_MAPPING = "locale-encoding-mapping"; private static final String ELEM_LOCALE = "locale"; private static final String ELEM_ENCODING = "encoding"; private static final String ELEM_JSP_CONFIG = "jsp-config"; private static final String ELEM_JSP_PROPERTY_GROUP = "jsp-property-group"; private static final String DISPATCHER_REQUEST = "REQUEST"; private static final String DISPATCHER_FORWARD = "FORWARD"; private static final String DISPATCHER_INCLUDE = "INCLUDE"; private static final String DISPATCHER_ERROR = "ERROR"; private static final String JSP_SERVLET_NAME = "JspServlet"; private static final String JSP_SERVLET_MAPPING = "*.jsp"; private static final String JSPX_SERVLET_MAPPING = "*.jspx"; private static final String JSP_SERVLET_LOG_LEVEL = "WARNING"; private static final String INVOKER_SERVLET_NAME = "invoker"; private static final String INVOKER_SERVLET_CLASS = "winstone.invoker.InvokerServlet"; private static final String DEFAULT_INVOKER_PREFIX = "/servlet/"; private static final String DEFAULT_SERVLET_NAME = "default"; private static final String DEFAULT_SERVLET_CLASS = "winstone.StaticResourceServlet"; private static final String DEFAULT_REALM_CLASS = "winstone.realm.ArgumentsRealm"; private static final String DEFAULT_JNDI_MGR_CLASS = "winstone.jndi.WebAppJNDIManager"; private static final String RELOADING_CL_CLASS = "winstone.classLoader.ReloadingClassLoader"; private static final String ERROR_SERVLET_NAME = "winstoneErrorServlet"; private static final String ERROR_SERVLET_CLASS = "winstone.ErrorServlet"; private static final String WEB_INF = "WEB-INF"; private static final String CLASSES = "classes/"; private static final String LIB = "lib"; static final String JSP_SERVLET_CLASS = "org.apache.jasper.servlet.JspServlet"; private HostConfiguration ownerHostConfig; private Cluster cluster; private String webRoot; private String prefix; private String contextName; private ClassLoader loader; private String displayName; private Map attributes; private Map initParameters; private Map sessions; private Map mimeTypes; private Map servletInstances; private Map filterInstances; private ServletContextAttributeListener contextAttributeListeners[]; private ServletContextListener contextListeners[]; private ServletRequestListener requestListeners[]; private ServletRequestAttributeListener requestAttributeListeners[]; private HttpSessionActivationListener sessionActivationListeners[]; private HttpSessionAttributeListener sessionAttributeListeners[]; private HttpSessionListener sessionListeners[]; private Throwable contextStartupError; private Map exactServletMatchMounts; private Mapping patternMatches[]; private Mapping filterPatternsRequest[]; private Mapping filterPatternsForward[]; private Mapping filterPatternsInclude[]; private Mapping filterPatternsError[]; private AuthenticationHandler authenticationHandler; private AuthenticationRealm authenticationRealm; private String welcomeFiles[]; private Integer sessionTimeout; private Class[] errorPagesByExceptionKeysSorted; private Map errorPagesByException; private Map errorPagesByCode; private Map localeEncodingMap; private String defaultServletName; private String errorServletName; private JNDIManager jndiManager; private AccessLogger accessLogger; private Map filterMatchCache; public static boolean booleanArg(Map args, String name, boolean defaultTrue) { String value = (String) args.get(name); if (defaultTrue) return (value == null) || (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); else return (value != null) && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); } public static String stringArg(Map args, String name, String defaultValue) { return (String) (args.get(name) == null ? defaultValue : args.get(name)); } public static int intArg(Map args, String name, int defaultValue) { return Integer.parseInt(stringArg(args, name, "" + defaultValue)); } public static String getTextFromNode(Node node) { if (node == null) { return null; } Node child = node.getFirstChild(); if (child == null) { return ""; } String textNode = child.getNodeValue(); if (textNode == null) { return ""; } else { return textNode.trim(); } } /** * Constructor. This parses the xml and sets up for basic routing */ public WebAppConfiguration(HostConfiguration ownerHostConfig, Cluster cluster, String webRoot, String prefix, ObjectPool objectPool, Map startupArgs, Node elm, ClassLoader parentClassLoader, File parentClassPaths[], String contextName) { this.ownerHostConfig = ownerHostConfig; this.webRoot = webRoot; this.prefix = prefix; this.contextName = contextName; List localLoaderClassPathFiles = new ArrayList(); this.loader = buildWebAppClassLoader(startupArgs, parentClassLoader, webRoot, localLoaderClassPathFiles); // Build switch values boolean useJasper = booleanArg(startupArgs, "useJasper", false); boolean useInvoker = booleanArg(startupArgs, "useInvoker", true); boolean useJNDI = booleanArg(startupArgs, "useJNDI", false); // Check jasper is available if (useJasper) { try { Class.forName(JSP_SERVLET_CLASS, false, this.loader); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.JasperNotFound"); Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.JasperLoadException", err); useJasper = false; } } if (useInvoker) { try { Class.forName(INVOKER_SERVLET_CLASS, false, this.loader); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvokerNotFound"); useInvoker = false; } } this.attributes = new Hashtable(); this.initParameters = new HashMap(); this.sessions = new Hashtable(); this.servletInstances = new HashMap(); this.filterInstances = new HashMap(); this.filterMatchCache = new HashMap(); List contextAttributeListeners = new ArrayList(); List contextListeners = new ArrayList(); List requestListeners = new ArrayList(); List requestAttributeListeners = new ArrayList(); List sessionActivationListeners = new ArrayList(); List sessionAttributeListeners = new ArrayList(); List sessionListeners = new ArrayList(); this.errorPagesByException = new HashMap(); this.errorPagesByCode = new HashMap(); boolean distributable = false; this.exactServletMatchMounts = new Hashtable(); List localFolderPatterns = new ArrayList(); List localExtensionPatterns = new ArrayList(); List lfpRequest = new ArrayList(); List lfpForward = new ArrayList(); List lfpInclude = new ArrayList(); List lfpError = new ArrayList(); List localWelcomeFiles = new ArrayList(); List startupServlets = new ArrayList(); Set rolesAllowed = new HashSet(); List constraintNodes = new ArrayList(); List envEntryNodes = new ArrayList(); List localErrorPagesByExceptionList = new ArrayList(); Node loginConfigNode = null; // Add the class loader as an implicit context listener if it implements the interface addListenerInstance(this.loader, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners); // init mimeTypes set this.mimeTypes = new Hashtable(); String allTypes = Launcher.RESOURCES.getString("WebAppConfig.DefaultMimeTypes"); StringTokenizer mappingST = new StringTokenizer(allTypes, ":", false); for (; mappingST.hasMoreTokens();) { String mapping = mappingST.nextToken(); int delimPos = mapping.indexOf('='); if (delimPos == -1) continue; String extension = mapping.substring(0, delimPos); String mimeType = mapping.substring(delimPos + 1); this.mimeTypes.put(extension.toLowerCase(), mimeType); } this.localeEncodingMap = new HashMap(); String encodingMapSet = Launcher.RESOURCES.getString("WebAppConfig.EncodingMap"); StringTokenizer st = new StringTokenizer(encodingMapSet, ";"); for (; st.hasMoreTokens();) { String token = st.nextToken(); int delimPos = token.indexOf("="); if (delimPos == -1) continue; this.localeEncodingMap.put(token.substring(0, delimPos), token .substring(delimPos + 1)); } // init jsp mappings set List jspMappings = new ArrayList(); jspMappings.add(JSP_SERVLET_MAPPING); jspMappings.add(JSPX_SERVLET_MAPPING); // Add required context atttributes File tmpDir = new File(new File(new File(System.getProperty("java.io.tmpdir"), "winstone.tmp"), ownerHostConfig.getHostname()), contextName); tmpDir.mkdirs(); this.attributes.put("javax.servlet.context.tempdir", tmpDir); // Parse the web.xml file if (elm != null) { NodeList children = elm.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node child = children.item(n); if (child.getNodeType() != Node.ELEMENT_NODE) continue; String nodeName = child.getNodeName(); if (nodeName.equals(ELEM_DISPLAY_NAME)) this.displayName = getTextFromNode(child); else if (nodeName.equals(ELEM_DISTRIBUTABLE)) distributable = true; else if (nodeName.equals(ELEM_SECURITY_CONSTRAINT)) constraintNodes.add(child); else if (nodeName.equals(ELEM_ENV_ENTRY)) envEntryNodes.add(child); else if (nodeName.equals(ELEM_LOGIN_CONFIG)) loginConfigNode = child; // Session config elements else if (nodeName.equals(ELEM_SESSION_CONFIG)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node timeoutElm = child.getChildNodes().item(m); if ((timeoutElm.getNodeType() == Node.ELEMENT_NODE) && (timeoutElm.getNodeName().equals(ELEM_SESSION_TIMEOUT))) { String timeoutStr = getTextFromNode(child); if (!timeoutStr.equals("")) { this.sessionTimeout = Integer.valueOf(timeoutStr); } } } } // Construct the security roles else if (child.getNodeName().equals(ELEM_SECURITY_ROLE)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node roleElm = child.getChildNodes().item(m); if ((roleElm.getNodeType() == Node.ELEMENT_NODE) && (roleElm.getNodeName() .equals(ELEM_ROLE_NAME))) rolesAllowed.add(getTextFromNode(roleElm)); } } // Construct the servlet instances else if (nodeName.equals(ELEM_SERVLET)) { ServletConfiguration instance = new ServletConfiguration( this, child); this.servletInstances.put(instance.getServletName(), instance); if (instance.getLoadOnStartup() >= 0) startupServlets.add(instance); } // Construct the servlet instances else if (nodeName.equals(ELEM_FILTER)) { FilterConfiguration instance = new FilterConfiguration( this, this.loader, child); this.filterInstances.put(instance.getFilterName(), instance); } // Construct the servlet instances else if (nodeName.equals(ELEM_LISTENER)) { String listenerClass = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node listenerElm = child.getChildNodes().item(m); if ((listenerElm.getNodeType() == Node.ELEMENT_NODE) && (listenerElm.getNodeName() .equals(ELEM_LISTENER_CLASS))) listenerClass = getTextFromNode(listenerElm); } if (listenerClass != null) try { Class listener = Class.forName(listenerClass, true, this.loader); Object listenerInstance = listener.newInstance(); addListenerInstance(listenerInstance, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners); Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.AddListener", listenerClass); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidListener", listenerClass); } } // Process the servlet mappings else if (nodeName.equals(ELEM_SERVLET_MAPPING)) { String name = null; String pattern = null; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node mapChild = child.getChildNodes().item(k); if (mapChild.getNodeType() != Node.ELEMENT_NODE) continue; String mapNodeName = mapChild.getNodeName(); if (mapNodeName.equals(ELEM_SERVLET_NAME)) name = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_URL_PATTERN)) pattern = getTextFromNode(mapChild); } processMapping(name, pattern, this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } // Process the filter mappings else if (nodeName.equals(ELEM_FILTER_MAPPING)) { String filterName = null; String servletName = null; String urlPattern = null; boolean onRequest = false; boolean onForward = false; boolean onInclude = false; boolean onError = false; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node mapChild = child.getChildNodes().item(k); if (mapChild.getNodeType() != Node.ELEMENT_NODE) continue; String mapNodeName = mapChild.getNodeName(); if (mapNodeName.equals(ELEM_FILTER_NAME)) filterName = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_SERVLET_NAME)) servletName = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_URL_PATTERN)) urlPattern = getTextFromNode(mapChild); else if (mapNodeName.equals(ELEM_DISPATCHER)) { String dispatcherValue = getTextFromNode(mapChild); if (dispatcherValue.equals(DISPATCHER_REQUEST)) onRequest = true; else if (dispatcherValue.equals(DISPATCHER_FORWARD)) onForward = true; else if (dispatcherValue.equals(DISPATCHER_INCLUDE)) onInclude = true; else if (dispatcherValue.equals(DISPATCHER_ERROR)) onError = true; } } if (!onRequest && !onInclude && !onForward && !onError) onRequest = true; Mapping mapping = null; if (servletName != null) { mapping = Mapping.createFromLink(filterName, servletName); } else if (urlPattern != null) { mapping = Mapping.createFromURL(filterName, urlPattern); } else { throw new WinstoneException("Error in filter mapping - no pattern and no servlet name"); } if (onRequest) lfpRequest.add(mapping); if (onForward) lfpForward.add(mapping); if (onInclude) lfpInclude.add(mapping); if (onError) lfpError.add(mapping); } // Process the list of welcome files else if (nodeName.equals(ELEM_WELCOME_FILES)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node welcomeFile = child.getChildNodes().item(m); if ((welcomeFile.getNodeType() == Node.ELEMENT_NODE) && welcomeFile.getNodeName().equals(ELEM_WELCOME_FILE)) { String welcomeStr = getTextFromNode(welcomeFile); if (!welcomeStr.equals("")) { localWelcomeFiles.add(welcomeStr); } } } } // Process the error pages else if (nodeName.equals(ELEM_ERROR_PAGE)) { String code = null; String exception = null; String location = null; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node errorChild = child.getChildNodes().item(k); if (errorChild.getNodeType() != Node.ELEMENT_NODE) continue; String errorChildName = errorChild.getNodeName(); if (errorChildName.equals(ELEM_ERROR_CODE)) code = getTextFromNode(errorChild); else if (errorChildName.equals(ELEM_EXCEPTION_TYPE)) exception = getTextFromNode(errorChild); else if (errorChildName.equals(ELEM_ERROR_LOCATION)) location = getTextFromNode(errorChild); } if ((code != null) && (location != null)) this.errorPagesByCode.put(code.trim(), location.trim()); if ((exception != null) && (location != null)) try { Class exceptionClass = Class.forName(exception .trim(), false, this.loader); localErrorPagesByExceptionList.add(exceptionClass); this.errorPagesByException.put(exceptionClass, location.trim()); } catch (ClassNotFoundException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ExceptionNotFound", exception); } } // Process the list of welcome files else if (nodeName.equals(ELEM_MIME_MAPPING)) { String extension = null; String mimeType = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node mimeTypeNode = child.getChildNodes().item(m); if (mimeTypeNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mimeTypeNode.getNodeName().equals( ELEM_MIME_EXTENSION)) extension = getTextFromNode(mimeTypeNode); else if (mimeTypeNode.getNodeName().equals( ELEM_MIME_TYPE)) mimeType = getTextFromNode(mimeTypeNode); } if ((extension != null) && (mimeType != null)) this.mimeTypes.put(extension.toLowerCase(), mimeType); else Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidMimeMapping", new String[] { extension, mimeType }); } // Process the list of welcome files else if (nodeName.equals(ELEM_CONTEXT_PARAM)) { String name = null; String value = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node contextParamNode = child.getChildNodes().item(m); if (contextParamNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (contextParamNode.getNodeName().equals( ELEM_PARAM_NAME)) name = getTextFromNode(contextParamNode); else if (contextParamNode.getNodeName().equals( ELEM_PARAM_VALUE)) value = getTextFromNode(contextParamNode); } if ((name != null) && (value != null)) this.initParameters.put(name, value); else Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidInitParam", new String[] { name, value }); } // Process locale encoding mapping elements else if (nodeName.equals(ELEM_LOCALE_ENC_MAP_LIST)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node mappingNode = child.getChildNodes().item(m); if (mappingNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mappingNode.getNodeName().equals(ELEM_LOCALE_ENC_MAPPING)) { String localeName = ""; String encoding = ""; for (int l = 0; l < mappingNode.getChildNodes().getLength(); l++) { Node mappingChildNode = mappingNode.getChildNodes().item(l); if (mappingChildNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mappingChildNode.getNodeName().equals(ELEM_LOCALE)) localeName = getTextFromNode(mappingChildNode); else if (mappingChildNode.getNodeName().equals(ELEM_ENCODING)) encoding = getTextFromNode(mappingChildNode); } if (!encoding.equals("") && !localeName.equals("")) this.localeEncodingMap.put(localeName, encoding); } } } // Record the url mappings for jsp files if set else if (nodeName.equals(ELEM_JSP_CONFIG)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node propertyGroupNode = child.getChildNodes().item(m); if ((propertyGroupNode.getNodeType() == Node.ELEMENT_NODE) && propertyGroupNode.getNodeName().equals(ELEM_JSP_PROPERTY_GROUP)) { for (int l = 0; l < propertyGroupNode.getChildNodes().getLength(); l++) { Node urlPatternNode = propertyGroupNode.getChildNodes().item(l); if ((urlPatternNode.getNodeType() == Node.ELEMENT_NODE) && urlPatternNode.getNodeName().equals(ELEM_URL_PATTERN)) { String jm = getTextFromNode(urlPatternNode); if (!jm.equals("")) { jspMappings.add(jm); } } } } } } } } // If not distributable, remove the cluster reference if (!distributable && (cluster != null)) { Logger.log(Logger.INFO, Launcher.RESOURCES, "WebAppConfig.ClusterOffNotDistributable", this.contextName); } else { this.cluster = cluster; } // Build the login/security role instance if (!constraintNodes.isEmpty() && (loginConfigNode != null)) { String authMethod = null; for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++) if (loginConfigNode.getChildNodes().item(n).getNodeName().equals("auth-method")) authMethod = getTextFromNode(loginConfigNode.getChildNodes().item(n)); // Load the appropriate auth class if (authMethod == null) authMethod = "BASIC"; else authMethod = WinstoneResourceBundle.globalReplace(authMethod, "-", ""); String realmClassName = stringArg(startupArgs, "realmClassName", DEFAULT_REALM_CLASS).trim(); String authClassName = "winstone.auth." + authMethod.substring(0, 1).toUpperCase() + authMethod.substring(1).toLowerCase() + "AuthenticationHandler"; try { // Build the realm Class realmClass = Class.forName(realmClassName); Constructor realmConstr = realmClass .getConstructor(new Class[] {Set.class, Map.class }); this.authenticationRealm = (AuthenticationRealm) realmConstr .newInstance(new Object[] { rolesAllowed, startupArgs }); // Build the authentication handler Class authClass = Class.forName(authClassName); Constructor authConstr = authClass .getConstructor(new Class[] { Node.class, List.class, Set.class, AuthenticationRealm.class }); this.authenticationHandler = (AuthenticationHandler) authConstr .newInstance(new Object[] { loginConfigNode, constraintNodes, rolesAllowed, authenticationRealm }); } catch (ClassNotFoundException err) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.AuthDisabled", authMethod); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.AuthError", new String[] { authClassName, realmClassName }, err); } } // Instantiate the JNDI manager String jndiMgrClassName = stringArg(startupArgs, "webappJndiClassName", DEFAULT_JNDI_MGR_CLASS).trim(); if (useJNDI) { try { // Build the realm Class jndiMgrClass = Class.forName(jndiMgrClassName, true, this.loader); Constructor jndiMgrConstr = jndiMgrClass.getConstructor(new Class[] { Map.class, List.class, ClassLoader.class }); this.jndiManager = (JNDIManager) jndiMgrConstr.newInstance(new Object[] { null, envEntryNodes, this.loader }); if (this.jndiManager != null) this.jndiManager.setup(); } catch (ClassNotFoundException err) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.JNDIDisabled"); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.JNDIError", jndiMgrClassName, err); } } String loggerClassName = stringArg(startupArgs, "accessLoggerClassName", "").trim(); if (!loggerClassName.equals("")) { try { // Build the realm Class loggerClass = Class.forName(loggerClassName, true, this.loader); Constructor loggerConstr = loggerClass.getConstructor(new Class[] { WebAppConfiguration.class, Map.class }); this.accessLogger = (AccessLogger) loggerConstr.newInstance(new Object[] { this, startupArgs}); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.LoggerError", loggerClassName, err); } } else { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.LoggerDisabled"); } // Add the default index.html welcomeFile if none are supplied if (localWelcomeFiles.isEmpty()) { if (useJasper) { localWelcomeFiles.add("index.jsp"); } localWelcomeFiles.add("index.html"); } // Put the name filters after the url filters, then convert to string // arrays this.filterPatternsRequest = (Mapping[]) lfpRequest.toArray(new Mapping[0]); this.filterPatternsForward = (Mapping[]) lfpForward.toArray(new Mapping[0]); this.filterPatternsInclude = (Mapping[]) lfpInclude.toArray(new Mapping[0]); this.filterPatternsError = (Mapping[]) lfpError.toArray(new Mapping[0]); if (this.filterPatternsRequest.length > 0) Arrays.sort(this.filterPatternsRequest, this.filterPatternsRequest[0]); if (this.filterPatternsForward.length > 0) Arrays.sort(this.filterPatternsForward, this.filterPatternsForward[0]); if (this.filterPatternsInclude.length > 0) Arrays.sort(this.filterPatternsInclude, this.filterPatternsInclude[0]); if (this.filterPatternsError.length > 0) Arrays.sort(this.filterPatternsError, this.filterPatternsError[0]); this.welcomeFiles = (String[]) localWelcomeFiles.toArray(new String[0]); this.errorPagesByExceptionKeysSorted = (Class[]) localErrorPagesByExceptionList .toArray(new Class[0]); Arrays.sort(this.errorPagesByExceptionKeysSorted, this); // Put the listeners into their arrays this.contextAttributeListeners = (ServletContextAttributeListener[]) contextAttributeListeners .toArray(new ServletContextAttributeListener[0]); this.contextListeners = (ServletContextListener[]) contextListeners .toArray(new ServletContextListener[0]); this.requestListeners = (ServletRequestListener[]) requestListeners .toArray(new ServletRequestListener[0]); this.requestAttributeListeners = (ServletRequestAttributeListener[]) requestAttributeListeners .toArray(new ServletRequestAttributeListener[0]); this.sessionActivationListeners = (HttpSessionActivationListener[]) sessionActivationListeners .toArray(new HttpSessionActivationListener[0]); this.sessionAttributeListeners = (HttpSessionAttributeListener[]) sessionAttributeListeners .toArray(new HttpSessionAttributeListener[0]); this.sessionListeners = (HttpSessionListener[]) sessionListeners .toArray(new HttpSessionListener[0]); // If we haven't explicitly mapped the default servlet, map it here if (this.defaultServletName == null) this.defaultServletName = DEFAULT_SERVLET_NAME; if (this.errorServletName == null) this.errorServletName = ERROR_SERVLET_NAME; // If we don't have an instance of the default servlet, mount the inbuilt one if (this.servletInstances.get(this.defaultServletName) == null) { boolean useDirLists = booleanArg(startupArgs, "directoryListings", true); Map staticParams = new Hashtable(); staticParams.put("webRoot", webRoot); staticParams.put("prefix", this.prefix); staticParams.put("directoryList", "" + useDirLists); ServletConfiguration defaultServlet = new ServletConfiguration( this, this.defaultServletName, DEFAULT_SERVLET_CLASS, staticParams, 0); // commented cause it should be called during startup servlet // defaultServlet.getRequestDispatcher(this.filterInstances); this.servletInstances.put(this.defaultServletName, defaultServlet); startupServlets.add(defaultServlet); } // If we don't have an instance of the default servlet, mount the inbuilt one if (this.servletInstances.get(this.errorServletName) == null) { ServletConfiguration errorServlet = new ServletConfiguration( this, this.errorServletName, ERROR_SERVLET_CLASS, new HashMap(), 0); // commented cause it should be called during startup servlet // errorServlet.getRequestDispatcher(this.filterInstances); this.servletInstances.put(this.errorServletName, errorServlet); startupServlets.add(errorServlet); } // Initialise jasper servlet if requested if (useJasper) { setAttribute("org.apache.catalina.classloader", this.loader); // Logger.log(Logger.DEBUG, "Setting JSP classpath: " + // this.loader.getClasspath()); try { StringBuffer cp = new StringBuffer(); for (Iterator i = localLoaderClassPathFiles.iterator(); i.hasNext(); ) { cp.append(((File) i.next()).getCanonicalPath()).append( File.pathSeparatorChar); } for (int n = 0; n < parentClassPaths.length; n++) { cp.append(parentClassPaths[n].getCanonicalPath()).append( File.pathSeparatorChar); } setAttribute("org.apache.catalina.jsp_classpath", (cp.length() > 0 ? cp.substring(0, cp.length() - 1) : "")); } catch (IOException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ErrorSettingJSPPaths", err); } Map jspParams = new HashMap(); addJspServletParams(jspParams); ServletConfiguration sc = new ServletConfiguration(this, JSP_SERVLET_NAME, JSP_SERVLET_CLASS, jspParams, 3); this.servletInstances.put(JSP_SERVLET_NAME, sc); startupServlets.add(sc); for (Iterator mapIt = jspMappings.iterator(); mapIt.hasNext(); ) { processMapping(JSP_SERVLET_NAME, (String) mapIt.next(), this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } } // Initialise invoker servlet if requested if (useInvoker) { // Get generic options String invokerPrefix = stringArg(startupArgs, "invokerPrefix", DEFAULT_INVOKER_PREFIX); Map invokerParams = new HashMap(); invokerParams.put("prefix", this.prefix); invokerParams.put("invokerPrefix", invokerPrefix); ServletConfiguration sc = new ServletConfiguration(this, INVOKER_SERVLET_NAME, INVOKER_SERVLET_CLASS, invokerParams, 3); this.servletInstances.put(INVOKER_SERVLET_NAME, sc); processMapping(INVOKER_SERVLET_NAME, invokerPrefix + Mapping.STAR, this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } // Sort the folder patterns so the longest paths are first localFolderPatterns.addAll(localExtensionPatterns); this.patternMatches = (Mapping[]) localFolderPatterns.toArray(new Mapping[0]); if (this.patternMatches.length > 0) Arrays.sort(this.patternMatches, this.patternMatches[0]); // Send init notifies try { for (int n = 0; n < this.contextListeners.length; n++) this.contextListeners[n].contextInitialized(new ServletContextEvent(this)); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ContextStartupError", this.contextName, err); this.contextStartupError = err; } if (this.contextStartupError == null) { // Initialise all the filters for (Iterator i = this.filterInstances.values().iterator(); i.hasNext();) { FilterConfiguration config = (FilterConfiguration) i.next(); try { config.getFilter(); } catch (ServletException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.FilterStartupError", config.getFilterName(), err); } } // Initialise load on startup servlets Object autoStarters[] = startupServlets.toArray(); Arrays.sort(autoStarters); for (int n = 0; n < autoStarters.length; n++) { ((ServletConfiguration) autoStarters[n]).ensureInitialization(); } } } /** * Build the web-app classloader. This tries to load the preferred classloader first, * but if it fails, falls back to a simple URLClassLoader. */ private ClassLoader buildWebAppClassLoader(Map startupArgs, ClassLoader parentClassLoader, String webRoot, List classPathFileList) { List urlList = new ArrayList(); try { // Web-inf folder File webInfFolder = new File(webRoot, WEB_INF); // Classes folder File classesFolder = new File(webInfFolder, CLASSES); if (classesFolder.exists()) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WinstoneClassLoader.WebAppClasses"); urlList.add(new URL("file", "", classesFolder.getCanonicalPath() + "/")); classPathFileList.add(classesFolder); } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneClassLoader.NoWebAppClasses", classesFolder.toString()); } // Lib folder's jar files File libFolder = new File(webInfFolder, LIB); if (libFolder.exists()) { File jars[] = libFolder.listFiles(); for (int n = 0; n < jars.length; n++) { String jarName = jars[n].getCanonicalPath().toLowerCase(); if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WinstoneClassLoader.WebAppLib", jars[n].getName()); urlList.add(jars[n].toURL()); classPathFileList.add(jars[n]); } } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneClassLoader.NoWebAppLib", libFolder .toString()); } } catch (MalformedURLException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WinstoneClassLoader.BadURL"), err); } catch (IOException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WinstoneClassLoader.IOException"), err); } URL jarURLs[] = (URL []) urlList.toArray(new URL[0]); boolean useReloading = booleanArg(startupArgs, "useServletReloading", false); String preferredClassLoader = stringArg(startupArgs, "preferredClassLoader", ""); if (preferredClassLoader.equals("") && useReloading) { preferredClassLoader = RELOADING_CL_CLASS; } // Try to set up the preferred class loader, and if we fail, use the normal one ClassLoader outputCL = null; if (!preferredClassLoader.equals("")) { try { Class preferredCL = Class.forName(preferredClassLoader, true, parentClassLoader); Constructor reloadConstr = preferredCL.getConstructor(new Class[] { (new URL[0]).getClass(), ClassLoader.class}); outputCL = (ClassLoader) reloadConstr.newInstance(new Object[] { jarURLs, parentClassLoader}); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.CLError", err); } } if (outputCL == null) { outputCL = new URLClassLoader(jarURLs, parentClassLoader); } Logger.log(Logger.MAX, Launcher.RESOURCES, "WebAppConfig.WebInfClassLoader", outputCL.toString()); return outputCL; } private void addListenerInstance(Object listenerInstance, List contextAttributeListeners, List contextListeners, List requestAttributeListeners, List requestListeners, List sessionActivationListeners, List sessionAttributeListeners, List sessionListeners) { if (listenerInstance instanceof ServletContextAttributeListener) contextAttributeListeners.add(listenerInstance); if (listenerInstance instanceof ServletContextListener) contextListeners.add(listenerInstance); if (listenerInstance instanceof ServletRequestAttributeListener) requestAttributeListeners.add(listenerInstance); if (listenerInstance instanceof ServletRequestListener) requestListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionActivationListener) sessionActivationListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionAttributeListener) sessionAttributeListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionListener) sessionListeners.add(listenerInstance); } public String getPrefix() { return this.prefix; } public String getWebroot() { return this.webRoot; } public ClassLoader getLoader() { return this.loader; } public AccessLogger getAccessLogger() { return this.accessLogger; } public Map getFilters() { return this.filterInstances; } public String getContextName() { return this.contextName; } public Class[] getErrorPageExceptions() { return this.errorPagesByExceptionKeysSorted; } public Map getErrorPagesByException() { return this.errorPagesByException; } public Map getErrorPagesByCode() { return this.errorPagesByCode; } public Map getLocaleEncodingMap() { return this.localeEncodingMap; } public String[] getWelcomeFiles() { return this.welcomeFiles; } // public boolean isDistributable() { // return this.distributable; // } public Map getFilterMatchCache() { return this.filterMatchCache; } public String getOwnerHostname() { return this.ownerHostConfig.getHostname(); } public ServletRequestListener[] getRequestListeners() { return this.requestListeners; } public ServletRequestAttributeListener[] getRequestAttributeListeners() { return this.requestAttributeListeners; } public static void addJspServletParams(Map jspParams) { jspParams.put("logVerbosityLevel", JSP_SERVLET_LOG_LEVEL); jspParams.put("fork", "false"); } public int compare(Object one, Object two) { if (!(one instanceof Class) || !(two instanceof Class)) throw new IllegalArgumentException( "This comparator is only for sorting classes"); Class classOne = (Class) one; Class classTwo = (Class) two; if (classOne.isAssignableFrom(classTwo)) return 1; else if (classTwo.isAssignableFrom(classOne)) return -1; else return 0; } public String getServletURIFromRequestURI(String requestURI) { if (prefix.equals("")) { return requestURI; } else if (requestURI.startsWith(prefix)) { return requestURI.substring(prefix.length()); } else { throw new WinstoneException("This shouldn't happen, " + "since we aborted earlier if we didn't match"); } } /** * Iterates through each of the servlets/filters and calls destroy on them */ public void destroy() { synchronized (this.filterMatchCache) { this.filterMatchCache.clear(); } Collection filterInstances = new ArrayList(this.filterInstances.values()); for (Iterator i = filterInstances.iterator(); i.hasNext();) { try { ((FilterConfiguration) i.next()).destroy(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.filterInstances.clear(); Collection servletInstances = new ArrayList(this.servletInstances.values()); for (Iterator i = servletInstances.iterator(); i.hasNext();) { try { ((ServletConfiguration) i.next()).destroy(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.servletInstances.clear(); // Drop all sessions Collection sessions = new ArrayList(this.sessions.values()); for (Iterator i = sessions.iterator(); i.hasNext();) { try { ((WinstoneSession) i.next()).invalidate(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.sessions.clear(); // Send destroy notifies - backwards for (int n = this.contextListeners.length - 1; n >= 0; n--) { try { this.contextListeners[n].contextDestroyed(new ServletContextEvent(this)); this.contextListeners[n] = null; } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.contextListeners = null; // Terminate class loader reloading thread if running if (this.loader != null) { // already shutdown/handled by the servlet context listeners // try { // Method methDestroy = this.loader.getClass().getMethod("destroy", new Class[0]); // methDestroy.invoke(this.loader, new Object[0]); // } catch (Throwable err) { // Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); // } this.loader = null; } // Kill JNDI manager if we have one if (this.jndiManager != null) { this.jndiManager.tearDown(); this.jndiManager = null; } // Kill JNDI manager if we have one if (this.accessLogger != null) { this.accessLogger.destroy(); this.accessLogger = null; } } /** * Triggered by the admin thread on the reloading class loader. This will * cause a full shutdown and reinstantiation of the web app - not real * graceful, but you shouldn't have reloading turned on in high load * environments. */ public void resetClassLoader() throws IOException { this.ownerHostConfig.reloadWebApp(getPrefix()); } /** * Here we process url patterns into the exactMatch and patternMatch lists */ private void processMapping(String name, String pattern, Map exactPatterns, List folderPatterns, List extensionPatterns) { Mapping urlPattern = null; try { urlPattern = Mapping.createFromURL(name, pattern); } catch (WinstoneException err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.ErrorMapURL", err.getMessage()); return; } // put the pattern in the correct list if (urlPattern.getPatternType() == Mapping.EXACT_PATTERN) { exactPatterns.put(urlPattern.getUrlPattern(), name); } else if (urlPattern.getPatternType() == Mapping.FOLDER_PATTERN) { folderPatterns.add(urlPattern); } else if (urlPattern.getPatternType() == Mapping.EXTENSION_PATTERN) { extensionPatterns.add(urlPattern); } else if (urlPattern.getPatternType() == Mapping.DEFAULT_SERVLET) { this.defaultServletName = name; } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidMount", new String[] { name, pattern }); } } /** * Execute the pattern match, and try to return a servlet that matches this * URL */ private ServletConfiguration urlMatch(String path, StringBuffer servletPath, StringBuffer pathInfo) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.URLMatch", path); // Check exact matches first String exact = (String) this.exactServletMatchMounts.get(path); if (exact != null) { if (this.servletInstances.get(exact) != null) { servletPath.append(path); // pathInfo.append(""); // a hack - empty becomes null later return (ServletConfiguration) this.servletInstances.get(exact); } } // Inexact mount check for (int n = 0; n < this.patternMatches.length; n++) { Mapping urlPattern = this.patternMatches[n]; if (urlPattern.match(path, servletPath, pathInfo) && (this.servletInstances.get(urlPattern.getMappedTo()) != null)) { return (ServletConfiguration) this.servletInstances .get(urlPattern.getMappedTo()); } } // return default servlet // servletPath.append(""); // unneeded if (this.servletInstances.get(this.defaultServletName) == null) throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.MatchedNonExistServlet", this.defaultServletName)); // pathInfo.append(path); servletPath.append(path); return (ServletConfiguration) this.servletInstances.get(this.defaultServletName); } /** * Constructs a session instance with the given sessionId * * @param sessionId The sessionID for the new session * @return A valid session object */ public WinstoneSession makeNewSession(String sessionId) { WinstoneSession ws = new WinstoneSession(sessionId, this, (this.cluster != null)); setSessionListeners(ws); if ((this.sessionTimeout != null) && (this.sessionTimeout.intValue() > 0)) ws.setMaxInactiveInterval(this.sessionTimeout.intValue() * 60); else ws.setMaxInactiveInterval(-1); ws.setLastAccessedDate(System.currentTimeMillis()); ws.sendCreatedNotifies(); this.sessions.put(sessionId, ws); return ws; } /** * Retrieves the session by id. If the web app is distributable, it asks the * other members of the cluster if it doesn't have it itself. * * @param sessionId The id of the session we want * @return A valid session instance */ public WinstoneSession getSessionById(String sessionId, boolean localOnly) { if (sessionId == null) { return null; } WinstoneSession session = (WinstoneSession) this.sessions.get(sessionId); if (session != null) { return session; } // If I'm distributable ... check remotely if ((this.cluster != null) && !localOnly) { session = this.cluster.askClusterForSession(sessionId, this); if (session != null) { this.sessions.put(sessionId, session); } return session; } else { return null; } } /** * Remove the session from the collection */ public void removeSessionById(String sessionId) { this.sessions.remove(sessionId); } public void setSessionListeners(WinstoneSession session) { session.setSessionActivationListeners(this.sessionActivationListeners); session.setSessionAttributeListeners(this.sessionAttributeListeners); session.setSessionListeners(this.sessionListeners); } public void removeServletConfigurationAndMappings(ServletConfiguration config) { this.servletInstances.remove(config.getServletName()); // The urlMatch method will only match to non-null mappings, so we don't need // to remove anything here } /*************************************************************************** * * OK ... from here to the end is the interface implementation methods for * the servletContext interface. * **************************************************************************/ // Application level attributes public Object getAttribute(String name) { return this.attributes.get(name); } public Enumeration getAttributeNames() { return Collections.enumeration(this.attributes.keySet()); } public void removeAttribute(String name) { Object me = this.attributes.get(name); this.attributes.remove(name); if (me != null) for (int n = 0; n < this.contextAttributeListeners.length; n++) this.contextAttributeListeners[n] .attributeRemoved(new ServletContextAttributeEvent( this, name, me)); } public void setAttribute(String name, Object object) { if (object == null) { removeAttribute(name); } else { Object me = this.attributes.get(name); this.attributes.put(name, object); if (me != null) { for (int n = 0; n < this.contextAttributeListeners.length; n++) this.contextAttributeListeners[n] .attributeReplaced(new ServletContextAttributeEvent( this, name, me)); } else { for (int n = 0; n < this.contextAttributeListeners.length; n++) this.contextAttributeListeners[n] .attributeAdded(new ServletContextAttributeEvent(this, name, object)); } } } // Application level init parameters public String getInitParameter(String name) { return (String) this.initParameters.get(name); } public Enumeration getInitParameterNames() { return Collections.enumeration(this.initParameters.keySet()); } // Server info public String getServerInfo() { return Launcher.RESOURCES.getString("ServerVersion"); } public int getMajorVersion() { return 2; } public int getMinorVersion() { return 4; } // Weird mostly deprecated crap to do with getting servlet instances public javax.servlet.ServletContext getContext(String uri) { return this.ownerHostConfig.getWebAppByURI(uri); } public String getServletContextName() { return this.displayName; } /** * Look up the map of mimeType extensions, and return the type that matches */ public String getMimeType(String fileName) { int dotPos = fileName.lastIndexOf('.'); if ((dotPos != -1) && (dotPos != fileName.length() - 1)) { String extension = fileName.substring(dotPos + 1).toLowerCase(); String mimeType = (String) this.mimeTypes.get(extension); return mimeType; } else return null; } // Context level log statements public void log(String message) { Logger.logDirectMessage(Logger.INFO, this.contextName, message, null); } public void log(String message, Throwable throwable) { Logger.logDirectMessage(Logger.ERROR, this.contextName, message, throwable); } /** * Named dispatcher - this basically gets us a simple exact dispatcher (no * url matching, no request attributes and no security) */ public javax.servlet.RequestDispatcher getNamedDispatcher(String name) { ServletConfiguration servlet = (ServletConfiguration) this.servletInstances.get(name); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForNamedDispatcher(this.filterPatternsForward, this.filterPatternsInclude); return rd; } } return null; } /** * Gets a dispatcher, which sets the request attributes, etc on a * forward/include. Doesn't execute security though. */ public javax.servlet.RequestDispatcher getRequestDispatcher( String uriInsideWebapp) { if (uriInsideWebapp == null) { return null; } else if (!uriInsideWebapp.startsWith("/")) { return null; } // Parse the url for query string, etc String queryString = ""; int questionPos = uriInsideWebapp.indexOf('?'); if (questionPos != -1) { if (questionPos != uriInsideWebapp.length() - 1) queryString = uriInsideWebapp.substring(questionPos + 1); uriInsideWebapp = uriInsideWebapp.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForURLDispatcher(servletPath.toString(), pathInfo.toString() .equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, this.filterPatternsForward, this.filterPatternsInclude); return rd; } } return null; } /** * Creates the dispatcher that corresponds to a request level dispatch (ie * the initial entry point). The difference here is that we need to set up * the dispatcher so that on a forward, it executes the security checks and * the request filters, while not setting any of the request attributes for * a forward. Also, we can't return a null dispatcher in error case - instead * we have to return a dispatcher pre-init'd for showing an error page (eg 404). * A null dispatcher is interpreted to mean a successful 302 has occurred. */ public RequestDispatcher getInitialDispatcher(String uriInsideWebapp, WinstoneRequest request, WinstoneResponse response) throws IOException { if (!uriInsideWebapp.equals("") && !uriInsideWebapp.startsWith("/")) { return this.getErrorDispatcherByCode( HttpServletResponse.SC_BAD_REQUEST, Launcher.RESOURCES.getString("WebAppConfig.InvalidURI", uriInsideWebapp), null); } else if (this.contextStartupError != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); this.contextStartupError.printStackTrace(pw); return this.getErrorDispatcherByCode( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Launcher.RESOURCES.getString("WebAppConfig.ErrorDuringStartup", sw.toString()), this.contextStartupError); } // Parse the url for query string, etc String queryString = ""; int questionPos = uriInsideWebapp.indexOf('?'); if (questionPos != -1) { if (questionPos != uriInsideWebapp.length() - 1) queryString = uriInsideWebapp.substring(questionPos + 1); uriInsideWebapp = uriInsideWebapp.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo); if (servlet != null) { // If the default servlet was returned, we should check for welcome files if (servlet.getServletName().equals(this.defaultServletName)) { // Is path a directory ? String directoryPath = servletPath.toString(); if (directoryPath.endsWith("/")) { directoryPath = directoryPath.substring(0, directoryPath.length() - 1); } if (directoryPath.startsWith("/")) { directoryPath = directoryPath.substring(1); } File res = new File(webRoot, directoryPath); if (res.exists() && res.isDirectory() && (request.getMethod().equals("GET") || request.getMethod().equals("HEAD"))) { // Check for the send back with slash case if (!servletPath.toString().endsWith("/")) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.FoundNonSlashDirectory", servletPath.toString()); response.sendRedirect(this.prefix + servletPath.toString() + pathInfo.toString() + "/" + (queryString.equals("") ? "" : "?" + queryString)); return null; } // Check for welcome files Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.CheckWelcomeFile", servletPath.toString() + pathInfo.toString()); String welcomeFile = matchWelcomeFiles(servletPath.toString() + pathInfo.toString(), request); if (welcomeFile != null) { response.sendRedirect(this.prefix + servletPath.toString() + pathInfo.toString() + welcomeFile + (queryString.equals("") ? "" : "?" + queryString)); return null; } } } RequestDispatcher rd = new RequestDispatcher(this, servlet); rd.setForInitialDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, this.filterPatternsRequest, this.authenticationHandler); return rd; } // If we are here, return a 404 return this.getErrorDispatcherByCode(HttpServletResponse.SC_NOT_FOUND, Launcher.RESOURCES.getString("StaticResourceServlet.PathNotFound", uriInsideWebapp), null); } /** * Gets a dispatcher, set up for error dispatch. */ public RequestDispatcher getErrorDispatcherByClass( Throwable exception) { // Check for exception class match Class exceptionClasses[] = this.errorPagesByExceptionKeysSorted; Throwable errWrapper = new ServletException(exception); while (errWrapper instanceof ServletException) { errWrapper = ((ServletException) errWrapper).getRootCause(); if (errWrapper == null) { break; } for (int n = 0; n < exceptionClasses.length; n++) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WinstoneResponse.TestingException", new String[] {this.errorPagesByExceptionKeysSorted[n].getName(), errWrapper.getClass().getName()}); if (exceptionClasses[n].isInstance(errWrapper)) { String errorURI = (String) this.errorPagesByException.get(exceptionClasses[n]); if (errorURI != null) { RequestDispatcher rd = buildErrorDispatcher(errorURI, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errWrapper.getMessage(), errWrapper); if (rd != null) { return rd; } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.SkippingException", new String[] {exceptionClasses[n].getName(), (String) this.errorPagesByException.get(exceptionClasses[n]) }); } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.ExceptionNotMatched", exceptionClasses[n].getName()); } } } // Otherwise throw a code error Throwable errPassDown = exception; while ((errPassDown instanceof ServletException) && (((ServletException) errPassDown).getRootCause() != null)) { errPassDown = ((ServletException) errPassDown).getRootCause(); } return getErrorDispatcherByCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errPassDown.getMessage(), errPassDown); } public RequestDispatcher getErrorDispatcherByCode( int statusCode, String summaryMessage, Throwable exception) { // Check for status code match String errorURI = (String) getErrorPagesByCode().get("" + statusCode); if (errorURI != null) { RequestDispatcher rd = buildErrorDispatcher(errorURI, statusCode, summaryMessage, exception); if (rd != null) { return rd; } } // If no dispatcher available, return a dispatcher to the default error formatter ServletConfiguration errorServlet = (ServletConfiguration) this.servletInstances.get(this.errorServletName); if (errorServlet != null) { RequestDispatcher rd = new RequestDispatcher(this, errorServlet); if (rd != null) { rd.setForErrorDispatcher(null, null, null, statusCode, summaryMessage, exception, null, this.filterPatternsError); return rd; } } // Otherwise log and return null Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.NoErrorServlet", "" + statusCode, exception); return null; } /** * Build a dispatcher to the error handler if it's available. If it fails, return null. */ private RequestDispatcher buildErrorDispatcher(String errorURI, int statusCode, String summaryMessage, Throwable exception) { // Parse the url for query string, etc String queryString = ""; int questionPos = errorURI.indexOf('?'); if (questionPos != -1) { if (questionPos != errorURI.length() - 1) { queryString = errorURI.substring(questionPos + 1); } errorURI = errorURI.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForErrorDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, statusCode, summaryMessage, exception, errorURI, this.filterPatternsError); return rd; } } return null; } /** * Check if any of the welcome files under this path are available. Returns the * name of the file if found, null otherwise */ private String matchWelcomeFiles(String path, WinstoneRequest request) { Set subfiles = getResourcePaths(path); for (int n = 0; n < this.welcomeFiles.length; n++) { String exact = (String) this.exactServletMatchMounts.get(path); if (exact != null) return this.welcomeFiles[n]; // Inexact folder mount check - note folder mounts only for (int j = 0; j < this.patternMatches.length; j++) { Mapping urlPattern = this.patternMatches[j]; if ((urlPattern.getPatternType() == Mapping.FOLDER_PATTERN) && urlPattern.match(path + this.welcomeFiles[n], null, null)) return this.welcomeFiles[n]; } if (subfiles.contains(path + this.welcomeFiles[n])) return this.welcomeFiles[n]; } return null; } // Getting resources via the classloader public URL getResource(String path) throws MalformedURLException { if (path == null) { return null; } else if (!path.startsWith("/")) { throw new MalformedURLException(Launcher.RESOURCES.getString( "WebAppConfig.BadResourcePath", path)); } else if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } File res = new File(webRoot, path.substring(1)); return (res != null) && res.exists() ? res.toURL() : null; } public InputStream getResourceAsStream(String path) { try { URL res = this.getResource(path); return res == null ? null : res.openStream(); } catch (IOException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WebAppConfig.ErrorOpeningStream"), err); } } public String getRealPath(String path) { // Trim the prefix if (path == null) return null; else { try { File res = new File(this.webRoot, path); if (res.isDirectory()) return res.getCanonicalPath() + "/"; else return res.getCanonicalPath(); } catch (IOException err) { return null; } } } public Set getResourcePaths(String path) { // Trim the prefix if (path == null) return null; else if (!path.startsWith("/")) throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.BadResourcePath", path)); else { String workingPath = null; if (path.equals("/")) workingPath = ""; else { boolean lastCharIsSlash = path.charAt(path.length() - 1) == '/'; workingPath = path.substring(1, path.length() - (lastCharIsSlash ? 1 : 0)); } File inPath = new File(this.webRoot, workingPath.equals("") ? "." : workingPath); if (!inPath.exists()) return null; else if (!inPath.isDirectory()) return null; // Find all the files in this folder File children[] = inPath.listFiles(); Set out = new HashSet(); for (int n = 0; n < children.length; n++) { // Write the entry as subpath + child element String entry = //this.prefix + "/" + (workingPath.length() != 0 ? workingPath + "/" : "") + children[n].getName() + (children[n].isDirectory() ? "/" : ""); out.add(entry); } return out; } } /** * @deprecated */ public javax.servlet.Servlet getServlet(String name) { return null; } /** * @deprecated */ public Enumeration getServletNames() { return Collections.enumeration(new ArrayList()); } /** * @deprecated */ public Enumeration getServlets() { return Collections.enumeration(new ArrayList()); } /** * @deprecated */ public void log(Exception exception, String msg) { this.log(msg, exception); } }
Fixed the getResource("/") case
src/java/winstone/WebAppConfiguration.java
Fixed the getResource("/") case
<ide><path>rc/java/winstone/WebAppConfiguration.java <ide> } else if (!path.startsWith("/")) { <ide> throw new MalformedURLException(Launcher.RESOURCES.getString( <ide> "WebAppConfig.BadResourcePath", path)); <del> } else if (path.endsWith("/")) { <add> } else if (!path.equals("/") && path.endsWith("/")) { <ide> path = path.substring(0, path.length() - 1); <ide> } <ide> File res = new File(webRoot, path.substring(1)); <ide> <ide> public InputStream getResourceAsStream(String path) { <ide> try { <del> URL res = this.getResource(path); <add> URL res = getResource(path); <ide> return res == null ? null : res.openStream(); <ide> } catch (IOException err) { <ide> throw new WinstoneException(Launcher.RESOURCES
Java
apache-2.0
a4f8ec1117e3a01bd116c5845daf37808e22fc41
0
yuruki/camel,trohovsky/camel,pplatek/camel,snurmine/camel,brreitme/camel,allancth/camel,dpocock/camel,borcsokj/camel,yuruki/camel,aaronwalker/camel,tadayosi/camel,DariusX/camel,DariusX/camel,christophd/camel,curso007/camel,gilfernandes/camel,cunningt/camel,qst-jdc-labs/camel,jollygeorge/camel,punkhorn/camel-upstream,pkletsko/camel,mnki/camel,gyc567/camel,drsquidop/camel,dpocock/camel,gnodet/camel,tlehoux/camel,sirlatrom/camel,jamesnetherton/camel,scranton/camel,gnodet/camel,yury-vashchyla/camel,CandleCandle/camel,askannon/camel,askannon/camel,gnodet/camel,johnpoth/camel,royopa/camel,erwelch/camel,grange74/camel,logzio/camel,neoramon/camel,mgyongyosi/camel,Thopap/camel,stalet/camel,JYBESSON/camel,pax95/camel,grange74/camel,mcollovati/camel,trohovsky/camel,davidwilliams1978/camel,nikhilvibhav/camel,jameszkw/camel,bfitzpat/camel,maschmid/camel,christophd/camel,NickCis/camel,rmarting/camel,jmandawg/camel,onders86/camel,CandleCandle/camel,tadayosi/camel,tdiesler/camel,MrCoder/camel,oalles/camel,NetNow/camel,duro1/camel,mgyongyosi/camel,tarilabs/camel,yogamaha/camel,royopa/camel,jollygeorge/camel,stravag/camel,manuelh9r/camel,ge0ffrey/camel,YMartsynkevych/camel,w4tson/camel,oscerd/camel,logzio/camel,ramonmaruko/camel,CandleCandle/camel,jpav/camel,tadayosi/camel,tkopczynski/camel,dmvolod/camel,MohammedHammam/camel,nikhilvibhav/camel,w4tson/camel,erwelch/camel,jlpedrosa/camel,bfitzpat/camel,lowwool/camel,acartapanis/camel,chirino/camel,JYBESSON/camel,stalet/camel,onders86/camel,grgrzybek/camel,sabre1041/camel,chirino/camel,onders86/camel,alvinkwekel/camel,atoulme/camel,adessaigne/camel,oscerd/camel,mzapletal/camel,jonmcewen/camel,askannon/camel,NetNow/camel,ge0ffrey/camel,prashant2402/camel,royopa/camel,cunningt/camel,noelo/camel,qst-jdc-labs/camel,prashant2402/camel,bhaveshdt/camel,iweiss/camel,sebi-hgdata/camel,gautric/camel,mzapletal/camel,oalles/camel,manuelh9r/camel,haku/camel,dkhanolkar/camel,pplatek/camel,nboukhed/camel,dmvolod/camel,coderczp/camel,lburgazzoli/camel,mnki/camel,curso007/camel,w4tson/camel,borcsokj/camel,jonmcewen/camel,jameszkw/camel,jarst/camel,mohanaraosv/camel,edigrid/camel,jlpedrosa/camel,logzio/camel,logzio/camel,johnpoth/camel,lburgazzoli/camel,chanakaudaya/camel,jkorab/camel,davidwilliams1978/camel,drsquidop/camel,sverkera/camel,mcollovati/camel,nikhilvibhav/camel,zregvart/camel,lburgazzoli/camel,NetNow/camel,tkopczynski/camel,akhettar/camel,Fabryprog/camel,gautric/camel,nikvaessen/camel,dkhanolkar/camel,royopa/camel,pplatek/camel,apache/camel,jmandawg/camel,zregvart/camel,woj-i/camel,alvinkwekel/camel,grange74/camel,duro1/camel,ullgren/camel,tadayosi/camel,oscerd/camel,zregvart/camel,hqstevenson/camel,CodeSmell/camel,jlpedrosa/camel,ullgren/camel,tarilabs/camel,ekprayas/camel,adessaigne/camel,bhaveshdt/camel,mzapletal/camel,curso007/camel,MrCoder/camel,veithen/camel,ekprayas/camel,trohovsky/camel,nboukhed/camel,snadakuduru/camel,FingolfinTEK/camel,grange74/camel,jpav/camel,duro1/camel,bhaveshdt/camel,snurmine/camel,rmarting/camel,iweiss/camel,JYBESSON/camel,gnodet/camel,JYBESSON/camel,YMartsynkevych/camel,tdiesler/camel,pmoerenhout/camel,driseley/camel,pkletsko/camel,manuelh9r/camel,gyc567/camel,tdiesler/camel,ekprayas/camel,satishgummadelli/camel,nboukhed/camel,sabre1041/camel,christophd/camel,DariusX/camel,borcsokj/camel,chirino/camel,rparree/camel,bfitzpat/camel,engagepoint/camel,manuelh9r/camel,partis/camel,pplatek/camel,objectiser/camel,pmoerenhout/camel,anoordover/camel,allancth/camel,gautric/camel,dvankleef/camel,stravag/camel,sebi-hgdata/camel,zregvart/camel,CodeSmell/camel,dvankleef/camel,jpav/camel,YoshikiHigo/camel,royopa/camel,rparree/camel,tlehoux/camel,jmandawg/camel,satishgummadelli/camel,jmandawg/camel,tdiesler/camel,neoramon/camel,arnaud-deprez/camel,grgrzybek/camel,grgrzybek/camel,jonmcewen/camel,MrCoder/camel,isururanawaka/camel,lasombra/camel,koscejev/camel,grgrzybek/camel,ramonmaruko/camel,rparree/camel,cunningt/camel,veithen/camel,anoordover/camel,ge0ffrey/camel,jlpedrosa/camel,jamesnetherton/camel,jamesnetherton/camel,oalles/camel,allancth/camel,pplatek/camel,brreitme/camel,qst-jdc-labs/camel,nicolaferraro/camel,mgyongyosi/camel,jkorab/camel,tlehoux/camel,isavin/camel,skinzer/camel,nicolaferraro/camel,lburgazzoli/apache-camel,apache/camel,edigrid/camel,tarilabs/camel,dpocock/camel,NetNow/camel,igarashitm/camel,pax95/camel,FingolfinTEK/camel,gilfernandes/camel,maschmid/camel,veithen/camel,CodeSmell/camel,oalles/camel,gilfernandes/camel,woj-i/camel,nikvaessen/camel,anton-k11/camel,erwelch/camel,ssharma/camel,partis/camel,jmandawg/camel,lowwool/camel,hqstevenson/camel,woj-i/camel,anton-k11/camel,eformat/camel,NickCis/camel,Fabryprog/camel,lburgazzoli/apache-camel,gilfernandes/camel,jonmcewen/camel,edigrid/camel,snurmine/camel,driseley/camel,pmoerenhout/camel,partis/camel,pax95/camel,jamesnetherton/camel,veithen/camel,lburgazzoli/camel,driseley/camel,bfitzpat/camel,logzio/camel,edigrid/camel,tlehoux/camel,salikjan/camel,coderczp/camel,snadakuduru/camel,rmarting/camel,ullgren/camel,nicolaferraro/camel,yuruki/camel,atoulme/camel,bgaudaen/camel,FingolfinTEK/camel,borcsokj/camel,adessaigne/camel,acartapanis/camel,curso007/camel,bfitzpat/camel,skinzer/camel,dsimansk/camel,atoulme/camel,nikvaessen/camel,ramonmaruko/camel,yuruki/camel,dpocock/camel,driseley/camel,sabre1041/camel,dvankleef/camel,joakibj/camel,scranton/camel,jarst/camel,mohanaraosv/camel,christophd/camel,sirlatrom/camel,gyc567/camel,nboukhed/camel,joakibj/camel,curso007/camel,driseley/camel,neoramon/camel,pkletsko/camel,lasombra/camel,Fabryprog/camel,noelo/camel,mzapletal/camel,mnki/camel,mcollovati/camel,acartapanis/camel,sverkera/camel,nikvaessen/camel,igarashitm/camel,davidkarlsen/camel,coderczp/camel,anoordover/camel,stalet/camel,askannon/camel,bgaudaen/camel,jkorab/camel,mgyongyosi/camel,hqstevenson/camel,drsquidop/camel,yogamaha/camel,jpav/camel,NetNow/camel,snadakuduru/camel,isavin/camel,sebi-hgdata/camel,hqstevenson/camel,lburgazzoli/apache-camel,borcsokj/camel,bhaveshdt/camel,ullgren/camel,anton-k11/camel,ssharma/camel,qst-jdc-labs/camel,lowwool/camel,sebi-hgdata/camel,scranton/camel,rmarting/camel,pmoerenhout/camel,jarst/camel,grange74/camel,punkhorn/camel-upstream,kevinearls/camel,akhettar/camel,NickCis/camel,Fabryprog/camel,tdiesler/camel,noelo/camel,maschmid/camel,bgaudaen/camel,jlpedrosa/camel,jmandawg/camel,tkopczynski/camel,maschmid/camel,MohammedHammam/camel,johnpoth/camel,yury-vashchyla/camel,johnpoth/camel,eformat/camel,tkopczynski/camel,hqstevenson/camel,lburgazzoli/camel,iweiss/camel,mgyongyosi/camel,aaronwalker/camel,tarilabs/camel,bhaveshdt/camel,sverkera/camel,christophd/camel,neoramon/camel,prashant2402/camel,MohammedHammam/camel,MohammedHammam/camel,yogamaha/camel,oscerd/camel,atoulme/camel,pkletsko/camel,koscejev/camel,aaronwalker/camel,chanakaudaya/camel,RohanHart/camel,alvinkwekel/camel,dvankleef/camel,haku/camel,YMartsynkevych/camel,manuelh9r/camel,ge0ffrey/camel,skinzer/camel,RohanHart/camel,ekprayas/camel,MohammedHammam/camel,mike-kukla/camel,sverkera/camel,koscejev/camel,sabre1041/camel,YoshikiHigo/camel,sirlatrom/camel,iweiss/camel,snadakuduru/camel,gyc567/camel,apache/camel,dsimansk/camel,mnki/camel,aaronwalker/camel,josefkarasek/camel,dmvolod/camel,dkhanolkar/camel,trohovsky/camel,aaronwalker/camel,adessaigne/camel,lowwool/camel,erwelch/camel,koscejev/camel,stravag/camel,atoulme/camel,mzapletal/camel,Thopap/camel,jollygeorge/camel,tkopczynski/camel,erwelch/camel,scranton/camel,jonmcewen/camel,kevinearls/camel,iweiss/camel,salikjan/camel,sverkera/camel,RohanHart/camel,brreitme/camel,lasombra/camel,apache/camel,dvankleef/camel,ssharma/camel,bdecoste/camel,yury-vashchyla/camel,pmoerenhout/camel,kevinearls/camel,RohanHart/camel,grange74/camel,anoordover/camel,rparree/camel,josefkarasek/camel,dvankleef/camel,pax95/camel,hqstevenson/camel,anoordover/camel,pkletsko/camel,akhettar/camel,davidkarlsen/camel,jarst/camel,akhettar/camel,anoordover/camel,tdiesler/camel,stravag/camel,yury-vashchyla/camel,aaronwalker/camel,mgyongyosi/camel,isururanawaka/camel,dsimansk/camel,qst-jdc-labs/camel,arnaud-deprez/camel,Thopap/camel,NickCis/camel,jamesnetherton/camel,veithen/camel,maschmid/camel,jameszkw/camel,gyc567/camel,ssharma/camel,FingolfinTEK/camel,prashant2402/camel,snurmine/camel,mnki/camel,woj-i/camel,MrCoder/camel,allancth/camel,ekprayas/camel,lburgazzoli/apache-camel,isururanawaka/camel,bgaudaen/camel,prashant2402/camel,pax95/camel,partis/camel,sebi-hgdata/camel,gyc567/camel,igarashitm/camel,satishgummadelli/camel,isavin/camel,lasombra/camel,sirlatrom/camel,bdecoste/camel,stravag/camel,nicolaferraro/camel,allancth/camel,noelo/camel,ge0ffrey/camel,duro1/camel,mike-kukla/camel,FingolfinTEK/camel,akhettar/camel,joakibj/camel,nboukhed/camel,davidkarlsen/camel,oalles/camel,eformat/camel,prashant2402/camel,jlpedrosa/camel,igarashitm/camel,rparree/camel,manuelh9r/camel,dpocock/camel,chanakaudaya/camel,igarashitm/camel,adessaigne/camel,oscerd/camel,arnaud-deprez/camel,objectiser/camel,w4tson/camel,kevinearls/camel,isavin/camel,NickCis/camel,cunningt/camel,dpocock/camel,CandleCandle/camel,arnaud-deprez/camel,objectiser/camel,yuruki/camel,rmarting/camel,rmarting/camel,JYBESSON/camel,gilfernandes/camel,DariusX/camel,atoulme/camel,anton-k11/camel,josefkarasek/camel,yury-vashchyla/camel,curso007/camel,isururanawaka/camel,tlehoux/camel,chanakaudaya/camel,gautric/camel,askannon/camel,ekprayas/camel,trohovsky/camel,tkopczynski/camel,bdecoste/camel,koscejev/camel,haku/camel,mohanaraosv/camel,chirino/camel,jonmcewen/camel,drsquidop/camel,woj-i/camel,jameszkw/camel,johnpoth/camel,MrCoder/camel,yogamaha/camel,apache/camel,davidwilliams1978/camel,jameszkw/camel,lburgazzoli/apache-camel,johnpoth/camel,ramonmaruko/camel,akhettar/camel,mohanaraosv/camel,anton-k11/camel,arnaud-deprez/camel,ge0ffrey/camel,jkorab/camel,bgaudaen/camel,snurmine/camel,partis/camel,lasombra/camel,davidkarlsen/camel,cunningt/camel,lowwool/camel,jkorab/camel,mzapletal/camel,sverkera/camel,CandleCandle/camel,tadayosi/camel,dmvolod/camel,jarst/camel,NetNow/camel,oalles/camel,engagepoint/camel,driseley/camel,YoshikiHigo/camel,partis/camel,gautric/camel,satishgummadelli/camel,iweiss/camel,YMartsynkevych/camel,joakibj/camel,davidwilliams1978/camel,onders86/camel,stalet/camel,duro1/camel,eformat/camel,gautric/camel,veithen/camel,sirlatrom/camel,jameszkw/camel,christophd/camel,coderczp/camel,RohanHart/camel,jarst/camel,joakibj/camel,apache/camel,eformat/camel,bgaudaen/camel,tadayosi/camel,sabre1041/camel,scranton/camel,maschmid/camel,MrCoder/camel,yogamaha/camel,YMartsynkevych/camel,tarilabs/camel,engagepoint/camel,davidwilliams1978/camel,adessaigne/camel,koscejev/camel,logzio/camel,jollygeorge/camel,neoramon/camel,josefkarasek/camel,davidwilliams1978/camel,yuruki/camel,kevinearls/camel,snadakuduru/camel,trohovsky/camel,gilfernandes/camel,borcsokj/camel,mike-kukla/camel,sebi-hgdata/camel,sirlatrom/camel,anton-k11/camel,mnki/camel,dkhanolkar/camel,CandleCandle/camel,brreitme/camel,onders86/camel,snurmine/camel,eformat/camel,haku/camel,ssharma/camel,bdecoste/camel,oscerd/camel,dsimansk/camel,ramonmaruko/camel,lasombra/camel,askannon/camel,noelo/camel,mohanaraosv/camel,JYBESSON/camel,chirino/camel,jamesnetherton/camel,Thopap/camel,lowwool/camel,jollygeorge/camel,pplatek/camel,edigrid/camel,onders86/camel,bdecoste/camel,lburgazzoli/camel,bdecoste/camel,jollygeorge/camel,mohanaraosv/camel,haku/camel,acartapanis/camel,dmvolod/camel,mike-kukla/camel,chanakaudaya/camel,acartapanis/camel,pplatek/camel,mcollovati/camel,joakibj/camel,nikvaessen/camel,ssharma/camel,qst-jdc-labs/camel,lburgazzoli/apache-camel,pkletsko/camel,satishgummadelli/camel,drsquidop/camel,acartapanis/camel,nikvaessen/camel,alvinkwekel/camel,FingolfinTEK/camel,haku/camel,chirino/camel,objectiser/camel,scranton/camel,coderczp/camel,woj-i/camel,stravag/camel,logzio/camel,Thopap/camel,engagepoint/camel,igarashitm/camel,josefkarasek/camel,punkhorn/camel-upstream,ramonmaruko/camel,tlehoux/camel,jpav/camel,isavin/camel,MohammedHammam/camel,rparree/camel,allancth/camel,isururanawaka/camel,NickCis/camel,grgrzybek/camel,w4tson/camel,noelo/camel,erwelch/camel,Thopap/camel,edigrid/camel,satishgummadelli/camel,isururanawaka/camel,YoshikiHigo/camel,dsimansk/camel,tarilabs/camel,skinzer/camel,jkorab/camel,yury-vashchyla/camel,royopa/camel,bfitzpat/camel,nikhilvibhav/camel,brreitme/camel,mike-kukla/camel,arnaud-deprez/camel,pax95/camel,dkhanolkar/camel,YMartsynkevych/camel,stalet/camel,bhaveshdt/camel,YoshikiHigo/camel,CodeSmell/camel,YoshikiHigo/camel,cunningt/camel,w4tson/camel,brreitme/camel,dmvolod/camel,punkhorn/camel-upstream,snadakuduru/camel,josefkarasek/camel,engagepoint/camel,stalet/camel,sabre1041/camel,skinzer/camel,grgrzybek/camel,dsimansk/camel,isavin/camel,drsquidop/camel,neoramon/camel,pmoerenhout/camel,kevinearls/camel,duro1/camel,yogamaha/camel,dkhanolkar/camel,skinzer/camel,nboukhed/camel,coderczp/camel,jpav/camel,chanakaudaya/camel,mike-kukla/camel,gnodet/camel,RohanHart/camel
/** * 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.component.jetty; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Ignore; import org.junit.Test; /** * Unit test to verify that we can have URI options for external system (endpoint is lenient) */ public class JettyHttpGetWithParamAsExchangeHeaderTest extends BaseJettyTest { private String serverUri = "http://localhost:" + getPort() + "/myservice"; @Test public void testHttpGetWithParamsViaURI() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("one", "einz"); mock.expectedHeaderReceived("two", "twei"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBody(serverUri + "?one=einz&two=twei", null, Object.class); assertMockEndpointsSatisfied(); } @Test public void testHttpGetWithUTF8EncodedParamsViaURI() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("message", "Keine gltige GPS-Daten!"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBody(serverUri + "?message=Keine%20gltige%20GPS-Daten!", null, Object.class); assertMockEndpointsSatisfied(); } @Test @Ignore public void testHttpGetWithISO8859EncodedParamsViaURI() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("message", "Keine gltige GPS-Daten!"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBody(serverUri + "?message=Keine+gltige+GPS-Daten%21", null, Object.class); assertMockEndpointsSatisfied(); } @Test public void testHttpGetWithParamsViaHeader() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("one", "uno"); mock.expectedHeaderReceived("two", "dos"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBodyAndHeader(serverUri, null, Exchange.HTTP_QUERY, "one=uno&two=dos"); assertMockEndpointsSatisfied(); } @Test public void testHttpPost() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "POST"); template.requestBody(serverUri, "Hello World"); assertMockEndpointsSatisfied(); } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("jetty:" + serverUri).to("mock:result"); } }; } }
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyHttpGetWithParamAsExchangeHeaderTest.java
/** * 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.component.jetty; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Ignore; import org.junit.Test; /** * Unit test to verify that we can have URI options for external system (endpoint is lenient) */ public class JettyHttpGetWithParamAsExchangeHeaderTest extends BaseJettyTest { private String serverUri = "http://localhost:" + getPort() + "/myservice"; @Test public void testHttpGetWithParamsViaURI() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("one", "einz"); mock.expectedHeaderReceived("two", "twei"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBody(serverUri + "?one=einz&two=twei", null, Object.class); assertMockEndpointsSatisfied(); } @Test public void testHttpGetWithUTF8EncodedParamsViaURI() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("message", "Keine gltige GPS-Daten!"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBody(serverUri + "?message=Keine%20g%C3%BCltige%20GPS-Daten!", null, Object.class); assertMockEndpointsSatisfied(); } @Test @Ignore public void testHttpGetWithISO8859EncodedParamsViaURI() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("message", "Keine gltige GPS-Daten!"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBody(serverUri + "?message=Keine+g%FCltige+GPS-Daten%21", null, Object.class); assertMockEndpointsSatisfied(); } @Test public void testHttpGetWithParamsViaHeader() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedHeaderReceived("one", "uno"); mock.expectedHeaderReceived("two", "dos"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); template.requestBodyAndHeader(serverUri, null, Exchange.HTTP_QUERY, "one=uno&two=dos"); assertMockEndpointsSatisfied(); } @Test public void testHttpPost() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "POST"); template.requestBody(serverUri, "Hello World"); assertMockEndpointsSatisfied(); } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("jetty:" + serverUri).to("mock:result"); } }; } }
Fix compile error by removing the non-utf8 chars. Someone may need to figure out what those chars should have been. git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@1152992 13f79535-47bb-0310-9956-ffa450edef68
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyHttpGetWithParamAsExchangeHeaderTest.java
Fix compile error by removing the non-utf8 chars. Someone may need to figure out what those chars should have been.
<ide><path>omponents/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyHttpGetWithParamAsExchangeHeaderTest.java <ide> mock.expectedHeaderReceived("message", "Keine gltige GPS-Daten!"); <ide> mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); <ide> <del> template.requestBody(serverUri + "?message=Keine%20g%C3%BCltige%20GPS-Daten!", null, Object.class); <add> template.requestBody(serverUri + "?message=Keine%20gltige%20GPS-Daten!", null, Object.class); <ide> <ide> assertMockEndpointsSatisfied(); <ide> } <ide> mock.expectedHeaderReceived("message", "Keine gltige GPS-Daten!"); <ide> mock.expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); <ide> <del> template.requestBody(serverUri + "?message=Keine+g%FCltige+GPS-Daten%21", null, Object.class); <add> template.requestBody(serverUri + "?message=Keine+gltige+GPS-Daten%21", null, Object.class); <ide> <ide> assertMockEndpointsSatisfied(); <ide> }
Java
apache-2.0
42033ccd8e8ac16b19293798f1a4d23de8ef09f0
0
SchunterKino/kinoapi
package de.schunterkino.kinoapi.websocket; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpCookie; import java.net.InetSocketAddress; import java.security.KeyFactory; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Duration; import java.time.Instant; import java.util.LinkedList; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.xml.bind.DatatypeConverter; import org.java_websocket.WebSocket; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; import org.java_websocket.server.WebSocketServer; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import de.schunterkino.kinoapi.App; import de.schunterkino.kinoapi.christie.ChristieCommand; import de.schunterkino.kinoapi.christie.ChristieSocketCommands; import de.schunterkino.kinoapi.christie.IChristieStatusUpdateReceiver; import de.schunterkino.kinoapi.christie.serial.ISolariaSerialStatusUpdateReceiver; import de.schunterkino.kinoapi.christie.serial.PowerMode; import de.schunterkino.kinoapi.christie.serial.SolariaCommand; import de.schunterkino.kinoapi.christie.serial.SolariaSocketCommands; import de.schunterkino.kinoapi.dolby.DecodeMode; import de.schunterkino.kinoapi.dolby.DolbyCommand; import de.schunterkino.kinoapi.dolby.DolbySocketCommands; import de.schunterkino.kinoapi.dolby.IDolbyStatusUpdateReceiver; import de.schunterkino.kinoapi.dolby.InputMode; import de.schunterkino.kinoapi.jnior.IJniorStatusUpdateReceiver; import de.schunterkino.kinoapi.jnior.JniorCommand; import de.schunterkino.kinoapi.jnior.JniorSocketCommands; import de.schunterkino.kinoapi.listen.IServerSocketStatusUpdateReceiver; import de.schunterkino.kinoapi.listen.SchunterServerSocket; import de.schunterkino.kinoapi.sockets.BaseSerialPortClient; import de.schunterkino.kinoapi.sockets.BaseSocketClient; import de.schunterkino.kinoapi.websocket.messages.BaseMessage; import de.schunterkino.kinoapi.websocket.messages.ErrorMessage; import de.schunterkino.kinoapi.websocket.messages.christie.ChristieConnectionMessage; import de.schunterkino.kinoapi.websocket.messages.christie.LampOffMessage; import de.schunterkino.kinoapi.websocket.messages.jnior.LightsConnectionMessage; import de.schunterkino.kinoapi.websocket.messages.volume.DecodeModeChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.DolbyConnectionMessage; import de.schunterkino.kinoapi.websocket.messages.volume.InputModeChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.MuteStatusChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.PowerModeChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.VolumeChangedMessage; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.impl.TextCodec; /** * WebSocket server class which serves the documented JSON API. This class acts * as a proxy and forwards the events from the different hardware connections - * like volume changes on the Dolby audio processor - to all connected websocket * clients. * * @see API.md */ public class CinemaWebSocketServer extends WebSocketServer implements IDolbyStatusUpdateReceiver, IJniorStatusUpdateReceiver, IChristieStatusUpdateReceiver, ISolariaSerialStatusUpdateReceiver, IServerSocketStatusUpdateReceiver { public static final int AUTH_ERROR_CODE = 4401; /** * Google JSON instance to convert Java objects into JSON objects. * {@link https://github.com/google/gson/blob/master/UserGuide.md} */ private Gson gson; /** * Socket connection and protocol handler for the Dolby CP750. */ private BaseSocketClient<DolbySocketCommands, IDolbyStatusUpdateReceiver, DolbyCommand> dolby; /** * Socket connection and protocol handler for the Integ Jnior 310 automation * box. */ private BaseSocketClient<JniorSocketCommands, IJniorStatusUpdateReceiver, JniorCommand> jnior; /** * Socket connection to trigger global triggers on the Christie IMB. */ private BaseSocketClient<ChristieSocketCommands, IChristieStatusUpdateReceiver, ChristieCommand> christie; /** * Serial connection to the PIB to get projector hardware updates. */ private BaseSerialPortClient<SolariaSocketCommands, ISolariaSerialStatusUpdateReceiver, SolariaCommand> solaria; /** * Server socket which is used to listen to the event of the projector lamp * being off. */ private SchunterServerSocket server; /** * List of JSON protocol incoming command handlers. Incoming messages on the * WebSockets are passed to the handlers until one claims responsibility for the * packet. */ private LinkedList<IWebSocketMessageHandler> messageHandlers; /** * Creates a CinemaWebSocketServer on the desired port. * * @param port * The desired server port to listen on. * @param dolby * Instance of Dolby socket client. * @param jnior * Instance of Jnior socket client. */ public CinemaWebSocketServer(int port, BaseSocketClient<DolbySocketCommands, IDolbyStatusUpdateReceiver, DolbyCommand> dolby, BaseSocketClient<JniorSocketCommands, IJniorStatusUpdateReceiver, JniorCommand> jnior, BaseSocketClient<ChristieSocketCommands, IChristieStatusUpdateReceiver, ChristieCommand> christie, BaseSerialPortClient<SolariaSocketCommands, ISolariaSerialStatusUpdateReceiver, SolariaCommand> solaria, SchunterServerSocket server) { super(new InetSocketAddress(port)); this.gson = new Gson(); this.messageHandlers = new LinkedList<>(); // Start listening for dolby events. this.dolby = dolby; // Start listening for Dolby events like volume changes. dolby.getCommands().registerListener(this); messageHandlers.add(dolby.getCommands()); this.jnior = jnior; // Start listening for Jnior events like connection updates. jnior.getCommands().registerListener(this); messageHandlers.add(jnior.getCommands()); this.christie = christie; // Start listening for Christie IMB events like connection updates. christie.getCommands().registerListener(this); messageHandlers.add(christie.getCommands()); this.solaria = solaria; solaria.getCommands().registerListener(this); messageHandlers.add(solaria.getCommands()); this.server = server; server.registerListener(this); } @Override public void start() { // Setup the SSL context for WSS support. // WebSocketImpl.DEBUG = true; SSLContext context = getSSLContext(); if (context != null) { setWebSocketFactory(new DefaultSSLWebSocketServerFactory(context)); } setConnectionLostTimeout(30); super.start(); } private void validateToken(ClientHandshake request) throws InvalidDataException { if (!request.hasFieldValue("Cookie")) throw new InvalidDataException(AUTH_ERROR_CODE, "Token missing."); List<HttpCookie> cookie = HttpCookie.parse(request.getFieldValue("Cookie")); // Malformed cookie. if (cookie.size() != 1) throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); HttpCookie tokenCookie = cookie.get(0); // Invalid cookie name. if (!tokenCookie.getName().equals("token")) throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); String compactJws = tokenCookie.getValue(); // System.out.println("Token is " + compactJws); // Validate the signature and the subject. The subject is just there // because. try { Jwts.parser().requireSubject("SchunterKinoRemote") .setSigningKey(TextCodec.BASE64.decode(App.getConfigurationString("jws_signature_key"))) .parseClaimsJws(compactJws); } catch (Exception e) { System.err.println(e.getMessage()); // e.printStackTrace(); throw new InvalidDataException(AUTH_ERROR_CODE, "Invalid token."); } } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { System.out.println("WebSocket: " + prettySocket(conn) + " connected!"); // Try to validate the token in the handshake cookie. // Close the connection correctly if there's a problem. try { validateToken(handshake); } catch (InvalidDataException e) { System.err.println("WebSocket: " + prettySocket(conn) + " failed to authenticate: " + e.getMessage()); conn.close(e.getCloseCode(), e.getMessage()); return; } // Inform the new client of the current status. // Let the client know if we were able to connect to the Dolby audio // processor. conn.send(gson.toJson(new DolbyConnectionMessage(dolby.isConnected()))); if (dolby.isConnected()) { // If we're connected, send the current status too. conn.send(gson.toJson(new VolumeChangedMessage(dolby.getCommands().getVolume()))); conn.send(gson.toJson(new MuteStatusChangedMessage(dolby.getCommands().isMuted()))); conn.send(gson.toJson(new InputModeChangedMessage(dolby.getCommands().getInputMode()))); conn.send(gson.toJson(new DecodeModeChangedMessage(dolby.getCommands().getDecodeMode()))); } // Also tell the client if we have a connection to the Jnior box. conn.send(gson.toJson(new LightsConnectionMessage(jnior.isConnected()))); // And if the projector is up. conn.send(gson.toJson(new ChristieConnectionMessage(christie.isConnected()))); if (christie.isConnected()) { Instant lampOffTime = server.getLampOffTime(); // Only send the lamp off time if it's been max. 2 hours ago. if (lampOffTime != null && Duration.between(lampOffTime, Instant.now()).toHours() < 2) conn.send(gson.toJson(new LampOffMessage(lampOffTime))); } // Tell which part of the projector is currently enabled. if (solaria.isConnected()) { conn.send(gson.toJson(new PowerModeChangedMessage(solaria.getCommands().getPowerMode(), solaria.getCommands().getPowerModeChangedTimestamp(), solaria.getCommands().getCooldownTime()))); } } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { System.out.println("WebSocket: " + prettySocket(conn) + " disconnected!"); } @Override public void onError(WebSocket conn, Exception ex) { if (conn != null) { // some errors like port binding failed may not be assignable to a // specific websocket System.err.println("WebSocket: ChildSocket " + prettySocket(conn) + " error: " + ex.getMessage()); } else { // TODO: Stop the application or try to start the server again in a // bit. System.err.println("WebSocket: ServerSocket error: " + ex.getMessage()); } ex.printStackTrace(); } @Override public void onMessage(WebSocket conn, String message) { System.out.println("WebSocket: " + prettySocket(conn) + ": " + message); try { // Try to parse this message as JSON and try to extract the message // type. BaseMessage baseMsg = gson.fromJson(message, BaseMessage.class); // Make sure the required fields are set in the JSON object. if (baseMsg.getMessageType() == null || baseMsg.getAction() == null) { System.err.println( "Websocket: Invalid JSON message from " + conn + " (missing required fields): " + message); conn.send(gson.toJson(new ErrorMessage( "Malformed message. Messages MUST include a \"msg_type\" and an \"action\"."))); return; } // Run through all handlers and see if one of them knows what to do // with that message. try { for (IWebSocketMessageHandler handler : messageHandlers) { if (handler.onMessage(baseMsg, message)) return; } } catch (WebSocketCommandException e) { // Tell the client why the command failed. conn.send(gson.toJson(new ErrorMessage(e.getMessage()))); return; } // No message handler was able to handle that message. Tell the // client! System.err.println("Websocket: Unhandled command from " + prettySocket(conn) + ": " + message); conn.send(gson.toJson( new ErrorMessage("Unhandled command: " + baseMsg.getMessageType() + " - " + baseMsg.getAction()))); } catch (JsonSyntaxException e) { System.err.println("Websocket: Error parsing message from " + prettySocket(conn) + ": " + e.getMessage()); conn.send(gson.toJson(new ErrorMessage(e.getMessage()))); } } @Override public void onStart() { System.out.println("Websocket server started!"); } private static String prettySocket(WebSocket conn) { return conn.getRemoteSocketAddress().getAddress().getHostAddress() + ":" + conn.getRemoteSocketAddress().getPort(); } @Override public void onDolbyConnected() { DolbyConnectionMessage msg = new DolbyConnectionMessage(true); broadcast(gson.toJson(msg)); } @Override public void onDolbyDisconnected() { DolbyConnectionMessage msg = new DolbyConnectionMessage(false); broadcast(gson.toJson(msg)); } @Override public void onVolumeChanged(int volume) { VolumeChangedMessage msg = new VolumeChangedMessage(volume); broadcast(gson.toJson(msg)); } @Override public void onMuteStatusChanged(boolean muted) { MuteStatusChangedMessage msg = new MuteStatusChangedMessage(muted); broadcast(gson.toJson(msg)); } @Override public void onJniorConnected() { LightsConnectionMessage msg = new LightsConnectionMessage(true); broadcast(gson.toJson(msg)); } @Override public void onJniorDisconnected() { LightsConnectionMessage msg = new LightsConnectionMessage(false); broadcast(gson.toJson(msg)); } @Override public void onInputModeChanged(InputMode mode) { InputModeChangedMessage msg = new InputModeChangedMessage(mode); broadcast(gson.toJson(msg)); } @Override public void onDecodeModeChanged(DecodeMode mode) { DecodeModeChangedMessage msg = new DecodeModeChangedMessage(mode); broadcast(gson.toJson(msg)); } @Override public void onChristieConnected() { ChristieConnectionMessage msg = new ChristieConnectionMessage(true); broadcast(gson.toJson(msg)); } @Override public void onChristieDisconnected() { ChristieConnectionMessage msg = new ChristieConnectionMessage(false); broadcast(gson.toJson(msg)); } @Override public void onLampTurnedOff(Instant lampOffTime) { LampOffMessage msg = new LampOffMessage(lampOffTime); broadcast(gson.toJson(msg)); } @Override public void onPowerModeChanged(PowerMode mode, PowerMode oldPowerMode, Instant timestamp, Integer cooldown) { PowerModeChangedMessage msg = new PowerModeChangedMessage(mode, timestamp, cooldown); broadcast(gson.toJson(msg)); } /* * SSL helpers */ private SSLContext getSSLContext() { SSLContext context; String password = App.getConfigurationString("ssl_keystore_password"); String pathname = App.getConfigurationString("ssl_basepath"); try { context = SSLContext.getInstance("TLS"); byte[] certBytes = parseDERFromPEM( getBytes(new File(pathname + File.separator + App.getConfigurationString("ssl_certificate_file"))), "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"); byte[] keyBytes = parseDERFromPEM( getBytes(new File(pathname + File.separator + App.getConfigurationString("ssl_privatekey_file"))), "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"); X509Certificate cert = generateCertificateFromDER(certBytes); RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes); KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(null); keystore.setCertificateEntry("cert-alias", cert); keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keystore, password.toCharArray()); KeyManager[] km = kmf.getKeyManagers(); context.init(km, null, null); } catch (Exception e) { System.err.printf("Error initializing SSL certificate. Websocket Server WON'T support SSL. Exception: %s%n", e.getMessage()); context = null; } return context; } private byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) { String data = new String(pem); String[] tokens = data.split(beginDelimiter); tokens = tokens[1].split(endDelimiter); return DatatypeConverter.parseBase64Binary(tokens[0]); } private RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory factory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) factory.generatePrivate(spec); } private X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes)); } private byte[] getBytes(File file) throws IOException { byte[] bytesArray = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytesArray); // read file into bytes[] fis.close(); return bytesArray; } }
src/main/java/de/schunterkino/kinoapi/websocket/CinemaWebSocketServer.java
package de.schunterkino.kinoapi.websocket; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpCookie; import java.net.InetSocketAddress; import java.security.KeyFactory; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Duration; import java.time.Instant; import java.util.LinkedList; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.xml.bind.DatatypeConverter; import org.java_websocket.WebSocket; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; import org.java_websocket.server.WebSocketServer; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import de.schunterkino.kinoapi.App; import de.schunterkino.kinoapi.christie.ChristieCommand; import de.schunterkino.kinoapi.christie.ChristieSocketCommands; import de.schunterkino.kinoapi.christie.IChristieStatusUpdateReceiver; import de.schunterkino.kinoapi.christie.serial.ISolariaSerialStatusUpdateReceiver; import de.schunterkino.kinoapi.christie.serial.PowerMode; import de.schunterkino.kinoapi.christie.serial.SolariaCommand; import de.schunterkino.kinoapi.christie.serial.SolariaSocketCommands; import de.schunterkino.kinoapi.dolby.DecodeMode; import de.schunterkino.kinoapi.dolby.DolbyCommand; import de.schunterkino.kinoapi.dolby.DolbySocketCommands; import de.schunterkino.kinoapi.dolby.IDolbyStatusUpdateReceiver; import de.schunterkino.kinoapi.dolby.InputMode; import de.schunterkino.kinoapi.jnior.IJniorStatusUpdateReceiver; import de.schunterkino.kinoapi.jnior.JniorCommand; import de.schunterkino.kinoapi.jnior.JniorSocketCommands; import de.schunterkino.kinoapi.listen.IServerSocketStatusUpdateReceiver; import de.schunterkino.kinoapi.listen.SchunterServerSocket; import de.schunterkino.kinoapi.sockets.BaseSerialPortClient; import de.schunterkino.kinoapi.sockets.BaseSocketClient; import de.schunterkino.kinoapi.websocket.messages.BaseMessage; import de.schunterkino.kinoapi.websocket.messages.ErrorMessage; import de.schunterkino.kinoapi.websocket.messages.christie.ChristieConnectionMessage; import de.schunterkino.kinoapi.websocket.messages.christie.LampOffMessage; import de.schunterkino.kinoapi.websocket.messages.jnior.LightsConnectionMessage; import de.schunterkino.kinoapi.websocket.messages.volume.DecodeModeChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.DolbyConnectionMessage; import de.schunterkino.kinoapi.websocket.messages.volume.InputModeChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.MuteStatusChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.PowerModeChangedMessage; import de.schunterkino.kinoapi.websocket.messages.volume.VolumeChangedMessage; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.impl.TextCodec; /** * WebSocket server class which serves the documented JSON API. This class acts * as a proxy and forwards the events from the different hardware connections - * like volume changes on the Dolby audio processor - to all connected websocket * clients. * * @see API.md */ public class CinemaWebSocketServer extends WebSocketServer implements IDolbyStatusUpdateReceiver, IJniorStatusUpdateReceiver, IChristieStatusUpdateReceiver, ISolariaSerialStatusUpdateReceiver, IServerSocketStatusUpdateReceiver { public static final int AUTH_ERROR_CODE = 4401; /** * Google JSON instance to convert Java objects into JSON objects. * {@link https://github.com/google/gson/blob/master/UserGuide.md} */ private Gson gson; /** * Socket connection and protocol handler for the Dolby CP750. */ private BaseSocketClient<DolbySocketCommands, IDolbyStatusUpdateReceiver, DolbyCommand> dolby; /** * Socket connection and protocol handler for the Integ Jnior 310 automation * box. */ private BaseSocketClient<JniorSocketCommands, IJniorStatusUpdateReceiver, JniorCommand> jnior; /** * Socket connection to trigger global triggers on the Christie IMB. */ private BaseSocketClient<ChristieSocketCommands, IChristieStatusUpdateReceiver, ChristieCommand> christie; /** * Serial connection to the PIB to get projector hardware updates. */ private BaseSerialPortClient<SolariaSocketCommands, ISolariaSerialStatusUpdateReceiver, SolariaCommand> solaria; /** * Server socket which is used to listen to the event of the projector lamp * being off. */ private SchunterServerSocket server; /** * List of JSON protocol incoming command handlers. Incoming messages on the * WebSockets are passed to the handlers until one claims responsibility for the * packet. */ private LinkedList<IWebSocketMessageHandler> messageHandlers; /** * Creates a CinemaWebSocketServer on the desired port. * * @param port * The desired server port to listen on. * @param dolby * Instance of Dolby socket client. * @param jnior * Instance of Jnior socket client. */ public CinemaWebSocketServer(int port, BaseSocketClient<DolbySocketCommands, IDolbyStatusUpdateReceiver, DolbyCommand> dolby, BaseSocketClient<JniorSocketCommands, IJniorStatusUpdateReceiver, JniorCommand> jnior, BaseSocketClient<ChristieSocketCommands, IChristieStatusUpdateReceiver, ChristieCommand> christie, BaseSerialPortClient<SolariaSocketCommands, ISolariaSerialStatusUpdateReceiver, SolariaCommand> solaria, SchunterServerSocket server) { super(new InetSocketAddress(port)); this.gson = new Gson(); this.messageHandlers = new LinkedList<>(); // Start listening for dolby events. this.dolby = dolby; // Start listening for Dolby events like volume changes. dolby.getCommands().registerListener(this); messageHandlers.add(dolby.getCommands()); this.jnior = jnior; // Start listening for Jnior events like connection updates. jnior.getCommands().registerListener(this); messageHandlers.add(jnior.getCommands()); this.christie = christie; // Start listening for Christie IMB events like connection updates. christie.getCommands().registerListener(this); messageHandlers.add(christie.getCommands()); this.solaria = solaria; solaria.getCommands().registerListener(this); messageHandlers.add(solaria.getCommands()); this.server = server; server.registerListener(this); } @Override public void start() { // Setup the SSL context for WSS support. // WebSocketImpl.DEBUG = true; SSLContext context = getSSLContext(); if (context != null) { setWebSocketFactory(new DefaultSSLWebSocketServerFactory(context)); } setConnectionLostTimeout(30); super.start(); } private void validateToken(ClientHandshake request) throws InvalidDataException { if (!request.hasFieldValue("Cookie")) throw new InvalidDataException(AUTH_ERROR_CODE, "Token missing."); List<HttpCookie> cookie = HttpCookie.parse(request.getFieldValue("Cookie")); // Malformed cookie. if (cookie.size() != 1) throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); HttpCookie tokenCookie = cookie.get(0); // Invalid cookie name. if (!tokenCookie.getName().equals("token")) throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "Not accepted!"); String compactJws = tokenCookie.getValue(); // System.out.println("Token is " + compactJws); // Validate the signature and the subject. The subject is just there // because. try { Jwts.parser().requireSubject("SchunterKinoRemote") .setSigningKey(TextCodec.BASE64.decode(App.getConfigurationString("jws_signature_key"))) .parseClaimsJws(compactJws); } catch (Exception e) { System.err.println(e.getMessage()); // e.printStackTrace(); throw new InvalidDataException(AUTH_ERROR_CODE, "Invalid token."); } } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { System.out.println("WebSocket: " + prettySocket(conn) + " connected!"); // Try to validate the token in the handshake cookie. // Close the connection correctly if there's a problem. try { validateToken(handshake); } catch (InvalidDataException e) { System.err.println("WebSocket: " + prettySocket(conn) + " failed to authenticate: " + e.getMessage()); conn.close(e.getCloseCode(), e.getMessage()); return; } // Inform the new client of the current status. // Let the client know if we were able to connect to the Dolby audio // processor. conn.send(gson.toJson(new DolbyConnectionMessage(dolby.isConnected()))); if (dolby.isConnected()) { // If we're connected, send the current status too. conn.send(gson.toJson(new VolumeChangedMessage(dolby.getCommands().getVolume()))); conn.send(gson.toJson(new MuteStatusChangedMessage(dolby.getCommands().isMuted()))); conn.send(gson.toJson(new InputModeChangedMessage(dolby.getCommands().getInputMode()))); conn.send(gson.toJson(new DecodeModeChangedMessage(dolby.getCommands().getDecodeMode()))); } // Also tell the client if we have a connection to the Jnior box. conn.send(gson.toJson(new LightsConnectionMessage(jnior.isConnected()))); // And if the projector is up. conn.send(gson.toJson(new ChristieConnectionMessage(christie.isConnected()))); if (christie.isConnected()) { Instant lampOffTime = server.getLampOffTime(); // Only send the lamp off time if it's been max. 2 hours ago. if (lampOffTime != null && Duration.between(lampOffTime, Instant.now()).toHours() < 2) conn.send(gson.toJson(new LampOffMessage(lampOffTime))); } // Tell which part of the projector is currently enabled. if (solaria.isConnected()) { conn.send(gson.toJson(new PowerModeChangedMessage(solaria.getCommands().getPowerMode(), solaria.getCommands().getPowerModeChangedTimestamp(), solaria.getCommands().getCooldownTime()))); } } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { System.out.println("WebSocket: " + prettySocket(conn) + " disconnected!"); } @Override public void onError(WebSocket conn, Exception ex) { if (conn != null) { // some errors like port binding failed may not be assignable to a // specific websocket System.err.println("WebSocket: ChildSocket " + prettySocket(conn) + " error: " + ex.getMessage()); } else { // TODO: Stop the application or try to start the server again in a // bit. System.err.println("WebSocket: ServerSocket error: " + ex.getMessage()); } } @Override public void onMessage(WebSocket conn, String message) { System.out.println("WebSocket: " + prettySocket(conn) + ": " + message); try { // Try to parse this message as JSON and try to extract the message // type. BaseMessage baseMsg = gson.fromJson(message, BaseMessage.class); // Make sure the required fields are set in the JSON object. if (baseMsg.getMessageType() == null || baseMsg.getAction() == null) { System.err.println( "Websocket: Invalid JSON message from " + conn + " (missing required fields): " + message); conn.send(gson.toJson(new ErrorMessage( "Malformed message. Messages MUST include a \"msg_type\" and an \"action\"."))); return; } // Run through all handlers and see if one of them knows what to do // with that message. try { for (IWebSocketMessageHandler handler : messageHandlers) { if (handler.onMessage(baseMsg, message)) return; } } catch (WebSocketCommandException e) { // Tell the client why the command failed. conn.send(gson.toJson(new ErrorMessage(e.getMessage()))); return; } // No message handler was able to handle that message. Tell the // client! System.err.println("Websocket: Unhandled command from " + prettySocket(conn) + ": " + message); conn.send(gson.toJson( new ErrorMessage("Unhandled command: " + baseMsg.getMessageType() + " - " + baseMsg.getAction()))); } catch (JsonSyntaxException e) { System.err.println("Websocket: Error parsing message from " + prettySocket(conn) + ": " + e.getMessage()); conn.send(gson.toJson(new ErrorMessage(e.getMessage()))); } } @Override public void onStart() { System.out.println("Websocket server started!"); } private static String prettySocket(WebSocket conn) { return conn.getRemoteSocketAddress().getAddress().getHostAddress() + ":" + conn.getRemoteSocketAddress().getPort(); } @Override public void onDolbyConnected() { DolbyConnectionMessage msg = new DolbyConnectionMessage(true); broadcast(gson.toJson(msg)); } @Override public void onDolbyDisconnected() { DolbyConnectionMessage msg = new DolbyConnectionMessage(false); broadcast(gson.toJson(msg)); } @Override public void onVolumeChanged(int volume) { VolumeChangedMessage msg = new VolumeChangedMessage(volume); broadcast(gson.toJson(msg)); } @Override public void onMuteStatusChanged(boolean muted) { MuteStatusChangedMessage msg = new MuteStatusChangedMessage(muted); broadcast(gson.toJson(msg)); } @Override public void onJniorConnected() { LightsConnectionMessage msg = new LightsConnectionMessage(true); broadcast(gson.toJson(msg)); } @Override public void onJniorDisconnected() { LightsConnectionMessage msg = new LightsConnectionMessage(false); broadcast(gson.toJson(msg)); } @Override public void onInputModeChanged(InputMode mode) { InputModeChangedMessage msg = new InputModeChangedMessage(mode); broadcast(gson.toJson(msg)); } @Override public void onDecodeModeChanged(DecodeMode mode) { DecodeModeChangedMessage msg = new DecodeModeChangedMessage(mode); broadcast(gson.toJson(msg)); } @Override public void onChristieConnected() { ChristieConnectionMessage msg = new ChristieConnectionMessage(true); broadcast(gson.toJson(msg)); } @Override public void onChristieDisconnected() { ChristieConnectionMessage msg = new ChristieConnectionMessage(false); broadcast(gson.toJson(msg)); } @Override public void onLampTurnedOff(Instant lampOffTime) { LampOffMessage msg = new LampOffMessage(lampOffTime); broadcast(gson.toJson(msg)); } @Override public void onPowerModeChanged(PowerMode mode, PowerMode oldPowerMode, Instant timestamp, Integer cooldown) { PowerModeChangedMessage msg = new PowerModeChangedMessage(mode, timestamp, cooldown); broadcast(gson.toJson(msg)); } /* * SSL helpers */ private SSLContext getSSLContext() { SSLContext context; String password = App.getConfigurationString("ssl_keystore_password"); String pathname = App.getConfigurationString("ssl_basepath"); try { context = SSLContext.getInstance("TLS"); byte[] certBytes = parseDERFromPEM( getBytes(new File(pathname + File.separator + App.getConfigurationString("ssl_certificate_file"))), "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"); byte[] keyBytes = parseDERFromPEM( getBytes(new File(pathname + File.separator + App.getConfigurationString("ssl_privatekey_file"))), "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"); X509Certificate cert = generateCertificateFromDER(certBytes); RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes); KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(null); keystore.setCertificateEntry("cert-alias", cert); keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keystore, password.toCharArray()); KeyManager[] km = kmf.getKeyManagers(); context.init(km, null, null); } catch (Exception e) { System.err.printf("Error initializing SSL certificate. Websocket Server WON'T support SSL. Exception: %s%n", e.getMessage()); context = null; } return context; } private byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) { String data = new String(pem); String[] tokens = data.split(beginDelimiter); tokens = tokens[1].split(endDelimiter); return DatatypeConverter.parseBase64Binary(tokens[0]); } private RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory factory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) factory.generatePrivate(spec); } private X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes)); } private byte[] getBytes(File file) throws IOException { byte[] bytesArray = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytesArray); // read file into bytes[] fis.close(); return bytesArray; } }
Print stack trace in websocket onError See where the exception was thrown - they should never happen!
src/main/java/de/schunterkino/kinoapi/websocket/CinemaWebSocketServer.java
Print stack trace in websocket onError
<ide><path>rc/main/java/de/schunterkino/kinoapi/websocket/CinemaWebSocketServer.java <ide> // bit. <ide> System.err.println("WebSocket: ServerSocket error: " + ex.getMessage()); <ide> } <add> ex.printStackTrace(); <ide> } <ide> <ide> @Override
Java
apache-2.0
f8e67bb770ceec47bcbcc6d867ba7d4b76f59c25
0
GoogleCloudPlatform/cloud-pubsub-samples-java,GoogleCloudPlatform/cloud-pubsub-samples-java,googlearchive/cloud-pubsub-samples-java,GoogleCloudPlatform/cloud-pubsub-samples-java,googlearchive/cloud-pubsub-samples-java,googlearchive/cloud-pubsub-samples-java
package com.google.cloud.pubsub.grpc.demos; import com.google.auth.oauth2.GoogleCredentials; import com.google.pubsub.v1.ListTopicsRequest; import com.google.pubsub.v1.ListTopicsResponse; import com.google.pubsub.v1.PublisherGrpc; import com.google.pubsub.v1.Topic; import io.grpc.ClientInterceptors; import io.grpc.auth.ClientAuthInterceptor; import io.grpc.internal.ManagedChannelImpl; import io.grpc.netty.NegotiationType; import io.grpc.netty.NettyChannelBuilder; import io.grpc.Channel; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public final class Main { private Main() { } public static void main(final String[] args) throws Exception { if (args.length == 0) { System.err.println("Please specify your project name."); System.exit(1); } final String project = args[0]; ManagedChannelImpl channelImpl = NettyChannelBuilder .forAddress("pubsub.googleapis.com", 443) .negotiationType(NegotiationType.TLS) .build(); GoogleCredentials creds = GoogleCredentials.getApplicationDefault(); // Down-scope the credential to just the scopes required by the service creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub")); // Intercept the channel to bind the credential ExecutorService executor = Executors.newSingleThreadExecutor(); ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor); Channel channel = ClientInterceptors.intercept(channelImpl, interceptor); // Create a stub using the channel that has the bound credential PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel); ListTopicsRequest request = ListTopicsRequest.newBuilder() .setPageSize(10) .setProject("projects/" + project) .build(); ListTopicsResponse resp = publisherStub.listTopics(request); System.out.println("Found " + resp.getTopicsCount() + " topics."); for (Topic topic : resp.getTopicsList()) { System.out.println(topic.getName()); } } }
grpc/src/main/java/com/google/cloud/pubsub/grpc/demos/Main.java
package com.google.cloud.pubsub.grpc.demos; import com.google.auth.oauth2.GoogleCredentials; import com.google.pubsub.v1.ListTopicsRequest; import com.google.pubsub.v1.ListTopicsResponse; import com.google.pubsub.v1.PublisherGrpc; import com.google.pubsub.v1.Topic; import io.grpc.ClientInterceptors; import io.grpc.auth.ClientAuthInterceptor; import io.grpc.internal.ManagedChannelImpl; import io.grpc.netty.NegotiationType; import io.grpc.netty.NettyChannelBuilder; import io.grpc.Channel; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public final class Main { private Main() { } public static void main(final String[] args) throws Exception { if (args.length == 0) { System.err.println("Please specify your project name."); System.exit(1); } final String project = args[0]; ManagedChannelImpl channelImpl = NettyChannelBuilder .forAddress("pubsub.googleapis.com", 443) .negotiationType(NegotiationType.TLS) .build(); GoogleCredentials creds = GoogleCredentials.getApplicationDefault(); // Down-scope the credential to just the scopes required by the service creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub")); // Intercept the channel to bind the credential ExecutorService executor = Executors.newSingleThreadExecutor(); ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor); Channel channel = ClientInterceptors.intercept(channelImpl, interceptor); // Create a stub using the channel that has the bound credential PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel); ListTopicsRequest request = ListTopicsRequest.newBuilder() .setPageSize(10) .setProject("projects/" + project) .build(); ListTopicsResponse resp = publisherStub.listTopics(request); for (Topic topic : resp.getTopicsList()) { System.out.println(topic.getName()); } } }
Update Main.java
grpc/src/main/java/com/google/cloud/pubsub/grpc/demos/Main.java
Update Main.java
<ide><path>rpc/src/main/java/com/google/cloud/pubsub/grpc/demos/Main.java <ide> .setProject("projects/" + project) <ide> .build(); <ide> ListTopicsResponse resp = publisherStub.listTopics(request); <add> System.out.println("Found " + resp.getTopicsCount() + " topics."); <ide> for (Topic topic : resp.getTopicsList()) { <ide> System.out.println(topic.getName()); <ide> }
Java
mit
c00102174d9f8b5770660876dcff64e02a7d6476
0
jbowkett/joxy
package info.bowkett.joxy.stepdefs; import cucumber.api.PendingException; import cucumber.api.java.After; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import info.bowkett.joxy.RequestParser; import info.bowkett.joxy.RequestReader; import info.bowkett.joxy.Server; import org.junit.Assert; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.io.File; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: jbowkett * Date: Jul 22, 2013 * Time: 10:22:24 AM * To change this template use File | Settings | File Templates. */ public class ServerStartupStepDefs { private WebDriver driver; private Server server; private static final int PROXY_SERVER_PORT = 4443; private static ChromeDriverService driverService; // todo: sort this into a @Beforeclass method static { driverService = new ChromeDriverService.Builder() .usingDriverExecutable(new File(System.getProperty("webdriver.chrome.driver"))) .usingAnyFreePort() .build(); try { driverService.start(); } catch (IOException e) { e.printStackTrace(); } } @Given("^a joxy server is started$") public void a_joxy_server_is_started() throws Throwable { server = new Server(PROXY_SERVER_PORT, new RequestReader(), new RequestParser()); server.start(); } @Given("^a web browser configured to use joxy$") public void a_web_browser_configured_to_use_joxy() throws Throwable { final DesiredCapabilities capabilities = DesiredCapabilities.chrome(); final Proxy proxy = new Proxy(); proxy.setHttpProxy("localhost:" + PROXY_SERVER_PORT); capabilities.setCapability("proxy", proxy); driver = new RemoteWebDriver(driverService.getUrl(), capabilities); } @When("^I navigate to a website$") public void I_navigate_to_a_website() throws Throwable { driver.get("http://www.google.co.uk"); } @Then("^I will see that website in the browser$") public void I_will_see_that_website_in_the_browser() throws Throwable { final String title = driver.getTitle(); //todo: need a much better assertion here - document not null, or check the specific title Assert.assertNotNull(title); } @Given("^a joxy server is started with a title augmenter$") public void a_joxy_server_is_started_with_a_title_augmenter() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @Then("^I will see a message in the html title$") public void I_will_see_a_message_in_the_html_title() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @Given("^a joxy server is started with an adult content URL filter$") public void a_joxy_server_is_started_with_an_adult_content_URL_filter() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @When("^I navigate to \"([^\"]*)\"$") public void I_navigate_to(String arg1) throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @Then("^I will see a permission denied message$") public void I_will_see_a_permission_denied_message() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @After public void tearDown() { if (driver != null) driver.close(); if (server != null) server.shutdown(); } }
src/test/java/info/bowkett/joxy/stepdefs/ServerStartupStepDefs.java
package info.bowkett.joxy.stepdefs; import cucumber.api.PendingException; import cucumber.api.java.After; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import info.bowkett.joxy.RequestParser; import info.bowkett.joxy.RequestReader; import info.bowkett.joxy.Server; import org.junit.Assert; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.io.File; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: jbowkett * Date: Jul 22, 2013 * Time: 10:22:24 AM * To change this template use File | Settings | File Templates. */ public class ServerStartupStepDefs { private WebDriver driver; private Server server; private static final int PROXY_SERVER_PORT = 4443; private static ChromeDriverService driverService; static { driverService = new ChromeDriverService.Builder() .usingDriverExecutable(new File(System.getProperty("webdriver.chrome.driver"))) .usingAnyFreePort() .build(); try { driverService.start(); } catch (IOException e) { e.printStackTrace(); } } @Given("^a joxy server is started$") public void a_joxy_server_is_started() throws Throwable { server = new Server(PROXY_SERVER_PORT, new RequestReader(), new RequestParser()); server.start(); } @Given("^a web browser configured to use joxy$") public void a_web_browser_configured_to_use_joxy() throws Throwable { final DesiredCapabilities capabilities = DesiredCapabilities.chrome(); final Proxy proxy = new Proxy(); proxy.setHttpProxy("localhost:" + PROXY_SERVER_PORT); capabilities.setCapability("proxy", proxy); driver = new RemoteWebDriver(driverService.getUrl(), capabilities); } @When("^I navigate to a website$") public void I_navigate_to_a_website() throws Throwable { driver.get("http://www.google.co.uk"); } @Then("^I will see that website in the browser$") public void I_will_see_that_website_in_the_browser() throws Throwable { final String title = driver.getTitle(); //todo: need a much better assertion here - document not null, or check the specific title Assert.assertNotNull(title); } @Given("^a joxy server is started with a title augmenter$") public void a_joxy_server_is_started_with_a_title_augmenter() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @Then("^I will see a message in the html title$") public void I_will_see_a_message_in_the_html_title() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @Given("^a joxy server is started with an adult content URL filter$") public void a_joxy_server_is_started_with_an_adult_content_URL_filter() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @When("^I navigate to \"([^\"]*)\"$") public void I_navigate_to(String arg1) throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @Then("^I will see a permission denied message$") public void I_will_see_a_permission_denied_message() throws Throwable { // Express the Regexp above with the code you wish you had throw new PendingException(); } @After public void tearDown() { if (driver != null) driver.close(); if (server != null) server.shutdown(); } }
commented
src/test/java/info/bowkett/joxy/stepdefs/ServerStartupStepDefs.java
commented
<ide><path>rc/test/java/info/bowkett/joxy/stepdefs/ServerStartupStepDefs.java <ide> private static final int PROXY_SERVER_PORT = 4443; <ide> private static ChromeDriverService driverService; <ide> <add>// todo: sort this into a @Beforeclass method <ide> static { <ide> driverService = new ChromeDriverService.Builder() <ide> .usingDriverExecutable(new File(System.getProperty("webdriver.chrome.driver")))
Java
apache-2.0
9ad3c1758d678e30538dd346ee4d7e31d9cbf5fd
0
iservport/helianto,iservport/helianto
/* Copyright 2005 I Serv Consultoria Empresarial Ltda. * * 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.helianto.core.test; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.TestCase; /** * Classs to support domain tests. * * @author Mauricio Fernandes de Castro */ public class DomainTestSupport extends TestCase { public static final String STRING_TEST_VALUE = "TEST"; public static final long LONG_TEST_VALUE = Long.MAX_VALUE; public static final int INT_TEST_VALUE = Integer.MAX_VALUE; public static final Date DATE_TEST_VALUE = new Date(Long.MAX_VALUE); /** * Verify equalty between the object under test and other. If other is * null, try to create a copy. * * @param objectUnderTest * @param other * @return an object of the same type. */ public static Object minimalEqualsTest(Object objectUnderTest, Object other) { assertNotNull("Cant test equals() with a null object", objectUnderTest); if (logger.isDebugEnabled()) { logger.debug("Object under test is is "+objectUnderTest); } assertTrue(objectUnderTest.equals(objectUnderTest)); assertFalse(objectUnderTest.equals(null)); assertFalse(objectUnderTest.equals(new Object())); if (other==null) { try { other = objectUnderTest.getClass().newInstance(); } catch (Exception e) { e.printStackTrace(); } } assertNotNull(other); assertFalse(objectUnderTest.equals(other)); if (logger.isDebugEnabled()) { logger.debug("Copy is "+other); } return other; } /** * Provide a new object and do the minimal equalty test. * * @param objectUnderTest * @return an object of the same type. */ public static Object minimalEqualsTest(Object objectUnderTest) { return minimalEqualsTest(objectUnderTest, null); } /** * Create a non-repeatable string value */ public static String getNonRepeatableStringValue(int testKey) { return getNonRepeatableStringValue(testKey, 20); } /** * Create a non-repeatable string value with a given size. */ public static String getNonRepeatableStringValue(int testKey, int size) { String localKey = testKey+"-"+String.valueOf(new Date().getTime()); while (localKey.length()!=size) { if (localKey.length() > size) { localKey = localKey.substring(0, size); } else if (localKey.length() < size) { localKey = localKey.concat(localKey); } } if (logger.isDebugEnabled()) { logger.debug("New value is "+localKey); } return localKey; } /** * Create a non-repeatable int value. */ public static int getNonRepeatableIntValue(int testKey) { if (logger.isDebugEnabled()) { logger.debug("New value is "+testKey); } return testKey; } /** * Create a non-repeatable int value. */ public static long getNonRepeatableLongValue(int testKey) { if (logger.isDebugEnabled()) { logger.debug("New value is "+testKey); } return testKey; } /** * Create a non-repeatable int value. */ public static Date getNonRepeatableDateValue(int testKey) { Date date = new Date(testKey); if (logger.isDebugEnabled()) { logger.debug("New date is "+date); } return date; } protected static Log logger = LogFactory.getLog(DomainTestSupport.class); }
helianto1/core/src/main/java/org/helianto/core/test/DomainTestSupport.java
/* Copyright 2005 I Serv Consultoria Empresarial Ltda. * * 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.helianto.core.test; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.TestCase; /** * Classs to support domain tests. * * @author Mauricio Fernandes de Castro */ public class DomainTestSupport extends TestCase { public static final String STRING_TEST_VALUE = "TEST"; public static final long LONG_TEST_VALUE = Long.MAX_VALUE; public static final int INT_TEST_VALUE = Integer.MAX_VALUE; public static final Date DATE_TEST_VALUE = new Date(Long.MAX_VALUE); /** * Provide a new object and do the minimal equalty test. * * @param objectUnderTest * @return an object of the same type. */ public static Object minimalEqualsTest(Object objectUnderTest) { assertNotNull("Cant test equals() with a null object", objectUnderTest); if (logger.isDebugEnabled()) { logger.debug("Object under test is is "+objectUnderTest); } assertTrue(objectUnderTest.equals(objectUnderTest)); assertFalse(objectUnderTest.equals(null)); assertFalse(objectUnderTest.equals(new Object())); Object copy = null; try { copy = objectUnderTest.getClass().newInstance(); } catch (Exception e) { e.printStackTrace(); } assertNotNull(copy); assertFalse(objectUnderTest.equals(copy)); if (logger.isDebugEnabled()) { logger.debug("Copy is "+copy); } return copy; } /** * Create a non-repeatable string value */ public static String getNonRepeatableStringValue(int testKey) { return getNonRepeatableStringValue(testKey, 20); } /** * Create a non-repeatable string value with a given size. */ public static String getNonRepeatableStringValue(int testKey, int size) { String localKey = testKey+"-"+String.valueOf(new Date().getTime()); while (localKey.length()!=size) { if (localKey.length() > size) { localKey = localKey.substring(0, size); } else if (localKey.length() < size) { localKey = localKey.concat(localKey); } } if (logger.isDebugEnabled()) { logger.debug("New value is "+localKey); } return localKey; } /** * Create a non-repeatable int value. */ public static int getNonRepeatableIntValue(int testKey) { if (logger.isDebugEnabled()) { logger.debug("New value is "+testKey); } return testKey; } /** * Create a non-repeatable int value. */ public static long getNonRepeatableLongValue(int testKey) { if (logger.isDebugEnabled()) { logger.debug("New value is "+testKey); } return testKey; } /** * Create a non-repeatable int value. */ public static Date getNonRepeatableDateValue(int testKey) { Date date = new Date(testKey); if (logger.isDebugEnabled()) { logger.debug("New date is "+date); } return date; } protected static Log logger = LogFactory.getLog(DomainTestSupport.class); }
Provide one more signature to test method git-svn-id: 8e38db1cf16c4a277275c2a31413431bbf4974e4@868 d46e4f78-7810-0410-b419-9f95c2a9a517
helianto1/core/src/main/java/org/helianto/core/test/DomainTestSupport.java
Provide one more signature to test method
<ide><path>elianto1/core/src/main/java/org/helianto/core/test/DomainTestSupport.java <ide> public static final Date DATE_TEST_VALUE = new Date(Long.MAX_VALUE); <ide> <ide> /** <del> * Provide a new object and do the minimal equalty test. <add> * Verify equalty between the object under test and other. If other is <add> * null, try to create a copy. <ide> * <ide> * @param objectUnderTest <add> * @param other <ide> * @return an object of the same type. <ide> */ <del> public static Object minimalEqualsTest(Object objectUnderTest) { <add> public static Object minimalEqualsTest(Object objectUnderTest, Object other) { <ide> assertNotNull("Cant test equals() with a null object", objectUnderTest); <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Object under test is is "+objectUnderTest); <ide> assertTrue(objectUnderTest.equals(objectUnderTest)); <ide> assertFalse(objectUnderTest.equals(null)); <ide> assertFalse(objectUnderTest.equals(new Object())); <del> Object copy = null; <del> try { <del> copy = objectUnderTest.getClass().newInstance(); <del> } catch (Exception e) { <del> e.printStackTrace(); <add> if (other==null) { <add> try { <add> other = objectUnderTest.getClass().newInstance(); <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } <add> } <add> assertNotNull(other); <add> assertFalse(objectUnderTest.equals(other)); <add> if (logger.isDebugEnabled()) { <add> logger.debug("Copy is "+other); <ide> } <del> assertNotNull(copy); <del> assertFalse(objectUnderTest.equals(copy)); <del> if (logger.isDebugEnabled()) { <del> logger.debug("Copy is "+copy); <del> } <del> return copy; <add> return other; <add> } <add> <add> /** <add> * Provide a new object and do the minimal equalty test. <add> * <add> * @param objectUnderTest <add> * @return an object of the same type. <add> */ <add> public static Object minimalEqualsTest(Object objectUnderTest) { <add> return minimalEqualsTest(objectUnderTest, null); <ide> } <ide> <ide> /**
Java
isc
9905a9f83e608cf0067b4bee433c9d54a1442484
0
MrZoraman/Homes
package com.lagopusempire.multihomes.homeIO.database; import com.avaje.ebean.validation.Length; import com.avaje.ebean.validation.NotEmpty; import com.avaje.ebean.validation.NotNull; import com.lagopusempire.multihomes.home.Home; import com.lagopusempire.multihomes.home.LoadResult; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; /** * * @author MrZoraman */ @Entity() @Table(name="multihomes") public class DBHome { @Id private int id; @Length(max=36) @NotEmpty private String owner; @NotNull private double x; @NotNull private double y; @NotNull private double z; @NotNull private float yaw; @NotNull private float pitch; @NotEmpty private String worldName; @NotEmpty private String homeName; public DBHome(Home home) { this.owner = home.getOwner().toString(); this.x = home.getLoc().getX(); this.y = home.getLoc().getY(); this.z = home.getLoc().getZ(); this.yaw = home.getLoc().getYaw(); this.pitch = home.getLoc().getPitch(); this.worldName = home.getLoc().getWorld().getName(); this.homeName = home.getName(); } public Home toHome() { final World world = Bukkit.getWorld(worldName); final UUID ownerUUID = UUID.fromString(owner); if(world == null) { return new Home(ownerUUID, homeName, LoadResult.NO_WORLD); } final Location loc = new Location(world, x, y, z, yaw, pitch); return new Home(ownerUUID, homeName, loc); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUUID() { return owner; } public void setUUID(String UUID) { this.owner = UUID; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } public float getYaw() { return yaw; } public void setYaw(float yaw) { this.yaw = yaw; } public float getPitch() { return pitch; } public void setPitch(float pitch) { this.pitch = pitch; } public String getWorldName() { return worldName; } public void setWorldName(String worldName) { this.worldName = worldName; } public String getHomeName() { return homeName; } public void setHomeName(String homeName) { this.homeName = homeName; } }
src/main/java/com/lagopusempire/multihomes/homeIO/database/DBHome.java
package com.lagopusempire.multihomes.homeIO.database; import com.avaje.ebean.validation.Length; import com.avaje.ebean.validation.NotEmpty; import com.avaje.ebean.validation.NotNull; import com.lagopusempire.multihomes.home.Home; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.bukkit.Bukkit; import org.bukkit.Location; /** * * @author MrZoraman */ @Entity() @Table(name="multihomes") public class DBHome { @Id private int id; @Length(max=36) @NotEmpty private String owner; @NotNull private double x; @NotNull private double y; @NotNull private double z; @NotNull private float yaw; @NotNull private float pitch; @NotEmpty private String worldName; @NotEmpty private String homeName; public DBHome(Home home) { this.owner = home.getOwner().toString(); this.x = home.getLoc().getX(); this.y = home.getLoc().getY(); this.z = home.getLoc().getZ(); this.yaw = home.getLoc().getYaw(); this.pitch = home.getLoc().getPitch(); this.worldName = home.getLoc().getWorld().getName(); this.homeName = home.getName(); } public Home toHome() { return new Home(UUID.fromString(owner), homeName, toLoc()); } private Location toLoc() { return new Location(Bukkit.getWorld(worldName), x, y, z, yaw, pitch); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUUID() { return owner; } public void setUUID(String UUID) { this.owner = UUID; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } public float getYaw() { return yaw; } public void setYaw(float yaw) { this.yaw = yaw; } public float getPitch() { return pitch; } public void setPitch(float pitch) { this.pitch = pitch; } public String getWorldName() { return worldName; } public void setWorldName(String worldName) { this.worldName = worldName; } public String getHomeName() { return homeName; } public void setHomeName(String homeName) { this.homeName = homeName; } }
DBHome gives the right home load result.
src/main/java/com/lagopusempire/multihomes/homeIO/database/DBHome.java
DBHome gives the right home load result.
<ide><path>rc/main/java/com/lagopusempire/multihomes/homeIO/database/DBHome.java <ide> import com.avaje.ebean.validation.NotEmpty; <ide> import com.avaje.ebean.validation.NotNull; <ide> import com.lagopusempire.multihomes.home.Home; <add>import com.lagopusempire.multihomes.home.LoadResult; <ide> import java.util.UUID; <ide> import javax.persistence.Entity; <ide> import javax.persistence.Id; <ide> import javax.persistence.Table; <ide> import org.bukkit.Bukkit; <ide> import org.bukkit.Location; <add>import org.bukkit.World; <ide> <ide> /** <ide> * <ide> <ide> public Home toHome() <ide> { <del> return new Home(UUID.fromString(owner), homeName, toLoc()); <del> } <del> <del> private Location toLoc() <del> { <del> return new Location(Bukkit.getWorld(worldName), x, y, z, yaw, pitch); <add> final World world = Bukkit.getWorld(worldName); <add> final UUID ownerUUID = UUID.fromString(owner); <add> if(world == null) <add> { <add> return new Home(ownerUUID, homeName, LoadResult.NO_WORLD); <add> } <add> <add> final Location loc = new Location(world, x, y, z, yaw, pitch); <add> <add> return new Home(ownerUUID, homeName, loc); <ide> } <ide> <ide> public int getId()
JavaScript
mit
24155b062540d8b77ea7c1710b7800a1abd290f3
0
zubairq/AppShare,zubairq/AppShare,zubairq/yazz,zubairq/gosharedata,zubairq/gosharedata,zubairq/yazz,zubairq/AppShare,zubairq/AppShare
async function component( args ) { /* base_component_id("vb_editor_component") control_type("SYSTEM") load_once_from_file(true) uses_javascript_librararies(["advanced_bundle"]) */ //alert(JSON.stringify(args,null,2)) var mm = null var texti = null if (args) { texti = args.text } var designMode = true var runtimeMode = false var selectProp = null var selectCodeObject = null var selectCodeAction = null Vue.component("vb_editor_component", { //*** COPY_START ***// props: [ "args"], template: `<div v-bind:id='uid2' v-if='uid2 != null' v-bind:style='"width: 100%; height: 100%; " + (design_mode?"background: white;":"")'> <div style='box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-color: lightgray; padding: 5px; padding-left: 15px;padding-bottom: 10px;' v-if='design_mode' > <slot style='display: inline-block;float: left;' v-if='text'> </slot> </div> <div v-bind:id='vb_editor_element_id' v-if='vb_editor_element_id != null' style='position:relative;display: flex;' v-on:drop="$event.stopPropagation(); dropEditor($event)" v-on:ondragover="$event.stopPropagation();maintainCursor(); allowDropEditor($event)"> <!-- ----------------------------------------- The left section of the UI editor ----------------------------------------- --> <div v-if='design_mode' v-on:click='selected_pane = "blocks";' v-bind:style='(design_mode?"border: 4px solid lightgray;":"") + " max-width: " + leftHandWidth + "px;height: 75vmin; display: inline-block;overflow-x: hidden;overflow-y: hidden;vertical-align: top; background-color: lightgray;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);float:left;;flex-grow: 0;flex-shrink: 0;"'> <div v-bind:style='"font-family:verdana,helvetica;font-size: 13px;border-radius: 3px;padding: 4px; margin-bottom: 10px;box-shadow: 2px 2px 10px lightgray;"' v-bind:class='(selected_pane == "blocks"?"selected_pane_title":"unselected_pane_title") '> Blocks </div> <div class='' > <div class='' style='display:flex;overflow-y:scroll;flex-flow: row wrap;height:65vh;'> <div class='flex' v-on:click='highlighted_control = null;' v-bind:style='"display:flex;cursor: grab;border-radius: 3px;width:50px;height:50px; margin: 0px;border: 0px;padding:4px;overflow-x:hidden;overflow-y:hidden;background-color: " + ((!highlighted_control)?"#E8E8E8;border-left: 2px solid gray;border-top: 2px solid gray;":"lightgray;")'> <img src='/driver_icons/cursor.png' style='width: 100%;' class='img-fluid'> </img> </div> <div v-for='av in available_components' draggable="true" class='' v-on:dragend='$event.stopPropagation();deleteCursor();' v-on:dragstart='$event.stopPropagation();switchCursor($event,"grab","grabbing");highlighted_control = av.base_component_id;drag($event,{ type: "add_component", text: av.base_component_id })' v-on:click='highlighted_control = av.base_component_id;' v-bind:style='"display:flex;cursor: grab;margin: 2px;border-radius: 3px;width:50px;;height: 50px; margin: 0px;border: 0px;padding:10px;overflow-x:auto;overflow-y:hidden;background-color: " + ((highlighted_control == av.base_component_id)?"#E8E8E8;border-left: 2px solid gray;border-top: 2px solid gray;":"lightgray;")'> <img v-if='isValidObject(av)' v-bind:src='av.logo_url' style='width: 100%;' class='img-fluid'> </img> </div> </div> </div> </div> <!-- The main center section of the UI editor --> <div v-bind:style='"display: flex;width:100%;" + (design_mode?"background-color: darkgray;":"background-color: white;")'> <!-- The code editor for events --> <div v-if='(design_mode && (design_mode_pane.type=="event_editor"))' v-bind:refresh='refresh' v-bind:style='"margin: 2px; display: inline-block; vertical-align: top; width: 100%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 15px;":"margin: 0px;" ) '> <div style='font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;background-color:lightgray; color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;'> <div style='height: 50px;' > <div id='select_code_object_parent' style='display: inline-block;margin: 5px;width: 200px;'></div> <div id='select_code_action_parent' style='display: inline-block;margin: 5px;width: 200px;'></div> <button type=button class=' btn btn-danger btn-sm' style="float: right;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;margin-bottom: 4px;" v-on:click='gotoDragDropEditor()' >x</button> </div> <div id='ui_code_editor'> </div> </div> </div> <div v-if='(design_mode && (design_mode_pane.type=="help"))' v-bind:refresh='refresh' v-bind:style='"margin: 2px; display: inline-block; vertical-align: top; width: 100%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 15px;":"margin: 0px;" ) '> <div style='font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-image: linear-gradient(to right, #000099, lightblue); color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;'> <div style='height: 30px;' > Help <button type=button class=' btn btn-danger btn-sm' style="float: right;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;margin-bottom: 4px;" v-on:click='gotoDragDropEditor()' >x</button> </div> <div id='show_help' style="background-color:white;color:black;"> <div style="font-weight:normal;" v-html="design_mode_pane.help"></div> </div> </div> </div> <!-- The control details editor --> <div v-if='(design_mode && (design_mode_pane.type=="control_details_editor"))' v-bind:style='"box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);margin: 2px; display: inline-block; vertical-align: top; width: 100%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 15px;":"margin: 0px;" ) '> <div v-if='design_mode' style='font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-image: linear-gradient(to right, #000099, lightblue); color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;'> <div style='height: 30px;' > Control details <button type=button class=' btn btn-danger btn-sm' style="float: right;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;margin-bottom: 4px;" v-on:click='gotoDragDropEditor()' >x</button> </div> </div> <div v-bind:style='"border: 5px solid lightgray;background: white;;overflow:none;height:100%; overflow: auto;"'> <component v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[model.active_component_detail_index].name + (design_mode?"_design":"")' v-bind:refresh='refresh' design_mode='detail_editor' v-bind:meta='{form: model.active_form,name: model.forms[model.active_form].components[model.active_component_detail_index].name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:delete_component='childDeleteComponent' v-bind:select_component='childSelectComponent' v-bind:children='getChildren( model.forms[model.active_form].components[model.active_component_detail_index].name)' v-on:send="processControlEvent" v-bind:is='model.forms[model.active_form].components[model.active_component_detail_index].base_component_id' v-bind:name='model.forms[model.active_form].components[model.active_component_detail_index].name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[model.active_component_detail_index]'> <template slot-scope="child_components" v-bind:refresh='refresh' style='position:relative;'> <component v-for='child_item in getChildren(model.forms[model.active_form].components[model.active_component_detail_index].name)' v-bind:design_mode='design_mode' v-bind:meta='{form: model.active_form,name: child_item.name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:refresh='refresh' v-bind:style='"z-index:100000;position: absolute; top: " + child_item.topY + "px; left: " + child_item.leftX + "px;height:" + child_item.height + "px;width:" + child_item.width + "px;overflow:auto;"' v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[child_item.index_in_parent_array].name + (design_mode?"_design":"")' v-on:send="processControlEvent" v-bind:is='child_item.base_component_id' v-bind:name='child_item.name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[child_item.index_in_parent_array]'> </component> </template> </component> </div> </div> <!-- The drag drop UI editor. but... Also the main view of the App --> <div v-if='(!design_mode) || (design_mode && (design_mode_pane.type=="drag_drop"))' v-bind:style='(design_mode?"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;":"") + "margin: 2px; display: inline-block; vertical-align: top; width: 95%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 0px;margin-left:15px;margin-top:15px;":"margin: 0px;" ) '> <div v-if='design_mode' style='display:inline-block;font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-image: linear-gradient(to right, #000099, lightblue); color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;width:100%;'> <img src='/driver_icons/form.png' style='width: 20px; margin-right: 10px;' class='img-fluid'> </img> {{model.active_form}} (Form) </div> <div style=''></div> <div id="grid_container" drop-target=false style='width:100%;background-color:white;height: 100%;position:relative;'> <!-- INACTIVE FORM RESIZERS --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:2px;top:2px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (7 + (model.forms[model.active_form].width/2)) + "px;top:2px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (15 +model.forms[model.active_form].width) + "px;top:2px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:2px;top:" + (7 + (model.forms[model.active_form].height/2)) + "px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:2px;top:" + (15 + model.forms[model.active_form].height) + "px;"'> </div> <!-- ACTIVE FORM RESIZERS --> <!-- bottom right --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:style='"cursor: nwse-resize;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (15 +model.forms[model.active_form].width) + "px;top:" + (15 + (model.forms[model.active_form].height)) + "px;"' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nwse-resize","crosshair");drag($event,{ type: "resize_form_bottom_right", form_name: model.active_form })' > </div> <!-- right --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"cursor: ew-resize;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (15 +model.forms[model.active_form].width) + "px;top:" + (7 + (model.forms[model.active_form].height/2)) + "px;"' v-bind:draggable='true' v-on:dragend='$event.stopPropagation();deleteCursor();' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ew-resize","col-resize");drag($event,{ type: "resize_form_right", form_name: model.active_form })' > </div> <!-- bottom --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"cursor: ns-resize;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (7 +model.forms[model.active_form].width/2) + "px;top:" + (15 + (model.forms[model.active_form].height)) + "px;"' v-bind:draggable='true' v-on:dragend='$event.stopPropagation();deleteCursor()' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ns-resize","row-resize");drag($event,{ type: "resize_form_bottom", form_name: model.active_form })' > </div> <div v-bind:id='vb_grid_element_id' v-if='vb_grid_element_id != null' v-on:drop="drop($event)" v-bind:refresh='refresh' v-on:ondragover="$event.stopPropagation();maintainCursor();allowDrop($event)" v-bind:class='(design_mode?"dotted":"" )' v-on:click='clickOnMainGrid($event)' v-bind:style='"position:absolute;display: inline-block; vertical-align: top; width: " + model.forms[model.active_form].width + ";height: " + model.forms[model.active_form].height + " ;" + (design_mode?"left:15px;top:15px;border: 4px solid lightgray;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);":"border: 0px;" ) '> <div v-bind:refresh='refresh' style='position:absolute;left:0px;top:0px;z-index:1000000;opacity:1;'> <!-- ACTIVE CONTROL RESIZERS --> <!-- top left --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nwse-resize;z-index:10000000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (getLeft(model.active_form,model.active_component_index) - 15) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) - 15) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nwse-resize","crosshair");drag($event,{ type: "resize_top_left", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- top middle --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ns-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width/2) - 7) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) - 15) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ns-resize","row-resize");drag($event,{ type: "resize_top", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- top right --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nesw-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) ) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) - 15) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nesw-resize","crosshair");drag($event,{ type: "resize_top_right", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- middle left --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ew-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) - 15) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height / 2)) - 7) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ew-resize","col-resize");drag($event,{ type: "resize_left", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- middle right --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ew-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width)) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height / 2)) - 7) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ew-resize","col-resize");drag($event,{ type: "resize_right", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- bottom left --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nesw-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) - 15) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height)) + 2) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nesw-resize","crosshair");drag($event,{ type: "resize_bottom_left", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- bottom middle --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ns-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width/2) - 7) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height)) + 2) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ns-resize","row-resize");drag($event,{ type: "resize_bottom", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- bottom right --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nwse-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) ) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height)) + 2) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nwse-resize","crosshair");drag($event,{ type: "resize_bottom_right", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- DELETE --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:refresh='refresh' class='btn btn-danger' v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;position: absolute; " + "left: " + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) + 15) + "px;" + "top: " + ((getTop(model.active_form,model.active_component_index)) - 45) + "px;" + "width: 30px; height: 30px; line-height:30px;text-align: center;vertical-align: middle;"' v-on:click='$event.stopPropagation();deleteComponent(model.active_component_index)'> X </div> <!-- More details ... button --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index) && hasMoreDetailsUi(model.active_form,model.active_component_index)' v-bind:refresh='refresh' class='btn btn-info' v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;position: absolute; " + "left: " + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) + 15) + "px;" + "top: " + ((getTop(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].height) + 15) + "px;" + "width: 30px; height: 30px; line-height:30px;text-align: center;vertical-align: middle;"' v-on:click='$event.stopPropagation();showComponentDetailedDesignUi(model.active_component_index)'> ... </div> <div v-bind:refresh='refresh' v-for='(item,index) in getActiveFormComponents()' ondrop="return false;" v-on:click='if ( isVisible(model.active_form,index)){ $event.stopPropagation();selectComponent(index,true); }' v-bind:style='((design_mode && isVisible(model.active_form,index))?"border: 1px solid black;background: white;":"") + "position: absolute;top: " + getTop(model.active_form,index) + ";left:" + getLeft(model.active_form,index) + ";height:" + item.height + "px;width:" + item.width + "px;;overflow:none;"'> <div ondrop="return false;" v-bind:style='"position: absolute; top: 0px; left: 0px;height:" + item.height + "px;width:" + item.width + "px;overflow:auto;"'> <component v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[index].name + (design_mode?"_design":"")' v-bind:refresh='refresh' v-bind:meta='{form: model.active_form,name: item.name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:design_mode='design_mode' v-bind:children='getChildren(item.name)' v-on:send="processControlEvent" v-bind:is='item.base_component_id' v-if='!item.parent' v-bind:name='item.name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[index]'> <template slot-scope="child_components" v-bind:refresh='refresh' style='position:relative;'> <component v-for='child_item in getChildren(item.name)' v-bind:design_mode='design_mode' v-bind:refresh='refresh' v-bind:meta='{form: model.active_form,name: child_item.name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:style='"z-index:100000;position: absolute; top: " + child_item.topY + "px; left: " + child_item.leftX + "px;height:" + child_item.height + "px;width:" + child_item.width + "px;overflow:auto;"' v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[child_item.index_in_parent_array].name + (design_mode?"_design":"")' v-on:send="processControlEvent" v-bind:is='child_item.base_component_id' v-bind:name='child_item.name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[child_item.index_in_parent_array]'> </component> </template> </component> </div> <div v-bind:style='"cursor: move;position: absolute; top: 0px; left: 0px;z-index: " + (item.is_container?"1":"10000000") + ";width: 100%;height: 100%;border: 1px solid black;"' v-bind:draggable='design_mode' v-if='design_mode && isVisible(model.active_form,index)' ondrop="return false;" v-on:dragstart='$event.stopPropagation();drag($event,{ type: "move_component", text: item.base_component_id, index: index })'> <div v-if='design_mode && isVisible(model.active_form,index)' ondrop="return false;" v-bind:refresh='refresh' v-bind:style='"position: absolute; top: 0px; left: 0px;z-index: 10000000;width: 100%;height: 100%; background-color: lightgray;" + ((index == model.active_component_index)?"opacity: 0;":"opacity: .6;") '> </div> </div> </div> </div> </div> </div> </div> </div> <!-- **************************************************************** * * * The right section of the UI editor * * * **************************************************************** --> <div v-if='design_mode' v-bind:style='(design_mode?"border: 4px solid lightgray;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;":"") + " float:right;top:0px;right:0px;width: 400px;height: 75vmin; display: inline-block;overflow-x: none;overflow: hidden;vertical-align: top;padding:0px;height:75vmin;background-color: lightgray; "' v-bind:refresh='refresh'> <div id='right_project_pane' v-bind:class='(right_mode == "project"?"right_project_pane_expanded":"right_project_pane_collapsed")' v-bind:refresh='refresh' v-bind:style='"padding:0px; border: 4px solid lightgray;white-space:nowrap"'> <div v-bind:style='"border-radius: 3px; padding: 4px;overflow-x:none;height: 40px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);font-family:verdana,helvetica;font-size: 13px;" ' v-bind:class='(selected_pane == "project"?"selected_pane_title":"unselected_pane_title") ' v-on:click='$event.stopPropagation();var s = (right_mode == "properties"?"project":"project");selected_pane = "project";chooseRight(s);' > Project explorer <button type=button class='btn btn-sm btn-warning' v-bind:style='"float: right;" + (right_mode == "project"?"":"display:;font-family:verdana,helvetica;font-size: 13px;")' v-on:click='$event.stopPropagation();selected_pane = "project"; chooseRight("project");addForm()' > Add form </button> </div> <div v-bind:style='"font-family:verdana,helvetica;font-size: 13px;border-radius: 3px; padding:4px; border-right:2px solid gray;border-bottom:2px solid gray; margin-top:2px;;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);height:80%;background-color:lightgray;" + (right_mode == "project"?"":"display:none;")'> <div style="align-items: stretch;border-radius: 3px;overflow-y:scroll; padding:0px; border: 0px solid lightgray;border-left: 2px solid gray;border-top: 2px solid gray; background-color:white;height:100%;"> <div v-bind:style='"border-radius: 0px;padding:4px;margin:0px;margin-top: 5px;" + (model.app_selected?"background-color:gray;color:white;":"background-color:white;color:black;")' v-on:click='$event.stopPropagation();selected_pane = "project";select_app()'> <b>{{edited_app_component_id}}</b> </div> <div v-for='form in getForms()' v-bind:refresh='refresh'> <div> <div v-bind:style='(((form.name == model.active_form) && (model.active_component_index == null) && (!model.app_selected)) ?"border: 0px solid red;background-color:gray;color:white;":"color:black;") + "padding:4px;margin:0px;margin-left:30px;border-radius: 3px;"' v-on:click='$event.stopPropagation();selected_pane = "project";selectForm(form.name)'> <img src='/driver_icons/form.png' style='width: 20px; margin-right: 10px;' class='img-fluid'> </img> {{form.name}} ({{form.components.length}}) </div> <div v-if='form.name == model.active_form' v-for='(av,index) in getActiveFormComponents()' v-on:click='$event.stopPropagation();selected_pane = "project";selectComponent(index)' > <div v-bind:style='(((index == model.active_component_index) && design_mode)?"border: 0px solid red;background-color: gray;color: white;":"") + "margin-left:80px; padding:2px;border-radius: 3px;width:90%;"' v-if='(av.parent == null)'> <div style='width:100%;display:inline-block;overflow: hidden;' > {{av.name}} <div v-if='form.name == model.active_form' v-for='(av2,index2) in getActiveFormComponents()' v-on:click='$event.stopPropagation();selected_pane = "project";selectComponent(index2)' > <div v-bind:style='(((index2 == model.active_component_index) && design_mode)?"border: 0px solid red;background-color: gray;color: white;":"") + "margin-left:20px; padding:2px;border-radius: 3px;width:90%;"' v-if='(av2.parent == av.name)'> <div style='width:100%;display:inline-block;overflow: hidden;' > {{av2.name}} </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div id='right_properties_pane' v-bind:class='(right_mode == "properties"?"right_properties_pane_collapsed":"right_properties_pane_collapsed")' v-bind:style='"padding:0px; border: 4px solid lightgray;padding:0px;background-color: lightgray;"'> <div v-bind:style='"border-radius: 3px;padding: 4px;height: 40px;overflow-x:none;white-space:nowrap;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);overflow:hidden ;text-overflow: ellipsis;font-family:verdana,helvetica;font-size: 13px;"' v-bind:class='(selected_pane == "properties"?"selected_pane_title_slower":"unselected_pane_title_slower") ' v-on:click='selected_pane = "properties";chooseRight("properties");'> Properties - {{isValidObject(model.active_component_index)?model.forms[model.active_form].components[model.active_component_index].name + " (Component)" : model.active_form + " (Form)"}} </div> <div id='property_selector_parent' style='margin: 5px;'> </div> <div style="border-radius: 3px; padding:4px; border-right:2px solid gray;border-bottom:2px solid gray; margin-top:2px;;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);height:65%;"> <div style="border-radius: 3px;overflow-y:scroll; padding:0px; border: 0px solid lightgray;border-left: 2px solid gray;border-top: 2px solid gray; background-color:white;height:100%;"> <div v-for='property in properties' style='font-family:verdana,helvetica;font-size: 13px;border-bottom: 1px solid lightgray;padding:0px;margin:0px;' > <div style='width:100%;padding:0px;margin:0px;display:flex;' v-if='!property.hidden'> <div v-bind:style='"text-overflow: ellipsis;white-space: pre-line;vertical-align: top;display:flex;width:40%;margin: 0px;font-family:verdana,helvetica;font-size: 13px;padding-left: 1px;padding-top:0px;padding-bottom:0px;" + (active_property_index == property.name?"background-color:#000099;color:white;":"")' v-on:click='selected_pane = "properties";active_property_index = property.name;'>{{property.name}} <div v-if="isValidObject(property.help)" style="width:100%;display:inline-block;"> <div style='margin-top:2px;margin-bottom:2px;border-right: 2px solid gray;border-bottom: 2px solid gray;background-color: pink; padding:0px; padding-right:5px;padding-left:5px;height: 20px;border-radius: 3px;font-family:verdana,helvetica;font-size: 13px;font-style:bold;color:black;width:20px;' v-on:click='$event.stopPropagation();showHelp({ help: property.help })' >?</div> </div> </div> <div style='display:flex;width:57%;padding:0px;padding-left:3px; border-left: 1px solid lightgray;' v-on:click='selected_pane = "properties";'> <div v-if='!property.readonly' style="width:100%"> <div v-if="(property.editor == 'detail_editor') " style="width:100%"> <div style='margin-top:2px;margin-bottom:2px;border-right: 2px solid gray;border-bottom: 2px solid gray;background-color: darkgray;float: right; padding:0px; padding-right:5px;padding-left:20px;height: 20px;color: white;border-radius: 3px;font-family:verdana,helvetica;font-size: 13px;font-style:bold;' v-on:click='$event.stopPropagation();showComponentDetailedDesignUi(model.active_component_index)' > ... </div> </div> <div v-if="(property.type == 'String') || (property.type == 'Number')"> <input @change='setVBEditorProperty($event, property)' v-bind:value='getVBEditorProperty(property)' style='width: 100%;border: 0px;font-family:verdana,helvetica;font-size: 13px;padding:0px;'> </input> </div> <div v-if="(property.type == 'Select') "> <select @change='setVBEditorProperty($event, property)'> <option v-for="propVal in property.values" v-bind:value="propVal.value" v-bind:selected="propVal.value == model.forms[model.active_form].components[model.active_component_index][property.id]"> {{propVal.display}} </option> </select> </div> <div v-if="(property.type == 'Image') "> <input type="file" id="image_file" @change="previewUpload(property)"> </input> </div> <div v-if="(property.type == 'Event') " style="width:100%"> <div style='margin-top:2px;margin-bottom:2px;border-right: 2px solid gray;border-bottom: 2px solid gray;background-color: darkgray;float: right; padding:0px; padding-right:5px;padding-left:20px;height: 20px;color: white;border-radius: 3px;font-family:verdana,helvetica;font-size: 13px;font-style:bold;' v-on:click='$event.stopPropagation();editAsCode({ app_selected: model.app_selected, active_form: model.active_form, active_component_index: model.active_component_index, property_id: property.id })' > ... </div> </div> </div> <div v-if='property.readonly'> <div v-if='model.active_component_index != null' style='padding:0px;font-family:verdana,helvetica;font-size: 13px;' class='col-md-12 small'> {{model.forms[model.active_form].components[model.active_component_index][property.id]}} </div> <div v-if='(model.active_component_index == null) && (model.active_form != null) && (model.app_selected == false)' class='col-md-12 small' v-model='model.forms[model.active_form][property.id]'> </div> <div v-if='model.app_selected' style='padding:0px;font-family:verdana,helvetica;font-size: 13px;' class='col-md-12 small' > {{property.get_fn?property.get_fn():model[property.id]}} </div> </div> </div> </div> </div> <div v-if='model.app_selected && (!add_property)' class='row'> <div class='col-md-12 small'> <button type=button class='btn btn-sm btn-info' style='font-family:verdana,helvetica;font-size: 13px;' v-on:click='$event.stopPropagation();addProperty()' > Add property </button> </div> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-12 small'> Add a property </div> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-4'> ID </div> <input style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-7 small' placeholder='background_color' v-model='new_property_id'> </input> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-4'> Name </div> <input class='col-md-7 small' placeholder='Background Color' style='border:0px;font-family:verdana,helvetica;font-size: 13px;' v-model='new_property_name'> </input> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div class='col-md-12'> <button style='font-family:verdana,helvetica;font-size: 13px;' type=button class='btn btn-sm btn-info' v-on:click='$event.stopPropagation();addPropertyCancel()' > Cancel </button> <button style='font-family:verdana,helvetica;font-size: 13px;' type=button class='btn btn-sm btn-info' v-on:click='$event.stopPropagation();addPropertySave()' > Save </button> </div> </div> </div> </div> </div> </div> </div> </div>` , /* -------------------------------------------------------------- mounted This is called whenever an app is loaded, either at design time or at runtime -------------------------------------------------------------- */ mounted: async function() { var mm = this mm.uid2 = uuidv4() mm.vb_grid_element_id = "vb_grid_"+ uuidv4() mm.vb_editor_element_id = "vb_editor_"+ uuidv4() mm.local_app = localAppshareApp // --------------------------------------------------------- // get the base component ID of the code to edit/run // // Save it in "this.edited_app_component_id" // --------------------------------------------------------- if (texti) { var json2 = this.getJsonModelFromCode( texti ) mm.model = json2 mm.edited_app_component_id = saveHelper.getValueOfCodeString(texti, "base_component_id") this.read_only = saveHelper.getValueOfCodeString(texti, "read_only") } mm.model.active_form = mm.model.default_form // --------------------------------------------------------- // find out which sub components are used by this app // // save the result in "this.component_usage" // --------------------------------------------------------- if (mm.edited_app_component_id) { var sql = "select child_component_id from component_usage where " + " base_component_id = '" + mm.edited_app_component_id + "'" var results = await callApp({ driver_name: "systemFunctions2",method_name: "sql"}, { sql: sql }) for (var i = 0; i < results.length; i++) { mm.component_usage[results[i].child_component_id] = true } } // --------------------------------------------------------- // load the forms and their controls // --------------------------------------------------------- // --------------------------------------------------------- // For each form ... // --------------------------------------------------------- var forms = this.getForms() for (var formIndex = 0; formIndex < forms.length; formIndex ++) { var formName = forms[formIndex].name var formProps = mm.getFormProperties() for (var cpp = 0 ; cpp < formProps.length; cpp ++) { var formprop = formProps[cpp] var propname = formprop.name var formDef = this.model.forms[formName] if (formprop.type == "Action") { formDef[formprop.id] = mm.getFormMethod( formName, formprop) } else if (!isValidObject(formprop)){ formDef[formprop.id] = "" } } // --------------------------------------------------------- // ... load the component definitions for all components in // the form // --------------------------------------------------------- var compsToLoad = [] for (var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length ; compenentInFormIndex++ ) { var newItem = mm.model.forms[formName].components[compenentInFormIndex] if (!component_loaded[newItem.base_component_id]) { compsToLoad.push(newItem.base_component_id) } } await loadV2(compsToLoad) // --------------------------------------------------------- // For each component in the form ... // --------------------------------------------------------- for (var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length ; compenentInFormIndex++ ) { // --------------------------------------------------------- // ... Make sure that the component is added as a // dependency of this app (Useful for // when we compile the app as standalone HTML) // --------------------------------------------------------- var componentConfig = mm.model.forms[formName].components[compenentInFormIndex] if (mm.edited_app_component_id) { mm.component_usage[ componentConfig.base_component_id ] = true } // --------------------------------------------------------- // ... // // // --------------------------------------------------------- var componentId = this.model.forms[formName].components[compenentInFormIndex].base_component_id var cachedComponentDefinition = component_cache[componentId] if (isValidObject(cachedComponentDefinition)) { var cachedComponentPropertiesDefinition = this.getControlProperties(this.model.forms[formName].components[compenentInFormIndex].base_component_id) if (isValidObject(cachedComponentPropertiesDefinition)) { for (var cpp = 0 ; cpp< cachedComponentPropertiesDefinition.length; cpp ++) { var prop = cachedComponentPropertiesDefinition[cpp].id var compId = this.model.forms[formName].components[compenentInFormIndex].base_component_id if (cachedComponentPropertiesDefinition[cpp].type == "Action") { this.model.forms[formName].components[compenentInFormIndex][prop] = mm.getControlMethod(cachedComponentPropertiesDefinition[cpp], mm.model.forms[formName].components[compenentInFormIndex]) } else if (!isValidObject(this.model.forms[formName].components[compenentInFormIndex][prop])){ this.model.forms[formName].components[compenentInFormIndex][prop] = "" } } } } } //call the load event on each component for (var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length ; compenentInFormIndex++ ) { var componentConfig = mm.model.forms[formName].components[compenentInFormIndex] if (isValidObject(componentConfig.load)) { //alert("Load event :" + formName + " : " + componentConfig.name) } } } //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) // // get the availabe components // if (online) { var sql = "select base_component_id,logo_url from system_code where " + " code_tag = 'LATEST' and logo_url is not null and control_type = 'VB'" var results = await callApp({ driver_name: "systemFunctions2",method_name: "sql"}, { sql: sql }) mm.available_components = results //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) } mm.updateAllFormCaches() //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) mm.$forceUpdate(); //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) mm.updatePropertySelector() texti = null setTimeout(function(){ mm.selectForm(mm.model.default_form) },500) mm.$root.$on('message', async function(text) { if (text.type == "delete_component") { //alert("Found: " + text.component_index) //alert(JSON.stringify(mm.model.forms[mm.model.active_form].components[text.component_index],null,2)) mm.model.forms[mm.model.active_form].components.splice(text.component_index, 1); //mm.design_mode_pane.type = "drag_drop"; } else if (text.type == "select_component") { mm.selectComponent(text.component_index, true); } }) hideProgressBar() }, methods: { getControlMethod: function(componentDefn,componentDetails) { var mm = this var methodId = componentDefn.id var methodFn = componentDefn.fn return async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { var me = componentDetails var fnDetails = null if (isValidObject(methodFn)) { var thecode = `(async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { ${methodFn} })` fnDetails = eval(thecode) } else { var controlDetails = globalControl[componentDetails.name] fnDetails = controlDetails[methodId] } var retv = await fnDetails(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) if (isValidObject(retv) && isValidObject(retv.failed)) { throw retv.failed } if (isValidObject(retv) && isValidObject(retv.value)) { return retv.value } return retv } } , getFormMethod: function(formName, formprop) { var mm = this return async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { var formDetails = mm.model.forms[formName] var thecode = `(async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { ${formprop.fn} })` fnDetails = eval(thecode) var retv = await fnDetails(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) if (isValidObject(retv) && isValidObject(retv.failed)) { throw retv.failed } return retv.value } } , deleteCursor: function() { document.getElementById(this.vb_grid_element_id).style.cursor = "crosshair" document.getElementById("grid_container").style.cursor = "default" if (this.oldCursor) { this.cursorSource.style.cursor = this.oldCursor this.oldCursor = null this.cursorSource = null this.newCursor = null } } , switchCursor: function(event, oldCursor, newCursor) { var mm = this mm.cursorSource = event.target mm.cursorSource.style.cursor = newCursor mm.newCursor = newCursor mm.oldCursor = oldCursor document.getElementById(mm.vb_grid_element_id).style.cursor = newCursor document.getElementById("grid_container").style.cursor = newCursor } , maintainCursor: function() { var mm = this } , clickOnMainGrid: function(event) { if (this.design_mode) { event.stopPropagation(); if (this.highlighted_control) { var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var rrr = event.target.getBoundingClientRect() var offsetX = (event.clientX - rrr.left ) var offsetY = (event.clientY - rrr.top ) var parentId = null var parentName = null var parentOffsetX = 0 var parentOffsetY = 0 var newItem2 = new Object() var data = { type: "add_component", text: this.highlighted_control, offsetX: offsetX, offsetY: offsetY } var parentContainer = this.getContainerForPoint( offsetX, offsetY ) if (parentContainer) { parentOffsetX = parentContainer.x parentOffsetY = parentContainer.y parentId = parentContainer.base_component_id parentName = parentContainer.name } this.addComponent( offsetX, offsetY, data, parentId, parentName, parentOffsetX, parentOffsetY, []) this.highlighted_control = null } else { this.selectForm(this.model.active_form, true); } } }, getContainerForPoint: function(leftX,topY) { var ccc = this.model.forms[this.model.active_form].components for (var ytr = 0;ytr < ccc.length;ytr++){ var baseId = ccc[ytr].base_component_id var controlNmae = ccc[ytr].name var x1 = ccc[ytr].leftX var x2 = ccc[ytr].leftX + ccc[ytr].width var y1 = ccc[ytr].topY var y2 = ccc[ytr].topY + ccc[ytr].height var isContainer = ccc[ytr].is_container if (isContainer && (x1 <= leftX) && (leftX <= x2) && (y1 <= topY) && (topY <= y2)) { return { x: x1, y: y1, base_component_id: ccc[ytr].base_component_id, name: ccc[ytr].name } } } return null } , addComponent: async function(leftX,topY,data, parentId, parentName, parentOffsetX, parentOffsetY,defProps) { var mm = this //alert(JSON.stringify(data,null,2)) var newItem = new Object() var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() //alert(parentId +": = (" + parentOffsetX + "," + parentOffsetY + ")") newItem.leftX = Math.floor(leftX) newItem.topY = Math.floor(topY) if (newItem.leftX < 0) { newItem.leftX = 0 } if (newItem.topY < 0) { newItem.topY = 0 } //alert(`(${newItem.leftX},${newItem.topY})`) if (parentId) { //alert(`${baseId}:(${x1},${y1}) - (${x2},${y2})`) newItem.parent = parentName } newItem.name = data.text + "_" + this.model.next_component_id++ newItem.base_component_id = data.text this.refresh++ if (!component_loaded[newItem.base_component_id]) { await loadV2([newItem.base_component_id]) this.component_usage[newItem.base_component_id] = true } var compEvaled1 = component_cache[newItem.base_component_id] if (isValidObject(compEvaled1)) { var compEvaled = compEvaled1.properties if (isValidObject(compEvaled)) { for (var cpp = 0 ; cpp < compEvaled.length; cpp ++){ var prop = compEvaled[cpp].id if (!isValidObject(newItem[prop])){ if (compEvaled[cpp].default) { newItem[prop] = JSON.parse(JSON.stringify(compEvaled[cpp].default)) } else { newItem[prop] = "" } } } } } if (!isValidObject(newItem.width)) { newItem.width = 100 } if (!isValidObject(newItem.height)) { newItem.height = 100 } if ((newItem.leftX + newItem.width) > this.model.forms[this.model.active_form].width) { newItem.leftX = Math.floor(this.model.forms[this.model.active_form].width - newItem.width) } if ((newItem.topY + newItem.height) > this.model.forms[this.model.active_form].height) { newItem.topY = Math.floor(this.model.forms[this.model.active_form].height - newItem.height) } if (isValidObject( defProps )) { var oo = Object.keys(defProps) for ( var ee = 0 ; ee < oo.length ; ee++ ) { var propName = oo[ee] var propValue = defProps[propName] newItem[propName] = propValue } } this.model.forms[this.model.active_form].components.push(newItem) this.model.active_component_index = this.model.forms[this.model.active_form].components.length - 1 setTimeout(function() { mm.selectComponent(mm.model.active_component_index, true) mm.refresh ++ },100) var compCode = component_cache[newItem.base_component_id].code var childrenCode = saveHelper.getValueOfCodeString(compCode, "children",")//children") if (isValidObject(childrenCode)) { for ( var ee = 0 ; ee < childrenCode.length ; ee++ ) { //alert(JSON.stringify(childrenCode[ee],null,2)) var childBaseId = childrenCode[ee].base_component_id var childDefProps = childrenCode[ee].properties await this.addComponent( 0 , 0 , {text: childBaseId} , newItem.base_component_id , newItem.name , 0 , 0 , childDefProps ) } } } , copyControl: function(controlDetails , props , genNewName) { var mm = this var xx = JSON.parse(JSON.stringify(controlDetails)) var yy = Object.assign(xx , props) if ( isValidObject(genNewName) ) { yy.name = "random_name" } return yy } , addControl: function(controlDetails) { var mm = this mm.model.forms.Form_1.components.push( controlDetails ) } , refreshControlIndexes: function() { if (this.model.active_component_detail_name) { var ccc = mm.model.forms[this.model.active_form].components for (var ytr = 0;ytr < ccc.length;ytr++) { if (this.model.active_component_detail_name == ccc[ytr].name) { this.model.active_component_detail_name = ytr break } } } else { this.model.active_component_detail_name = null } } , hasMoreDetailsUi: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++) { if (component.parent == ccc[ytr].name) { if (ccc[ytr].hide_children) { return false } break } } } if (component.has_details_ui) { return true } return false } , isVisible: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (!component) { return false } if (component.hidden) { return false } if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++) { if (ccc[ytr]) { if (component.parent == ccc[ytr].name) { if (ccc[ytr].hide_children) { return false } break } } } } return true } , getLeft: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (!component) { return 0 } var left = component.leftX if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++){ if (component.parent == ccc[ytr].name) { left = left + ccc[ytr].leftX break } } } return left } , getTop: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (!component) { return 0 } var top = component.topY if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++){ if (component.parent == ccc[ytr].name) { top = top + ccc[ytr].topY break } } } return top } , getChildren: function( itemName ) { var mm = this var ccc = mm.model.forms[mm.model.active_form].components var chh = [] for (var ytr = 0;ytr < ccc.length;ytr++){ if (ccc[ytr].parent == itemName) { ccc[ytr].index_in_parent_array = ytr chh.push(ccc[ytr]) } } return chh } , previewUpload: function(property) { var mm = this; var file = document.getElementById('image_file').files[0]; var reader = new FileReader(); reader.addEventListener("load", function () { mm.model.forms[mm.model.active_form].components[mm.model.active_component_index][property.id] = reader.result mm.refresh ++ }, false); if (file) { reader.readAsDataURL(file); } } , showHelp: async function(aa) { var mm = this if (this.ui_code_editor) { if (mm.ui_code_editor.completer) { mm.ui_code_editor.completer.detach() } mm.ui_code_editor.destroy() mm.ui_code_editor = null // ------------------ HACK CITY! ------------------------- // we need this line as otherwise the ace editor isnt always destroyed // properly (related to deletion of the Ace editor parent nodes in Vue) mm.design_mode_pane.type = null // ------------------------------------------------------- } setTimeout(function(){ mm.model.active_component_detail_name = null mm.model.active_component_detail_index = null mm.design_mode_pane.type = "help" mm.design_mode_pane.help = aa.help mm.refresh++ },200) } , // ----------------------------------------------------- // editAsCode // // This is called when the "..." button is pressed for // a property in the property inspector // // This can show code for the app, a form, and for // controls // // ----------------------------------------------------- editAsCode: async function(aa) { // // if the code editor is already open then close it // var mm = this if (mm.ui_code_editor) { if (mm.ui_code_editor.completer) { mm.ui_code_editor.completer.detach() } mm.ui_code_editor.destroy() mm.ui_code_editor = null } // // Set up the new code editor // setTimeout(function(){ mm.design_mode_pane.type = "event_editor" mm.design_mode_pane.app_selected = aa.app_selected mm.design_mode_pane.active_form = aa.active_form mm.design_mode_pane.active_component_index = aa.active_component_index mm.design_mode_pane.property_id = aa.property_id setTimeout(function(){ if (document.getElementById('ui_code_editor') && (mm.ui_code_editor == null)) { // //set up the ace editor for the timeline view // ace.config.set('basePath', '/'); mm.ui_code_editor = ace.edit( "ui_code_editor", { selectionStyle: "text", mode: "ace/mode/javascript" }) // //Hack city! Need a delay when setting theme or view is corrupted // setTimeout(function(){ mm.ui_code_editor.setTheme("ace/theme/sqlserver"); },100) // // Stylize the code editor // document.getElementById("ui_code_editor").style["font-size"] = "16px" document.getElementById("ui_code_editor").style.width = "100%" document.getElementById("ui_code_editor").style.border = "0px solid #2C2828" document.getElementById("ui_code_editor").style.height = "55vh" // // Get the code and store it in "ccode" // // The code is obtained from the VueJS model, depending on whether // it is a control, a form, or application code // var ccode = "" // application code (THIS MUST BE FIST IN THE IF STATEMENT) if (mm.model.app_selected) { ccode = mm.model[aa.property_id] // form code } else if ((mm.model.active_component_index == null) && (mm.model.active_form != null)) { ccode = mm.model.forms[mm.model.active_form][aa.property_id] // component code } else if ((mm.model.active_component_index != null) && (mm.model.active_form != null)) { ccode = mm.model.forms[mm.model.active_form].components[mm.model.active_component_index][aa.property_id] } if (!isValidObject(ccode)) { ccode = "" } mm.ui_code_editor.getSession().setValue(ccode); mm.ui_code_editor.getSession().setUseWorker(false); mm.ui_code_editor.on("change", function(e) { var newC = mm.ui_code_editor.getValue() if (aa.app_selected) { mm.model[aa.property_id] = newC } else if ((mm.model.active_component_index == null) && (mm.model.active_form != null)) { mm.model.forms[mm.model.active_form][aa.property_id] = newC } else if ((mm.model.active_component_index != null) && (mm.model.active_form != null)) { mm.model.forms[mm.model.active_form].components[mm.model.active_component_index][aa.property_id] = newC } }) mm.updateAllFormCaches() mm.setupCodeAutocompletions() mm.ui_code_editor.focus(); } },100) },100) mm.setupCodeEditorSelectors(aa.property_id) } , // ----------------------------------------------------- // setupCodeAutocompletions // // This is called when editing event code to autocomplete // form names, control names, and methods // // // // ----------------------------------------------------- setupCodeAutocompletions: function() { var mm = this var langTools = ace.require("ace/ext/language_tools"); // // Clear any default autocompleters that have been set // langTools.setCompleters([]); // // Create the autocompleter // var autocompleterFunction = { identifierRegexps: [/[a-zA-Z_0-9.]/] , getCompletions: function(editor, session, pos, prefix, callback) { console.log("Called autocompleterFunction: " + pos + " : " + prefix) // // If no text entered then do nothing // if (prefix.length === 0) { callback(null, []); return } // // Get the first part of the text to autocomplete // var firstObjectToAutocomplete = null if (prefix.indexOf(".") != -1) { firstObjectToAutocomplete = prefix.substring(0,prefix.indexOf(".")) console.log("firstObjectToAutocomplete: " + firstObjectToAutocomplete) } var wordList = [] // // Create the list of initial objects to complete: // app, forms, controls // if (firstObjectToAutocomplete == null) { wordList.push( {"word": "app", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "Main application" }) wordList.push( {"word": "forms", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "List of forms" }) if (mm.design_mode_pane.app_selected) { wordList.push( {"word": "me", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current app" }) } else if (mm.design_mode_pane.active_component_index == null) { wordList.push( {"word": "me", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current form" }) } else { wordList.push( {"word": "me", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current control" }) wordList.push( {"word": "myForm", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current form" }) } wordList.push( {"word": "parent", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The parent/container control of this" }) var ccc = mm.model.forms[mm.model.active_form].components for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { var component = ccc[ytr] wordList.push( {"word": component.name, "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "Control" }) } ccc = Object.keys(mm.model.forms) for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { wordList.push( {"word": ccc[ytr], "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "Form" }) } // // If we have ented an object and pressed "." (period) // then we need to add the method that comes after the // period, eg: // // my_label.set| // .setText() // .setWidth() <- choose one // .setHeight() // } else { // // Find out what the left hand side of the "." represents. Is // it a component, a form, or the app? // var componentId = null var formName = null var isApp = false if (firstObjectToAutocomplete == "me") { if (mm.design_mode_pane.app_selected) { } else if (isValidObject(mm.design_mode_pane.active_component_index)) { componentId = mm.model.forms[mm.model.active_form].components[ mm.design_mode_pane.active_component_index ].base_component_id } else if (isValidObject(mm.design_mode_pane.active_form)) { formName = mm.model.active_form } } else if (firstObjectToAutocomplete == "myForm") { formName = mm.model.active_form } else if (firstObjectToAutocomplete == "parent") { if (mm.design_mode_pane.app_selected) { } else if (isValidObject(mm.design_mode_pane.active_component_index)) { var parentId = mm.model.forms[mm.model.active_form].components[ mm.design_mode_pane.active_component_index ].parent if (isValidObject(parentId)) { componentId = mm.form_runtime_info[mm.model.active_form].component_lookup_by_name[parentId].base_component_id } } else if (isValidObject(mm.design_mode_pane.active_form)) { } } else if (firstObjectToAutocomplete == "app") { isApp = true } else { // // see if the word is a component // var comps = mm.model.forms[mm.model.active_form].components for (var rt=0; rt < comps.length; rt++) { if (comps[rt].name == firstObjectToAutocomplete) { componentId = comps[rt].base_component_id } } // // see if the word is a form // var formNames = Object.keys(mm.model.forms) for (var rt=0; rt < formNames.length; rt++) { var formName1 = formNames[rt] if (formName1 == firstObjectToAutocomplete) { formName = formName1 } } } // // if a component was entered // if (componentId) { var controlProperties = mm.getControlProperties(componentId) for (var fg=0;fg < controlProperties.length;fg++){ var comm = controlProperties[fg] var propName = firstObjectToAutocomplete + "." + comm.id var meta = "Property" if (isValidObject(comm.snippet)) { propName = firstObjectToAutocomplete + "." + comm.snippet } if (isValidObject(comm.pre_snippet)) { propName = comm.pre_snippet + propName } if (comm.type == "Action") { meta = "Method" } wordList.push({ "word": propName , "freq": 24, "score": 300, "flags": "bc", "syllables": "1", "meta": meta }) } // // if a form was entered // } else if (formName) { var formProps = mm.getFormProperties(formName) for (var formPropIndex = 0 ; formPropIndex < formProps.length ; formPropIndex++ ) { var propDetails = formProps[formPropIndex] var propName = firstObjectToAutocomplete + "." + propDetails.id var meta = "Property" if (isValidObject(propDetails.snippet)) { propName = firstObjectToAutocomplete + "." + propDetails.snippet } if (isValidObject(propDetails.pre_snippet)) { propName = propDetails.pre_snippet + propName } if (propDetails.type == "Action") { meta = "Method" } if (propDetails.type == "Event") { meta = "Event" } wordList.push({ "word": propName , "freq": 24, "score": 300, "flags": "bc", "syllables": "1", "meta": meta }) } // // if the main object is the VB app // } else if (isApp) { var appProps = mm.get_default_app_propeties() for (var formPropIndex = 0 ; formPropIndex < appProps.length ; formPropIndex++ ) { var propDetails = appProps[formPropIndex] var propName = firstObjectToAutocomplete + "." + propDetails.id var meta = "Property" if (isValidObject(propDetails.snippet)) { propName = firstObjectToAutocomplete + "." + propDetails.snippet } if (isValidObject(propDetails.snippet)) { propName = propDetails.snippet + propName } if (propDetails.type == "Action") { meta = "Method" } if (propDetails.type == "Event") { meta = "Event" } wordList.push({ "word": propName , "freq": 24, "score": 300, "flags": "bc", "syllables": "1", "meta": meta }) } } } callback(null, wordList.map(function(ea) { return {name: ea.word, value: ea.word, score: ea.score, meta: ea.meta} })); } } langTools.addCompleter(autocompleterFunction); mm.ui_code_editor.commands.addCommand({ name: "showOtherCompletions", bindKey: ".", exec: function(editor) { mm.ui_code_editor.session.insert(mm.ui_code_editor.getCursorPosition(), ".") mm.ui_code_editor.completer.updateCompletions() } }) mm.ui_code_editor.setOptions({ enableBasicAutocompletion: false, enableSnippets: false, enableLiveAutocompletion: true }); } , setupCodeEditorSelectors: function( property_id ) { var mm = this setTimeout( function() { // // Add the selectors using the SelectR library // if (!document.getElementById("select_code_object_parent")) { return; } document.getElementById("select_code_object_parent").innerHTML=' <select id=select_code_object ></select>' if (!document.getElementById("select_code_action_parent")) { return; } document.getElementById("select_code_action_parent").innerHTML=' <select id=select_code_action ></select>' // // initialise vars // var objectListForSelector = [] var methodListForSelector = [] var indexObjectSelector = 0 var indexActionSelector = 0 var selectedCodeObject = null var selectedCodeAction = null // // if we selected the app or a form // if (mm.model.app_selected || (!isValidObject(mm.model.active_component_index))) { if (mm.edited_app_component_id) { objectListForSelector.push( { value: "" + indexObjectSelector, app: mm.edited_app_component_id, form: null, component: null }) } if (mm.model.app_selected) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ var forms = mm.getForms() for ( var ere = 0; ere < forms.length; ere++ ) { var form = forms[ ere ] objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: form.name, component: null } ) if ((!mm.model.app_selected) && (form.name == mm.model.active_form)) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ // // show the sub controls of this form if it is the current form // if ((!mm.model.app_selected) && (form.name == mm.model.active_form)) { var components = mm.getActiveFormComponents() for ( var ere1 = 0; ere1 < components.length; ere1++ ) { var component = components[ ere1 ] objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: mm.model.active_form, component: " - " + component.name, component_type: component.base_component_id, component_index: ere1 } ) if (mm.model.active_component_index == ere1) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ } } } // // if we selected a component // } else if (isValidObject(mm.model.active_component_index)) { objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: mm.model.active_form, component: null } ) indexObjectSelector++ var components = mm.getActiveFormComponents() for ( var ere = 0; ere < components.length; ere++ ) { var component = components[ ere ] objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: mm.model.active_form, component: " - " + component.name, component_type: component.base_component_id, component_index: ere } ) if (mm.model.active_component_index == ere) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ } } // // get the list of properties // // // get the app methods // if (mm.model.app_selected) { methodListForSelector.push( { value: "" + indexActionSelector, app: mm.edited_app_component_id, form: mm.model.active_form, component: null, action_id: "app_started_event", action_name: "Called when the app is started", action_type: "Event" } ) selectedCodeAction = indexActionSelector indexActionSelector++ } else if ( isValidObject(mm.model.active_component_index) ) { var ccc = mm.model.forms[mm.model.active_form].components[mm.model.active_component_index] var properties = mm.getComponentProperties( ccc.base_component_id ) for ( var ere = 0; ere < properties.length; ere++ ) { var property = properties[ ere ] if (property.type == "Event") { methodListForSelector.push( { value: "" + indexActionSelector, app: null, form: mm.model.active_form, component: ccc.name, action_id: property.id, action_name: property.name, action_type: property.type, action_index: ere } ) if (property.id == property_id) { selectedCodeAction = indexActionSelector } indexActionSelector++ } } methodListForSelector.push( { value: "" + indexActionSelector, app: null, form: mm.model.active_form, component: ccc.name, action_id: "load", action_name: "Load event", action_type: "Event", action_index: ere }) if ( property_id == "load" ) { selectedCodeAction = indexActionSelector } indexActionSelector++ // get the actions for the forms } else if ( isValidObject(mm.model.active_form) ) { var ccc = mm.model.forms[mm.model.active_form] var properties = mm.getComponentProperties( ccc.base_component_id ) methodListForSelector.push( { value: "" + indexActionSelector, app: null, form: mm.model.active_form, component: ccc.name, action_id: "form_activate", action_name: "Activate Event", action_type: "Event", action_index: ere }) if ( property_id == "form_activate" ) { selectedCodeAction = indexActionSelector } indexActionSelector++ } selectCodeObject = new Selectr( document.getElementById('select_code_object'), { renderOption: mm.myDataRenderFunction, renderSelection: mm.myDataRenderFunction, selectedValue: selectedCodeObject, data: objectListForSelector, customClass: 'my-custom-selectr', searchable: false }); selectCodeAction = new Selectr( document.getElementById('select_code_action'), { renderOption: mm.actionRenderFunction, renderSelection: mm.actionRenderFunction, selectedValue: selectedCodeAction, data: methodListForSelector, customClass: 'my-custom-selectr', searchable: false }); document.getElementsByClassName("selectr-selected")[0].style.padding = "1px" document.getElementsByClassName("selectr-selected")[0].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[0].style["border-left"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[1].style.padding = "1px" document.getElementsByClassName("selectr-selected")[1].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[1].style["border-left"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[2].style.padding = "1px" document.getElementsByClassName("selectr-selected")[2].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[2].style["border-left"] = "2px solid gray" selectCodeObject.on('selectr.select', function(option) { var dd = objectListForSelector[option.idx] if (dd.component) { mm.selectComponent(dd.component_index) mm.editAsCode({ app_selected: false, active_form: mm.model.active_form, active_component_index: mm.model.active_component_index, property_id: "load" }) } else if (dd.form) { mm.selectForm(dd.form) mm.editAsCode({ app_selected: false, active_form: dd.form, active_component_index: null, property_id: "form_activate" }) } else if (dd.app) { mm.select_app() mm.editAsCode({ app_selected: true, active_form: mm.model.active_form, active_component_index: null, property_id: "app_started_event" }) } }); selectCodeAction.on('selectr.select', function(option) { var dd = methodListForSelector[option.idx] mm.editAsCode({ app_selected: mm.app_selected, active_form: mm.model.active_form, active_component_index: mm.model.active_component_index, property_id: dd.action_id }) }); },100) } , getActiveFormComponents: function() { return this.model.forms[this.model.active_form].components }, updateAllFormCaches: function() { var llf = Object.keys(this.model.forms) for (var ii = 0; ii < llf.length ; ii ++) { var formqq = this.model.forms[llf[ii]] if (formqq != null) { this.updateFormCache(formqq.name) } } }, gotoDragDropEditor: function() { this.design_mode_pane.type = "drag_drop"; if (this.ui_code_editor) { if (this.ui_code_editor.completer) { this.ui_code_editor.completer.detach() } this.ui_code_editor.destroy() this.ui_code_editor = null } this.model.active_component_detail_name = null this.model.active_component_detail_index = null } , updateFormCache: function(formName) { var form = this.model.forms[formName] var components = form.components if (!isValidObject(this.form_runtime_info[formName])) { this.form_runtime_info[formName] = new Object() } this.form_runtime_info[formName].component_lookup_by_name = {} for (var gjh = 0; gjh < components.length; gjh ++) { var cc = components[gjh] if (isValidObject(cc)) { this.form_runtime_info[formName].component_lookup_by_name[cc.name] = cc } } }, chooseRight: function(ff) { this.right_mode = ff }, //------------------------------------------------------------------- getForms: function() { //------------------------------------------------------------------- var forms = [] var llf = Object.keys(this.model.forms) for (var ii = 0; ii < llf.length ; ii ++) { var form = this.model.forms[llf[ii]] if (form != null) { forms.push(form) } } return forms }, //------------------------------------------------------------------- // setVBEditorProperty // // event, property //------------------------------------------------------------------- getFormProperties: function( formName ) { var props = [] props.push({ id: "name", name: "Name", type: "String" }) props.push({ id: "width", name: "Width", type: "Number" }) props.push({ id: "height", name: "Height", type: "Number" }) props.push({ id: "form_activate", name: "Activate Event", type: "Event" }) props.push({ id: "add_control", name: "Add Control", type: "Action" , snippet: `add_control({name: "name_of_new_control"})`, fn: `debugger mm.addControl( arg1 ) return {} ` }) return props } , //------------------------------------------------------------------- setVBEditorProperty: function(event, property) { //------------------------------------------------------------------- var mm = this var val = event.target.value var type = null if (this.model.active_component_index != null) { type = "component" } else if ((this.model.active_component_index == null) && (this.model.active_form != null) && (!this.model.app_selected)) { type = "form" } else if (this.model.app_selected) { type = "app" } if (type == 'component') { this.model.forms[this.model.active_form].components[this.model.active_component_index][property.id] = val //this.generateCodeFromModel( ) this.refresh ++ } else if (type == 'form') { if (property.id == "name" ) { this.properties = [] var oldval = this.model.active_form //alert("Rename form " + oldval + " to " + val) this.model.forms[val] = this.model.forms[oldval] this.model.forms[val]["name"] = val this.form_runtime_info[val] = this.form_runtime_info[oldval] if (this.model.default_form == oldval) { this.model.default_form = val } //this.model.active_form = val mm.form_runtime_info[oldval] = null mm.model.forms[oldval] = null //alert(this.model.active_form) //alj(this.form_runtime_info[val]) //mm.refresh ++ //mm.updateAllFormCaches() mm.selectForm(val) } else { this.model.forms[this.model.active_form][property.id] = val } } else if (type == 'app') { this.model[property.id] = val } }, //------------------------------------------------------------------- getVBEditorProperty: function(property) { //------------------------------------------------------------------- var val = "" var type if (this.model.active_component_index != null) { type = "component" } else if ((this.model.active_component_index == null) && (this.model.active_form != null) && (!this.model.app_selected)) { type = "form" } else if (this.model.app_selected) { type = "app" } if (type == 'component') { val = this.model.forms[this.model.active_form].components[this.model.active_component_index][property.id] } else if (type == 'form') { val = this.model.forms[this.model.active_form][property.id] } else if (type == 'app') { val = this.model[property.id] } return val }, //------------------------------------------------------------------- addProperty: function() { //------------------------------------------------------------------- var mm = this mm.add_property = true mm.new_property_id = "" mm.new_property_name = "" } , //------------------------------------------------------------------- addPropertySave: function() { //------------------------------------------------------------------- var mm = this if ((mm.new_property_name.length == 0) || (mm.new_property_id.length == 0)) { alert("You must enter a property name and ID") return; } mm.add_property = false mm.model.app_properties.push({ id: mm.new_property_id, name: mm.new_property_name, type: "String" }) mm.generateCodeFromModel( ) setTimeout(function() { mm.refresh ++ mm.select_app() } ,100) } , //------------------------------------------------------------------- addPropertyCancel: function() { //------------------------------------------------------------------- var mm = this mm.add_property = false } , //------------------------------------------------------------------- getComponentProperties: function(componentName) { //------------------------------------------------------------------- var compEvaled1 = component_cache[componentName] if (isValidObject(compEvaled1)) { var compEvaled = compEvaled1.properties if (isValidObject(compEvaled)) { return compEvaled } } return [] } , //------------------------------------------------------------------- selectForm: function(formId, showProps) { //------------------------------------------------------------------- var mm = this mm.model.active_component_index = null mm.model.app_selected = false mm.properties = mm.getFormProperties(formId) mm.model.active_form = formId mm.refresh ++ if ( mm.model.forms[ formId ].form_activate && (!mm.design_mode)) { if (!isValidObject(this.args)) { mm.args = mm.model } var args = mm.args var app = mm.model var crt = mm.model.forms[formId].form_activate var formEvent = { type: "form_event", form_name: formId, code: crt } mm.processControlEvent(formEvent) } mm.updatePropertySelector() if (isValidObject(showProps) && showProps) { this.selected_pane = "properties"; this.chooseRight("properties"); } mm.refresh ++ }, //------------------------------------------------------------------- // processControlEvent // // This is used to run user written event code //------------------------------------------------------------------- processControlEvent: async function( eventMessage ) { var mm = this if ((!mm.design_mode) && (mm.model)) { this.updateAllFormCaches() // // set up property access for all forms // var formHandler = { get: function(target,name){ var formName = target.name if (mm.model.forms[formName][name]) { return mm.model.forms[formName][name] } if (mm.form_runtime_info[formName].component_lookup_by_name[name]) { return mm.form_runtime_info[formName].component_lookup_by_name[name] } return "Not found" } } var formEval = "" var allForms = this.getForms(); for (var fi =0; fi < allForms.length ; fi ++) { var aForm = allForms[fi] formEval += ("var " + aForm.name + " = new Proxy({name: '" + aForm.name + "'}, formHandler);") } eval(formEval) // // set up property access for all controls on this form // var allC = this.model.forms[this.model.active_form].components var cacc ="" for (var xi =0; xi< allC.length ; xi ++) { var comp = allC[xi] cacc += ( "var " + comp.name + " = mm.form_runtime_info['" + this.model.active_form + "'].component_lookup_by_name['" + comp.name + "'];") } eval(cacc) if (eventMessage.type == "subcomponent_event") { var fcc = `(async function(){ ${eventMessage.code} })` var thisControl = this.form_runtime_info[ this.model.active_form ].component_lookup_by_name[ eventMessage.control_name ] if (isValidObject(thisControl)) { if (isValidObject(thisControl.parent)) { var cacc ="" cacc += ( "var parent = mm.form_runtime_info['" + this.model.active_form + "'].component_lookup_by_name['" + thisControl.parent + "'];") eval(cacc) } var meCode ="" meCode += ( "var me = mm.form_runtime_info['" + this.model.active_form + "'].component_lookup_by_name['" + thisControl.name + "'];") eval(meCode) var appCode ="" appCode += ( "var app = mm.model;") eval(appCode) var meCode ="" meCode += ( "var myForm = mm.model.forms['" + this.model.active_form + "'];") eval(meCode) var debugFcc = getDebugCode(mm.model.active_form +"_"+eventMessage.control_name+"_"+eventMessage.sub_type,fcc,{skipFirstAndLastLine: true}) var efcc = eval(debugFcc) try { await efcc() } catch( err ) { alert(JSON.stringify(err,null,2)) } } // // form events // } else if (eventMessage.type == "form_event") { var fcc = `(async function(){ ${eventMessage.code} })` var meCode ="" meCode += ( "var me = mm.model.forms['" + this.model.active_form + "'];") eval(meCode) var appCode ="" appCode += ( "var app = mm.model;") eval(appCode) var debugFcc = getDebugCode(this.model.active_form ,fcc,{skipFirstAndLastLine: true}) var efcc = eval(debugFcc) try { await efcc() } catch( err ) { alert(JSON.stringify(err,null,2)) } } mm.refresh ++ mm.$forceUpdate(); } }, //------------------------------------------------------------------- allowDropEditor: function(ev) { //------------------------------------------------------------------- ev.preventDefault(); }, //------------------------------------------------------------------- dropEditor: async function (ev) { //------------------------------------------------------------------- ev.preventDefault(); var mm = this var data2 = ev.dataTransfer.getData("message"); var data = eval("(" + data2 + ")") var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0) ; var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); if (data.type == "resize_form_bottom_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newWidth = (ev.clientX - 8) - rrr.left ; var newHeight = (ev.clientY - 8) - rrr.top ; this.model.forms[this.model.active_form].width = Math.floor(newWidth) this.model.forms[this.model.active_form].height = Math.floor(newHeight) this.model.active_component_index = null mm.refresh ++ } else if (data.type == "resize_form_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newWidth = (ev.clientX - 8) - rrr.left ; this.model.forms[this.model.active_form].width = Math.floor(newWidth) this.model.active_component_index = null mm.refresh ++ } else if (data.type == "resize_form_bottom") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newHeight = (ev.clientY - 8) - rrr.top ; this.model.forms[this.model.active_form].height = Math.floor(newHeight) this.model.active_component_index = null mm.refresh ++ } }, setInfo: function(text) { this.$root.$emit('message', { type: "set_info_text", text: text }) }, //------------------------------------------------------------------- allowDrop: function(ev) { //------------------------------------------------------------------- //ev.preventDefault(); }, //------------------------------------------------------------------- drag: function(ev,message) { //------------------------------------------------------------------- var mm = this var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var rrr = ev.target.getBoundingClientRect() message.offsetX = (ev.clientX - rrr.left ) message.offsetY = (ev.clientY - rrr.top ) if (!isValidObject(ev.dataTransfer)) { return } ev.dataTransfer.setData("message", JSON.stringify(message,null,2)); }, showComponentDetailedDesignUi: async function(index) { var mm = this mm.design_mode_pane.type = "control_details_editor" this.model.active_component_detail_index = index; this.model.active_component_detail_name = this.model.forms[this.model.active_form].components[index].name; setTimeout(function() { mm.refresh ++ mm.$forceUpdate(); },400) }, deleteComponent: async function(index) { var mm = this var thisComponentName = this.model.forms[this.model.active_form].components[index].name this.model.forms[this.model.active_form].components.splice(index, 1); var ccc = mm.model.forms[mm.model.active_form].components for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { var component = ccc[ytr] if (component.parent == thisComponentName) { this.model.forms[this.model.active_form].components.splice(ytr, 1); } } this.refreshControlIndexes() this.selectForm(this.model.active_form) setTimeout(function() { mm.refresh ++ mm.$forceUpdate(); },400) }, deleteComponentByName: async function(thisComponentName) { debugger var mm = this var ccc2 = mm.model.forms[mm.model.active_form].components for ( var ytr = ccc2.length - 1; ytr >= 0; ytr-- ) { var component = ccc2[ytr] if (component.name == thisComponentName) { this.model.forms[this.model.active_form].components.splice(ytr, 1); break; } } this.model.forms[this.model.active_form].components.splice(index, 1); var ccc = mm.model.forms[mm.model.active_form].components for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { var component = ccc[ytr] if (component.parent == thisComponentName) { this.model.forms[this.model.active_form].components.splice(ytr, 1); } } this.refreshControlIndexes() this.selectForm(this.model.active_form) setTimeout(function() { mm.refresh ++ mm.$forceUpdate(); },400) return {} }, childDeleteComponent: function(index) { this.$root.$emit('message', { type: "delete_component", component_index: index }) } , childSelectComponent: function(index) { this.$root.$emit('message', { type: "select_component", component_index: index }) } , //------------------------------------------------------------------- drop: async function (ev) { // // This is called when something happens on the main drag and drop // grid // //------------------------------------------------------------------- ev.preventDefault(); var mm = this if (this.oldCursor) { this.cursorSource.style.cursor = this.oldCursor this.oldCursor = null this.cursorSource = null } var data2 = ev.dataTransfer.getData("message"); var data = eval("(" + data2 + ")") var newItem2 = new Object() var rrr2 = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() newItem2.leftX = (ev.clientX - rrr2.left) - data.offsetX; newItem2.topY = (ev.clientY - rrr2.top) - data.offsetY; var parentId = null var parentName = null var parentOffsetX = 0 var parentOffsetY = 0 var parentOffsetWidth = 0 var parentOffsetHeight = 0 var parentContainer = this.getContainerForPoint( newItem2.leftX, newItem2.topY ) if (parentContainer) { parentOffsetX = parentContainer.x parentOffsetY = parentContainer.y parentId = parentContainer.base_component_id parentName = parentContainer.name } if (data.type == "add_component") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var xx = ((ev.clientX - rrr.left) - data.offsetX) - parentOffsetX - 10; var yy = ((ev.clientY - rrr.top) - data.offsetY) - parentOffsetY - 10; await mm.addComponent(xx,yy,data, parentId, parentName, parentOffsetX, parentOffsetY,[]) this.highlighted_control = null } else if (data.type == "move_component") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newLeftX = (ev.clientX - rrr.left) - data.offsetX; var newTopY = (ev.clientY - rrr.top) - data.offsetY; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newLeftX < 0) { newLeftX = 0 } if (newTopY < 0) { newTopY = 0 } if ((newLeftX + this.model.forms[this.model.active_form].components[data.index].width) > this.model.forms[this.model.active_form].width) { newLeftX = this.model.forms[this.model.active_form].width - this.model.forms[this.model.active_form].components[data.index].width } if ((newTopY + this.model.forms[this.model.active_form].components[data.index].height) > this.model.forms[this.model.active_form].height) { newTopY = this.model.forms[this.model.active_form].height - this.model.forms[this.model.active_form].components[data.index].height } this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newLeftX) this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newTopY) this.model.active_component_index = data.index } else if (data.type == "resize_top_left") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var oldX = this.model.forms[this.model.active_form].components[data.index].leftX var oldY = this.model.forms[this.model.active_form].components[data.index].topY var newLeftX = ev.clientX + 2 - rrr.left ; var newTopY = ev.clientY + 2 - rrr.top ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newLeftX < 0) { newLeftX = 0 } if (newTopY < 0) { newTopY = 0 } this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newLeftX) this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newTopY) var diffX = this.model.forms[this.model.active_form].components[data.index].leftX - oldX var diffY = this.model.forms[this.model.active_form].components[data.index].topY - oldY this.model.forms[this.model.active_form].components[data.index].width -= Math.floor(diffX) this.model.forms[this.model.active_form].components[data.index].height -= Math.floor(diffY) this.model.active_component_index = data.index } else if (data.type == "resize_left") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var oldX = this.model.forms[this.model.active_form].components[data.index].leftX var newLeftX = ev.clientX + 2 - rrr.left ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newLeftX < 0) { newLeftX = 0 } this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newLeftX) var diffX = this.model.forms[this.model.active_form].components[data.index].leftX - oldX this.model.forms[this.model.active_form].components[data.index].width -= Math.floor(diffX) this.model.active_component_index = data.index } else if (data.type == "resize_top") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var oldY = this.model.forms[this.model.active_form].components[data.index].topY var newTopY = ev.clientY + 2 - rrr.top ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newTopY < 0) { newTopY = 0 } this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newTopY) var diffY = this.model.forms[this.model.active_form].components[data.index].topY - oldY this.model.forms[this.model.active_form].components[data.index].height -= Math.floor(diffY) this.model.active_component_index = data.index } else if (data.type == "resize_top_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX - 10 - rrr.left ; var newY = ev.clientY + 2 - rrr.top; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newX - this.model.forms[this.model.active_form].components[data.index].leftX) var newHeight = (this.model.forms[this.model.active_form].components[data.index].topY + this.model.forms[this.model.active_form].components[data.index].height) - newY this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newY) this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } else if (data.type == "resize_bottom_left") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX + 8 - rrr.left ; var newY = ev.clientY - 12 - rrr.top ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newWidth = (this.model.forms[this.model.active_form].components[data.index].leftX + this.model.forms[this.model.active_form].components[data.index].width) - newX var newHeight = newY - this.model.forms[this.model.active_form].components[data.index].topY this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newX) this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newWidth) this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } else if (data.type == "resize_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX - rrr.left - 10; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newWidth = newX - this.model.forms[this.model.active_form].components[data.index].leftX this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newWidth) this.model.active_component_index = data.index } else if (data.type == "resize_bottom_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX - rrr.left - 10; var newY = ev.clientY - rrr.top - 12; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newWidth = newX - this.model.forms[this.model.active_form].components[data.index].leftX this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newWidth) var newHeight = newY - this.model.forms[this.model.active_form].components[data.index].topY this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } else if (data.type == "resize_bottom") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newY = ev.clientY - rrr.top - 12; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newHeight = newY - this.model.forms[this.model.active_form].components[data.index].topY this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } this.selectComponent(this.model.active_component_index) this.refresh ++ }, //------------------------------------------------------------------- get_default_app_propeties: function() { var mm = this return [ { id: "id", name: "ID", type: "String" , readonly: true, get_fn: function() { return mm.edited_app_component_id } } , { id: "default_form", name: "Load form on startup", type: "String"} , { id: "app_started_event", name: "Called when the app is started", type: "Event"} ] } , //------------------------------------------------------------------- // select_app // // //------------------------------------------------------------------- select_app: function() { var mm = this this.model.active_component_index = null this.model.app_selected = true this.active_property_index = null this.properties = mm.get_default_app_propeties() if (this.model.app_properties) { this.properties = this.properties.concat(this.model.app_properties) } this.updatePropertySelector() this.refresh ++ } , //------------------------------------------------------------------- // myDataRenderFunction // // //------------------------------------------------------------------- myDataRenderFunction: function(data) { if (!isValidObject(data)) { return "<div></div>" } var center = "" if (data.app) { center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + (data.app?data.app:data.form) + "</b> " } else if (data.component) { center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + data.component + "</b> " + data.component_type } else if (data.form) { center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + data.form + "</b> " } var template = "<div style='font-weight:normal;color:black;overflow:hidden ;text-overflow: ellipsis;border-radius: 1px;margin: 0px;padding:0px;border:0px;font-family:verdana,helvetica;font-size: 13px;'>" + center + "</div>"; return template; }, actionRenderFunction: function(data) { if (!isValidObject(data)) { return "<div></div>" } var center = "" center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + data.action_id + "</b> " + data.action_name var template = "<div style='font-weight:normal;color:black;overflow:hidden ;text-overflow: ellipsis;border-radius: 1px;margin: 0px;padding:0px;border:0px;font-family:verdana,helvetica;font-size: 13px;'>" + center + "</div>"; return template; }, // ------------------------------------------------------------------- // updatePropertySelector // // This updates the property selector on the right of the editor, // and it uses the currently selected object to figure out what // to display // ------------------------------------------------------------------- updatePropertySelector: function() { var mm = this // // if we are not in edit mode then do nothing // if (!designMode){ return } // // If the property selector is not available then do nothing // if (!document.getElementById("property_selector_parent")) { return } // // Set up the property selector // document.getElementById("property_selector_parent").innerHTML=' <select id=property_selector ></select>' var sdata = [] var indexProp = 0 var selectedItem = null if (mm.model.app_selected || (!isValidObject(mm.model.active_component_index))) { if (mm.edited_app_component_id) { sdata.push( { value: "" + indexProp, app: mm.edited_app_component_id, form: null, component: null }) } if (mm.model.app_selected) { selectedItem = indexProp } indexProp++ var forms = mm.getForms() for ( var ere = 0; ere < forms.length; ere++ ) { var form = forms[ ere ] sdata.push( { value: "" + indexProp, app: null, form: form.name, component: null } ) if ((!mm.model.app_selected) && (form.name == mm.model.active_form)) { selectedItem = indexProp } indexProp++ } } else if (isValidObject(mm.model.active_component_index)) { sdata.push( { value: "" + indexProp, app: null, form: mm.model.active_form, component: null } ) indexProp++ var components = mm.getActiveFormComponents() for ( var ere = 0; ere < components.length; ere++ ) { var component = components[ ere ] sdata.push( { value: "" + indexProp, app: null, form: mm.model.active_form, component: component.name, component_type: component.base_component_id, component_index: ere } ) if (mm.model.active_component_index == ere) { selectedItem = indexProp } indexProp++ } } // // selector for property inspector // selectProp = new Selectr( document.getElementById('property_selector'), { renderOption: mm.myDataRenderFunction, renderSelection: mm.myDataRenderFunction, selectedValue: selectedItem, data: sdata, customClass: 'my-custom-selectr', searchable: false }); document.getElementsByClassName("selectr-selected")[0].style.padding = "1px" document.getElementsByClassName("selectr-selected")[0].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[0].style["border-left"] = "2px solid gray" selectProp.on('selectr.select', function(option) { var dd = sdata[option.idx] if (dd.component) { mm.selectComponent(dd.component_index) } else if (dd.form) { mm.selectForm(dd.form) } else if (dd.app) { mm.select_app() } }); }, existsProp: function(compEvaled,propName) { for (var eee = 0 ;eee < compEvaled.length; eee++) { if (compEvaled[eee].id == propName) { return true } } return false } , //------------------------------------------------------------------- getControlProperties: function(base_component_id) { var properties = [] var compEvaled = this.getComponentProperties(base_component_id) properties.push({ id: "name", name: "Name", type: "String" }) properties.push({ id: "base_component_id", name: "Type", type: "String" , readonly: true }) properties.push({ id: "leftX", name: "X", type: "Number" }) properties.push({ id: "topY", name: "Y", type: "Number" }) if (!this.existsProp(compEvaled,"width")) { properties.push({ id: "width", name: "Width", type: "Number" }) } if (!this.existsProp(compEvaled,"height")) { properties.push({ id: "height", name: "Height", type: "Number" }) } if (!this.existsProp(compEvaled,"load")) { properties.push({ id: "load", name: "Load Event", type: "Event" }) } properties.push({ id: "clone", name: "Clone", type: "Action" , pre_snippet: `await `, snippet: `clone("new_name")`, fn: ` var newObject = JSON.parse(JSON.stringify(me)) newObject.name = arg1 return newObject ` }) //zzz if (this.existsProp(compEvaled,"is_container")) { properties.push({ id: "addChild", name: "Add Child", type: "Action" , pre_snippet: `await `, snippet: `addChild({})`, fn: `debugger mm.addControl( arg1 ) return {} ` }) } //parent. properties = properties.concat(compEvaled) return properties } //------------------------------------------------------------------- , //------------------------------------------------------------------- selectComponent: async function(index, showProps) { //------------------------------------------------------------------- if (!this.design_mode) { return } var mm = this if (index == null) { return } this.active_property_index = null this.model.app_selected = false this.model.active_component_index = index this.properties = this.getControlProperties(this.model.forms[this.model.active_form].components[index].base_component_id) this.updatePropertySelector() if (isValidObject(showProps) && showProps) { this.selected_pane = "properties"; this.chooseRight("properties"); } this.refresh ++ }, //------------------------------------------------------------------- addForm: function() { //------------------------------------------------------------------- var mm = this mm.model.active_component_index = null mm.properties = mm.getFormProperties() mm.model.max_form ++ var newFormName = "form_" + mm.model.max_form mm.model.forms[newFormName] = { name: newFormName, components: [], width: 300, height: 300, add_control: "alert('Add control called')" } mm.model.active_form = newFormName mm.refresh ++ } , //------------------------------------------------------------------- moveUp: function( fieldId ) { //------------------------------------------------------------------- var mm = this var itemD = null for (var tt=0; tt < mm.model.forms[mm.model.active_form].fields.length ; tt++) { var ciurr = mm.model.forms[mm.model.active_form].fields[tt] if (ciurr.id == fieldId) { itemD = ciurr } } if (itemD) { var index = mm.model.forms[mm.model.active_form].fields.indexOf( itemD ); if (index > -1) { mm.model.fields.splice(index, 1); mm.model.fields.splice(index - 1, 0, itemD); } } }, //------------------------------------------------------------------- moveDown: function( fieldId ) { //------------------------------------------------------------------- var mm = this var itemD = null for (var tt=0; tt < mm.model.forms[mm.model.active_form].fields.length ; tt++) { var ciurr = mm.model.forms[mm.model.active_form].fields[tt] if (ciurr.id == fieldId) { itemD = ciurr } } if (itemD) { var index = mm.model.forms[mm.model.active_form].fields.indexOf( itemD ); if (index > -1) { mm.model.fields.splice(index, 1); mm.model.fields.splice(index + 1, 0, itemD); } } }, //------------------------------------------------------------------- deleteField: function( fieldId ) { //------------------------------------------------------------------- var mm = this var itemD = null for (var tt=0; tt < mm.model.forms[mm.model.active_form].fields.length ; tt++) { var ciurr = mm.model.forms[mm.model.active_form].fields[tt] if (ciurr.id == fieldId) { itemD = ciurr } } if (itemD) { var index = mm.model.forms[mm.model.active_form].fields.indexOf( itemD ); if (index > -1) { mm.model.fields.splice(index, 1); } } }, //------------------------------------------------------------------- getText: async function() { //------------------------------------------------------------------- //console.log("2) VB: getText") await this.generateCodeFromModel() return this.text }, //------------------------------------------------------------------- setText: function(textValue) { //------------------------------------------------------------------- //console.log("start setText") var mm = this this.text = textValue var json2 = this.getJsonModelFromCode( textValue ) //console.log("setText: mm.model = json2") mm.edited_app_component_id = saveHelper.getValueOfCodeString(textValue, "base_component_id") mm.model = json2 mm.updatePropertySelector() mm.refresh ++ //console.log("end setText") } , //------------------------------------------------------------------- getJsonModelFromCode: function( codeV ) { //------------------------------------------------------------------- var mm = this mm.edited_app_component_id = saveHelper.getValueOfCodeString(codeV, "base_component_id") var json2 = saveHelper.getValueOfCodeString(codeV,"formEditor",")//formEditor") return json2 } , //------------------------------------------------------------------- generateCodeFromModel: async function( ) { //------------------------------------------------------------------- var mm = this if (this.in_generate_code_from_model) { return } if (!this.design_mode) { return } this.in_generate_code_from_model = true if (online && this.design_mode) { //console.log("start generateCodeFromModel") var startIndex = this.text.indexOf("//** gen_" + "start **//") var endIndex = this.text.indexOf("//** gen_" + "end **//") var sql = "select cast(code as text) as code from system_code where " + " base_component_id = 'vb_editor_component' and code_tag = 'LATEST' " var results = await callApp({ driver_name: "systemFunctions2",method_name: "sql"}, { sql: sql }) var editorCode = results[0].code var stt = "//*** COPY_" + "START ***//" var editorCodeToCopyStart = editorCode.indexOf(stt) + stt.length var editorCodeToCopyEnd = editorCode.indexOf("//*** COPY_" + "END ***//") var editorCodeToCopy = editorCode.substring(editorCodeToCopyStart, editorCodeToCopyEnd) this.text = this.text.substring(0,startIndex) + `//** gen_start **// var mm = null var texti = null var designMode = false var runtimeMode = true Vue.component('${this.edited_app_component_id}', {` + editorCodeToCopy + `, data: function () { return { uid2: null, vb_grid_element_id: null, vb_editor_element_id: null, design_mode: designMode, design_mode_pane: {}, local_app: false, refresh: 0, runtime_mode: runtimeMode, component_usage: new Object(), ui_code_editor: null, form_runtime_info: {}, text: texti, model: ` + JSON.stringify( mm.model, function(key, value) { if (typeof value === 'string') { return value.toString() } return value; }, 2) + `} } })` + this.text.substring(endIndex) var subComponents = saveHelper.getValueOfCodeString(this.text, "sub_components") var subComponentsMap = {} if (subComponents) { this.text = saveHelper.deleteCodeString(this.text, "sub_components") } else { subComponents = [] } for (var tt = 0; tt < subComponents.length ; tt++) { var subComponentName = subComponents[tt] subComponentsMap[subComponentName] = {} } var forms = mm.getForms() for ( var formIndex = 0; formIndex < forms.length; formIndex ++ ) { var formName = forms[formIndex].name for ( var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length; compenentInFormIndex ++ ) { var newItem = mm.model.forms[formName].components[compenentInFormIndex] if (newItem && newItem.base_component_id) { if (!subComponentsMap[newItem.base_component_id]) { subComponentsMap[newItem.base_component_id] = {} } } } } var newListOfSubcomponents = Object.keys( subComponentsMap ) this.text = saveHelper.insertCodeString(this.text, "sub_components", newListOfSubcomponents) this.text = saveHelper.deleteCodeString( this.text, "control_type") this.text = saveHelper.insertCodeString( this.text, "control_type", "SYSTEM") this.text = saveHelper.deleteCodeString( this.text, "formEditor", ")//form" + "Editor") this.text = saveHelper.insertCodeString( this.text, "formEditor", mm.model, ")//form" + "Editor") this.text = saveHelper.deleteCodeString( this.text, "properties", ")//prope" + "rties") this.text = saveHelper.insertCodeString( this.text, "properties", mm.model.app_properties, ")//prope" + "rties") //console.log("end generateCodeFromModel.Done") this.in_generate_code_from_model = false return } } } //*** COPY_END ***// , data: function () { return { newCursor: null, oldCursor: null, cursorSource: null, uid2: null, vb_grid_element_id: null, vb_editor_element_id: null, in_generate_code_from_model: false, design_mode: designMode, runtime_mode: runtimeMode, highlighted_control: null, edited_app_component_id: null, event_code: null, text: texti, leftHandWidth: 130, right_mode: "project", add_property: false, new_property_name: "", new_property_id: "", local_app: false, refresh: 0, properties: [], read_only: false, selected_pane: null, active_property_index: null, design_mode_pane: {type: "drag_drop"}, available_components: [], component_usage: new Object(), form_runtime_info: {}, model: { next_id: 1, next_component_id: 1, max_form: 1, active_form: "Form_1", active_component_index: null, active_component_detail_index: null, active_component_detail_name: null, app_selected: false, default_form: "Form_1", app_properties: [], fields: [ ], forms: { "Form_1": { name: "Form_1", components: [ ] } } } } } } ) }
public/visifile_drivers/ui_components/vbEditorComponent.js
async function component( args ) { /* base_component_id("vb_editor_component") control_type("SYSTEM") load_once_from_file(true) uses_javascript_librararies(["advanced_bundle"]) */ //alert(JSON.stringify(args,null,2)) var mm = null var texti = null if (args) { texti = args.text } var designMode = true var runtimeMode = false var selectProp = null var selectCodeObject = null var selectCodeAction = null Vue.component("vb_editor_component", { //*** COPY_START ***// props: [ "args"], template: `<div v-bind:id='uid2' v-if='uid2 != null' v-bind:style='"width: 100%; height: 100%; " + (design_mode?"background: white;":"")'> <div style='box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-color: lightgray; padding: 5px; padding-left: 15px;padding-bottom: 10px;' v-if='design_mode' > <slot style='display: inline-block;float: left;' v-if='text'> </slot> </div> <div v-bind:id='vb_editor_element_id' v-if='vb_editor_element_id != null' style='position:relative;display: flex;' v-on:drop="$event.stopPropagation(); dropEditor($event)" v-on:ondragover="$event.stopPropagation();maintainCursor(); allowDropEditor($event)"> <!-- ----------------------------------------- The left section of the UI editor ----------------------------------------- --> <div v-if='design_mode' v-on:click='selected_pane = "blocks";' v-bind:style='(design_mode?"border: 4px solid lightgray;":"") + " max-width: " + leftHandWidth + "px;height: 75vmin; display: inline-block;overflow-x: hidden;overflow-y: hidden;vertical-align: top; background-color: lightgray;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);float:left;;flex-grow: 0;flex-shrink: 0;"'> <div v-bind:style='"font-family:verdana,helvetica;font-size: 13px;border-radius: 3px;padding: 4px; margin-bottom: 10px;box-shadow: 2px 2px 10px lightgray;"' v-bind:class='(selected_pane == "blocks"?"selected_pane_title":"unselected_pane_title") '> Blocks </div> <div class='' > <div class='' style='display:flex;overflow-y:scroll;flex-flow: row wrap;height:65vh;'> <div class='flex' v-on:click='highlighted_control = null;' v-bind:style='"display:flex;cursor: grab;border-radius: 3px;width:50px;height:50px; margin: 0px;border: 0px;padding:4px;overflow-x:hidden;overflow-y:hidden;background-color: " + ((!highlighted_control)?"#E8E8E8;border-left: 2px solid gray;border-top: 2px solid gray;":"lightgray;")'> <img src='/driver_icons/cursor.png' style='width: 100%;' class='img-fluid'> </img> </div> <div v-for='av in available_components' draggable="true" class='' v-on:dragend='$event.stopPropagation();deleteCursor();' v-on:dragstart='$event.stopPropagation();switchCursor($event,"grab","grabbing");highlighted_control = av.base_component_id;drag($event,{ type: "add_component", text: av.base_component_id })' v-on:click='highlighted_control = av.base_component_id;' v-bind:style='"display:flex;cursor: grab;margin: 2px;border-radius: 3px;width:50px;;height: 50px; margin: 0px;border: 0px;padding:10px;overflow-x:auto;overflow-y:hidden;background-color: " + ((highlighted_control == av.base_component_id)?"#E8E8E8;border-left: 2px solid gray;border-top: 2px solid gray;":"lightgray;")'> <img v-if='isValidObject(av)' v-bind:src='av.logo_url' style='width: 100%;' class='img-fluid'> </img> </div> </div> </div> </div> <!-- The main center section of the UI editor --> <div v-bind:style='"display: flex;width:100%;" + (design_mode?"background-color: darkgray;":"background-color: white;")'> <!-- The code editor for events --> <div v-if='(design_mode && (design_mode_pane.type=="event_editor"))' v-bind:refresh='refresh' v-bind:style='"margin: 2px; display: inline-block; vertical-align: top; width: 100%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 15px;":"margin: 0px;" ) '> <div style='font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;background-color:lightgray; color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;'> <div style='height: 50px;' > <div id='select_code_object_parent' style='display: inline-block;margin: 5px;width: 200px;'></div> <div id='select_code_action_parent' style='display: inline-block;margin: 5px;width: 200px;'></div> <button type=button class=' btn btn-danger btn-sm' style="float: right;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;margin-bottom: 4px;" v-on:click='gotoDragDropEditor()' >x</button> </div> <div id='ui_code_editor'> </div> </div> </div> <div v-if='(design_mode && (design_mode_pane.type=="help"))' v-bind:refresh='refresh' v-bind:style='"margin: 2px; display: inline-block; vertical-align: top; width: 100%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 15px;":"margin: 0px;" ) '> <div style='font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-image: linear-gradient(to right, #000099, lightblue); color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;'> <div style='height: 30px;' > Help <button type=button class=' btn btn-danger btn-sm' style="float: right;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;margin-bottom: 4px;" v-on:click='gotoDragDropEditor()' >x</button> </div> <div id='show_help' style="background-color:white;color:black;"> <div style="font-weight:normal;" v-html="design_mode_pane.help"></div> </div> </div> </div> <!-- The control details editor --> <div v-if='(design_mode && (design_mode_pane.type=="control_details_editor"))' v-bind:style='"box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);margin: 2px; display: inline-block; vertical-align: top; width: 100%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 15px;":"margin: 0px;" ) '> <div v-if='design_mode' style='font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-image: linear-gradient(to right, #000099, lightblue); color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;'> <div style='height: 30px;' > Control details <button type=button class=' btn btn-danger btn-sm' style="float: right;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;margin-bottom: 4px;" v-on:click='gotoDragDropEditor()' >x</button> </div> </div> <div v-bind:style='"border: 5px solid lightgray;background: white;;overflow:none;height:100%; overflow: auto;"'> <component v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[model.active_component_detail_index].name + (design_mode?"_design":"")' v-bind:refresh='refresh' design_mode='detail_editor' v-bind:meta='{form: model.active_form,name: model.forms[model.active_form].components[model.active_component_detail_index].name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:delete_component='childDeleteComponent' v-bind:select_component='childSelectComponent' v-bind:children='getChildren( model.forms[model.active_form].components[model.active_component_detail_index].name)' v-on:send="processControlEvent" v-bind:is='model.forms[model.active_form].components[model.active_component_detail_index].base_component_id' v-bind:name='model.forms[model.active_form].components[model.active_component_detail_index].name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[model.active_component_detail_index]'> <template slot-scope="child_components" v-bind:refresh='refresh' style='position:relative;'> <component v-for='child_item in getChildren(model.forms[model.active_form].components[model.active_component_detail_index].name)' v-bind:design_mode='design_mode' v-bind:meta='{form: model.active_form,name: child_item.name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:refresh='refresh' v-bind:style='"z-index:100000;position: absolute; top: " + child_item.topY + "px; left: " + child_item.leftX + "px;height:" + child_item.height + "px;width:" + child_item.width + "px;overflow:auto;"' v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[child_item.index_in_parent_array].name + (design_mode?"_design":"")' v-on:send="processControlEvent" v-bind:is='child_item.base_component_id' v-bind:name='child_item.name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[child_item.index_in_parent_array]'> </component> </template> </component> </div> </div> <!-- The drag drop UI editor. but... Also the main view of the App --> <div v-if='(!design_mode) || (design_mode && (design_mode_pane.type=="drag_drop"))' v-bind:style='(design_mode?"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;":"") + "margin: 2px; display: inline-block; vertical-align: top; width: 95%;height: 65vh ;" + (design_mode?"border: 0px solid lightgray; padding:0px;margin: 0px;margin-left:15px;margin-top:15px;":"margin: 0px;" ) '> <div v-if='design_mode' style='display:inline-block;font-family:verdana,helvetica;font-size: 13px;font-weight:bold;border-radius: 0px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);background-image: linear-gradient(to right, #000099, lightblue); color: white; border: 4px solid lightgray; padding:4px; margin:0;border-bottom: 0px;width:100%;'> <img src='/driver_icons/form.png' style='width: 20px; margin-right: 10px;' class='img-fluid'> </img> {{model.active_form}} (Form) </div> <div style=''></div> <div id="grid_container" drop-target=false style='width:100%;background-color:white;height: 100%;position:relative;'> <!-- INACTIVE FORM RESIZERS --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:2px;top:2px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (7 + (model.forms[model.active_form].width/2)) + "px;top:2px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (15 +model.forms[model.active_form].width) + "px;top:2px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:2px;top:" + (7 + (model.forms[model.active_form].height/2)) + "px;"'> </div> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"display:inline-block;background-color: white; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:2px;top:" + (15 + model.forms[model.active_form].height) + "px;"'> </div> <!-- ACTIVE FORM RESIZERS --> <!-- bottom right --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:style='"cursor: nwse-resize;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (15 +model.forms[model.active_form].width) + "px;top:" + (15 + (model.forms[model.active_form].height)) + "px;"' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nwse-resize","crosshair");drag($event,{ type: "resize_form_bottom_right", form_name: model.active_form })' > </div> <!-- right --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"cursor: ew-resize;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (15 +model.forms[model.active_form].width) + "px;top:" + (7 + (model.forms[model.active_form].height/2)) + "px;"' v-bind:draggable='true' v-on:dragend='$event.stopPropagation();deleteCursor();' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ew-resize","col-resize");drag($event,{ type: "resize_form_right", form_name: model.active_form })' > </div> <!-- bottom --> <div v-if='design_mode && (!isValidObject(model.active_component_index))' v-bind:style='"cursor: ns-resize;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (7 +model.forms[model.active_form].width/2) + "px;top:" + (15 + (model.forms[model.active_form].height)) + "px;"' v-bind:draggable='true' v-on:dragend='$event.stopPropagation();deleteCursor()' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ns-resize","row-resize");drag($event,{ type: "resize_form_bottom", form_name: model.active_form })' > </div> <div v-bind:id='vb_grid_element_id' v-if='vb_grid_element_id != null' v-on:drop="drop($event)" v-bind:refresh='refresh' v-on:ondragover="$event.stopPropagation();maintainCursor();allowDrop($event)" v-bind:class='(design_mode?"dotted":"" )' v-on:click='clickOnMainGrid($event)' v-bind:style='"position:absolute;display: inline-block; vertical-align: top; width: " + model.forms[model.active_form].width + ";height: " + model.forms[model.active_form].height + " ;" + (design_mode?"left:15px;top:15px;border: 4px solid lightgray;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);":"border: 0px;" ) '> <div v-bind:refresh='refresh' style='position:absolute;left:0px;top:0px;z-index:1000000;opacity:1;'> <!-- ACTIVE CONTROL RESIZERS --> <!-- top left --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nwse-resize;z-index:10000000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + (getLeft(model.active_form,model.active_component_index) - 15) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) - 15) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nwse-resize","crosshair");drag($event,{ type: "resize_top_left", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- top middle --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ns-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width/2) - 7) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) - 15) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ns-resize","row-resize");drag($event,{ type: "resize_top", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- top right --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nesw-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) ) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) - 15) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nesw-resize","crosshair");drag($event,{ type: "resize_top_right", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- middle left --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ew-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) - 15) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height / 2)) - 7) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ew-resize","col-resize");drag($event,{ type: "resize_left", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- middle right --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ew-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width)) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height / 2)) - 7) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ew-resize","col-resize");drag($event,{ type: "resize_right", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- bottom left --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nesw-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) - 15) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height)) + 2) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nesw-resize","crosshair");drag($event,{ type: "resize_bottom_left", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- bottom middle --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: ns-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width/2) - 7) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height)) + 2) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"ns-resize","row-resize");drag($event,{ type: "resize_bottom", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- bottom right --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:style='"cursor: nwse-resize;z-index:1000;display:inline-block;background-color: gray; border: 3px solid gray; margin:0;width:12px;height:12px;position:absolute;left:" + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) ) + "px;top:" + ((getTop(model.active_form,model.active_component_index)) + ((model.forms[model.active_form].components[model.active_component_index].height)) + 2) + "px;"' v-on:dragend='$event.stopPropagation();deleteCursor();' v-bind:draggable='true' v-on:dragstart='$event.stopPropagation();switchCursor($event,"nwse-resize","crosshair");drag($event,{ type: "resize_bottom_right", text: model.forms[model.active_form].components[model.active_component_index].base_component_id, index: model.active_component_index })'> </div> <!-- DELETE --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index)' v-bind:refresh='refresh' class='btn btn-danger' v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;position: absolute; " + "left: " + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) + 15) + "px;" + "top: " + ((getTop(model.active_form,model.active_component_index)) - 45) + "px;" + "width: 30px; height: 30px; line-height:30px;text-align: center;vertical-align: middle;"' v-on:click='$event.stopPropagation();deleteComponent(model.active_component_index)'> X </div> <!-- More details ... button --> <div v-if='design_mode && isValidObject(model.active_component_index) && isVisible(model.active_form,model.active_component_index) && hasMoreDetailsUi(model.active_form,model.active_component_index)' v-bind:refresh='refresh' class='btn btn-info' v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;position: absolute; " + "left: " + ((getLeft(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].width) + 15) + "px;" + "top: " + ((getTop(model.active_form,model.active_component_index)) + (model.forms[model.active_form].components[model.active_component_index].height) + 15) + "px;" + "width: 30px; height: 30px; line-height:30px;text-align: center;vertical-align: middle;"' v-on:click='$event.stopPropagation();showComponentDetailedDesignUi(model.active_component_index)'> ... </div> <div v-bind:refresh='refresh' v-for='(item,index) in getActiveFormComponents()' ondrop="return false;" v-on:click='if ( isVisible(model.active_form,index)){ $event.stopPropagation();selectComponent(index,true); }' v-bind:style='((design_mode && isVisible(model.active_form,index))?"border: 1px solid black;background: white;":"") + "position: absolute;top: " + getTop(model.active_form,index) + ";left:" + getLeft(model.active_form,index) + ";height:" + item.height + "px;width:" + item.width + "px;;overflow:none;"'> <div ondrop="return false;" v-bind:style='"position: absolute; top: 0px; left: 0px;height:" + item.height + "px;width:" + item.width + "px;overflow:auto;"'> <component v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[index].name + (design_mode?"_design":"")' v-bind:refresh='refresh' v-bind:meta='{form: model.active_form,name: item.name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:design_mode='design_mode' v-bind:children='getChildren(item.name)' v-on:send="processControlEvent" v-bind:is='item.base_component_id' v-if='!item.parent' v-bind:name='item.name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[index]'> <template slot-scope="child_components" v-bind:refresh='refresh' style='position:relative;'> <component v-for='child_item in getChildren(item.name)' v-bind:design_mode='design_mode' v-bind:refresh='refresh' v-bind:meta='{form: model.active_form,name: child_item.name + (design_mode?"_design":"")}' v-bind:form="model.active_form" v-bind:style='"z-index:100000;position: absolute; top: " + child_item.topY + "px; left: " + child_item.leftX + "px;height:" + child_item.height + "px;width:" + child_item.width + "px;overflow:auto;"' v-bind:id='model.active_form + "_" + model.forms[model.active_form].components[child_item.index_in_parent_array].name + (design_mode?"_design":"")' v-on:send="processControlEvent" v-bind:is='child_item.base_component_id' v-bind:name='child_item.name + "_design_mode_" + design_mode' v-bind:args='model.forms[model.active_form].components[child_item.index_in_parent_array]'> </component> </template> </component> </div> <div v-bind:style='"cursor: move;position: absolute; top: 0px; left: 0px;z-index: " + (item.is_container?"1":"10000000") + ";width: 100%;height: 100%;border: 1px solid black;"' v-bind:draggable='design_mode' v-if='design_mode && isVisible(model.active_form,index)' ondrop="return false;" v-on:dragstart='$event.stopPropagation();drag($event,{ type: "move_component", text: item.base_component_id, index: index })'> <div v-if='design_mode && isVisible(model.active_form,index)' ondrop="return false;" v-bind:refresh='refresh' v-bind:style='"position: absolute; top: 0px; left: 0px;z-index: 10000000;width: 100%;height: 100%; background-color: lightgray;" + ((index == model.active_component_index)?"opacity: 0;":"opacity: .6;") '> </div> </div> </div> </div> </div> </div> </div> </div> <!-- **************************************************************** * * * The right section of the UI editor * * * **************************************************************** --> <div v-if='design_mode' v-bind:style='(design_mode?"border: 4px solid lightgray;box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;":"") + " float:right;top:0px;right:0px;width: 400px;height: 75vmin; display: inline-block;overflow-x: none;overflow: hidden;vertical-align: top;padding:0px;height:75vmin;background-color: lightgray; "' v-bind:refresh='refresh'> <div id='right_project_pane' v-bind:class='(right_mode == "project"?"right_project_pane_expanded":"right_project_pane_collapsed")' v-bind:refresh='refresh' v-bind:style='"padding:0px; border: 4px solid lightgray;white-space:nowrap"'> <div v-bind:style='"border-radius: 3px; padding: 4px;overflow-x:none;height: 40px;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);font-family:verdana,helvetica;font-size: 13px;" ' v-bind:class='(selected_pane == "project"?"selected_pane_title":"unselected_pane_title") ' v-on:click='$event.stopPropagation();var s = (right_mode == "properties"?"project":"project");selected_pane = "project";chooseRight(s);' > Project explorer <button type=button class='btn btn-sm btn-warning' v-bind:style='"float: right;" + (right_mode == "project"?"":"display:;font-family:verdana,helvetica;font-size: 13px;")' v-on:click='$event.stopPropagation();selected_pane = "project"; chooseRight("project");addForm()' > Add form </button> </div> <div v-bind:style='"font-family:verdana,helvetica;font-size: 13px;border-radius: 3px; padding:4px; border-right:2px solid gray;border-bottom:2px solid gray; margin-top:2px;;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);height:80%;background-color:lightgray;" + (right_mode == "project"?"":"display:none;")'> <div style="align-items: stretch;border-radius: 3px;overflow-y:scroll; padding:0px; border: 0px solid lightgray;border-left: 2px solid gray;border-top: 2px solid gray; background-color:white;height:100%;"> <div v-bind:style='"border-radius: 0px;padding:4px;margin:0px;margin-top: 5px;" + (model.app_selected?"background-color:gray;color:white;":"background-color:white;color:black;")' v-on:click='$event.stopPropagation();selected_pane = "project";select_app()'> <b>{{edited_app_component_id}}</b> </div> <div v-for='form in getForms()' v-bind:refresh='refresh'> <div> <div v-bind:style='(((form.name == model.active_form) && (model.active_component_index == null) && (!model.app_selected)) ?"border: 0px solid red;background-color:gray;color:white;":"color:black;") + "padding:4px;margin:0px;margin-left:30px;border-radius: 3px;"' v-on:click='$event.stopPropagation();selected_pane = "project";selectForm(form.name)'> <img src='/driver_icons/form.png' style='width: 20px; margin-right: 10px;' class='img-fluid'> </img> {{form.name}} ({{form.components.length}}) </div> <div v-if='form.name == model.active_form' v-for='(av,index) in getActiveFormComponents()' v-on:click='$event.stopPropagation();selected_pane = "project";selectComponent(index)' > <div v-bind:style='(((index == model.active_component_index) && design_mode)?"border: 0px solid red;background-color: gray;color: white;":"") + "margin-left:80px; padding:2px;border-radius: 3px;width:90%;"' v-if='(av.parent == null)'> <div style='width:100%;display:inline-block;overflow: hidden;' > {{av.name}} <div v-if='form.name == model.active_form' v-for='(av2,index2) in getActiveFormComponents()' v-on:click='$event.stopPropagation();selected_pane = "project";selectComponent(index2)' > <div v-bind:style='(((index2 == model.active_component_index) && design_mode)?"border: 0px solid red;background-color: gray;color: white;":"") + "margin-left:20px; padding:2px;border-radius: 3px;width:90%;"' v-if='(av2.parent == av.name)'> <div style='width:100%;display:inline-block;overflow: hidden;' > {{av2.name}} </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div id='right_properties_pane' v-bind:class='(right_mode == "properties"?"right_properties_pane_collapsed":"right_properties_pane_collapsed")' v-bind:style='"padding:0px; border: 4px solid lightgray;padding:0px;background-color: lightgray;"'> <div v-bind:style='"border-radius: 3px;padding: 4px;height: 40px;overflow-x:none;white-space:nowrap;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);overflow:hidden ;text-overflow: ellipsis;font-family:verdana,helvetica;font-size: 13px;"' v-bind:class='(selected_pane == "properties"?"selected_pane_title_slower":"unselected_pane_title_slower") ' v-on:click='selected_pane = "properties";chooseRight("properties");'> Properties - {{isValidObject(model.active_component_index)?model.forms[model.active_form].components[model.active_component_index].name + " (Component)" : model.active_form + " (Form)"}} </div> <div id='property_selector_parent' style='margin: 5px;'> </div> <div style="border-radius: 3px; padding:4px; border-right:2px solid gray;border-bottom:2px solid gray; margin-top:2px;;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);height:65%;"> <div style="border-radius: 3px;overflow-y:scroll; padding:0px; border: 0px solid lightgray;border-left: 2px solid gray;border-top: 2px solid gray; background-color:white;height:100%;"> <div v-for='property in properties' style='font-family:verdana,helvetica;font-size: 13px;border-bottom: 1px solid lightgray;padding:0px;margin:0px;' > <div style='width:100%;padding:0px;margin:0px;display:flex;' v-if='!property.hidden'> <div v-bind:style='"text-overflow: ellipsis;white-space: pre-line;vertical-align: top;display:flex;width:40%;margin: 0px;font-family:verdana,helvetica;font-size: 13px;padding-left: 1px;padding-top:0px;padding-bottom:0px;" + (active_property_index == property.name?"background-color:#000099;color:white;":"")' v-on:click='selected_pane = "properties";active_property_index = property.name;'>{{property.name}} <div v-if="isValidObject(property.help)" style="width:100%;display:inline-block;"> <div style='margin-top:2px;margin-bottom:2px;border-right: 2px solid gray;border-bottom: 2px solid gray;background-color: pink; padding:0px; padding-right:5px;padding-left:5px;height: 20px;border-radius: 3px;font-family:verdana,helvetica;font-size: 13px;font-style:bold;color:black;width:20px;' v-on:click='$event.stopPropagation();showHelp({ help: property.help })' >?</div> </div> </div> <div style='display:flex;width:57%;padding:0px;padding-left:3px; border-left: 1px solid lightgray;' v-on:click='selected_pane = "properties";'> <div v-if='!property.readonly' style="width:100%"> <div v-if="(property.editor == 'detail_editor') " style="width:100%"> <div style='margin-top:2px;margin-bottom:2px;border-right: 2px solid gray;border-bottom: 2px solid gray;background-color: darkgray;float: right; padding:0px; padding-right:5px;padding-left:20px;height: 20px;color: white;border-radius: 3px;font-family:verdana,helvetica;font-size: 13px;font-style:bold;' v-on:click='$event.stopPropagation();showComponentDetailedDesignUi(model.active_component_index)' > ... </div> </div> <div v-if="(property.type == 'String') || (property.type == 'Number')"> <input @change='setVBEditorProperty($event, property)' v-bind:value='getVBEditorProperty(property)' style='width: 100%;border: 0px;font-family:verdana,helvetica;font-size: 13px;padding:0px;'> </input> </div> <div v-if="(property.type == 'Select') "> <select @change='setVBEditorProperty($event, property)'> <option v-for="propVal in property.values" v-bind:value="propVal.value" v-bind:selected="propVal.value == model.forms[model.active_form].components[model.active_component_index][property.id]"> {{propVal.display}} </option> </select> </div> <div v-if="(property.type == 'Image') "> <input type="file" id="image_file" @change="previewUpload(property)"> </input> </div> <div v-if="(property.type == 'Event') " style="width:100%"> <div style='margin-top:2px;margin-bottom:2px;border-right: 2px solid gray;border-bottom: 2px solid gray;background-color: darkgray;float: right; padding:0px; padding-right:5px;padding-left:20px;height: 20px;color: white;border-radius: 3px;font-family:verdana,helvetica;font-size: 13px;font-style:bold;' v-on:click='$event.stopPropagation();editAsCode({ app_selected: model.app_selected, active_form: model.active_form, active_component_index: model.active_component_index, property_id: property.id })' > ... </div> </div> </div> <div v-if='property.readonly'> <div v-if='model.active_component_index != null' style='padding:0px;font-family:verdana,helvetica;font-size: 13px;' class='col-md-12 small'> {{model.forms[model.active_form].components[model.active_component_index][property.id]}} </div> <div v-if='(model.active_component_index == null) && (model.active_form != null) && (model.app_selected == false)' class='col-md-12 small' v-model='model.forms[model.active_form][property.id]'> </div> <div v-if='model.app_selected' style='padding:0px;font-family:verdana,helvetica;font-size: 13px;' class='col-md-12 small' > {{property.get_fn?property.get_fn():model[property.id]}} </div> </div> </div> </div> </div> <div v-if='model.app_selected && (!add_property)' class='row'> <div class='col-md-12 small'> <button type=button class='btn btn-sm btn-info' style='font-family:verdana,helvetica;font-size: 13px;' v-on:click='$event.stopPropagation();addProperty()' > Add property </button> </div> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-12 small'> Add a property </div> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-4'> ID </div> <input style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-7 small' placeholder='background_color' v-model='new_property_id'> </input> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div style='font-family:verdana,helvetica;font-size: 13px;' class='col-md-4'> Name </div> <input class='col-md-7 small' placeholder='Background Color' style='border:0px;font-family:verdana,helvetica;font-size: 13px;' v-model='new_property_name'> </input> </div> <div v-if='(model.app_selected) && (add_property)' class='row'> <div class='col-md-12'> <button style='font-family:verdana,helvetica;font-size: 13px;' type=button class='btn btn-sm btn-info' v-on:click='$event.stopPropagation();addPropertyCancel()' > Cancel </button> <button style='font-family:verdana,helvetica;font-size: 13px;' type=button class='btn btn-sm btn-info' v-on:click='$event.stopPropagation();addPropertySave()' > Save </button> </div> </div> </div> </div> </div> </div> </div> </div>` , /* -------------------------------------------------------------- mounted This is called whenever an app is loaded, either at design time or at runtime -------------------------------------------------------------- */ mounted: async function() { var mm = this mm.uid2 = uuidv4() mm.vb_grid_element_id = "vb_grid_"+ uuidv4() mm.vb_editor_element_id = "vb_editor_"+ uuidv4() mm.local_app = localAppshareApp // --------------------------------------------------------- // get the base component ID of the code to edit/run // // Save it in "this.edited_app_component_id" // --------------------------------------------------------- if (texti) { var json2 = this.getJsonModelFromCode( texti ) mm.model = json2 mm.edited_app_component_id = saveHelper.getValueOfCodeString(texti, "base_component_id") this.read_only = saveHelper.getValueOfCodeString(texti, "read_only") } mm.model.active_form = mm.model.default_form // --------------------------------------------------------- // find out which sub components are used by this app // // save the result in "this.component_usage" // --------------------------------------------------------- if (mm.edited_app_component_id) { var sql = "select child_component_id from component_usage where " + " base_component_id = '" + mm.edited_app_component_id + "'" var results = await callApp({ driver_name: "systemFunctions2",method_name: "sql"}, { sql: sql }) for (var i = 0; i < results.length; i++) { mm.component_usage[results[i].child_component_id] = true } } // --------------------------------------------------------- // load the forms and their controls // --------------------------------------------------------- // --------------------------------------------------------- // For each form ... // --------------------------------------------------------- var forms = this.getForms() for (var formIndex = 0; formIndex < forms.length; formIndex ++) { var formName = forms[formIndex].name var formProps = mm.getFormProperties() for (var cpp = 0 ; cpp < formProps.length; cpp ++) { var formprop = formProps[cpp] var propname = formprop.name var formDef = this.model.forms[formName] if (formprop.type == "Action") { formDef[formprop.id] = mm.getFormMethod( formName, formprop) } else if (!isValidObject(formprop)){ formDef[formprop.id] = "" } } // --------------------------------------------------------- // ... load the component definitions for all components in // the form // --------------------------------------------------------- var compsToLoad = [] for (var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length ; compenentInFormIndex++ ) { var newItem = mm.model.forms[formName].components[compenentInFormIndex] if (!component_loaded[newItem.base_component_id]) { compsToLoad.push(newItem.base_component_id) } } await loadV2(compsToLoad) // --------------------------------------------------------- // For each component in the form ... // --------------------------------------------------------- for (var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length ; compenentInFormIndex++ ) { // --------------------------------------------------------- // ... Make sure that the component is added as a // dependency of this app (Useful for // when we compile the app as standalone HTML) // --------------------------------------------------------- var componentConfig = mm.model.forms[formName].components[compenentInFormIndex] if (mm.edited_app_component_id) { mm.component_usage[ componentConfig.base_component_id ] = true } // --------------------------------------------------------- // ... // // // --------------------------------------------------------- var componentId = this.model.forms[formName].components[compenentInFormIndex].base_component_id var cachedComponentDefinition = component_cache[componentId] if (isValidObject(cachedComponentDefinition)) { var cachedComponentPropertiesDefinition = this.getControlProperties(this.model.forms[formName].components[compenentInFormIndex].base_component_id) if (isValidObject(cachedComponentPropertiesDefinition)) { for (var cpp = 0 ; cpp< cachedComponentPropertiesDefinition.length; cpp ++) { var prop = cachedComponentPropertiesDefinition[cpp].id var compId = this.model.forms[formName].components[compenentInFormIndex].base_component_id if (cachedComponentPropertiesDefinition[cpp].type == "Action") { this.model.forms[formName].components[compenentInFormIndex][prop] = mm.getControlMethod(cachedComponentPropertiesDefinition[cpp], mm.model.forms[formName].components[compenentInFormIndex]) } else if (!isValidObject(this.model.forms[formName].components[compenentInFormIndex][prop])){ this.model.forms[formName].components[compenentInFormIndex][prop] = "" } } } } } //call the load event on each component for (var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length ; compenentInFormIndex++ ) { var componentConfig = mm.model.forms[formName].components[compenentInFormIndex] if (isValidObject(componentConfig.load)) { //alert("Load event :" + formName + " : " + componentConfig.name) } } } //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) // // get the availabe components // if (online) { var sql = "select base_component_id,logo_url from system_code where " + " code_tag = 'LATEST' and logo_url is not null and control_type = 'VB'" var results = await callApp({ driver_name: "systemFunctions2",method_name: "sql"}, { sql: sql }) mm.available_components = results //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) } mm.updateAllFormCaches() //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) mm.$forceUpdate(); //console.log("Time " + (ttq++) + ": " + (new Date().getTime()- startTime)) mm.updatePropertySelector() texti = null setTimeout(function(){ mm.selectForm(mm.model.default_form) },500) mm.$root.$on('message', async function(text) { if (text.type == "delete_component") { //alert("Found: " + text.component_index) //alert(JSON.stringify(mm.model.forms[mm.model.active_form].components[text.component_index],null,2)) mm.model.forms[mm.model.active_form].components.splice(text.component_index, 1); //mm.design_mode_pane.type = "drag_drop"; } else if (text.type == "select_component") { mm.selectComponent(text.component_index, true); } }) hideProgressBar() }, methods: { getControlMethod: function(componentDefn,componentDetails) { var mm = this var methodId = componentDefn.id var methodFn = componentDefn.fn return async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { var me = componentDetails var fnDetails = null if (isValidObject(methodFn)) { var thecode = `(async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { ${methodFn} })` fnDetails = eval(thecode) } else { var controlDetails = globalControl[componentDetails.name] fnDetails = controlDetails[methodId] } var retv = await fnDetails(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) if (isValidObject(retv) && isValidObject(retv.failed)) { throw retv.failed } if (isValidObject(retv) && isValidObject(retv.value)) { return retv.value } return retv } } , getFormMethod: function(formName, formprop) { var mm = this return async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { var formDetails = mm.model.forms[formName] var thecode = `(async function(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) { ${formprop.fn} })` fnDetails = eval(thecode) var retv = await fnDetails(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) if (isValidObject(retv) && isValidObject(retv.failed)) { throw retv.failed } return retv.value } } , deleteCursor: function() { document.getElementById(this.vb_grid_element_id).style.cursor = "crosshair" document.getElementById("grid_container").style.cursor = "default" if (this.oldCursor) { this.cursorSource.style.cursor = this.oldCursor this.oldCursor = null this.cursorSource = null this.newCursor = null } } , switchCursor: function(event, oldCursor, newCursor) { var mm = this mm.cursorSource = event.target mm.cursorSource.style.cursor = newCursor mm.newCursor = newCursor mm.oldCursor = oldCursor document.getElementById(mm.vb_grid_element_id).style.cursor = newCursor document.getElementById("grid_container").style.cursor = newCursor } , maintainCursor: function() { var mm = this } , clickOnMainGrid: function(event) { if (this.design_mode) { event.stopPropagation(); if (this.highlighted_control) { var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var rrr = event.target.getBoundingClientRect() var offsetX = (event.clientX - rrr.left ) var offsetY = (event.clientY - rrr.top ) var parentId = null var parentName = null var parentOffsetX = 0 var parentOffsetY = 0 var newItem2 = new Object() var data = { type: "add_component", text: this.highlighted_control, offsetX: offsetX, offsetY: offsetY } var parentContainer = this.getContainerForPoint( offsetX, offsetY ) if (parentContainer) { parentOffsetX = parentContainer.x parentOffsetY = parentContainer.y parentId = parentContainer.base_component_id parentName = parentContainer.name } this.addComponent( offsetX, offsetY, data, parentId, parentName, parentOffsetX, parentOffsetY, []) this.highlighted_control = null } else { this.selectForm(this.model.active_form, true); } } }, getContainerForPoint: function(leftX,topY) { var ccc = this.model.forms[this.model.active_form].components for (var ytr = 0;ytr < ccc.length;ytr++){ var baseId = ccc[ytr].base_component_id var controlNmae = ccc[ytr].name var x1 = ccc[ytr].leftX var x2 = ccc[ytr].leftX + ccc[ytr].width var y1 = ccc[ytr].topY var y2 = ccc[ytr].topY + ccc[ytr].height var isContainer = ccc[ytr].is_container if (isContainer && (x1 <= leftX) && (leftX <= x2) && (y1 <= topY) && (topY <= y2)) { return { x: x1, y: y1, base_component_id: ccc[ytr].base_component_id, name: ccc[ytr].name } } } return null } , addComponent: async function(leftX,topY,data, parentId, parentName, parentOffsetX, parentOffsetY,defProps) { var mm = this //alert(JSON.stringify(data,null,2)) var newItem = new Object() var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() //alert(parentId +": = (" + parentOffsetX + "," + parentOffsetY + ")") newItem.leftX = Math.floor(leftX) newItem.topY = Math.floor(topY) if (newItem.leftX < 0) { newItem.leftX = 0 } if (newItem.topY < 0) { newItem.topY = 0 } //alert(`(${newItem.leftX},${newItem.topY})`) if (parentId) { //alert(`${baseId}:(${x1},${y1}) - (${x2},${y2})`) newItem.parent = parentName } newItem.name = data.text + "_" + this.model.next_component_id++ newItem.base_component_id = data.text this.refresh++ if (!component_loaded[newItem.base_component_id]) { await loadV2([newItem.base_component_id]) this.component_usage[newItem.base_component_id] = true } var compEvaled1 = component_cache[newItem.base_component_id] if (isValidObject(compEvaled1)) { var compEvaled = compEvaled1.properties if (isValidObject(compEvaled)) { for (var cpp = 0 ; cpp < compEvaled.length; cpp ++){ var prop = compEvaled[cpp].id if (!isValidObject(newItem[prop])){ if (compEvaled[cpp].default) { newItem[prop] = JSON.parse(JSON.stringify(compEvaled[cpp].default)) } else { newItem[prop] = "" } } } } } if (!isValidObject(newItem.width)) { newItem.width = 100 } if (!isValidObject(newItem.height)) { newItem.height = 100 } if ((newItem.leftX + newItem.width) > this.model.forms[this.model.active_form].width) { newItem.leftX = Math.floor(this.model.forms[this.model.active_form].width - newItem.width) } if ((newItem.topY + newItem.height) > this.model.forms[this.model.active_form].height) { newItem.topY = Math.floor(this.model.forms[this.model.active_form].height - newItem.height) } if (isValidObject( defProps )) { var oo = Object.keys(defProps) for ( var ee = 0 ; ee < oo.length ; ee++ ) { var propName = oo[ee] var propValue = defProps[propName] newItem[propName] = propValue } } this.model.forms[this.model.active_form].components.push(newItem) this.model.active_component_index = this.model.forms[this.model.active_form].components.length - 1 setTimeout(function() { mm.selectComponent(mm.model.active_component_index, true) mm.refresh ++ },100) var compCode = component_cache[newItem.base_component_id].code var childrenCode = saveHelper.getValueOfCodeString(compCode, "children",")//children") if (isValidObject(childrenCode)) { for ( var ee = 0 ; ee < childrenCode.length ; ee++ ) { //alert(JSON.stringify(childrenCode[ee],null,2)) var childBaseId = childrenCode[ee].base_component_id var childDefProps = childrenCode[ee].properties await this.addComponent( 0 , 0 , {text: childBaseId} , newItem.base_component_id , newItem.name , 0 , 0 , childDefProps ) } } } , copyControl: function(controlDetails , props , genNewName) { var mm = this var xx = JSON.parse(JSON.stringify(controlDetails)) var yy = Object.assign(xx , props) if ( isValidObject(genNewName) ) { yy.name = "random_name" } return yy } , addControl: function(controlDetails) { var mm = this mm.model.forms.Form_1.components.push( controlDetails ) } , refreshControlIndexes: function() { if (this.model.active_component_detail_name) { var ccc = mm.model.forms[this.model.active_form].components for (var ytr = 0;ytr < ccc.length;ytr++) { if (this.model.active_component_detail_name == ccc[ytr].name) { this.model.active_component_detail_name = ytr break } } } else { this.model.active_component_detail_name = null } } , hasMoreDetailsUi: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++) { if (component.parent == ccc[ytr].name) { if (ccc[ytr].hide_children) { return false } break } } } if (component.has_details_ui) { return true } return false } , isVisible: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (!component) { return false } if (component.hidden) { return false } if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++) { if (ccc[ytr]) { if (component.parent == ccc[ytr].name) { if (ccc[ytr].hide_children) { return false } break } } } } return true } , getLeft: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (!component) { return 0 } var left = component.leftX if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++){ if (component.parent == ccc[ytr].name) { left = left + ccc[ytr].leftX break } } } return left } , getTop: function(formName, componentIndex) { var mm = this var component = mm.model.forms[formName].components[componentIndex] if (!component) { return 0 } var top = component.topY if (isValidObject(component.parent)) { var ccc = mm.model.forms[formName].components for (var ytr = 0;ytr < ccc.length;ytr++){ if (component.parent == ccc[ytr].name) { top = top + ccc[ytr].topY break } } } return top } , getChildren: function( itemName ) { var mm = this var ccc = mm.model.forms[mm.model.active_form].components var chh = [] for (var ytr = 0;ytr < ccc.length;ytr++){ if (ccc[ytr].parent == itemName) { ccc[ytr].index_in_parent_array = ytr chh.push(ccc[ytr]) } } return chh } , previewUpload: function(property) { var mm = this; var file = document.getElementById('image_file').files[0]; var reader = new FileReader(); reader.addEventListener("load", function () { mm.model.forms[mm.model.active_form].components[mm.model.active_component_index][property.id] = reader.result mm.refresh ++ }, false); if (file) { reader.readAsDataURL(file); } } , showHelp: async function(aa) { var mm = this if (this.ui_code_editor) { if (mm.ui_code_editor.completer) { mm.ui_code_editor.completer.detach() } mm.ui_code_editor.destroy() mm.ui_code_editor = null // ------------------ HACK CITY! ------------------------- // we need this line as otherwise the ace editor isnt always destroyed // properly (related to deletion of the Ace editor parent nodes in Vue) mm.design_mode_pane.type = null // ------------------------------------------------------- } setTimeout(function(){ mm.model.active_component_detail_name = null mm.model.active_component_detail_index = null mm.design_mode_pane.type = "help" mm.design_mode_pane.help = aa.help mm.refresh++ },200) } , // ----------------------------------------------------- // editAsCode // // This is called when the "..." button is pressed for // a property in the property inspector // // This can show code for the app, a form, and for // controls // // ----------------------------------------------------- editAsCode: async function(aa) { // // if the code editor is already open then close it // var mm = this if (mm.ui_code_editor) { if (mm.ui_code_editor.completer) { mm.ui_code_editor.completer.detach() } mm.ui_code_editor.destroy() mm.ui_code_editor = null } // // Set up the new code editor // setTimeout(function(){ mm.design_mode_pane.type = "event_editor" mm.design_mode_pane.app_selected = aa.app_selected mm.design_mode_pane.active_form = aa.active_form mm.design_mode_pane.active_component_index = aa.active_component_index mm.design_mode_pane.property_id = aa.property_id setTimeout(function(){ if (document.getElementById('ui_code_editor') && (mm.ui_code_editor == null)) { // //set up the ace editor for the timeline view // ace.config.set('basePath', '/'); mm.ui_code_editor = ace.edit( "ui_code_editor", { selectionStyle: "text", mode: "ace/mode/javascript" }) // //Hack city! Need a delay when setting theme or view is corrupted // setTimeout(function(){ mm.ui_code_editor.setTheme("ace/theme/sqlserver"); },100) // // Stylize the code editor // document.getElementById("ui_code_editor").style["font-size"] = "16px" document.getElementById("ui_code_editor").style.width = "100%" document.getElementById("ui_code_editor").style.border = "0px solid #2C2828" document.getElementById("ui_code_editor").style.height = "55vh" // // Get the code and store it in "ccode" // // The code is obtained from the VueJS model, depending on whether // it is a control, a form, or application code // var ccode = "" // application code (THIS MUST BE FIST IN THE IF STATEMENT) if (mm.model.app_selected) { ccode = mm.model[aa.property_id] // form code } else if ((mm.model.active_component_index == null) && (mm.model.active_form != null)) { ccode = mm.model.forms[mm.model.active_form][aa.property_id] // component code } else if ((mm.model.active_component_index != null) && (mm.model.active_form != null)) { ccode = mm.model.forms[mm.model.active_form].components[mm.model.active_component_index][aa.property_id] } if (!isValidObject(ccode)) { ccode = "" } mm.ui_code_editor.getSession().setValue(ccode); mm.ui_code_editor.getSession().setUseWorker(false); mm.ui_code_editor.on("change", function(e) { var newC = mm.ui_code_editor.getValue() if (aa.app_selected) { mm.model[aa.property_id] = newC } else if ((mm.model.active_component_index == null) && (mm.model.active_form != null)) { mm.model.forms[mm.model.active_form][aa.property_id] = newC } else if ((mm.model.active_component_index != null) && (mm.model.active_form != null)) { mm.model.forms[mm.model.active_form].components[mm.model.active_component_index][aa.property_id] = newC } }) mm.updateAllFormCaches() mm.setupCodeAutocompletions() mm.ui_code_editor.focus(); } },100) },100) mm.setupCodeEditorSelectors(aa.property_id) } , // ----------------------------------------------------- // setupCodeAutocompletions // // This is called when editing event code to autocomplete // form names, control names, and methods // // // // ----------------------------------------------------- setupCodeAutocompletions: function() { var mm = this var langTools = ace.require("ace/ext/language_tools"); // // Clear any default autocompleters that have been set // langTools.setCompleters([]); // // Create the autocompleter // var autocompleterFunction = { identifierRegexps: [/[a-zA-Z_0-9.]/] , getCompletions: function(editor, session, pos, prefix, callback) { console.log("Called autocompleterFunction: " + pos + " : " + prefix) // // If no text entered then do nothing // if (prefix.length === 0) { callback(null, []); return } // // Get the first part of the text to autocomplete // var firstObjectToAutocomplete = null if (prefix.indexOf(".") != -1) { firstObjectToAutocomplete = prefix.substring(0,prefix.indexOf(".")) console.log("firstObjectToAutocomplete: " + firstObjectToAutocomplete) } var wordList = [] // // Create the list of initial objects to complete: // app, forms, controls // if (firstObjectToAutocomplete == null) { wordList.push( {"word": "app", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "Main application" }) wordList.push( {"word": "forms", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "List of forms" }) if (mm.design_mode_pane.app_selected) { wordList.push( {"word": "me", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current app" }) } else if (mm.design_mode_pane.active_component_index == null) { wordList.push( {"word": "me", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current form" }) } else { wordList.push( {"word": "me", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current control" }) wordList.push( {"word": "myForm", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The current form" }) } wordList.push( {"word": "parent", "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "The parent/container control of this" }) var ccc = mm.model.forms[mm.model.active_form].components for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { var component = ccc[ytr] wordList.push( {"word": component.name, "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "Control" }) } ccc = Object.keys(mm.model.forms) for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { wordList.push( {"word": ccc[ytr], "freq": 24, "score": 300, "flags": "bc", "syllables":"1", meta: "Form" }) } // // If we have ented an object and pressed "." (period) // then we need to add the method that comes after the // period, eg: // // my_label.set| // .setText() // .setWidth() <- choose one // .setHeight() // } else { // // Find out what the left hand side of the "." represents. Is // it a component, a form, or the app? // var componentId = null var formName = null var isApp = false if (firstObjectToAutocomplete == "me") { if (mm.design_mode_pane.app_selected) { } else if (isValidObject(mm.design_mode_pane.active_component_index)) { componentId = mm.model.forms[mm.model.active_form].components[ mm.design_mode_pane.active_component_index ].base_component_id } else if (isValidObject(mm.design_mode_pane.active_form)) { formName = mm.model.active_form } } else if (firstObjectToAutocomplete == "myForm") { formName = mm.model.active_form } else if (firstObjectToAutocomplete == "parent") { if (mm.design_mode_pane.app_selected) { } else if (isValidObject(mm.design_mode_pane.active_component_index)) { var parentId = mm.model.forms[mm.model.active_form].components[ mm.design_mode_pane.active_component_index ].parent if (isValidObject(parentId)) { componentId = mm.form_runtime_info[mm.model.active_form].component_lookup_by_name[parentId].base_component_id } } else if (isValidObject(mm.design_mode_pane.active_form)) { } } else if (firstObjectToAutocomplete == "app") { isApp = true } else { // // see if the word is a component // var comps = mm.model.forms[mm.model.active_form].components for (var rt=0; rt < comps.length; rt++) { if (comps[rt].name == firstObjectToAutocomplete) { componentId = comps[rt].base_component_id } } // // see if the word is a form // var formNames = Object.keys(mm.model.forms) for (var rt=0; rt < formNames.length; rt++) { var formName1 = formNames[rt] if (formName1 == firstObjectToAutocomplete) { formName = formName1 } } } // // if a component was entered // if (componentId) { var controlProperties = mm.getControlProperties(componentId) for (var fg=0;fg < controlProperties.length;fg++){ var comm = controlProperties[fg] var propName = firstObjectToAutocomplete + "." + comm.id var meta = "Property" if (isValidObject(comm.snippet)) { propName = firstObjectToAutocomplete + "." + comm.snippet } if (isValidObject(comm.pre_snippet)) { propName = comm.pre_snippet + propName } if (comm.type == "Action") { meta = "Method" } wordList.push({ "word": propName , "freq": 24, "score": 300, "flags": "bc", "syllables": "1", "meta": meta }) } // // if a form was entered // } else if (formName) { var formProps = mm.getFormProperties(formName) for (var formPropIndex = 0 ; formPropIndex < formProps.length ; formPropIndex++ ) { var propDetails = formProps[formPropIndex] var propName = firstObjectToAutocomplete + "." + propDetails.id var meta = "Property" if (isValidObject(propDetails.snippet)) { propName = firstObjectToAutocomplete + "." + propDetails.snippet } if (isValidObject(propDetails.pre_snippet)) { propName = propDetails.pre_snippet + propName } if (propDetails.type == "Action") { meta = "Method" } if (propDetails.type == "Event") { meta = "Event" } wordList.push({ "word": propName , "freq": 24, "score": 300, "flags": "bc", "syllables": "1", "meta": meta }) } // // if the main object is the VB app // } else if (isApp) { var appProps = mm.get_default_app_propeties() for (var formPropIndex = 0 ; formPropIndex < appProps.length ; formPropIndex++ ) { var propDetails = appProps[formPropIndex] var propName = firstObjectToAutocomplete + "." + propDetails.id var meta = "Property" if (isValidObject(propDetails.snippet)) { propName = firstObjectToAutocomplete + "." + propDetails.snippet } if (isValidObject(propDetails.snippet)) { propName = propDetails.snippet + propName } if (propDetails.type == "Action") { meta = "Method" } if (propDetails.type == "Event") { meta = "Event" } wordList.push({ "word": propName , "freq": 24, "score": 300, "flags": "bc", "syllables": "1", "meta": meta }) } } } callback(null, wordList.map(function(ea) { return {name: ea.word, value: ea.word, score: ea.score, meta: ea.meta} })); } } langTools.addCompleter(autocompleterFunction); mm.ui_code_editor.commands.addCommand({ name: "showOtherCompletions", bindKey: ".", exec: function(editor) { mm.ui_code_editor.session.insert(mm.ui_code_editor.getCursorPosition(), ".") mm.ui_code_editor.completer.updateCompletions() } }) mm.ui_code_editor.setOptions({ enableBasicAutocompletion: false, enableSnippets: false, enableLiveAutocompletion: true }); } , setupCodeEditorSelectors: function( property_id ) { var mm = this setTimeout( function() { // // Add the selectors using the SelectR library // if (!document.getElementById("select_code_object_parent")) { return; } document.getElementById("select_code_object_parent").innerHTML=' <select id=select_code_object ></select>' if (!document.getElementById("select_code_action_parent")) { return; } document.getElementById("select_code_action_parent").innerHTML=' <select id=select_code_action ></select>' // // initialise vars // var objectListForSelector = [] var methodListForSelector = [] var indexObjectSelector = 0 var indexActionSelector = 0 var selectedCodeObject = null var selectedCodeAction = null // // if we selected the app or a form // if (mm.model.app_selected || (!isValidObject(mm.model.active_component_index))) { if (mm.edited_app_component_id) { objectListForSelector.push( { value: "" + indexObjectSelector, app: mm.edited_app_component_id, form: null, component: null }) } if (mm.model.app_selected) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ var forms = mm.getForms() for ( var ere = 0; ere < forms.length; ere++ ) { var form = forms[ ere ] objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: form.name, component: null } ) if ((!mm.model.app_selected) && (form.name == mm.model.active_form)) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ // // show the sub controls of this form if it is the current form // if ((!mm.model.app_selected) && (form.name == mm.model.active_form)) { var components = mm.getActiveFormComponents() for ( var ere1 = 0; ere1 < components.length; ere1++ ) { var component = components[ ere1 ] objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: mm.model.active_form, component: " - " + component.name, component_type: component.base_component_id, component_index: ere1 } ) if (mm.model.active_component_index == ere1) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ } } } // // if we selected a component // } else if (isValidObject(mm.model.active_component_index)) { objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: mm.model.active_form, component: null } ) indexObjectSelector++ var components = mm.getActiveFormComponents() for ( var ere = 0; ere < components.length; ere++ ) { var component = components[ ere ] objectListForSelector.push( { value: "" + indexObjectSelector, app: null, form: mm.model.active_form, component: " - " + component.name, component_type: component.base_component_id, component_index: ere } ) if (mm.model.active_component_index == ere) { selectedCodeObject = indexObjectSelector } indexObjectSelector++ } } // // get the list of properties // // // get the app methods // if (mm.model.app_selected) { methodListForSelector.push( { value: "" + indexActionSelector, app: mm.edited_app_component_id, form: mm.model.active_form, component: null, action_id: "app_started_event", action_name: "Called when the app is started", action_type: "Event" } ) selectedCodeAction = indexActionSelector indexActionSelector++ } else if ( isValidObject(mm.model.active_component_index) ) { var ccc = mm.model.forms[mm.model.active_form].components[mm.model.active_component_index] var properties = mm.getComponentProperties( ccc.base_component_id ) for ( var ere = 0; ere < properties.length; ere++ ) { var property = properties[ ere ] if (property.type == "Event") { methodListForSelector.push( { value: "" + indexActionSelector, app: null, form: mm.model.active_form, component: ccc.name, action_id: property.id, action_name: property.name, action_type: property.type, action_index: ere } ) if (property.id == property_id) { selectedCodeAction = indexActionSelector } indexActionSelector++ } } methodListForSelector.push( { value: "" + indexActionSelector, app: null, form: mm.model.active_form, component: ccc.name, action_id: "load", action_name: "Load event", action_type: "Event", action_index: ere }) if ( property_id == "load" ) { selectedCodeAction = indexActionSelector } indexActionSelector++ // get the actions for the forms } else if ( isValidObject(mm.model.active_form) ) { var ccc = mm.model.forms[mm.model.active_form] var properties = mm.getComponentProperties( ccc.base_component_id ) methodListForSelector.push( { value: "" + indexActionSelector, app: null, form: mm.model.active_form, component: ccc.name, action_id: "form_activate", action_name: "Activate Event", action_type: "Event", action_index: ere }) if ( property_id == "form_activate" ) { selectedCodeAction = indexActionSelector } indexActionSelector++ } selectCodeObject = new Selectr( document.getElementById('select_code_object'), { renderOption: mm.myDataRenderFunction, renderSelection: mm.myDataRenderFunction, selectedValue: selectedCodeObject, data: objectListForSelector, customClass: 'my-custom-selectr', searchable: false }); selectCodeAction = new Selectr( document.getElementById('select_code_action'), { renderOption: mm.actionRenderFunction, renderSelection: mm.actionRenderFunction, selectedValue: selectedCodeAction, data: methodListForSelector, customClass: 'my-custom-selectr', searchable: false }); document.getElementsByClassName("selectr-selected")[0].style.padding = "1px" document.getElementsByClassName("selectr-selected")[0].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[0].style["border-left"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[1].style.padding = "1px" document.getElementsByClassName("selectr-selected")[1].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[1].style["border-left"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[2].style.padding = "1px" document.getElementsByClassName("selectr-selected")[2].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[2].style["border-left"] = "2px solid gray" selectCodeObject.on('selectr.select', function(option) { var dd = objectListForSelector[option.idx] if (dd.component) { mm.selectComponent(dd.component_index) mm.editAsCode({ app_selected: false, active_form: mm.model.active_form, active_component_index: mm.model.active_component_index, property_id: "load" }) } else if (dd.form) { mm.selectForm(dd.form) mm.editAsCode({ app_selected: false, active_form: dd.form, active_component_index: null, property_id: "form_activate" }) } else if (dd.app) { mm.select_app() mm.editAsCode({ app_selected: true, active_form: mm.model.active_form, active_component_index: null, property_id: "app_started_event" }) } }); selectCodeAction.on('selectr.select', function(option) { var dd = methodListForSelector[option.idx] mm.editAsCode({ app_selected: mm.app_selected, active_form: mm.model.active_form, active_component_index: mm.model.active_component_index, property_id: dd.action_id }) }); },100) } , getActiveFormComponents: function() { return this.model.forms[this.model.active_form].components }, updateAllFormCaches: function() { var llf = Object.keys(this.model.forms) for (var ii = 0; ii < llf.length ; ii ++) { var formqq = this.model.forms[llf[ii]] if (formqq != null) { this.updateFormCache(formqq.name) } } }, gotoDragDropEditor: function() { this.design_mode_pane.type = "drag_drop"; if (this.ui_code_editor) { if (this.ui_code_editor.completer) { this.ui_code_editor.completer.detach() } this.ui_code_editor.destroy() this.ui_code_editor = null } this.model.active_component_detail_name = null this.model.active_component_detail_index = null } , updateFormCache: function(formName) { var form = this.model.forms[formName] var components = form.components if (!isValidObject(this.form_runtime_info[formName])) { this.form_runtime_info[formName] = new Object() } this.form_runtime_info[formName].component_lookup_by_name = {} for (var gjh = 0; gjh < components.length; gjh ++) { var cc = components[gjh] if (isValidObject(cc)) { this.form_runtime_info[formName].component_lookup_by_name[cc.name] = cc } } }, chooseRight: function(ff) { this.right_mode = ff }, //------------------------------------------------------------------- getForms: function() { //------------------------------------------------------------------- var forms = [] var llf = Object.keys(this.model.forms) for (var ii = 0; ii < llf.length ; ii ++) { var form = this.model.forms[llf[ii]] if (form != null) { forms.push(form) } } return forms }, //------------------------------------------------------------------- // setVBEditorProperty // // event, property //------------------------------------------------------------------- getFormProperties: function( formName ) { var props = [] props.push({ id: "name", name: "Name", type: "String" }) props.push({ id: "width", name: "Width", type: "Number" }) props.push({ id: "height", name: "Height", type: "Number" }) props.push({ id: "form_activate", name: "Activate Event", type: "Event" }) props.push({ id: "add_control", name: "Add Control", type: "Action" , snippet: `add_control({name: "name_of_new_control"})`, fn: `debugger mm.addControl( arg1 ) return {} ` }) return props } , //------------------------------------------------------------------- setVBEditorProperty: function(event, property) { //------------------------------------------------------------------- var mm = this var val = event.target.value var type = null if (this.model.active_component_index != null) { type = "component" } else if ((this.model.active_component_index == null) && (this.model.active_form != null) && (!this.model.app_selected)) { type = "form" } else if (this.model.app_selected) { type = "app" } if (type == 'component') { this.model.forms[this.model.active_form].components[this.model.active_component_index][property.id] = val //this.generateCodeFromModel( ) this.refresh ++ } else if (type == 'form') { if (property.id == "name" ) { this.properties = [] var oldval = this.model.active_form //alert("Rename form " + oldval + " to " + val) this.model.forms[val] = this.model.forms[oldval] this.model.forms[val]["name"] = val this.form_runtime_info[val] = this.form_runtime_info[oldval] if (this.model.default_form == oldval) { this.model.default_form = val } //this.model.active_form = val mm.form_runtime_info[oldval] = null mm.model.forms[oldval] = null //alert(this.model.active_form) //alj(this.form_runtime_info[val]) //mm.refresh ++ //mm.updateAllFormCaches() mm.selectForm(val) } else { this.model.forms[this.model.active_form][property.id] = val } } else if (type == 'app') { this.model[property.id] = val } }, //------------------------------------------------------------------- getVBEditorProperty: function(property) { //------------------------------------------------------------------- var val = "" var type if (this.model.active_component_index != null) { type = "component" } else if ((this.model.active_component_index == null) && (this.model.active_form != null) && (!this.model.app_selected)) { type = "form" } else if (this.model.app_selected) { type = "app" } if (type == 'component') { val = this.model.forms[this.model.active_form].components[this.model.active_component_index][property.id] } else if (type == 'form') { val = this.model.forms[this.model.active_form][property.id] } else if (type == 'app') { val = this.model[property.id] } return val }, //------------------------------------------------------------------- addProperty: function() { //------------------------------------------------------------------- var mm = this mm.add_property = true mm.new_property_id = "" mm.new_property_name = "" } , //------------------------------------------------------------------- addPropertySave: function() { //------------------------------------------------------------------- var mm = this if ((mm.new_property_name.length == 0) || (mm.new_property_id.length == 0)) { alert("You must enter a property name and ID") return; } mm.add_property = false mm.model.app_properties.push({ id: mm.new_property_id, name: mm.new_property_name, type: "String" }) mm.generateCodeFromModel( ) setTimeout(function() { mm.refresh ++ mm.select_app() } ,100) } , //------------------------------------------------------------------- addPropertyCancel: function() { //------------------------------------------------------------------- var mm = this mm.add_property = false } , //------------------------------------------------------------------- getComponentProperties: function(componentName) { //------------------------------------------------------------------- var compEvaled1 = component_cache[componentName] if (isValidObject(compEvaled1)) { var compEvaled = compEvaled1.properties if (isValidObject(compEvaled)) { return compEvaled } } return [] } , //------------------------------------------------------------------- selectForm: function(formId, showProps) { //------------------------------------------------------------------- var mm = this mm.model.active_component_index = null mm.model.app_selected = false mm.properties = mm.getFormProperties(formId) mm.model.active_form = formId mm.refresh ++ if ( mm.model.forms[ formId ].form_activate && (!mm.design_mode)) { if (!isValidObject(this.args)) { mm.args = mm.model } var args = mm.args var app = mm.model var crt = mm.model.forms[formId].form_activate var formEvent = { type: "form_event", form_name: formId, code: crt } mm.processControlEvent(formEvent) } mm.updatePropertySelector() if (isValidObject(showProps) && showProps) { this.selected_pane = "properties"; this.chooseRight("properties"); } mm.refresh ++ }, //------------------------------------------------------------------- // processControlEvent // // This is used to run user written event code //------------------------------------------------------------------- processControlEvent: async function( eventMessage ) { var mm = this if ((!mm.design_mode) && (mm.model)) { this.updateAllFormCaches() // // set up property access for all forms // var formHandler = { get: function(target,name){ var formName = target.name if (mm.model.forms[formName][name]) { return mm.model.forms[formName][name] } if (mm.form_runtime_info[formName].component_lookup_by_name[name]) { return mm.form_runtime_info[formName].component_lookup_by_name[name] } return "Not found" } } var formEval = "" var allForms = this.getForms(); for (var fi =0; fi < allForms.length ; fi ++) { var aForm = allForms[fi] formEval += ("var " + aForm.name + " = new Proxy({name: '" + aForm.name + "'}, formHandler);") } eval(formEval) // // set up property access for all controls on this form // var allC = this.model.forms[this.model.active_form].components var cacc ="" for (var xi =0; xi< allC.length ; xi ++) { var comp = allC[xi] cacc += ( "var " + comp.name + " = mm.form_runtime_info['" + this.model.active_form + "'].component_lookup_by_name['" + comp.name + "'];") } eval(cacc) if (eventMessage.type == "subcomponent_event") { var fcc = `(async function(){ ${eventMessage.code} })` var thisControl = this.form_runtime_info[ this.model.active_form ].component_lookup_by_name[ eventMessage.control_name ] if (isValidObject(thisControl)) { if (isValidObject(thisControl.parent)) { var cacc ="" cacc += ( "var parent = mm.form_runtime_info['" + this.model.active_form + "'].component_lookup_by_name['" + thisControl.parent + "'];") eval(cacc) } var meCode ="" meCode += ( "var me = mm.form_runtime_info['" + this.model.active_form + "'].component_lookup_by_name['" + thisControl.name + "'];") eval(meCode) var appCode ="" appCode += ( "var app = mm.model;") eval(appCode) var meCode ="" meCode += ( "var myForm = mm.model.forms['" + this.model.active_form + "'];") eval(meCode) var debugFcc = getDebugCode(mm.model.active_form +"_"+eventMessage.control_name+"_"+eventMessage.sub_type,fcc,{skipFirstAndLastLine: true}) var efcc = eval(debugFcc) try { await efcc() } catch( err ) { alert(JSON.stringify(err,null,2)) } } // // form events // } else if (eventMessage.type == "form_event") { var fcc = `(async function(){ ${eventMessage.code} })` var meCode ="" meCode += ( "var me = mm.model.forms['" + this.model.active_form + "'];") eval(meCode) var appCode ="" appCode += ( "var app = mm.model;") eval(appCode) var debugFcc = getDebugCode(this.model.active_form ,fcc,{skipFirstAndLastLine: true}) var efcc = eval(debugFcc) try { await efcc() } catch( err ) { alert(JSON.stringify(err,null,2)) } } mm.refresh ++ mm.$forceUpdate(); } }, //------------------------------------------------------------------- allowDropEditor: function(ev) { //------------------------------------------------------------------- ev.preventDefault(); }, //------------------------------------------------------------------- dropEditor: async function (ev) { //------------------------------------------------------------------- ev.preventDefault(); var mm = this var data2 = ev.dataTransfer.getData("message"); var data = eval("(" + data2 + ")") var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0) ; var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); if (data.type == "resize_form_bottom_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newWidth = (ev.clientX - 8) - rrr.left ; var newHeight = (ev.clientY - 8) - rrr.top ; this.model.forms[this.model.active_form].width = Math.floor(newWidth) this.model.forms[this.model.active_form].height = Math.floor(newHeight) this.model.active_component_index = null mm.refresh ++ } else if (data.type == "resize_form_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newWidth = (ev.clientX - 8) - rrr.left ; this.model.forms[this.model.active_form].width = Math.floor(newWidth) this.model.active_component_index = null mm.refresh ++ } else if (data.type == "resize_form_bottom") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newHeight = (ev.clientY - 8) - rrr.top ; this.model.forms[this.model.active_form].height = Math.floor(newHeight) this.model.active_component_index = null mm.refresh ++ } }, setInfo: function(text) { this.$root.$emit('message', { type: "set_info_text", text: text }) }, //------------------------------------------------------------------- allowDrop: function(ev) { //------------------------------------------------------------------- //ev.preventDefault(); }, //------------------------------------------------------------------- drag: function(ev,message) { //------------------------------------------------------------------- var mm = this var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var rrr = ev.target.getBoundingClientRect() message.offsetX = (ev.clientX - rrr.left ) message.offsetY = (ev.clientY - rrr.top ) if (!isValidObject(ev.dataTransfer)) { return } ev.dataTransfer.setData("message", JSON.stringify(message,null,2)); }, showComponentDetailedDesignUi: async function(index) { var mm = this mm.design_mode_pane.type = "control_details_editor" this.model.active_component_detail_index = index; this.model.active_component_detail_name = this.model.forms[this.model.active_form].components[index].name; setTimeout(function() { mm.refresh ++ mm.$forceUpdate(); },400) }, deleteComponent: async function(index) { var mm = this var thisComponentName = this.model.forms[this.model.active_form].components[index].name this.model.forms[this.model.active_form].components.splice(index, 1); var ccc = mm.model.forms[mm.model.active_form].components for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { var component = ccc[ytr] if (component.parent == thisComponentName) { this.model.forms[this.model.active_form].components.splice(ytr, 1); } } this.refreshControlIndexes() this.selectForm(this.model.active_form) setTimeout(function() { mm.refresh ++ mm.$forceUpdate(); },400) }, childDeleteComponent: function(index) { this.$root.$emit('message', { type: "delete_component", component_index: index }) } , childSelectComponent: function(index) { this.$root.$emit('message', { type: "select_component", component_index: index }) } , //------------------------------------------------------------------- drop: async function (ev) { // // This is called when something happens on the main drag and drop // grid // //------------------------------------------------------------------- ev.preventDefault(); var mm = this if (this.oldCursor) { this.cursorSource.style.cursor = this.oldCursor this.oldCursor = null this.cursorSource = null } var data2 = ev.dataTransfer.getData("message"); var data = eval("(" + data2 + ")") var newItem2 = new Object() var rrr2 = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() newItem2.leftX = (ev.clientX - rrr2.left) - data.offsetX; newItem2.topY = (ev.clientY - rrr2.top) - data.offsetY; var parentId = null var parentName = null var parentOffsetX = 0 var parentOffsetY = 0 var parentOffsetWidth = 0 var parentOffsetHeight = 0 var parentContainer = this.getContainerForPoint( newItem2.leftX, newItem2.topY ) if (parentContainer) { parentOffsetX = parentContainer.x parentOffsetY = parentContainer.y parentId = parentContainer.base_component_id parentName = parentContainer.name } if (data.type == "add_component") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var xx = ((ev.clientX - rrr.left) - data.offsetX) - parentOffsetX - 10; var yy = ((ev.clientY - rrr.top) - data.offsetY) - parentOffsetY - 10; await mm.addComponent(xx,yy,data, parentId, parentName, parentOffsetX, parentOffsetY,[]) this.highlighted_control = null } else if (data.type == "move_component") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newLeftX = (ev.clientX - rrr.left) - data.offsetX; var newTopY = (ev.clientY - rrr.top) - data.offsetY; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newLeftX < 0) { newLeftX = 0 } if (newTopY < 0) { newTopY = 0 } if ((newLeftX + this.model.forms[this.model.active_form].components[data.index].width) > this.model.forms[this.model.active_form].width) { newLeftX = this.model.forms[this.model.active_form].width - this.model.forms[this.model.active_form].components[data.index].width } if ((newTopY + this.model.forms[this.model.active_form].components[data.index].height) > this.model.forms[this.model.active_form].height) { newTopY = this.model.forms[this.model.active_form].height - this.model.forms[this.model.active_form].components[data.index].height } this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newLeftX) this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newTopY) this.model.active_component_index = data.index } else if (data.type == "resize_top_left") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var oldX = this.model.forms[this.model.active_form].components[data.index].leftX var oldY = this.model.forms[this.model.active_form].components[data.index].topY var newLeftX = ev.clientX + 2 - rrr.left ; var newTopY = ev.clientY + 2 - rrr.top ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newLeftX < 0) { newLeftX = 0 } if (newTopY < 0) { newTopY = 0 } this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newLeftX) this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newTopY) var diffX = this.model.forms[this.model.active_form].components[data.index].leftX - oldX var diffY = this.model.forms[this.model.active_form].components[data.index].topY - oldY this.model.forms[this.model.active_form].components[data.index].width -= Math.floor(diffX) this.model.forms[this.model.active_form].components[data.index].height -= Math.floor(diffY) this.model.active_component_index = data.index } else if (data.type == "resize_left") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var oldX = this.model.forms[this.model.active_form].components[data.index].leftX var newLeftX = ev.clientX + 2 - rrr.left ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newLeftX < 0) { newLeftX = 0 } this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newLeftX) var diffX = this.model.forms[this.model.active_form].components[data.index].leftX - oldX this.model.forms[this.model.active_form].components[data.index].width -= Math.floor(diffX) this.model.active_component_index = data.index } else if (data.type == "resize_top") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var oldY = this.model.forms[this.model.active_form].components[data.index].topY var newTopY = ev.clientY + 2 - rrr.top ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newLeftX = newLeftX - parentOffsetX newTopY = newTopY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } if (newTopY < 0) { newTopY = 0 } this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newTopY) var diffY = this.model.forms[this.model.active_form].components[data.index].topY - oldY this.model.forms[this.model.active_form].components[data.index].height -= Math.floor(diffY) this.model.active_component_index = data.index } else if (data.type == "resize_top_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX - 10 - rrr.left ; var newY = ev.clientY + 2 - rrr.top; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newX - this.model.forms[this.model.active_form].components[data.index].leftX) var newHeight = (this.model.forms[this.model.active_form].components[data.index].topY + this.model.forms[this.model.active_form].components[data.index].height) - newY this.model.forms[this.model.active_form].components[data.index].topY = Math.floor(newY) this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } else if (data.type == "resize_bottom_left") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX + 8 - rrr.left ; var newY = ev.clientY - 12 - rrr.top ; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newWidth = (this.model.forms[this.model.active_form].components[data.index].leftX + this.model.forms[this.model.active_form].components[data.index].width) - newX var newHeight = newY - this.model.forms[this.model.active_form].components[data.index].topY this.model.forms[this.model.active_form].components[data.index].leftX = Math.floor(newX) this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newWidth) this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } else if (data.type == "resize_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX - rrr.left - 10; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newWidth = newX - this.model.forms[this.model.active_form].components[data.index].leftX this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newWidth) this.model.active_component_index = data.index } else if (data.type == "resize_bottom_right") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newX = ev.clientX - rrr.left - 10; var newY = ev.clientY - rrr.top - 12; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newX = newX - parentOffsetX newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newWidth = newX - this.model.forms[this.model.active_form].components[data.index].leftX this.model.forms[this.model.active_form].components[data.index].width = Math.floor(newWidth) var newHeight = newY - this.model.forms[this.model.active_form].components[data.index].topY this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } else if (data.type == "resize_bottom") { var rrr = document.getElementById(this.vb_grid_element_id).getBoundingClientRect() var newY = ev.clientY - rrr.top - 12; if (!this.model.forms[this.model.active_form].components[data.index].is_container) { if (parentId) { this.model.forms[this.model.active_form].components[data.index].parent = parentName newY = newY - parentOffsetY } else { this.model.forms[this.model.active_form].components[data.index].parent = null } } var newHeight = newY - this.model.forms[this.model.active_form].components[data.index].topY this.model.forms[this.model.active_form].components[data.index].height = Math.floor(newHeight) this.model.active_component_index = data.index } this.selectComponent(this.model.active_component_index) this.refresh ++ }, //------------------------------------------------------------------- get_default_app_propeties: function() { var mm = this return [ { id: "id", name: "ID", type: "String" , readonly: true, get_fn: function() { return mm.edited_app_component_id } } , { id: "default_form", name: "Load form on startup", type: "String"} , { id: "app_started_event", name: "Called when the app is started", type: "Event"} ] } , //------------------------------------------------------------------- // select_app // // //------------------------------------------------------------------- select_app: function() { var mm = this this.model.active_component_index = null this.model.app_selected = true this.active_property_index = null this.properties = mm.get_default_app_propeties() if (this.model.app_properties) { this.properties = this.properties.concat(this.model.app_properties) } this.updatePropertySelector() this.refresh ++ } , //------------------------------------------------------------------- // myDataRenderFunction // // //------------------------------------------------------------------- myDataRenderFunction: function(data) { if (!isValidObject(data)) { return "<div></div>" } var center = "" if (data.app) { center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + (data.app?data.app:data.form) + "</b> " } else if (data.component) { center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + data.component + "</b> " + data.component_type } else if (data.form) { center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + data.form + "</b> " } var template = "<div style='font-weight:normal;color:black;overflow:hidden ;text-overflow: ellipsis;border-radius: 1px;margin: 0px;padding:0px;border:0px;font-family:verdana,helvetica;font-size: 13px;'>" + center + "</div>"; return template; }, actionRenderFunction: function(data) { if (!isValidObject(data)) { return "<div></div>" } var center = "" center = "<b style='font-family:verdana,helvetica;font-size: 13px;'>" + data.action_id + "</b> " + data.action_name var template = "<div style='font-weight:normal;color:black;overflow:hidden ;text-overflow: ellipsis;border-radius: 1px;margin: 0px;padding:0px;border:0px;font-family:verdana,helvetica;font-size: 13px;'>" + center + "</div>"; return template; }, // ------------------------------------------------------------------- // updatePropertySelector // // This updates the property selector on the right of the editor, // and it uses the currently selected object to figure out what // to display // ------------------------------------------------------------------- updatePropertySelector: function() { var mm = this // // if we are not in edit mode then do nothing // if (!designMode){ return } // // If the property selector is not available then do nothing // if (!document.getElementById("property_selector_parent")) { return } // // Set up the property selector // document.getElementById("property_selector_parent").innerHTML=' <select id=property_selector ></select>' var sdata = [] var indexProp = 0 var selectedItem = null if (mm.model.app_selected || (!isValidObject(mm.model.active_component_index))) { if (mm.edited_app_component_id) { sdata.push( { value: "" + indexProp, app: mm.edited_app_component_id, form: null, component: null }) } if (mm.model.app_selected) { selectedItem = indexProp } indexProp++ var forms = mm.getForms() for ( var ere = 0; ere < forms.length; ere++ ) { var form = forms[ ere ] sdata.push( { value: "" + indexProp, app: null, form: form.name, component: null } ) if ((!mm.model.app_selected) && (form.name == mm.model.active_form)) { selectedItem = indexProp } indexProp++ } } else if (isValidObject(mm.model.active_component_index)) { sdata.push( { value: "" + indexProp, app: null, form: mm.model.active_form, component: null } ) indexProp++ var components = mm.getActiveFormComponents() for ( var ere = 0; ere < components.length; ere++ ) { var component = components[ ere ] sdata.push( { value: "" + indexProp, app: null, form: mm.model.active_form, component: component.name, component_type: component.base_component_id, component_index: ere } ) if (mm.model.active_component_index == ere) { selectedItem = indexProp } indexProp++ } } // // selector for property inspector // selectProp = new Selectr( document.getElementById('property_selector'), { renderOption: mm.myDataRenderFunction, renderSelection: mm.myDataRenderFunction, selectedValue: selectedItem, data: sdata, customClass: 'my-custom-selectr', searchable: false }); document.getElementsByClassName("selectr-selected")[0].style.padding = "1px" document.getElementsByClassName("selectr-selected")[0].style["border-top"] = "2px solid gray" document.getElementsByClassName("selectr-selected")[0].style["border-left"] = "2px solid gray" selectProp.on('selectr.select', function(option) { var dd = sdata[option.idx] if (dd.component) { mm.selectComponent(dd.component_index) } else if (dd.form) { mm.selectForm(dd.form) } else if (dd.app) { mm.select_app() } }); }, existsProp: function(compEvaled,propName) { for (var eee = 0 ;eee < compEvaled.length; eee++) { if (compEvaled[eee].id == propName) { return true } } return false } , //------------------------------------------------------------------- getControlProperties: function(base_component_id) { var properties = [] var compEvaled = this.getComponentProperties(base_component_id) properties.push({ id: "name", name: "Name", type: "String" }) properties.push({ id: "base_component_id", name: "Type", type: "String" , readonly: true }) properties.push({ id: "leftX", name: "X", type: "Number" }) properties.push({ id: "topY", name: "Y", type: "Number" }) if (!this.existsProp(compEvaled,"width")) { properties.push({ id: "width", name: "Width", type: "Number" }) } if (!this.existsProp(compEvaled,"height")) { properties.push({ id: "height", name: "Height", type: "Number" }) } if (!this.existsProp(compEvaled,"load")) { properties.push({ id: "load", name: "Load Event", type: "Event" }) } properties.push({ id: "clone", name: "Clone", type: "Action" , pre_snippet: `await `, snippet: `clone("new_name")`, fn: ` var newObject = JSON.parse(JSON.stringify(me)) newObject.name = arg1 return newObject ` }) //zzz if (this.existsProp(compEvaled,"is_container")) { properties.push({ id: "addChild", name: "Add Child", type: "Action" , pre_snippet: `await `, snippet: `addChild({})`, fn: `debugger mm.addControl( arg1 ) return {} ` }) } //parent. properties = properties.concat(compEvaled) return properties } //------------------------------------------------------------------- , //------------------------------------------------------------------- selectComponent: async function(index, showProps) { //------------------------------------------------------------------- if (!this.design_mode) { return } var mm = this if (index == null) { return } this.active_property_index = null this.model.app_selected = false this.model.active_component_index = index this.properties = this.getControlProperties(this.model.forms[this.model.active_form].components[index].base_component_id) this.updatePropertySelector() if (isValidObject(showProps) && showProps) { this.selected_pane = "properties"; this.chooseRight("properties"); } this.refresh ++ }, //------------------------------------------------------------------- addForm: function() { //------------------------------------------------------------------- var mm = this mm.model.active_component_index = null mm.properties = mm.getFormProperties() mm.model.max_form ++ var newFormName = "form_" + mm.model.max_form mm.model.forms[newFormName] = { name: newFormName, components: [], width: 300, height: 300, add_control: "alert('Add control called')" } mm.model.active_form = newFormName mm.refresh ++ } , //------------------------------------------------------------------- moveUp: function( fieldId ) { //------------------------------------------------------------------- var mm = this var itemD = null for (var tt=0; tt < mm.model.forms[mm.model.active_form].fields.length ; tt++) { var ciurr = mm.model.forms[mm.model.active_form].fields[tt] if (ciurr.id == fieldId) { itemD = ciurr } } if (itemD) { var index = mm.model.forms[mm.model.active_form].fields.indexOf( itemD ); if (index > -1) { mm.model.fields.splice(index, 1); mm.model.fields.splice(index - 1, 0, itemD); } } }, //------------------------------------------------------------------- moveDown: function( fieldId ) { //------------------------------------------------------------------- var mm = this var itemD = null for (var tt=0; tt < mm.model.forms[mm.model.active_form].fields.length ; tt++) { var ciurr = mm.model.forms[mm.model.active_form].fields[tt] if (ciurr.id == fieldId) { itemD = ciurr } } if (itemD) { var index = mm.model.forms[mm.model.active_form].fields.indexOf( itemD ); if (index > -1) { mm.model.fields.splice(index, 1); mm.model.fields.splice(index + 1, 0, itemD); } } }, //------------------------------------------------------------------- deleteField: function( fieldId ) { //------------------------------------------------------------------- var mm = this var itemD = null for (var tt=0; tt < mm.model.forms[mm.model.active_form].fields.length ; tt++) { var ciurr = mm.model.forms[mm.model.active_form].fields[tt] if (ciurr.id == fieldId) { itemD = ciurr } } if (itemD) { var index = mm.model.forms[mm.model.active_form].fields.indexOf( itemD ); if (index > -1) { mm.model.fields.splice(index, 1); } } }, //------------------------------------------------------------------- getText: async function() { //------------------------------------------------------------------- //console.log("2) VB: getText") await this.generateCodeFromModel() return this.text }, //------------------------------------------------------------------- setText: function(textValue) { //------------------------------------------------------------------- //console.log("start setText") var mm = this this.text = textValue var json2 = this.getJsonModelFromCode( textValue ) //console.log("setText: mm.model = json2") mm.edited_app_component_id = saveHelper.getValueOfCodeString(textValue, "base_component_id") mm.model = json2 mm.updatePropertySelector() mm.refresh ++ //console.log("end setText") } , //------------------------------------------------------------------- getJsonModelFromCode: function( codeV ) { //------------------------------------------------------------------- var mm = this mm.edited_app_component_id = saveHelper.getValueOfCodeString(codeV, "base_component_id") var json2 = saveHelper.getValueOfCodeString(codeV,"formEditor",")//formEditor") return json2 } , //------------------------------------------------------------------- generateCodeFromModel: async function( ) { //------------------------------------------------------------------- var mm = this if (this.in_generate_code_from_model) { return } if (!this.design_mode) { return } this.in_generate_code_from_model = true if (online && this.design_mode) { //console.log("start generateCodeFromModel") var startIndex = this.text.indexOf("//** gen_" + "start **//") var endIndex = this.text.indexOf("//** gen_" + "end **//") var sql = "select cast(code as text) as code from system_code where " + " base_component_id = 'vb_editor_component' and code_tag = 'LATEST' " var results = await callApp({ driver_name: "systemFunctions2",method_name: "sql"}, { sql: sql }) var editorCode = results[0].code var stt = "//*** COPY_" + "START ***//" var editorCodeToCopyStart = editorCode.indexOf(stt) + stt.length var editorCodeToCopyEnd = editorCode.indexOf("//*** COPY_" + "END ***//") var editorCodeToCopy = editorCode.substring(editorCodeToCopyStart, editorCodeToCopyEnd) this.text = this.text.substring(0,startIndex) + `//** gen_start **// var mm = null var texti = null var designMode = false var runtimeMode = true Vue.component('${this.edited_app_component_id}', {` + editorCodeToCopy + `, data: function () { return { uid2: null, vb_grid_element_id: null, vb_editor_element_id: null, design_mode: designMode, design_mode_pane: {}, local_app: false, refresh: 0, runtime_mode: runtimeMode, component_usage: new Object(), ui_code_editor: null, form_runtime_info: {}, text: texti, model: ` + JSON.stringify( mm.model, function(key, value) { if (typeof value === 'string') { return value.toString() } return value; }, 2) + `} } })` + this.text.substring(endIndex) var subComponents = saveHelper.getValueOfCodeString(this.text, "sub_components") var subComponentsMap = {} if (subComponents) { this.text = saveHelper.deleteCodeString(this.text, "sub_components") } else { subComponents = [] } for (var tt = 0; tt < subComponents.length ; tt++) { var subComponentName = subComponents[tt] subComponentsMap[subComponentName] = {} } var forms = mm.getForms() for ( var formIndex = 0; formIndex < forms.length; formIndex ++ ) { var formName = forms[formIndex].name for ( var compenentInFormIndex = 0; compenentInFormIndex < mm.model.forms[formName].components.length; compenentInFormIndex ++ ) { var newItem = mm.model.forms[formName].components[compenentInFormIndex] if (newItem && newItem.base_component_id) { if (!subComponentsMap[newItem.base_component_id]) { subComponentsMap[newItem.base_component_id] = {} } } } } var newListOfSubcomponents = Object.keys( subComponentsMap ) this.text = saveHelper.insertCodeString(this.text, "sub_components", newListOfSubcomponents) this.text = saveHelper.deleteCodeString( this.text, "control_type") this.text = saveHelper.insertCodeString( this.text, "control_type", "SYSTEM") this.text = saveHelper.deleteCodeString( this.text, "formEditor", ")//form" + "Editor") this.text = saveHelper.insertCodeString( this.text, "formEditor", mm.model, ")//form" + "Editor") this.text = saveHelper.deleteCodeString( this.text, "properties", ")//prope" + "rties") this.text = saveHelper.insertCodeString( this.text, "properties", mm.model.app_properties, ")//prope" + "rties") //console.log("end generateCodeFromModel.Done") this.in_generate_code_from_model = false return } } } //*** COPY_END ***// , data: function () { return { newCursor: null, oldCursor: null, cursorSource: null, uid2: null, vb_grid_element_id: null, vb_editor_element_id: null, in_generate_code_from_model: false, design_mode: designMode, runtime_mode: runtimeMode, highlighted_control: null, edited_app_component_id: null, event_code: null, text: texti, leftHandWidth: 130, right_mode: "project", add_property: false, new_property_name: "", new_property_id: "", local_app: false, refresh: 0, properties: [], read_only: false, selected_pane: null, active_property_index: null, design_mode_pane: {type: "drag_drop"}, available_components: [], component_usage: new Object(), form_runtime_info: {}, model: { next_id: 1, next_component_id: 1, max_form: 1, active_form: "Form_1", active_component_index: null, active_component_detail_index: null, active_component_detail_name: null, app_selected: false, default_form: "Form_1", app_properties: [], fields: [ ], forms: { "Form_1": { name: "Form_1", components: [ ] } } } } } } ) }
Trying to create a delete component function Not working yet as we get an errot
public/visifile_drivers/ui_components/vbEditorComponent.js
Trying to create a delete component function
<ide><path>ublic/visifile_drivers/ui_components/vbEditorComponent.js <ide> mm.$forceUpdate(); <ide> },400) <ide> }, <add> deleteComponentByName: async function(thisComponentName) { <add> debugger <add> var mm = this <add> var ccc2 = mm.model.forms[mm.model.active_form].components <add> for ( var ytr = ccc2.length - 1; ytr >= 0; ytr-- ) { <add> var component = ccc2[ytr] <add> if (component.name == thisComponentName) { <add> this.model.forms[this.model.active_form].components.splice(ytr, 1); <add> break; <add> } <add> } <add> this.model.forms[this.model.active_form].components.splice(index, 1); <add> var ccc = mm.model.forms[mm.model.active_form].components <add> for ( var ytr = ccc.length - 1; ytr >= 0; ytr-- ) { <add> var component = ccc[ytr] <add> if (component.parent == thisComponentName) { <add> this.model.forms[this.model.active_form].components.splice(ytr, 1); <add> } <add> } <add> <add> this.refreshControlIndexes() <add> this.selectForm(this.model.active_form) <add> setTimeout(function() { <add> mm.refresh ++ <add> mm.$forceUpdate(); <add> },400) <add> return {} <add> }, <ide> <ide> <ide> childDeleteComponent: function(index) {
Java
apache-2.0
cfc32cd92dc2427230ffed6235101139a5a1c924
0
brandt/GridSphere,brandt/GridSphere
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.portletcontainer; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.SportletLog; import java.util.Iterator; import java.util.Collection; import java.util.List; import java.io.IOException; /** * The <code>PortletInvoker</code> provides static lifecycle routines for performing portlet operations on * concrete portlets. * * @see org.gridlab.gridsphere.portletcontainer.PortletDispatcher */ public class PortletInvoker { private static PortletLog log = SportletLog.getInstance(PortletInvoker.class); private static PortletRegistry registry = PortletRegistry.getInstance(); /** * Initializes an application portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void init(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in init " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { // really want to try with a new dispatcher to see //PortletDispatcher(RequestDispatcher rd, ApplicationPortletConfig portletApp) PortletDispatcher portletDispatcher = appPortlet.getPortletDispatcher(); // init the application portlet portletDispatcher.init(req, res); } else { log.info("in init: Unable to find portlet in registry: " + concretePortletID); } } /** * Initializes a concrete portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void initConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in initConcrete " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher portletDispatcher = appPortlet.getPortletDispatcher(); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(concretePortletID); PortletSettings settings = concPortlet.getPortletSettings(); // init the concrete portlet portletDispatcher.initConcrete(settings, req, res); } else { log.info("in initConcrete: Unable to find portlet in registry: " + concretePortletID); } } /** * Shuts down an application portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void destroy(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in destroy " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); // destroy the application portlet dispatcher.destroy(req, res); } else { log.info("in destroy: Unable to find portlet in registry: " + concretePortletID); } } /** * Shuts down a concrete portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void destroyConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in destroyConcrete " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(concretePortletID); PortletSettings settings = concPortlet.getPortletSettings(); // destroy the concrete portlet dispatcher.destroyConcrete(settings, req, res); } else { log.info("in destroyConcrete: Unable to find portlet in registry: " + concretePortletID); } } /** * Initializes a concrete portlet instance for a user * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void login(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in login " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.login(req, res); } else { log.info("in login: Unable to find portlet in registry: " + concretePortletID); } } /** * Shutds down a concrete portlet instance for a user * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void logout(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.info("in logout " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.logout(req, res); } else { log.info("in logout: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs service method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void service(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in service " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.service(req, res); } else { log.info("in service: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs action performed method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void actionPerformed(String concretePortletID, DefaultPortletAction action, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in actionPerformed " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.actionPerformed(action, req, res); } else { log.info("in actionPerformed: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs doTitle method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void doTitle(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in doTitle " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.doTitle(req, res); } else { log.info("in doTitle: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs window event method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void windowEvent(String concretePortletID, WindowEvent winEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in windowEvent " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.windowEvent(winEvent, req, res); } else { log.info("in windowEvent: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs message event method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void messageEvent(String concretePortletID, DefaultPortletMessage msgEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in messageEvent " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.messageEvent(msgEvent, req, res); } else { log.info("in messageEvent: Unable to find portlet in registry: " + concretePortletID); } } /** * Initializes all application portlets * * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void initAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { // Initialize all concrete portlets for each application portlet Collection appPortlets = registry.getAllApplicationPortlets(); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; // initialize the application portlet log.info("initializing application portlet " + appPortlet.getApplicationPortletID()); portletDispatcher.init(req, res); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // initialize the concrete portlet log.info("initializing concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.initConcrete(settings, req, res); } } } /** * Initializes all application portlets in a portlet web application * * @param webApplicationName the name of the portlet web application * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void initPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { // Initialize all concrete portlets for each application portlet Collection appPortlets = registry.getApplicationPortlets(webApplicationName); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; // initialize the application portlet log.info("initializing application portlet " + appPortlet.getApplicationPortletID()); portletDispatcher.init(req, res); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // initialize the concrete portlet log.info("initializing concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.initConcrete(settings, req, res); } } } /** * Shuts down all application portlets * * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void destroyAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { // First destroy all concrete portlets for each application portlet Collection appPortlets = registry.getAllApplicationPortlets(); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; log.info("destroying application portlet " + appPortlet.getApplicationPortletID()); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // destroy the concrete portlet log.info("destroying concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.destroyConcrete(settings, req, res); } } // destroy the application portlet portletDispatcher.destroy(req, res); } /** * Shuts down all application portlets in a portlet web application * * @param webApplicationName the name of the portlet web application * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public final static synchronized void destroyPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { // First destroy all concrete portlets for each application portlet Collection appPortlets = registry.getApplicationPortlets(webApplicationName); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; log.info("destroying application portlet " + appPortlet.getApplicationPortletID()); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // destroy the concrete portlet log.info("destroying concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.destroyConcrete(settings, req, res); } // destroy the application portlet portletDispatcher.destroy(req, res); } } /** * Returns the application portlet id from the supplied concrete portlet id * * @param concretePortletID the concrete portlet id * @return the application portlet id */ protected static String getApplicationPortletID(String concretePortletID) { int i = concretePortletID.lastIndexOf("."); if (i < 0) return ""; return concretePortletID.substring(0, i); } }
src/org/gridlab/gridsphere/portletcontainer/PortletInvoker.java
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.portletcontainer; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.SportletLog; import java.util.Iterator; import java.util.Collection; import java.util.List; import java.io.IOException; /** * The <code>PortletInvoker</code> provides static lifecycle routines for performing portlet operations on * concrete portlets. * * @see org.gridlab.gridsphere.portletcontainer.PortletDispatcher */ public class PortletInvoker { private static PortletLog log = SportletLog.getInstance(PortletInvoker.class); private static PortletRegistry registry = PortletRegistry.getInstance(); /** * Initializes an application portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void init(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in init " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { // really want to try with a new dispatcher to see //PortletDispatcher(RequestDispatcher rd, ApplicationPortletConfig portletApp) PortletDispatcher portletDispatcher = appPortlet.getPortletDispatcher(); // init the application portlet portletDispatcher.init(req, res); } else { log.info("in init: Unable to find portlet in registry: " + concretePortletID); } } /** * Initializes a concrete portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void initConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in initConcrete " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher portletDispatcher = appPortlet.getPortletDispatcher(); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(concretePortletID); PortletSettings settings = concPortlet.getPortletSettings(); // init the concrete portlet portletDispatcher.initConcrete(settings, req, res); } else { log.info("in initConcrete: Unable to find portlet in registry: " + concretePortletID); } } /** * Shuts down an application portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void destroy(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in destroy " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); // destroy the application portlet dispatcher.destroy(req, res); } else { log.info("in destroy: Unable to find portlet in registry: " + concretePortletID); } } /** * Shuts down a concrete portlet * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void destroyConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in destroyConcrete " + concretePortletID); String appID = getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(concretePortletID); PortletSettings settings = concPortlet.getPortletSettings(); // destroy the concrete portlet dispatcher.destroyConcrete(settings, req, res); } else { log.info("in destroyConcrete: Unable to find portlet in registry: " + concretePortletID); } } /** * Initializes a concrete portlet instance for a user * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void login(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in login " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.login(req, res); } else { log.info("in login: Unable to find portlet in registry: " + concretePortletID); } } /** * Shutds down a concrete portlet instance for a user * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void logout(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.info("in logout " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.logout(req, res); } else { log.info("in logout: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs service method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void service(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in service " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.service(req, res); } else { log.info("in service: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs action performed method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void actionPerformed(String concretePortletID, DefaultPortletAction action, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in actionPerformed " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.actionPerformed(action, req, res); } else { log.info("in actionPerformed: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs doTitle method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void doTitle(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in doTitle " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.doTitle(req, res); } else { log.info("in doTitle: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs window event method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void windowEvent(String concretePortletID, WindowEvent winEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in windowEvent " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.windowEvent(winEvent, req, res); } else { log.info("in windowEvent: Unable to find portlet in registry: " + concretePortletID); } } /** * Performs message event method on a concrete portlet instance * * @param concretePortletID the concrete portlet id * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void messageEvent(String concretePortletID, DefaultPortletMessage msgEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { log.debug("in messageEvent " + concretePortletID); String appID = registry.getApplicationPortletID(concretePortletID); ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); if (appPortlet != null) { PortletDispatcher dispatcher = appPortlet.getPortletDispatcher(); dispatcher.messageEvent(msgEvent, req, res); } else { log.info("in messageEvent: Unable to find portlet in registry: " + concretePortletID); } } /** * Initializes all application portlets * * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void initAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { // Initialize all concrete portlets for each application portlet Collection appPortlets = registry.getAllApplicationPortlets(); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; // initialize the application portlet log.info("initializing application portlet " + appPortlet.getApplicationPortletID()); portletDispatcher.init(req, res); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // initialize the concrete portlet log.info("initializing concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.initConcrete(settings, req, res); } } } /** * Initializes all application portlets in a portlet web application * * @param webApplicationName the name of the portlet web application * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void initPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { // Initialize all concrete portlets for each application portlet Collection appPortlets = registry.getApplicationPortlets(webApplicationName); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; // initialize the application portlet log.info("initializing application portlet " + appPortlet.getApplicationPortletID()); portletDispatcher.init(req, res); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // initialize the concrete portlet log.info("initializing concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.initConcrete(settings, req, res); } } } /** * Shuts down all application portlets * * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void destroyAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { // First destroy all concrete portlets for each application portlet Collection appPortlets = registry.getAllApplicationPortlets(); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; log.info("destroying application portlet " + appPortlet.getApplicationPortletID()); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // destroy the concrete portlet log.info("destroying concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.destroyConcrete(settings, req, res); } } // destroy the application portlet portletDispatcher.destroy(req, res); } /** * Shuts down all application portlets in a portlet web application * * @param webApplicationName the name of the portlet web application * @param req the <code>PortletRequest</code> * @param res the <code>PortletResponse</code> * @throws IOException if an I/O error occurs * @throws PortletException if a portlet/servlet error occurs */ public static final void destroyPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { // First destroy all concrete portlets for each application portlet Collection appPortlets = registry.getApplicationPortlets(webApplicationName); PortletDispatcher portletDispatcher = null; Iterator it = appPortlets.iterator(); while (it.hasNext()) { ApplicationPortlet appPortlet = (ApplicationPortlet) it.next(); portletDispatcher = appPortlet.getPortletDispatcher(); List concPortlets = appPortlet.getConcretePortlets(); Iterator concIt = concPortlets.iterator(); PortletSettings settings = null; log.info("destroying application portlet " + appPortlet.getApplicationPortletID()); while (concIt.hasNext()) { ConcretePortlet concPortlet = (ConcretePortlet) concIt.next(); settings = concPortlet.getPortletSettings(); // destroy the concrete portlet log.info("destroying concrete portlet " + concPortlet.getConcretePortletID()); portletDispatcher.destroyConcrete(settings, req, res); } // destroy the application portlet portletDispatcher.destroy(req, res); } } /** * Returns the application portlet id from the supplied concrete portlet id * * @param concretePortletID the concrete portlet id * @return the application portlet id */ protected static String getApplicationPortletID(String concretePortletID) { int i = concretePortletID.lastIndexOf("."); if (i < 0) return ""; return concretePortletID.substring(0, i); } }
added synchronization git-svn-id: 616481d960d639df1c769687dde8737486ca2a9a@1462 9c99c85f-4d0c-0410-8460-a9a1c48a3a7f
src/org/gridlab/gridsphere/portletcontainer/PortletInvoker.java
added synchronization
<ide><path>rc/org/gridlab/gridsphere/portletcontainer/PortletInvoker.java <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void init(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void init(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in init " + concretePortletID); <ide> String appID = getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void initConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void initConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in initConcrete " + concretePortletID); <ide> String appID = getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void destroy(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void destroy(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in destroy " + concretePortletID); <ide> String appID = getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void destroyConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void destroyConcrete(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in destroyConcrete " + concretePortletID); <ide> String appID = getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void login(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void login(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in login " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void logout(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void logout(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.info("in logout " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void service(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void service(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in service " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void actionPerformed(String concretePortletID, DefaultPortletAction action, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void actionPerformed(String concretePortletID, DefaultPortletAction action, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in actionPerformed " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void doTitle(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void doTitle(String concretePortletID, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in doTitle " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void windowEvent(String concretePortletID, WindowEvent winEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void windowEvent(String concretePortletID, WindowEvent winEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in windowEvent " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void messageEvent(String concretePortletID, DefaultPortletMessage msgEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void messageEvent(String concretePortletID, DefaultPortletMessage msgEvent, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> log.debug("in messageEvent " + concretePortletID); <ide> String appID = registry.getApplicationPortletID(concretePortletID); <ide> ApplicationPortlet appPortlet = registry.getApplicationPortlet(appID); <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void initAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void initAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> // Initialize all concrete portlets for each application portlet <ide> Collection appPortlets = registry.getAllApplicationPortlets(); <ide> PortletDispatcher portletDispatcher = null; <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void initPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void initPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> // Initialize all concrete portlets for each application portlet <ide> Collection appPortlets = registry.getApplicationPortlets(webApplicationName); <ide> PortletDispatcher portletDispatcher = null; <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void destroyAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void destroyAllPortlets(PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> // First destroy all concrete portlets for each application portlet <ide> Collection appPortlets = registry.getAllApplicationPortlets(); <ide> PortletDispatcher portletDispatcher = null; <ide> * @throws IOException if an I/O error occurs <ide> * @throws PortletException if a portlet/servlet error occurs <ide> */ <del> public static final void destroyPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { <add> public final static synchronized void destroyPortletWebApp(String webApplicationName, PortletRequest req, PortletResponse res) throws IOException, PortletException { <ide> // First destroy all concrete portlets for each application portlet <ide> Collection appPortlets = registry.getApplicationPortlets(webApplicationName); <ide> PortletDispatcher portletDispatcher = null;
Java
apache-2.0
2aa0bba0d5c56289ba6ce7969d267a58e3b3e074
0
xiongzheng/Cassandra-Research,sivikt/cassandra,taigetco/cassandra_read,scaledata/cassandra,jsanda/cassandra,jeffjirsa/cassandra,Jaumo/cassandra,sriki77/cassandra,blerer/cassandra,Stratio/cassandra,AtwooTM/cassandra,DikangGu/cassandra,sbtourist/cassandra,fengshao0907/Cassandra-Research,regispl/cassandra,WorksApplications/cassandra,pauloricardomg/cassandra,clohfink/cassandra,pallavi510/cassandra,weideng1/cassandra,bcoverston/cassandra,cooldoger/cassandra,GabrielNicolasAvellaneda/cassandra,tongjixianing/projects,GabrielNicolasAvellaneda/cassandra,rdio/cassandra,weideng1/cassandra,wreda/cassandra,sivikt/cassandra,belliottsmith/cassandra,bpupadhyaya/cassandra,yonglehou/cassandra,hhorii/cassandra,jsanda/cassandra,Jaumo/cassandra,EnigmaCurry/cassandra,vramaswamy456/cassandra,ptuckey/cassandra,mariusae/cassandra,krummas/cassandra,scylladb/scylla-tools-java,Instagram/cassandra,mambocab/cassandra,GabrielNicolasAvellaneda/cassandra,michaelmior/cassandra,DavidHerzogTU-Berlin/cassandraToRun,modempachev4/kassandra,mt0803/cassandra,kgreav/cassandra,guard163/cassandra,mklew/mmp,stef1927/cassandra,beobal/cassandra,blerer/cassandra,pbailis/cassandra-pbs,phact/cassandra,lalithsuresh/cassandra-c3,thelastpickle/cassandra,cooldoger/cassandra,b/project-cassandra,aureagle/cassandra,sammyyu/Cassandra,mariusae/cassandra,blambov/cassandra,fengshao0907/cassandra-1,nvoron23/cassandra,ejankan/cassandra,ben-manes/cassandra,sluk3r/cassandra,tjake/cassandra,ollie314/cassandra,pcn/cassandra-1,yonglehou/cassandra,iamaleksey/cassandra,instaclustr/cassandra,Stratio/stratio-cassandra,kangkot/stratio-cassandra,jrwest/cassandra,adelapena/cassandra,caidongyun/cassandra,bdeggleston/cassandra,blerer/cassandra,WorksApplications/cassandra,shookari/cassandra,bmel/cassandra,nlalevee/cassandra,ptuckey/cassandra,bdeggleston/cassandra,christian-esken/cassandra,kangkot/stratio-cassandra,yhnishi/cassandra,xiongzheng/Cassandra-Research,b/project-cassandra,adejanovski/cassandra,sharvanath/cassandra,tjake/cassandra,RyanMagnusson/cassandra,carlyeks/cassandra,fengshao0907/Cassandra-Research,nitsanw/cassandra,EnigmaCurry/cassandra,pthomaid/cassandra,hengxin/cassandra,macintoshio/cassandra,taigetco/cassandra_read,jbellis/cassandra,rdio/cassandra,hhorii/cassandra,szhou1234/cassandra,scylladb/scylla-tools-java,fengshao0907/cassandra-1,macintoshio/cassandra,mshuler/cassandra,spodkowinski/cassandra,sedulam/CASSANDRA-12201,sedulam/CASSANDRA-12201,ben-manes/cassandra,yukim/cassandra,ejankan/cassandra,nitsanw/cassandra,weipinghe/cassandra,DICL/cassandra,thelastpickle/cassandra,jasobrown/cassandra,matthewtt/cassandra_read,pcmanus/cassandra,LatencyUtils/cassandra-stress2,segfault/apache_cassandra,bmel/cassandra,scylladb/scylla-tools-java,HidemotoNakada/cassandra-udf,sammyyu/Cassandra,carlyeks/cassandra,yanbit/cassandra,bcoverston/apache-hosted-cassandra,yonglehou/cassandra,guanxi55nba/db-improvement,jbellis/cassandra,knifewine/cassandra,project-zerus/cassandra,aweisberg/cassandra,aureagle/cassandra,aarushi12002/cassandra,mike-tr-adamson/cassandra,szhou1234/cassandra,pthomaid/cassandra,qinjin/mdtc-cassandra,chbatey/cassandra-1,RyanMagnusson/cassandra,bcoverston/cassandra,qinjin/mdtc-cassandra,mariusae/cassandra,tjake/cassandra,WorksApplications/cassandra,szhou1234/cassandra,yukim/cassandra,mashuai/Cassandra-Research,matthewtt/cassandra_read,fengshao0907/cassandra-1,likaiwalkman/cassandra,adelapena/cassandra,jasonwee/cassandra,sriki77/cassandra,Imran-C/cassandra,Instagram/cassandra,sluk3r/cassandra,nakomis/cassandra,jasonwee/cassandra,yanbit/cassandra,MasahikoSawada/cassandra,lalithsuresh/cassandra-c3,bmel/cassandra,Jaumo/cassandra,mashuai/Cassandra-Research,b/project-cassandra,clohfink/cassandra,juiceblender/cassandra,vramaswamy456/cassandra,jasobrown/cassandra,beobal/cassandra,szhou1234/cassandra,mambocab/cassandra,pallavi510/cassandra,nutbunnies/cassandra,juiceblender/cassandra,weipinghe/cassandra,bpupadhyaya/cassandra,thelastpickle/cassandra,mariusae/cassandra,kangkot/stratio-cassandra,jkni/cassandra,mike-tr-adamson/cassandra,pofallon/cassandra,mshuler/cassandra,heiko-braun/cassandra,a-buck/cassandra,beobal/cassandra,codefollower/Cassandra-Research,mgmuscari/cassandra-cdh4,yhnishi/cassandra,krummas/cassandra,sharvanath/cassandra,whitepages/cassandra,regispl/cassandra,pcmanus/cassandra,WorksApplications/cassandra,sedulam/CASSANDRA-12201,rackerlabs/cloudmetrics-cassandra,rogerchina/cassandra,christian-esken/cassandra,jasonwee/cassandra,LatencyUtils/cassandra-stress2,chbatey/cassandra-1,jeromatron/cassandra,Stratio/stratio-cassandra,cooldoger/cassandra,ollie314/cassandra,rdio/cassandra,guanxi55nba/key-value-store,dongjiaqiang/cassandra,regispl/cassandra,jeromatron/cassandra,mt0803/cassandra,guanxi55nba/key-value-store,sbtourist/cassandra,project-zerus/cassandra,AtwooTM/cassandra,jrwest/cassandra,rogerchina/cassandra,helena/cassandra,ifesdjeen/cassandra,guanxi55nba/key-value-store,chaordic/cassandra,sayanh/ViewMaintenanceSupport,bcoverston/apache-hosted-cassandra,aarushi12002/cassandra,ifesdjeen/cassandra,vaibhi9/cassandra,caidongyun/cassandra,pthomaid/cassandra,heiko-braun/cassandra,pbailis/cassandra-pbs,ollie314/cassandra,modempachev4/kassandra,belliottsmith/cassandra,leomrocha/cassandra,DavidHerzogTU-Berlin/cassandra,mheffner/cassandra-1,emolsson/cassandra,hhorii/cassandra,driftx/cassandra,shookari/cassandra,iamaleksey/cassandra,michaelsembwever/cassandra,guard163/cassandra,mkjellman/cassandra,fengshao0907/Cassandra-Research,sluk3r/cassandra,shawnkumar/cstargraph,Stratio/stratio-cassandra,yangzhe1991/cassandra,HidemotoNakada/cassandra-udf,rmarchei/cassandra,juiceblender/cassandra,pbailis/cassandra-pbs,ptnapoleon/cassandra,krummas/cassandra,nvoron23/cassandra,shawnkumar/cstargraph,rmarchei/cassandra,dprguiuc/Cassandra-Wasef,jeffjirsa/cassandra,aarushi12002/cassandra,adelapena/cassandra,bcoverston/cassandra,sayanh/ViewMaintenanceCassandra,Jollyplum/cassandra,exoscale/cassandra,strapdata/cassandra,leomrocha/cassandra,strapdata/cassandra,Stratio/cassandra,mshuler/cassandra,iburmistrov/Cassandra,spodkowinski/cassandra,Jollyplum/cassandra,miguel0afd/cassandra-cqlMod,jeffjirsa/cassandra,guard163/cassandra,darach/cassandra,pofallon/cassandra,boneill42/cassandra,pauloricardomg/cassandra,jkni/cassandra,kangkot/stratio-cassandra,modempachev4/kassandra,sayanh/ViewMaintenanceCassandra,mambocab/cassandra,jasobrown/cassandra,mt0803/cassandra,scaledata/cassandra,mheffner/cassandra-1,thelastpickle/cassandra,Instagram/cassandra,apache/cassandra,apache/cassandra,nutbunnies/cassandra,lalithsuresh/cassandra-c3,dprguiuc/Cassandra-Wasef,driftx/cassandra,belliottsmith/cassandra,sayanh/ViewMaintenanceCassandra,whitepages/cassandra,chaordic/cassandra,Instagram/cassandra,jeromatron/cassandra,Stratio/stratio-cassandra,mashuai/Cassandra-Research,likaiwalkman/cassandra,clohfink/cassandra,guanxi55nba/db-improvement,josh-mckenzie/cassandra,michaelsembwever/cassandra,helena/cassandra,josh-mckenzie/cassandra,aboudreault/cassandra,jasobrown/cassandra,gdusbabek/cassandra,jrwest/cassandra,shookari/cassandra,blambov/cassandra,aboudreault/cassandra,DavidHerzogTU-Berlin/cassandraToRun,jasonstack/cassandra,bcoverston/apache-hosted-cassandra,Bj0rnen/cassandra,iamaleksey/cassandra,pkdevbox/cassandra,pkdevbox/cassandra,tjake/cassandra,Bj0rnen/cassandra,matthewtt/cassandra_read,yangzhe1991/cassandra,aweisberg/cassandra,pauloricardomg/cassandra,mkjellman/cassandra,darach/cassandra,exoscale/cassandra,asias/cassandra,joesiewert/cassandra,mshuler/cassandra,vaibhi9/cassandra,joesiewert/cassandra,sivikt/cassandra,chbatey/cassandra-1,jasonstack/cassandra,rogerchina/cassandra,aweisberg/cassandra,scaledata/cassandra,aureagle/cassandra,tommystendahl/cassandra,nitsanw/cassandra,apache/cassandra,instaclustr/cassandra,mgmuscari/cassandra-cdh4,rackerlabs/cloudmetrics-cassandra,pauloricardomg/cassandra,vramaswamy456/cassandra,bpupadhyaya/cassandra,shawnkumar/cstargraph,michaelsembwever/cassandra,spodkowinski/cassandra,driftx/cassandra,stef1927/cassandra,iburmistrov/Cassandra,ifesdjeen/cassandra,Stratio/stratio-cassandra,strapdata/cassandra,stuhood/cassandra-old,sriki77/cassandra,segfault/apache_cassandra,belliottsmith/cassandra,pcn/cassandra-1,jkni/cassandra,cooldoger/cassandra,stef1927/cassandra,whitepages/cassandra,mkjellman/cassandra,stuhood/cassandra-old,swps/cassandra,ibmsoe/cassandra,spodkowinski/cassandra,ibmsoe/cassandra,kangkot/stratio-cassandra,ifesdjeen/cassandra,asias/cassandra,mklew/mmp,clohfink/cassandra,tommystendahl/cassandra,mklew/mmp,segfault/apache_cassandra,michaelmior/cassandra,ptnapoleon/cassandra,josh-mckenzie/cassandra,snazy/cassandra,joesiewert/cassandra,HidemotoNakada/cassandra-udf,sayanh/ViewMaintenanceSupport,strapdata/cassandra,yukim/cassandra,JeremiahDJordan/cassandra,aboudreault/cassandra,asias/cassandra,emolsson/cassandra,b/project-cassandra,newrelic-forks/cassandra,gdusbabek/cassandra,DICL/cassandra,project-zerus/cassandra,codefollower/Cassandra-Research,adelapena/cassandra,bcoverston/cassandra,kgreav/cassandra,dkua/cassandra,yangzhe1991/cassandra,JeremiahDJordan/cassandra,jsanda/cassandra,rackerlabs/cloudmetrics-cassandra,sharvanath/cassandra,wreda/cassandra,macintoshio/cassandra,ptnapoleon/cassandra,Imran-C/cassandra,AtwooTM/cassandra,DavidHerzogTU-Berlin/cassandra,swps/cassandra,tongjixianing/projects,a-buck/cassandra,krummas/cassandra,kgreav/cassandra,EnigmaCurry/cassandra,stuhood/cassandra-old,dongjiaqiang/cassandra,michaelsembwever/cassandra,MasahikoSawada/cassandra,carlyeks/cassandra,rmarchei/cassandra,taigetco/cassandra_read,sammyyu/Cassandra,guanxi55nba/db-improvement,heiko-braun/cassandra,nlalevee/cassandra,Bj0rnen/cassandra,thobbs/cassandra,thobbs/cassandra,mike-tr-adamson/cassandra,dkua/cassandra,nlalevee/cassandra,Imran-C/cassandra,nutbunnies/cassandra,Jollyplum/cassandra,adejanovski/cassandra,mheffner/cassandra-1,ibmsoe/cassandra,codefollower/Cassandra-Research,dongjiaqiang/cassandra,MasahikoSawada/cassandra,darach/cassandra,nakomis/cassandra,DavidHerzogTU-Berlin/cassandraToRun,stuhood/cassandra-old,snazy/cassandra,phact/cassandra,nakomis/cassandra,iamaleksey/cassandra,emolsson/cassandra,jrwest/cassandra,knifewine/cassandra,blerer/cassandra,bdeggleston/cassandra,yhnishi/cassandra,stef1927/cassandra,mgmuscari/cassandra-cdh4,caidongyun/cassandra,DikangGu/cassandra,boneill42/cassandra,a-buck/cassandra,jasonstack/cassandra,sbtourist/cassandra,pallavi510/cassandra,blambov/cassandra,weideng1/cassandra,weipinghe/cassandra,LatencyUtils/cassandra-stress2,pcn/cassandra-1,driftx/cassandra,DikangGu/cassandra,pcmanus/cassandra,scylladb/scylla-tools-java,jeffjirsa/cassandra,nvoron23/cassandra,newrelic-forks/cassandra,boneill42/cassandra,hengxin/cassandra,thobbs/cassandra,snazy/cassandra,beobal/cassandra,knifewine/cassandra,mariusae/cassandra,ptuckey/cassandra,RyanMagnusson/cassandra,dprguiuc/Cassandra-Wasef,mkjellman/cassandra,jbellis/cassandra,kgreav/cassandra,wreda/cassandra,apache/cassandra,tommystendahl/cassandra,mike-tr-adamson/cassandra,newrelic-forks/cassandra,gdusbabek/cassandra,snazy/cassandra,adejanovski/cassandra,michaelmior/cassandra,ejankan/cassandra,instaclustr/cassandra,juiceblender/cassandra,chaordic/cassandra,christian-esken/cassandra,vaibhi9/cassandra,helena/cassandra,ben-manes/cassandra,pkdevbox/cassandra,aweisberg/cassandra,xiongzheng/Cassandra-Research,tommystendahl/cassandra,blambov/cassandra,bdeggleston/cassandra,qinjin/mdtc-cassandra,leomrocha/cassandra,DICL/cassandra,DavidHerzogTU-Berlin/cassandra,swps/cassandra,exoscale/cassandra,dkua/cassandra,yanbit/cassandra,iburmistrov/Cassandra,instaclustr/cassandra,JeremiahDJordan/cassandra,yukim/cassandra,likaiwalkman/cassandra,josh-mckenzie/cassandra,miguel0afd/cassandra-cqlMod,hengxin/cassandra,tongjixianing/projects,phact/cassandra,Stratio/cassandra,miguel0afd/cassandra-cqlMod,pofallon/cassandra
/** * 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.service; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Arrays; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import com.facebook.fb303.FacebookBase; import com.facebook.fb303.fb_status; import com.facebook.thrift.TException; import com.facebook.thrift.protocol.TBinaryProtocol; import com.facebook.thrift.protocol.TProtocolFactory; import com.facebook.thrift.server.TThreadPoolServer; import com.facebook.thrift.server.TThreadPoolServer.Options; import com.facebook.thrift.transport.TServerSocket; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql.common.CqlResult; import org.apache.cassandra.cql.driver.CqlDriver; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.IColumn; import org.apache.cassandra.db.Row; import org.apache.cassandra.db.RowMutation; import org.apache.cassandra.db.RowMutationMessage; import org.apache.cassandra.net.EndPoint; import org.apache.cassandra.net.Message; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.net.IAsyncResult; import org.apache.cassandra.utils.LogUtil; import org.apache.cassandra.io.DataInputBuffer; import org.apache.cassandra.io.DataOutputBuffer; /** * Author : Avinash Lakshman ( [email protected]) & Prashant Malik ( [email protected] ) */ public class CassandraServer extends FacebookBase implements Cassandra.Iface { private static Logger logger_ = Logger.getLogger(CassandraServer.class); /* * Handle to the storage service to interact with the other machines in the * cluster. */ protected StorageService storageService; protected CassandraServer(String name) { super(name); // Create the instance of the storage service storageService = StorageService.instance(); } public CassandraServer() { super("CassandraServer"); // Create the instance of the storage service storageService = StorageService.instance(); } /* * The start function initializes the server and start's listening on the * specified port. */ public void start() throws Throwable { LogUtil.init(); //LogUtil.setLogLevel("com.facebook", "DEBUG"); // Start the storage service storageService.start(); } private void validateTable(String table) throws CassandraException { if ( !DatabaseDescriptor.getTables().contains(table) ) { throw new CassandraException("Table " + table + " does not exist in this schema."); } } protected ColumnFamily get_cf(String tablename, String key, String columnFamily, List<String> columNames) throws CassandraException, TException { ColumnFamily cfamily = null; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily, columNames, StorageService.ConsistencyLevel.WEAK); if (row == null) { throw new CassandraException("No row exists for key " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily " + columnFamily + " map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily + " is missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the column family " + values[0] + " is not present."); } } catch (Throwable ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return cfamily; } public ArrayList<column_t> get_columns_since(String tablename, String key, String columnFamily_column, long timeStamp) throws CassandraException,TException { ArrayList<column_t> retlist = new ArrayList<column_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, timeStamp, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily " + columnFamily_column + " map is missing.....: " + " key:" + key); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily_column + " is missing.....: "+" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 1 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { column_t thrift_column = new column_t(); thrift_column.columnName = column.name(); thrift_column.value = new String(column.value()); // This needs to be Utf8ed thrift_column.timestamp = column.timestamp(); retlist.add(thrift_column); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public List<column_t> get_slice_by_names(String tablename, String key, String columnFamily, List<String> columnNames) throws CassandraException, TException { ArrayList<column_t> retlist = new ArrayList<column_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); ColumnFamily cfamily = get_cf(tablename, key, columnFamily, columnNames); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily + " is missing.....: " +" key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("Either the key " + key + " is not present or the columnFamily requested" + columnFamily + "is not present."); } Collection<IColumn> columns = null; columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); } for(IColumn column : columns) { column_t thrift_column = new column_t(); thrift_column.columnName = column.name(); thrift_column.value = new String(column.value()); // This needs to be Utf8ed thrift_column.timestamp = column.timestamp(); retlist.add(thrift_column); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public ArrayList<column_t> get_slice(String tablename, String key, String columnFamily_column, int start, int count) throws CassandraException,TException { ArrayList<column_t> retlist = new ArrayList<column_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, start, count, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily " + columnFamily_column + " map is missing.....: " + " key:" + key); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily_column + " is missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 1 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { column_t thrift_column = new column_t(); thrift_column.columnName = column.name(); thrift_column.value = new String(column.value()); // This needs to be Utf8ed thrift_column.timestamp = column.timestamp(); retlist.add(thrift_column); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public column_t get_column(String tablename, String key, String columnFamily_column) throws CassandraException,TException { column_t ret = null; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 2 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, -1, Integer.MAX_VALUE, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 2 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } ret = new column_t(); for(IColumn column : columns) { ret.columnName = column.name(); ret.value = new String(column.value()); ret.timestamp = column.timestamp(); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return ret; } public int get_column_count(String tablename, String key, String columnFamily_column) throws CassandraException { int count = -1; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, -1, Integer.MAX_VALUE, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 1 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } count = columns.size(); } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return count; } public void insert(String tablename, String key, String columnFamily_column, String cellData, long timestamp) { try { validateTable(tablename); RowMutation rm = new RowMutation(tablename, key.trim()); rm.add(columnFamily_column, cellData.getBytes(), timestamp); StorageProxy.insert(rm); } catch (Exception e) { logger_.debug( LogUtil.throwableToString(e) ); } return; } public boolean batch_insert_blocking(batch_mutation_t batchMutation) { logger_.debug("batch_insert_blocking"); RowMutation rm = RowMutation.getRowMutation(batchMutation); return StorageProxy.insertBlocking(rm); } public void batch_insert(batch_mutation_t batchMutation) { logger_.debug("batch_insert"); RowMutation rm = RowMutation.getRowMutation(batchMutation); StorageProxy.insert(rm); } public void remove(String tablename, String key, String columnFamily_column) { throw new UnsupportedOperationException("Remove is coming soon"); } public boolean remove(String tablename, String key, String columnFamily_column, long timestamp, int block_for) { logger_.debug("remove"); RowMutation rm = new RowMutation(tablename, key.trim()); rm.delete(columnFamily_column, timestamp); if (block_for > 0) { return StorageProxy.insertBlocking(rm); } else { StorageProxy.insert(rm); return true; } } public List<superColumn_t> get_slice_super_by_names(String tablename, String key, String columnFamily, List<String> superColumnNames) throws CassandraException, TException { ArrayList<superColumn_t> retlist = new ArrayList<superColumn_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); ColumnFamily cfamily = get_cf(tablename, key, columnFamily, superColumnNames); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily + " is missing.....: "+" key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("Either the key " + key + " is not present or the column family requested" + columnFamily + "is not present."); } Collection<IColumn> columns = null; columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); } for(IColumn column : columns) { superColumn_t thrift_superColumn = new superColumn_t(); thrift_superColumn.name = column.name(); Collection<IColumn> subColumns = column.getSubColumns(); if(subColumns.size() != 0 ) { thrift_superColumn.columns = new ArrayList<column_t>(); for( IColumn subColumn : subColumns ) { column_t thrift_column = new column_t(); thrift_column.columnName = subColumn.name(); thrift_column.value = new String(subColumn.value()); thrift_column.timestamp = subColumn.timestamp(); thrift_superColumn.columns.add(thrift_column); } } retlist.add(thrift_superColumn); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public ArrayList<superColumn_t> get_slice_super(String tablename, String key, String columnFamily_superColumnName, int start, int count) throws CassandraException { ArrayList<superColumn_t> retlist = new ArrayList<superColumn_t>(); try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_superColumnName); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_superColumnName + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_superColumnName, start, count, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_superColumnName + "are not present."); } Collection<IColumn> columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { superColumn_t thrift_superColumn = new superColumn_t(); thrift_superColumn.name = column.name(); Collection<IColumn> subColumns = column.getSubColumns(); if(subColumns.size() != 0 ) { thrift_superColumn.columns = new ArrayList<column_t>(); for( IColumn subColumn : subColumns ) { column_t thrift_column = new column_t(); thrift_column.columnName = subColumn.name(); thrift_column.value = new String(subColumn.value()); thrift_column.timestamp = subColumn.timestamp(); thrift_superColumn.columns.add(thrift_column); } } retlist.add(thrift_superColumn); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return retlist; } public superColumn_t get_superColumn(String tablename, String key, String columnFamily_column) throws CassandraException { superColumn_t ret = null; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 2 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, -1, Integer.MAX_VALUE, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { ret = new superColumn_t(); ret.name = column.name(); Collection<IColumn> subColumns = column.getSubColumns(); if(subColumns.size() != 0 ) { ret.columns = new ArrayList<column_t>(); for(IColumn subColumn : subColumns) { column_t thrift_column = new column_t(); thrift_column.columnName = subColumn.name(); thrift_column.value = new String(subColumn.value()); thrift_column.timestamp = subColumn.timestamp(); ret.columns.add(thrift_column); } } } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return ret; } public boolean batch_insert_superColumn_blocking(batch_mutation_super_t batchMutationSuper) { logger_.debug("batch_insert_SuperColumn_blocking"); RowMutation rm = RowMutation.getRowMutation(batchMutationSuper); return StorageProxy.insertBlocking(rm); } public void batch_insert_superColumn(batch_mutation_super_t batchMutationSuper) { logger_.debug("batch_insert_SuperColumn"); RowMutation rm = RowMutation.getRowMutation(batchMutationSuper); StorageProxy.insert(rm); } public String getStringProperty(String propertyName) throws TException { if (propertyName.equals("cluster name")) { return DatabaseDescriptor.getClusterName(); } else if (propertyName.equals("config file")) { String filename = DatabaseDescriptor.getConfigFileName(); try { StringBuffer fileData = new StringBuffer(8192); BufferedInputStream stream = new BufferedInputStream(new FileInputStream(filename)); byte[] buf = new byte[1024]; int numRead; while( (numRead = stream.read(buf)) != -1) { String str = new String(buf, 0, numRead); fileData.append(str); } stream.close(); return fileData.toString(); } catch (IOException e) { return "file not found!"; } } else if (propertyName.equals("version")) { return getVersion(); } else { return "?"; } } public List<String> getStringListProperty(String propertyName) throws TException { if (propertyName.equals("tables")) { return DatabaseDescriptor.getTables(); } else { return new ArrayList<String>(); } } public String describeTable(String tableName) throws TException { String desc = ""; Map<String, CFMetaData> tableMetaData = DatabaseDescriptor.getTableMetaData(tableName); if (tableMetaData == null) { return "Table " + tableName + " not found."; } Iterator iter = tableMetaData.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, CFMetaData> pairs = (Map.Entry<String, CFMetaData>)iter.next(); desc = desc + pairs.getValue().pretty() + "-----\n"; } return desc; } public CqlResult_t executeQuery(String query) throws TException { CqlResult_t result = new CqlResult_t(); CqlResult cqlResult = CqlDriver.executeQuery(query); // convert CQL result type to Thrift specific return type if (cqlResult != null) { result.errorTxt = cqlResult.errorTxt; result.resultSet = cqlResult.resultSet; result.errorCode = cqlResult.errorCode; } return result; } /* * This method is used to ensure that all keys * prior to the specified key, as dtermined by * the SSTable index bucket it falls in, are in * buffer cache. */ public void touch (String key , boolean fData) { try { StorageProxy.touchProtocol(DatabaseDescriptor.getTables().get(0), key, fData, StorageService.ConsistencyLevel.WEAK); } catch ( Exception e) { logger_.info( LogUtil.throwableToString(e) ); } } public String getVersion() { return "1"; } public int getStatus() { return fb_status.ALIVE; } public String getStatusDetails() { return null; } public static void main(String[] args) throws Throwable { int port = 9160; Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { logger_.error("Fatal exception in thread " + t, e); } }); try { CassandraServer peerStorageServer = new CassandraServer(); peerStorageServer.start(); Cassandra.Processor processor = new Cassandra.Processor( peerStorageServer); // Transport TServerSocket tServerSocket = new TServerSocket(port); // Protocol factory TProtocolFactory tProtocolFactory = new TBinaryProtocol.Factory(); // ThreadPool Server Options options = new Options(); options.minWorkerThreads = 64; TThreadPoolServer serverEngine = new TThreadPoolServer(processor, tServerSocket, tProtocolFactory); serverEngine.serve(); } catch (Exception x) { System.err.println("UNCAUGHT EXCEPTION IN main()"); x.printStackTrace(); System.exit(1); } } }
src/org/apache/cassandra/service/CassandraServer.java
/** * 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.service; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Arrays; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import com.facebook.fb303.FacebookBase; import com.facebook.fb303.fb_status; import com.facebook.thrift.TException; import com.facebook.thrift.protocol.TBinaryProtocol; import com.facebook.thrift.protocol.TProtocolFactory; import com.facebook.thrift.server.TThreadPoolServer; import com.facebook.thrift.server.TThreadPoolServer.Options; import com.facebook.thrift.transport.TServerSocket; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql.common.CqlResult; import org.apache.cassandra.cql.driver.CqlDriver; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.IColumn; import org.apache.cassandra.db.Row; import org.apache.cassandra.db.RowMutation; import org.apache.cassandra.db.RowMutationMessage; import org.apache.cassandra.net.EndPoint; import org.apache.cassandra.net.Message; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.net.IAsyncResult; import org.apache.cassandra.utils.LogUtil; import org.apache.cassandra.io.DataInputBuffer; import org.apache.cassandra.io.DataOutputBuffer; /** * Author : Avinash Lakshman ( [email protected]) & Prashant Malik ( [email protected] ) */ public class CassandraServer extends FacebookBase implements Cassandra.Iface { private static Logger logger_ = Logger.getLogger(CassandraServer.class); /* * Handle to the storage service to interact with the other machines in the * cluster. */ protected StorageService storageService; protected CassandraServer(String name) { super(name); // Create the instance of the storage service storageService = StorageService.instance(); } public CassandraServer() { super("CassandraServer"); // Create the instance of the storage service storageService = StorageService.instance(); } /* * The start function initializes the server and start's listening on the * specified port. */ public void start() throws Throwable { LogUtil.init(); //LogUtil.setLogLevel("com.facebook", "DEBUG"); // Start the storage service storageService.start(); } private void validateTable(String table) throws CassandraException { if ( !DatabaseDescriptor.getTables().contains(table) ) { throw new CassandraException("Table " + table + " does not exist in this schema."); } } protected ColumnFamily get_cf(String tablename, String key, String columnFamily, List<String> columNames) throws CassandraException, TException { ColumnFamily cfamily = null; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily, columNames, StorageService.ConsistencyLevel.WEAK); if (row == null) { throw new CassandraException("No row exists for key " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily " + columnFamily + " map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily + " is missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the column family " + values[0] + " is not present."); } } catch (Throwable ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return cfamily; } public ArrayList<column_t> get_columns_since(String tablename, String key, String columnFamily_column, long timeStamp) throws CassandraException,TException { ArrayList<column_t> retlist = new ArrayList<column_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, timeStamp, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily " + columnFamily_column + " map is missing.....: " + " key:" + key); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily_column + " is missing.....: "+" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 1 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { column_t thrift_column = new column_t(); thrift_column.columnName = column.name(); thrift_column.value = new String(column.value()); // This needs to be Utf8ed thrift_column.timestamp = column.timestamp(); retlist.add(thrift_column); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public List<column_t> get_slice_by_names(String tablename, String key, String columnFamily, List<String> columnNames) throws CassandraException, TException { ArrayList<column_t> retlist = new ArrayList<column_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); ColumnFamily cfamily = get_cf(tablename, key, columnFamily, columnNames); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily + " is missing.....: " +" key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("Either the key " + key + " is not present or the columnFamily requested" + columnFamily + "is not present."); } Collection<IColumn> columns = null; columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); } for(IColumn column : columns) { column_t thrift_column = new column_t(); thrift_column.columnName = column.name(); thrift_column.value = new String(column.value()); // This needs to be Utf8ed thrift_column.timestamp = column.timestamp(); retlist.add(thrift_column); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public ArrayList<column_t> get_slice(String tablename, String key, String columnFamily_column, int start, int count) throws CassandraException,TException { ArrayList<column_t> retlist = new ArrayList<column_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, start, count, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily " + columnFamily_column + " map is missing.....: " + " key:" + key); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily_column + " is missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 1 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { column_t thrift_column = new column_t(); thrift_column.columnName = column.name(); thrift_column.value = new String(column.value()); // This needs to be Utf8ed thrift_column.timestamp = column.timestamp(); retlist.add(thrift_column); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public column_t get_column(String tablename, String key, String columnFamily_column) throws CassandraException,TException { column_t ret = null; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 2 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, -1, Integer.MAX_VALUE, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 2 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } ret = new column_t(); for(IColumn column : columns) { ret.columnName = column.name(); ret.value = new String(column.value()); ret.timestamp = column.timestamp(); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return ret; } public int get_column_count(String tablename, String key, String columnFamily_column) throws CassandraException { int count = -1; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, -1, Integer.MAX_VALUE, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = null; if( values.length > 1 ) { // this is the super column case IColumn column = cfamily.getColumn(values[1]); if(column != null) columns = column.getSubColumns(); } else { columns = cfamily.getAllColumns(); } if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } count = columns.size(); } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return count; } public void insert(String tablename, String key, String columnFamily_column, String cellData, long timestamp) { try { validateTable(tablename); RowMutation rm = new RowMutation(tablename, key.trim()); rm.add(columnFamily_column, cellData.getBytes(), timestamp); StorageProxy.insert(rm); } catch (Exception e) { logger_.debug( LogUtil.throwableToString(e) ); } return; } public boolean batch_insert_blocking(batch_mutation_t batchMutation) { logger_.debug("batch_insert_blocking"); RowMutation rm = RowMutation.getRowMutation(batchMutation); return StorageProxy.insertBlocking(rm); } public void batch_insert(batch_mutation_t batchMutation) { logger_.debug("batch_insert"); RowMutation rm = RowMutation.getRowMutation(batchMutation); StorageProxy.insert(rm); } public void remove(String tablename, String key, String columnFamily_column) { throw new UnsupportedOperationException("Remove is coming soon"); } public boolean remove(String tablename, String key, String columnFamily_column, long timestamp, int block_for) { logger_.debug("remove"); RowMutation rm = new RowMutation(tablename, key.trim()); rm.delete(columnFamily_column, timestamp); if (block_for > 0) { return StorageProxy.insertBlocking(rm); } else { StorageProxy.insert(rm); return true; } } public List<superColumn_t> get_slice_super_by_names(String tablename, String key, String columnFamily, List<String> superColumnNames) throws CassandraException, TException { ArrayList<superColumn_t> retlist = new ArrayList<superColumn_t>(); long startTime = System.currentTimeMillis(); try { validateTable(tablename); ColumnFamily cfamily = get_cf(tablename, key, columnFamily, superColumnNames); if (cfamily == null) { logger_.info("ERROR ColumnFamily " + columnFamily + " is missing.....: "+" key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("Either the key " + key + " is not present or the column family requested" + columnFamily + "is not present."); } Collection<IColumn> columns = null; columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + columnFamily); } for(IColumn column : columns) { superColumn_t thrift_superColumn = new superColumn_t(); thrift_superColumn.name = column.name(); Collection<IColumn> subColumns = column.getSubColumns(); if(subColumns.size() != 0 ) { thrift_superColumn.columns = new ArrayList<column_t>(); for( IColumn subColumn : subColumns ) { column_t thrift_column = new column_t(); thrift_column.columnName = subColumn.name(); thrift_column.value = new String(subColumn.value()); thrift_column.timestamp = subColumn.timestamp(); thrift_superColumn.columns.add(thrift_column); } } retlist.add(thrift_superColumn); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } logger_.debug("get_slice2: " + (System.currentTimeMillis() - startTime) + " ms."); return retlist; } public ArrayList<superColumn_t> get_slice_super(String tablename, String key, String columnFamily_superColumnName, int start, int count) throws CassandraException { ArrayList<superColumn_t> retlist = new ArrayList<superColumn_t>(); try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_superColumnName); // check for values if( values.length < 1 ) { throw new CassandraException("Column Family " + columnFamily_superColumnName + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_superColumnName, start, count, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_superColumnName + "are not present."); } Collection<IColumn> columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { superColumn_t thrift_superColumn = new superColumn_t(); thrift_superColumn.name = column.name(); Collection<IColumn> subColumns = column.getSubColumns(); if(subColumns.size() != 0 ) { thrift_superColumn.columns = new ArrayList<column_t>(); for( IColumn subColumn : subColumns ) { column_t thrift_column = new column_t(); thrift_column.columnName = subColumn.name(); thrift_column.value = new String(subColumn.value()); thrift_column.timestamp = subColumn.timestamp(); thrift_superColumn.columns.add(thrift_column); } } retlist.add(thrift_superColumn); } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return retlist; } public superColumn_t get_superColumn(String tablename, String key, String columnFamily_column) throws CassandraException { superColumn_t ret = null; try { validateTable(tablename); String[] values = RowMutation.getColumnAndColumnFamily(columnFamily_column); // check for values if( values.length < 2 ) { throw new CassandraException("Column Family " + columnFamily_column + " is invalid."); } Row row = StorageProxy.readProtocol(tablename, key, columnFamily_column, -1, Integer.MAX_VALUE, StorageService.ConsistencyLevel.WEAK); if (row == null) { logger_.info("ERROR No row for this key .....: " + key); throw new CassandraException("ERROR No row for this key .....: " + key); } Map<String, ColumnFamily> cfMap = row.getColumnFamilyMap(); if (cfMap == null || cfMap.size() == 0) { logger_ .info("ERROR ColumnFamily map is missing.....: " + " key:" + key ); throw new CassandraException("Either the key " + key + " is not present or the columns requested are not present."); } ColumnFamily cfamily = cfMap.get(values[0]); if (cfamily == null) { logger_.info("ERROR ColumnFamily is missing.....: " +" key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("Either the key " + key + " is not present or the columns requested" + columnFamily_column + "are not present."); } Collection<IColumn> columns = cfamily.getAllColumns(); if (columns == null || columns.size() == 0) { logger_ .info("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); throw new CassandraException("ERROR Columns are missing.....: " + " key:" + key + " ColumnFamily:" + values[0]); } for(IColumn column : columns) { ret = new superColumn_t(); ret.name = column.name(); Collection<IColumn> subColumns = column.getSubColumns(); if(subColumns.size() != 0 ) { ret.columns = new ArrayList<column_t>(); for(IColumn subColumn : subColumns) { column_t thrift_column = new column_t(); thrift_column.columnName = subColumn.name(); thrift_column.value = new String(subColumn.value()); thrift_column.timestamp = subColumn.timestamp(); ret.columns.add(thrift_column); } } } } catch (Exception ex) { String exception = LogUtil.throwableToString(ex); logger_.info( exception ); throw new CassandraException(exception); } return ret; } public boolean batch_insert_superColumn_blocking(batch_mutation_super_t batchMutationSuper) { logger_.debug("batch_insert_SuperColumn_blocking"); RowMutation rm = RowMutation.getRowMutation(batchMutationSuper); return StorageProxy.insertBlocking(rm); } public void batch_insert_superColumn(batch_mutation_super_t batchMutationSuper) { logger_.debug("batch_insert_SuperColumn"); RowMutation rm = RowMutation.getRowMutation(batchMutationSuper); StorageProxy.insert(rm); } public String getStringProperty(String propertyName) throws TException { if (propertyName.equals("cluster name")) { return DatabaseDescriptor.getClusterName(); } else if (propertyName.equals("config file")) { String filename = DatabaseDescriptor.getConfigFileName(); try { StringBuffer fileData = new StringBuffer(8192); BufferedInputStream stream = new BufferedInputStream(new FileInputStream(filename)); byte[] buf = new byte[1024]; int numRead; while( (numRead = stream.read(buf)) != -1) { String str = new String(buf, 0, numRead); fileData.append(str); } stream.close(); return fileData.toString(); } catch (IOException e) { return "file not found!"; } } else if (propertyName.equals("version")) { return getVersion(); } else { return "?"; } } public List<String> getStringListProperty(String propertyName) throws TException { if (propertyName.equals("tables")) { return DatabaseDescriptor.getTables(); } else { return new ArrayList<String>(); } } public String describeTable(String tableName) throws TException { String desc = ""; Map<String, CFMetaData> tableMetaData = DatabaseDescriptor.getTableMetaData(tableName); if (tableMetaData == null) { return "Table " + tableName + " not found."; } Iterator iter = tableMetaData.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, CFMetaData> pairs = (Map.Entry<String, CFMetaData>)iter.next(); desc = desc + pairs.getValue().pretty() + "-----\n"; } return desc; } public CqlResult_t executeQuery(String query) throws TException { CqlResult_t result = new CqlResult_t(); CqlResult cqlResult = CqlDriver.executeQuery(query); // convert CQL result type to Thrift specific return type if (cqlResult != null) { result.errorTxt = cqlResult.errorTxt; result.resultSet = cqlResult.resultSet; result.errorCode = cqlResult.errorCode; } return result; } /* * This method is used to ensure that all keys * prior to the specified key, as dtermined by * the SSTable index bucket it falls in, are in * buffer cache. */ public void touch (String key , boolean fData) { try { StorageProxy.touchProtocol(DatabaseDescriptor.getTables().get(0), key, fData, StorageService.ConsistencyLevel.WEAK); } catch ( Exception e) { logger_.info( LogUtil.throwableToString(e) ); } } public String getVersion() { return "1"; } public int getStatus() { return fb_status.ALIVE; } public String getStatusDetails() { return null; } public static void main(String[] args) throws Throwable { int port = 9160; try { CassandraServer peerStorageServer = new CassandraServer(); peerStorageServer.start(); Cassandra.Processor processor = new Cassandra.Processor( peerStorageServer); // Transport TServerSocket tServerSocket = new TServerSocket(port); // Protocol factory TProtocolFactory tProtocolFactory = new TBinaryProtocol.Factory(); // ThreadPool Server Options options = new Options(); options.minWorkerThreads = 64; TThreadPoolServer serverEngine = new TThreadPoolServer(processor, tServerSocket, tProtocolFactory); serverEngine.serve(); } catch (Exception x) { System.err.println("UNCAUGHT EXCEPTION IN main()"); x.printStackTrace(); System.exit(1); } } }
add defaultuncaughtexceptionhandler that logs runtime errors git-svn-id: 1e8683751772dd0ef52a45d586103b4a82d616ff@758994 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/cassandra/service/CassandraServer.java
add defaultuncaughtexceptionhandler that logs runtime errors
<ide><path>rc/org/apache/cassandra/service/CassandraServer.java <ide> { <ide> int port = 9160; <ide> <add> Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() <add> { <add> public void uncaughtException(Thread t, Throwable e) <add> { <add> logger_.error("Fatal exception in thread " + t, e); <add> } <add> }); <add> <ide> try <ide> { <ide> CassandraServer peerStorageServer = new CassandraServer();
JavaScript
bsd-3-clause
670fe4194ed0d9d7e88e78925afa290fedf3762d
0
BhaveshSGupta/FreeCodeCamp,jonathanihm/freeCodeCamp,pahosler/freecodecamp,otavioarc/freeCodeCamp,BhaveshSGupta/FreeCodeCamp,BhaveshSGupta/FreeCodeCamp,jonathanihm/freeCodeCamp,otavioarc/freeCodeCamp,FreeCodeCamp/FreeCodeCamp,pahosler/freecodecamp,raisedadead/FreeCodeCamp,HKuz/FreeCodeCamp,raisedadead/FreeCodeCamp,FreeCodeCamp/FreeCodeCamp,HKuz/FreeCodeCamp
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import ChallengeTitle from './Challenge-Title'; import ChallengeDescription from './Challenge-Description'; import ToolPanel from './Tool-Panel'; import TestSuite from './Test-Suite'; import Spacer from '../../../components/util/Spacer'; import { initConsole, challengeTestsSelector } from '../redux'; import { createSelector } from 'reselect'; import './side-panel.css'; const mapStateToProps = createSelector(challengeTestsSelector, tests => ({ tests })); const mapDispatchToProps = dispatch => bindActionCreators( { initConsole }, dispatch ); const MathJax = global.MathJax; const propTypes = { description: PropTypes.arrayOf(PropTypes.string), guideUrl: PropTypes.string, initConsole: PropTypes.func.isRequired, tests: PropTypes.arrayOf(PropTypes.object), title: PropTypes.string }; export class SidePanel extends PureComponent { constructor(props) { super(props); this.bindTopDiv = this.bindTopDiv.bind(this); MathJax.Hub.Config({ tex2jax: { inlineMath: [['$inlineMath$', '$inlineMath$']] } }); } componentDidMount() { MathJax.Hub.Queue(['Typeset', MathJax.Hub, document.querySelector('.challenge-instructions')]); this.props.initConsole(''); } componentDidUpdate(prevProps) { MathJax.Hub.Queue(['Typeset', MathJax.Hub, document.querySelector('.challenge-instructions')]); const { title, initConsole } = this.props; if (title !== prevProps.title) { initConsole(''); const node = ReactDom.findDOMNode(this.descriptionTop); setTimeout(() => { node.scrollIntoView({ behavior: 'smooth' }); }, 0); } } bindTopDiv(node) { this.descriptionTop = node; } render() { const { title, description, guideUrl, tests } = this.props; return ( <div className='instructions-panel' role='complementary'> <div ref={this.bindTopDiv} /> <Spacer /> <div> <ChallengeTitle>{title}</ChallengeTitle> <ChallengeDescription description={description} /> </div> <ToolPanel guideUrl={guideUrl} /> <TestSuite tests={tests} /> </div> ); } } SidePanel.displayName = 'SidePanel'; SidePanel.propTypes = propTypes; export default connect(mapStateToProps, mapDispatchToProps)(SidePanel);
packages/learn/src/templates/Challenges/components/Side-Panel.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import ChallengeTitle from './Challenge-Title'; import ChallengeDescription from './Challenge-Description'; import ToolPanel from './Tool-Panel'; import TestSuite from './Test-Suite'; import Spacer from '../../../components/util/Spacer'; import { initConsole, challengeTestsSelector } from '../redux'; import { createSelector } from 'reselect'; import './side-panel.css'; const mapStateToProps = createSelector(challengeTestsSelector, tests => ({ tests })); const mapDispatchToProps = dispatch => bindActionCreators( { initConsole }, dispatch ); const MathJax = global.MathJax; const propTypes = { description: PropTypes.arrayOf(PropTypes.string), guideUrl: PropTypes.string, initConsole: PropTypes.func.isRequired, tests: PropTypes.arrayOf(PropTypes.object), title: PropTypes.string }; export class SidePanel extends PureComponent { constructor(props) { super(props); this.bindTopDiv = this.bindTopDiv.bind(this); // MathJax.Hub.Config({ // tex2jax: { inlineMath: [['$', '$'], ['\\(', '\\)']] } // }); MathJax.Hub.Config({ tex2jax: { inlineMath: [['$$', '$$']] } }); } componentDidMount() { MathJax.Hub.Queue(['Typeset', MathJax.Hub, document.querySelector('.challenge-instructions')]); this.props.initConsole(''); } componentDidUpdate(prevProps) { MathJax.Hub.Queue(['Typeset', MathJax.Hub, document.querySelector('.challenge-instructions')]); const { title, initConsole } = this.props; if (title !== prevProps.title) { initConsole(''); const node = ReactDom.findDOMNode(this.descriptionTop); setTimeout(() => { node.scrollIntoView({ behavior: 'smooth' }); }, 0); } } bindTopDiv(node) { this.descriptionTop = node; } render() { const { title, description, guideUrl, tests } = this.props; return ( <div className='instructions-panel' role='complementary'> <div ref={this.bindTopDiv} /> <Spacer /> <div> <ChallengeTitle>{title}</ChallengeTitle> <ChallengeDescription description={description} /> </div> <ToolPanel guideUrl={guideUrl} /> <TestSuite tests={tests} /> </div> ); } } SidePanel.displayName = 'SidePanel'; SidePanel.propTypes = propTypes; export default connect(mapStateToProps, mapDispatchToProps)(SidePanel);
Reimplemented MathJax with custom `$inlineMath$` delimeters to prevent it from rendering SASS and other challenge descriptions as math functions.
packages/learn/src/templates/Challenges/components/Side-Panel.js
Reimplemented MathJax with custom `$inlineMath$` delimeters to prevent it from rendering SASS and other challenge descriptions as math functions.
<ide><path>ackages/learn/src/templates/Challenges/components/Side-Panel.js <ide> constructor(props) { <ide> super(props); <ide> this.bindTopDiv = this.bindTopDiv.bind(this); <del> // MathJax.Hub.Config({ <del> // tex2jax: { inlineMath: [['$', '$'], ['\\(', '\\)']] } <del> // }); <ide> MathJax.Hub.Config({ <del> tex2jax: { inlineMath: [['$$', '$$']] } <add> tex2jax: { inlineMath: [['$inlineMath$', '$inlineMath$']] } <ide> }); <ide> } <ide>
Java
epl-1.0
102cfde44d70cd76c302d6fd73648da47386b1c3
0
bendisposto/prob2-ui,bendisposto/prob2-ui,bendisposto/prob2-ui,bendisposto/prob2-ui
package de.prob2.ui.visualisation; import java.io.File; import java.io.FileNotFoundException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import com.google.inject.Inject; import de.prob.Main; import de.prob.animator.command.ExecuteRightClickCommand; import de.prob.animator.command.GetImagesForMachineCommand; import de.prob.animator.command.GetImagesForStateCommand; import de.prob.animator.command.GetRightClickOptionsForStateVisualizationCommand; import de.prob.statespace.State; import de.prob.statespace.StateSpace; import de.prob.statespace.Trace; import de.prob2.ui.internal.StageManager; import de.prob2.ui.prob2fx.CurrentProject; import de.prob2.ui.prob2fx.CurrentTrace; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; public class StateVisualisationView extends AnchorPane { @FXML private GridPane visualisationGridPane; private final ResourceBundle bundle; private final CurrentProject currentProject; private final CurrentTrace currentTrace; private BooleanProperty visualisationPossible = new SimpleBooleanProperty(false); @Inject public StateVisualisationView(final StageManager stageManager, final ResourceBundle bundle, final CurrentProject currentProject, final CurrentTrace currentTrace) { this.bundle = bundle; this.currentProject = currentProject; this.currentTrace = currentTrace; stageManager.loadFXML(this, "state_visualisation_view.fxml"); } public void visualiseState(State state) throws FileNotFoundException { visualisationGridPane.getChildren().clear(); visualisationPossible.set(false); if (state == null || !state.isInitialised() || currentProject.getCurrentMachine() == null) { return; } StateSpace stateSpace = state.getStateSpace(); GetImagesForMachineCommand getImagesForMachineCommand = new GetImagesForMachineCommand(); stateSpace.execute(getImagesForMachineCommand); Map<Integer, String> images = getImagesForMachineCommand.getImages(); if (!images.isEmpty()) { showImages(state, images); visualisationPossible.set(true); } } public BooleanProperty visualisationPossibleProperty() { return visualisationPossible; } private void showImages(State state, Map<Integer, String> images) throws FileNotFoundException { GetImagesForStateCommand getImagesForStateCommand = new GetImagesForStateCommand(state.getId()); state.getStateSpace().execute(getImagesForStateCommand); Integer[][] imageMatrix = getImagesForStateCommand.getMatrix(); int rowNr = getImagesForStateCommand.getRows(); int columnNr = getImagesForStateCommand.getColumns(); for (int r = 0; r < rowNr; r++) { for (int c = 0; c < columnNr; c++) { Integer imageId = imageMatrix[r][c]; if (imageId != null) { String imageURL = images.get(imageId); Image image = getImage(imageURL); ImageView imageView = new ImageView(image); ContextMenu contextMenu = getContextMenu(state, r, c); imageView.setOnContextMenuRequested( e -> contextMenu.show(imageView, e.getScreenX(), e.getScreenY())); visualisationGridPane.add(imageView, c, r); } } } } private ContextMenu getContextMenu(State state, int row, int column) { ContextMenu contextMenu = new ContextMenu(); if (row>9 || column>9) { // hack: in case there are many images // todo: better improve the performance of ExecuteRightClickCommand or do it on demand final MenuItem item = new MenuItem("Menu disabled for performance reasons"); item.setDisable(true); contextMenu.getItems().add(item); } else { StateSpace stateSpace = state.getStateSpace(); GetRightClickOptionsForStateVisualizationCommand getOptionsCommand = new GetRightClickOptionsForStateVisualizationCommand( state.getId(), row, column); stateSpace.execute(getOptionsCommand); List<String> options = getOptionsCommand.getOptions(); // does this call getOptions in Prolog for every image? for (String opt : options) { final MenuItem item = new MenuItem(opt); Trace trace = getTraceToState(currentTrace.get(), state); if (trace == null) { item.setDisable(true); } item.setOnAction(e -> { ExecuteRightClickCommand executeCommand = new ExecuteRightClickCommand(state.getId(), row, column, opt); stateSpace.execute(executeCommand); String transitionId = executeCommand.getTransitionID(); currentTrace.set(trace.add(transitionId)); }); contextMenu.getItems().add(item); } if (options.isEmpty()) { final MenuItem item = new MenuItem(bundle.getString("visualisation.noRightClickOptions")); item.setDisable(true); contextMenu.getItems().add(item); } } return contextMenu; } private Trace getTraceToState(Trace trace, State state) { if (trace.getCurrentState().equals(state)) { return trace; } else if (trace.canGoBack()) { return getTraceToState(trace.back(), state); } else { return null; } } private Image getImage(String imageURL) throws FileNotFoundException { final Path projectFolder = currentProject.get().getLocation(); // look in machine folder final Path machineFile = currentProject.getCurrentMachine().getPath(); final Path machineFolder = projectFolder.resolve(machineFile).getParent(); File imagePath = machineFolder.resolve(imageURL).toFile(); final File imageInMachineFolder = imagePath; // look in project folder if (!imageInMachineFolder.exists()) { imagePath = projectFolder.resolve(imageURL).toFile(); final File imageInProjectFolder = imagePath; if (!imageInProjectFolder.exists()) { // look in ProB folder imagePath = Paths.get(Main.getProBDirectory()).resolve(imageURL).toFile(); final File imageInProbFolder = imagePath; if (!imageInProbFolder.exists()) { throw new FileNotFoundException(String.format(bundle.getString("visualisation.error.imageNotFound"), imagePath.getName(), imageInMachineFolder.getParent(), imageInProjectFolder.getParent(), imageInProbFolder.getParent())); } } } return new Image(imagePath.toURI().toString()); } }
src/main/java/de/prob2/ui/visualisation/StateVisualisationView.java
package de.prob2.ui.visualisation; import java.io.File; import java.io.FileNotFoundException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import com.google.inject.Inject; import de.prob.Main; import de.prob.animator.command.ExecuteRightClickCommand; import de.prob.animator.command.GetImagesForMachineCommand; import de.prob.animator.command.GetImagesForStateCommand; import de.prob.animator.command.GetRightClickOptionsForStateVisualizationCommand; import de.prob.statespace.State; import de.prob.statespace.StateSpace; import de.prob.statespace.Trace; import de.prob2.ui.internal.StageManager; import de.prob2.ui.prob2fx.CurrentProject; import de.prob2.ui.prob2fx.CurrentTrace; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; public class StateVisualisationView extends AnchorPane { @FXML private GridPane visualisationGridPane; private final ResourceBundle bundle; private final CurrentProject currentProject; private final CurrentTrace currentTrace; private BooleanProperty visualisationPossible = new SimpleBooleanProperty(false); @Inject public StateVisualisationView(final StageManager stageManager, final ResourceBundle bundle, final CurrentProject currentProject, final CurrentTrace currentTrace) { this.bundle = bundle; this.currentProject = currentProject; this.currentTrace = currentTrace; stageManager.loadFXML(this, "state_visualisation_view.fxml"); } public void visualiseState(State state) throws FileNotFoundException { visualisationGridPane.getChildren().clear(); visualisationPossible.set(false); if (state == null || !state.isInitialised() || currentProject.getCurrentMachine() == null) { return; } StateSpace stateSpace = state.getStateSpace(); GetImagesForMachineCommand getImagesForMachineCommand = new GetImagesForMachineCommand(); stateSpace.execute(getImagesForMachineCommand); Map<Integer, String> images = getImagesForMachineCommand.getImages(); if (!images.isEmpty()) { showImages(state, images); visualisationPossible.set(true); } } public BooleanProperty visualisationPossibleProperty() { return visualisationPossible; } private void showImages(State state, Map<Integer, String> images) throws FileNotFoundException { GetImagesForStateCommand getImagesForStateCommand = new GetImagesForStateCommand(state.getId()); state.getStateSpace().execute(getImagesForStateCommand); Integer[][] imageMatrix = getImagesForStateCommand.getMatrix(); int rowNr = getImagesForStateCommand.getRows(); int columnNr = getImagesForStateCommand.getColumns(); for (int r = 0; r < rowNr; r++) { for (int c = 0; c < columnNr; c++) { Integer imageId = imageMatrix[r][c]; if (imageId != null) { String imageURL = images.get(imageId); Image image = getImage(imageURL); ImageView imageView = new ImageView(image); ContextMenu contextMenu = getContextMenu(state, r, c); imageView.setOnContextMenuRequested( e -> contextMenu.show(imageView, e.getScreenX(), e.getScreenY())); visualisationGridPane.add(imageView, c, r); } } } } private ContextMenu getContextMenu(State state, int row, int column) { StateSpace stateSpace = state.getStateSpace(); ContextMenu contextMenu = new ContextMenu(); GetRightClickOptionsForStateVisualizationCommand getOptionsCommand = new GetRightClickOptionsForStateVisualizationCommand( state.getId(), row, column); stateSpace.execute(getOptionsCommand); List<String> options = getOptionsCommand.getOptions(); for (String opt : options) { final MenuItem item = new MenuItem(opt); Trace trace = getTraceToState(currentTrace.get(), state); if (trace == null) { item.setDisable(true); } item.setOnAction(e -> { ExecuteRightClickCommand executeCommand = new ExecuteRightClickCommand(state.getId(), row, column, opt); stateSpace.execute(executeCommand); String transitionId = executeCommand.getTransitionID(); currentTrace.set(trace.add(transitionId)); }); contextMenu.getItems().add(item); } if (options.isEmpty()) { final MenuItem item = new MenuItem(bundle.getString("visualisation.noRightClickOptions")); item.setDisable(true); contextMenu.getItems().add(item); } return contextMenu; } private Trace getTraceToState(Trace trace, State state) { if (trace.getCurrentState().equals(state)) { return trace; } else if (trace.canGoBack()) { return getTraceToState(trace.back(), state); } else { return null; } } private Image getImage(String imageURL) throws FileNotFoundException { final Path projectFolder = currentProject.get().getLocation(); // look in machine folder final Path machineFile = currentProject.getCurrentMachine().getPath(); final Path machineFolder = projectFolder.resolve(machineFile).getParent(); File imagePath = machineFolder.resolve(imageURL).toFile(); final File imageInMachineFolder = imagePath; // look in project folder if (!imageInMachineFolder.exists()) { imagePath = projectFolder.resolve(imageURL).toFile(); final File imageInProjectFolder = imagePath; if (!imageInProjectFolder.exists()) { // look in ProB folder imagePath = Paths.get(Main.getProBDirectory()).resolve(imageURL).toFile(); final File imageInProbFolder = imagePath; if (!imageInProbFolder.exists()) { throw new FileNotFoundException(String.format(bundle.getString("visualisation.error.imageNotFound"), imagePath.getName(), imageInMachineFolder.getParent(), imageInProjectFolder.getParent(), imageInProbFolder.getParent())); } } } return new Image(imagePath.toURI().toString()); } }
avoid calling ExecuteRightClickCommand when there are many images in the Tk visualisation; temporary fix for PROB2UI-228
src/main/java/de/prob2/ui/visualisation/StateVisualisationView.java
avoid calling ExecuteRightClickCommand when there are many
<ide><path>rc/main/java/de/prob2/ui/visualisation/StateVisualisationView.java <ide> } <ide> <ide> private ContextMenu getContextMenu(State state, int row, int column) { <del> StateSpace stateSpace = state.getStateSpace(); <ide> ContextMenu contextMenu = new ContextMenu(); <del> GetRightClickOptionsForStateVisualizationCommand getOptionsCommand = new GetRightClickOptionsForStateVisualizationCommand( <del> state.getId(), row, column); <del> stateSpace.execute(getOptionsCommand); <del> List<String> options = getOptionsCommand.getOptions(); <del> for (String opt : options) { <del> final MenuItem item = new MenuItem(opt); <del> Trace trace = getTraceToState(currentTrace.get(), state); <del> if (trace == null) { <del> item.setDisable(true); <del> } <del> item.setOnAction(e -> { <del> ExecuteRightClickCommand executeCommand = new ExecuteRightClickCommand(state.getId(), row, column, opt); <del> stateSpace.execute(executeCommand); <del> String transitionId = executeCommand.getTransitionID(); <del> currentTrace.set(trace.add(transitionId)); <del> }); <del> contextMenu.getItems().add(item); <del> } <del> if (options.isEmpty()) { <del> final MenuItem item = new MenuItem(bundle.getString("visualisation.noRightClickOptions")); <add> if (row>9 || column>9) { <add> // hack: in case there are many images <add> // todo: better improve the performance of ExecuteRightClickCommand or do it on demand <add> final MenuItem item = new MenuItem("Menu disabled for performance reasons"); <ide> item.setDisable(true); <ide> contextMenu.getItems().add(item); <add> } else <add> { <add> StateSpace stateSpace = state.getStateSpace(); <add> GetRightClickOptionsForStateVisualizationCommand getOptionsCommand = new GetRightClickOptionsForStateVisualizationCommand( <add> state.getId(), row, column); <add> stateSpace.execute(getOptionsCommand); <add> List<String> options = getOptionsCommand.getOptions(); // does this call getOptions in Prolog for every image? <add> for (String opt : options) { <add> final MenuItem item = new MenuItem(opt); <add> Trace trace = getTraceToState(currentTrace.get(), state); <add> if (trace == null) { <add> item.setDisable(true); <add> } <add> item.setOnAction(e -> { <add> ExecuteRightClickCommand executeCommand = new ExecuteRightClickCommand(state.getId(), row, column, opt); <add> stateSpace.execute(executeCommand); <add> String transitionId = executeCommand.getTransitionID(); <add> currentTrace.set(trace.add(transitionId)); <add> }); <add> contextMenu.getItems().add(item); <add> } <add> if (options.isEmpty()) { <add> final MenuItem item = new MenuItem(bundle.getString("visualisation.noRightClickOptions")); <add> item.setDisable(true); <add> contextMenu.getItems().add(item); <add> } <ide> } <ide> return contextMenu; <ide> }
JavaScript
mit
48b89af6e151127bf2c809514c60f0fd71bc8bdd
0
torgartor21/mfl_admin_web,MasterFacilityList/mfl_admin_web,torgartor21/mfl_admin_web,MasterFacilityList/mfl_admin_web,MasterFacilityList/mfl_admin_web,torgartor21/mfl_admin_web,MasterFacilityList/mfl_admin_web,torgartor21/mfl_admin_web
(function (angular, _) { "use strict"; angular.module("mfl.reports.controllers.facility_reporting", [ "mfl.reports.services" ]) .controller("mfl.reports.controllers.helper", ["mfl.reports.services.wrappers", function(wrappers){ this.initCtrl = function($scope, report_type, data_param, transform_fxn){ $scope.search = ""; $scope.filters = { "report_type":report_type }; wrappers.reporting.filter($scope.filters) .success(function (data) { var transform = transform_fxn || _.identity; $scope[data_param] = transform(data.results, $scope); }) .error(function (err) { $scope.errors = err; }); }; } ]) .controller("mfl.reports.controllers.facility_counties", ["$scope", "$controller", function($scope, $controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_county", "county_facilities"); } ]) .controller("mfl.reports.controllers.facility_constituencies", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_consituency", "const_facilities"); } ]) .controller("mfl.reports.controllers.facility_types", ["$scope","$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_facility_type", "type_facilities"); } ]) .controller("mfl.reports.controllers.facility_owner_categories", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_owner_category", "owner_cat_facilities"); } ]) .controller("mfl.reports.controllers.facility_owners", ["$scope","$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_owner", "owner_facilities"); } ]) .controller("mfl.reports.controllers.keph_levels", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); var results_transform = function (results, $scope) { var data = _.groupBy(results, function (a) {return a.county;}); $scope.counties = _.keys(data); return _.map($scope.counties, function (c) { return { "county": c, "facilities": data[c] }; }); }; helper.initCtrl($scope, "facility_keph_level_report", "keph_facilities", results_transform); } ]) .controller("mfl.reports.controllers.county_facility_types", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_facility_type_detailed", "county_types_facilities"); } ]) .controller("mfl.reports.controllers.county_constituencies", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_constituency_report", "county_constituencies_facilities"); } ]); })(window.angular, window._);
src/app/reports/controllers/facility_reporting.js
(function (angular) { "use strict"; angular.module("mfl.reports.controllers.facility_reporting", [ "mfl.reports.services" ]) .controller("mfl.reports.controllers.helper", ["mfl.reports.services.wrappers", function(wrappers){ this.initCtrl = function($scope, report_type, data_param){ $scope.search = ""; $scope.filters = { "report_type":report_type }; wrappers.reporting.filter($scope.filters) .success(function (data) { $scope[data_param] = data.results; }) .error(function (err) { $scope.errors = err; }); }; } ]) .controller("mfl.reports.controllers.facility_counties", ["$scope", "$controller", function($scope, $controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_county", "county_facilities"); } ]) .controller("mfl.reports.controllers.facility_constituencies", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_consituency", "const_facilities"); } ]) .controller("mfl.reports.controllers.facility_types", ["$scope","$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_facility_type", "type_facilities"); } ]) .controller("mfl.reports.controllers.facility_owner_categories", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_owner_category", "owner_cat_facilities"); } ]) .controller("mfl.reports.controllers.facility_owners", ["$scope","$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_owner", "owner_facilities"); } ]) .controller("mfl.reports.controllers.keph_levels", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_keph_level_report", "keph_facilities"); } ]) .controller("mfl.reports.controllers.county_facility_types", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_count_by_facility_type_detailed", "county_types_facilities"); } ]) .controller("mfl.reports.controllers.county_constituencies", ["$scope", "$controller", function($scope,$controller){ var helper = $controller("mfl.reports.controllers.helper"); helper.initCtrl($scope, "facility_constituency_report", "county_constituencies_facilities"); } ]); })(window.angular);
add report transforms
src/app/reports/controllers/facility_reporting.js
add report transforms
<ide><path>rc/app/reports/controllers/facility_reporting.js <del>(function (angular) { <add>(function (angular, _) { <ide> <ide> "use strict"; <ide> <ide> <ide> .controller("mfl.reports.controllers.helper", ["mfl.reports.services.wrappers", <ide> function(wrappers){ <del> this.initCtrl = function($scope, report_type, data_param){ <add> this.initCtrl = function($scope, report_type, data_param, transform_fxn){ <ide> $scope.search = ""; <ide> $scope.filters = { <ide> "report_type":report_type <ide> }; <ide> wrappers.reporting.filter($scope.filters) <ide> .success(function (data) { <del> $scope[data_param] = data.results; <add> var transform = transform_fxn || _.identity; <add> $scope[data_param] = transform(data.results, $scope); <ide> }) <ide> .error(function (err) { <ide> $scope.errors = err; <ide> "$controller", <ide> function($scope,$controller){ <ide> var helper = $controller("mfl.reports.controllers.helper"); <add> var results_transform = function (results, $scope) { <add> var data = _.groupBy(results, function (a) {return a.county;}); <add> $scope.counties = _.keys(data); <add> return _.map($scope.counties, function (c) { <add> return { <add> "county": c, <add> "facilities": data[c] <add> }; <add> }); <add> }; <ide> helper.initCtrl($scope, "facility_keph_level_report", <del> "keph_facilities"); <add> "keph_facilities", results_transform); <ide> } <ide> ]) <ide> .controller("mfl.reports.controllers.county_facility_types", ["$scope", <ide> "county_constituencies_facilities"); <ide> } <ide> ]); <del>})(window.angular); <add>})(window.angular, window._);
JavaScript
mit
81a825a4fa4945ab98acc4abb81f15c1ed1db025
0
mikemaccana/styleselect,mikemaccana/styleselect
define(function() { var VisualSelect = function(selector) { // Quick aliases var query = document.querySelector.bind(document); var queryAll = document.querySelectorAll.bind(document); if ( ! NodeList.prototype.forEach ) { NodeList.prototype.forEach = Array.prototype.forEach; } var log = console.log.bind(console) var queryChildren = function(elem, children) { return query(elem).querySelectorAll(':scope ' + children) }; var body = document.body, select = query(selectId), options = queryChildren(selectId, 'option'), uuid = 'vs-xxxx-xxxx-xxxx-xxxx-xxxx'.replace( /[xy]/g, function(c) { var r = Math.random() * 16|0, v = c == 'x'? r : r&0x3|0x8; return v.toString(16); } ), vs_select_html = '<div class="visual-select" data-vs-uuid="' + uuid + '">'; select.setAttribute('data-vs-uuid', uuid); for (var i = 0; i < options.length; i++) { var html = options[i].innerHTML, text = options[i].innerText, attr = options[i].attributes, val = options[i].getAttribute('value') === null ? '' : options[i].getAttribute('value'); if (i === 0) { // log('Default option', '"' + text + '"'); vs_select_html += '<div class="vs-default-option" data-value="' + val + '">' + html + '</div>' + '<ul class="">' + '<li class="vs-option" data-value="' + val + '">' + html + '</li>'; } else { vs_select_html += '<li class="vs-option" data-value="' + val + '">' + html + '</li>'; } }; vs_select_html += '</ul></div>'; select.insertAdjacentHTML('afterend', vs_select_html); // Event listeners var vs_container = query('[data-vs-uuid]'), vs_options = queryAll('[data-vs-uuid] li'); for (var i = 0; i < vs_options.length; i++) { var vs_option = vs_options.item(i); vs_option.addEventListener('click', function(ev) { var target = ev.target, uuid = target.parentNode.parentNode.getAttribute('data-vs-uuid'); query('select[data-vs-uuid="' + uuid + '"]').value = target.getAttribute('data-value'); query('.visual-select[data-vs-uuid="' + uuid +'"] .vs-default-option').innerHTML = target.innerText; // log('Target text', target.innerText) target.parentNode.parentNode.classList.remove('open'); // log('New select - ' + uuid + ' value', query('select[data-vs-uuid="' + uuid + '"]').value); }); }; query('.visual-select[data-vs-uuid="' + uuid + '"] .vs-default-option').addEventListener('click', function(ev) { ev.preventDefault(); ev.stopPropagation(); // Close all Visual Selects queryAll('.visual-select').forEach(function(vs) { vs.classList.remove('open'); }); // log('Visual Select open'); var target = ev.target; // log('Target', target.parentNode); target.parentNode.classList.add('open'); var close = document.addEventListener('click', function(ev) { ev.preventDefault(); ev.stopPropagation(); var closeTarget = ev.target; if (!closeTarget.classList.contains('vs-option', 'vs-default-option')) { // log('%cClose ', 'color: red;'); queryAll('.visual-select').forEach(function(vs) { vs.classList.remove('open'); }); } }); }); }; return VisualSelect });
js/visualselect.js
define([ 'waves/utils' ], function() { var VisualSelect = function(selectId) { var body = document.body, select = query(selectId), options = queryChildren(selectId, 'option'), uuid = 'vs-xxxx-xxxx-xxxx-xxxx-xxxx'.replace( /[xy]/g, function(c) { var r = Math.random() * 16|0, v = c == 'x'? r : r&0x3|0x8; return v.toString(16); } ), vs_select_html = '<div class="visual-select" data-vs-uuid="' + uuid + '">'; select.setAttribute('data-vs-uuid', uuid); for (var i = 0; i < options.length; i++) { var html = options[i].innerHTML, text = options[i].innerText, attr = options[i].attributes, val = options[i].getAttribute('value') === null ? '' : options[i].getAttribute('value'); if (i === 0) { // log('Default option', '"' + text + '"'); vs_select_html += '<div class="vs-default-option" data-value="' + val + '">' + html + '</div>' + '<ul class="">' + '<li class="vs-option" data-value="' + val + '">' + html + '</li>'; } else { vs_select_html += '<li class="vs-option" data-value="' + val + '">' + html + '</li>'; } }; vs_select_html += '</ul></div>'; select.insertAdjacentHTML('afterend', vs_select_html); // Event listeners var vs_container = query('[data-vs-uuid]'), vs_options = queryAll('[data-vs-uuid] li'); for (var i = 0; i < vs_options.length; i++) { var vs_option = vs_options.item(i); vs_option.addEventListener('click', function(ev) { var target = ev.target, uuid = target.parentNode.parentNode.getAttribute('data-vs-uuid'); query('select[data-vs-uuid="' + uuid + '"]').value = target.getAttribute('data-value'); query('.visual-select[data-vs-uuid="' + uuid +'"] .vs-default-option').innerHTML = target.innerText; // log('Target text', target.innerText) target.parentNode.parentNode.classList.remove('open'); // log('New select - ' + uuid + ' value', query('select[data-vs-uuid="' + uuid + '"]').value); }); }; query('.visual-select[data-vs-uuid="' + uuid + '"] .vs-default-option').addEventListener('click', function(ev) { ev.preventDefault(); ev.stopPropagation(); // Close all Visual Selects queryAll('.visual-select').forEach(function(vs) { vs.classList.remove('open'); }); // log('Visual Select open'); var target = ev.target; // log('Target', target.parentNode); target.parentNode.classList.add('open'); var close = document.addEventListener('click', function(ev) { ev.preventDefault(); ev.stopPropagation(); var closeTarget = ev.target; if (!closeTarget.classList.contains('vs-option', 'vs-default-option')) { // log('%cClose ', 'color: red;'); queryAll('.visual-select').forEach(function(vs) { vs.classList.remove('open'); }); } }); }); }; return VisualSelect });
Add required utility functions so visualselect is standalone
js/visualselect.js
Add required utility functions so visualselect is standalone
<ide><path>s/visualselect.js <del>define([ <del> 'waves/utils' <del>], function() { <add>define(function() { <add> var VisualSelect = function(selector) { <ide> <del> var VisualSelect = function(selectId) { <add> // Quick aliases <add> var query = document.querySelector.bind(document); <add> var queryAll = document.querySelectorAll.bind(document); <add> if ( ! NodeList.prototype.forEach ) { <add> NodeList.prototype.forEach = Array.prototype.forEach; <add> } <add> var log = console.log.bind(console) <add> <add> <add> var queryChildren = function(elem, children) { <add> return query(elem).querySelectorAll(':scope ' + children) <add> }; <ide> <ide> var body = document.body, <ide> select = query(selectId),
Java
apache-2.0
b27f53d8a107aad65c013c94ec928a6c8a98bf0e
0
kidaa/realm-java,santoshmehta82/realm-java,teddywest32/realm-java,avipars/realm-java,realm/realm-java,ppamorim/realm-java,androiddream/realm-java,JetXing/realm-java,kidaa/realm-java,arunlodhi/realm-java,angcyo/realm-java,dantman/realm-java,santoshmehta82/realm-java,GeorgeMe/realm-java,androiddream/realm-java,JetXing/realm-java,GavinThePacMan/realm-java,Ryan800/realm-java,awesome-niu/realm-java,teddywest32/realm-java,FabianTerhorst/realm-java,GeorgeMe/realm-java,msdgwzhy6/realm-java,Rowandjj/realm-java,awesome-niu/realm-java,angcyo/realm-java,avipars/realm-java,DuongNTdev/realm-java,FabianTerhorst/realm-java,teddywest32/realm-java,ShikaSD/realm-java,msdgwzhy6/realm-java,nartex/realm-java,davicaetano/realm-java,cpinan/realm-java,ppamorim/realm-java,mobileperfman/realm-java,dantman/realm-java,realm/realm-java,dantman/realm-java,yuuki1224/realm-java,yuuki1224/realm-java,xxccll/realm-java,mio4kon/realm-java,davicaetano/realm-java,ShikaSD/realm-java,bunnyblue/realm-java,nartex/realm-java,alwakelab/realm-java,myroid/realm-java,santoshmehta82/realm-java,GeorgeMe/realm-java,myroid/realm-java,hgl888/realm-java,bunnyblue/realm-java,msdgwzhy6/realm-java,GeorgeMe/realm-java,ShikaSD/realm-java,alwakelab/realm-java,bunnyblue/realm-java,nartex/realm-java,yuuki1224/realm-java,Rowandjj/realm-java,DuongNTdev/realm-java,mio4kon/realm-java,DuongNTdev/realm-java,horie1024/realm-java,Ryan800/realm-java,ShikaSD/realm-java,ppamorim/realm-java,hgl888/realm-java,GavinThePacMan/realm-java,arunlodhi/realm-java,arunlodhi/realm-java,mobileperfman/realm-java,horie1024/realm-java,Rowandjj/realm-java,qingsong-xu/realm-java,GavinThePacMan/realm-java,Ryan800/realm-java,JetXing/realm-java,mio4kon/realm-java,davicaetano/realm-java,cpinan/realm-java,androiddream/realm-java,ShikaSD/realm-java,thdtjsdn/realm-java,realm/realm-java,awesome-niu/realm-java,awesome-niu/realm-java,qingsong-xu/realm-java,ppamorim/realm-java,qingsong-xu/realm-java,mobileperfman/realm-java,ysnows/realm-java,alwakelab/realm-java,realm/realm-java,myroid/realm-java,horie1024/realm-java,avipars/realm-java,ysnows/realm-java,DuongNTdev/realm-java,teddywest32/realm-java,xxccll/realm-java,ysnows/realm-java,angcyo/realm-java,msdgwzhy6/realm-java,hgl888/realm-java,thdtjsdn/realm-java,thdtjsdn/realm-java,angcyo/realm-java,thdtjsdn/realm-java,cpinan/realm-java,realm/realm-java,xxccll/realm-java,kidaa/realm-java,teddywest32/realm-java,realm/realm-java,FabianTerhorst/realm-java,hgl888/realm-java,realm/realm-java,GavinThePacMan/realm-java
package com.tightdb.lib; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.nio.ByteBuffer; import java.util.Date; import org.testng.annotations.Test; import com.tightdb.Mixed; import com.tightdb.example.generated.Employee; import com.tightdb.example.generated.EmployeeQuery; import com.tightdb.example.generated.EmployeeView; import com.tightdb.test.EmployeesFixture; public class CursorColumnsTest extends AbstractTest { @Test public void shouldGetCorrectColumnValues() throws IllegalAccessException { Employee employee0 = employees.first(); checkCursor(EmployeesFixture.EMPLOYEES[0], employee0); Employee employee1 = employees.at(1); checkCursor(EmployeesFixture.EMPLOYEES[1], employee1); Employee employee2 = employee1.next(); checkCursor(EmployeesFixture.EMPLOYEES[2], employee2); } @Test public void shouldSetAndGetCorrectColumnValues() { checkSetAndGetCorrectColumnValues(employees); checkSetAndGetCorrectColumnValues(employeesView); } private void checkSetAndGetCorrectColumnValues( AbstractRowset<Employee, EmployeeView, EmployeeQuery> empls) { Employee employee0 = empls.first(); checkCursor(EmployeesFixture.EMPLOYEES[0], employee0); updateEmployee(employee0, EmployeesFixture.EMPLOYEES[2]); checkCursor(EmployeesFixture.EMPLOYEES[2], employee0); updateEmployee(employee0, EmployeesFixture.EMPLOYEES[1]); checkCursor(EmployeesFixture.EMPLOYEES[1], employee0); checkCursor(EmployeesFixture.EMPLOYEES[1], empls.first()); } @Test public void shouldSetAndGetMixedValues() throws Exception { checkSetAndGetMixedValues(employees); checkSetAndGetMixedValues(employeesView); } private void checkSetAndGetMixedValues(AbstractRowset<Employee, EmployeeView, EmployeeQuery> empls) throws Exception { Employee employee = empls.first(); employee.extra.set(true); assertEquals(true, employee.extra.get().getBooleanValue()); byte[] arr = { 1, 3, 5 }; employee.extra.set(arr); // FIXME: shouldn't be BINARY_TYPE_BYTE_ARRAY an expected type here? assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get() .getBinaryType()); assertEquals(ByteBuffer.wrap(arr), employee.extra.get() .getBinaryValue()); ByteBuffer buf = ByteBuffer.allocateDirect(3); byte[] arr2 = { 10, 20, 30 }; buf.put(arr2); employee.extra.set(buf); assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get() .getBinaryType()); assertEquals(ByteBuffer.wrap(arr2), employee.extra.get() .getBinaryValue()); Date date = new Date(6547); employee.extra.set(date); assertEquals(date, employee.extra.get().getDateValue()); long num = 135L; employee.extra.set(num); assertEquals(num, employee.extra.get().getLongValue()); Mixed mixed = Mixed.mixedValue("mixed"); employee.extra.set(mixed); assertEquals(mixed, employee.extra.get()); employee.extra.set("abc"); assertEquals("abc", employee.extra.get().getStringValue()); } @Test(expectedExceptions = UnsupportedOperationException.class) public void shouldntSetTableValue() { // the "set" operation is not supported yet for sub-table columns employees.first().phones.set(employees.last().phones.get()); } public void shouldProvideReadableValue() { Employee employee = employees.first(); assertNotNull(employee.firstName.getReadableValue()); assertNotNull(employee.lastName.getReadableValue()); assertNotNull(employee.salary.getReadableValue()); assertNotNull(employee.driver.getReadableValue()); assertNotNull(employee.photo.getReadableValue()); assertNotNull(employee.birthdate.getReadableValue()); assertNotNull(employee.extra.getReadableValue()); assertNotNull(employee.phones.getReadableValue()); } }
src/test/java/com/tightdb/lib/CursorColumnsTest.java
package com.tightdb.lib; import static org.testng.AssertJUnit.*; import java.nio.ByteBuffer; import java.util.Date; import org.testng.annotations.Test; import com.tightdb.Mixed; import com.tightdb.example.generated.Employee; import com.tightdb.example.generated.PhoneTable; import com.tightdb.test.EmployeesFixture; public class CursorColumnsTest extends AbstractTest { @Test public void shouldGetCorrectColumnValues() throws IllegalAccessException { Employee employee0 = employees.first(); checkCursor(EmployeesFixture.EMPLOYEES[0], employee0); Employee employee1 = employees.at(1); checkCursor(EmployeesFixture.EMPLOYEES[1], employee1); Employee employee2 = employee1.next(); checkCursor(EmployeesFixture.EMPLOYEES[2], employee2); } @Test public void shouldSetAndGetCorrectColumnValues() { Employee employee0 = employees.first(); checkCursor(EmployeesFixture.EMPLOYEES[0], employee0); // FIXME: Fails with exception. You can't currently use // ByteBuffer.wrap(byte[]) for binary data - it creates a // "HeapByteBuffer" updateEmployee(employee0, EmployeesFixture.EMPLOYEES[2]); checkCursor(EmployeesFixture.EMPLOYEES[2], employee0); updateEmployee(employee0, EmployeesFixture.EMPLOYEES[1]); checkCursor(EmployeesFixture.EMPLOYEES[1], employee0); checkCursor(EmployeesFixture.EMPLOYEES[1], employees.first()); } @Test public void shouldSetAndGetMixedValues() throws Exception { Employee employee = employees.first(); employee.extra.set(true); assertEquals(true, employee.extra.get().getBooleanValue()); byte[] arr = { 1, 3, 5 }; employee.extra.set(arr); // FIXME: shouldn't be BINARY_TYPE_BYTE_ARRAY an expected type here? assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get().getBinaryType()); assertEquals(ByteBuffer.wrap(arr), employee.extra.get().getBinaryValue()); ByteBuffer buf = ByteBuffer.allocateDirect(3); byte[] arr2 = { 10, 20, 30 }; buf.put(arr2); employee.extra.set(buf); assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get().getBinaryType()); assertEquals(ByteBuffer.wrap(arr2), employee.extra.get().getBinaryValue()); Date date = new Date(6547); employee.extra.set(date); assertEquals(date, employee.extra.get().getDateValue()); long num = 135L; employee.extra.set(num); assertEquals(num, employee.extra.get().getLongValue()); Mixed mixed = Mixed.mixedValue("mixed"); employee.extra.set(mixed); assertEquals(mixed, employee.extra.get()); employee.extra.set("abc"); assertEquals("abc", employee.extra.get().getStringValue()); } @Test(expectedExceptions = UnsupportedOperationException.class) public void shouldntSetTableValue() { // the "set" operation is not supported yet for sub-table columns employees.first().phones.set(employees.last().phones.get()); } public void shouldProvideReadableValue() { Employee employee = employees.first(); assertNotNull(employee.firstName.getReadableValue()); assertNotNull(employee.lastName.getReadableValue()); assertNotNull(employee.salary.getReadableValue()); assertNotNull(employee.driver.getReadableValue()); assertNotNull(employee.photo.getReadableValue()); assertNotNull(employee.birthdate.getReadableValue()); assertNotNull(employee.extra.getReadableValue()); assertNotNull(employee.phones.getReadableValue()); } }
Improved column operations tests to exercise the view columns, too.
src/test/java/com/tightdb/lib/CursorColumnsTest.java
Improved column operations tests to exercise the view columns, too.
<ide><path>rc/test/java/com/tightdb/lib/CursorColumnsTest.java <ide> package com.tightdb.lib; <ide> <del>import static org.testng.AssertJUnit.*; <add>import static org.testng.AssertJUnit.assertEquals; <add>import static org.testng.AssertJUnit.assertNotNull; <ide> <ide> import java.nio.ByteBuffer; <ide> import java.util.Date; <ide> <ide> import com.tightdb.Mixed; <ide> import com.tightdb.example.generated.Employee; <del>import com.tightdb.example.generated.PhoneTable; <add>import com.tightdb.example.generated.EmployeeQuery; <add>import com.tightdb.example.generated.EmployeeView; <ide> import com.tightdb.test.EmployeesFixture; <ide> <ide> public class CursorColumnsTest extends AbstractTest { <ide> <ide> @Test <ide> public void shouldSetAndGetCorrectColumnValues() { <del> Employee employee0 = employees.first(); <add> checkSetAndGetCorrectColumnValues(employees); <add> checkSetAndGetCorrectColumnValues(employeesView); <add> } <add> <add> private void checkSetAndGetCorrectColumnValues( <add> AbstractRowset<Employee, EmployeeView, EmployeeQuery> empls) { <add> Employee employee0 = empls.first(); <ide> checkCursor(EmployeesFixture.EMPLOYEES[0], employee0); <ide> <del> // FIXME: Fails with exception. You can't currently use <del> // ByteBuffer.wrap(byte[]) for binary data - it creates a <del> // "HeapByteBuffer" <ide> updateEmployee(employee0, EmployeesFixture.EMPLOYEES[2]); <del> <ide> checkCursor(EmployeesFixture.EMPLOYEES[2], employee0); <ide> <ide> updateEmployee(employee0, EmployeesFixture.EMPLOYEES[1]); <ide> checkCursor(EmployeesFixture.EMPLOYEES[1], employee0); <del> checkCursor(EmployeesFixture.EMPLOYEES[1], employees.first()); <add> checkCursor(EmployeesFixture.EMPLOYEES[1], empls.first()); <ide> } <ide> <ide> @Test <ide> public void shouldSetAndGetMixedValues() throws Exception { <del> Employee employee = employees.first(); <add> checkSetAndGetMixedValues(employees); <add> checkSetAndGetMixedValues(employeesView); <add> } <add> <add> private void checkSetAndGetMixedValues(AbstractRowset<Employee, EmployeeView, EmployeeQuery> empls) throws Exception { <add> Employee employee = empls.first(); <ide> <ide> employee.extra.set(true); <ide> assertEquals(true, employee.extra.get().getBooleanValue()); <ide> byte[] arr = { 1, 3, 5 }; <ide> employee.extra.set(arr); <ide> // FIXME: shouldn't be BINARY_TYPE_BYTE_ARRAY an expected type here? <del> assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get().getBinaryType()); <del> assertEquals(ByteBuffer.wrap(arr), employee.extra.get().getBinaryValue()); <add> assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get() <add> .getBinaryType()); <add> assertEquals(ByteBuffer.wrap(arr), employee.extra.get() <add> .getBinaryValue()); <ide> <ide> ByteBuffer buf = ByteBuffer.allocateDirect(3); <ide> byte[] arr2 = { 10, 20, 30 }; <ide> buf.put(arr2); <ide> employee.extra.set(buf); <del> assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get().getBinaryType()); <del> assertEquals(ByteBuffer.wrap(arr2), employee.extra.get().getBinaryValue()); <add> assertEquals(Mixed.BINARY_TYPE_BYTE_BUFFER, employee.extra.get() <add> .getBinaryType()); <add> assertEquals(ByteBuffer.wrap(arr2), employee.extra.get() <add> .getBinaryValue()); <ide> <ide> Date date = new Date(6547); <ide> employee.extra.set(date); <ide> <ide> public void shouldProvideReadableValue() { <ide> Employee employee = employees.first(); <del> <add> <ide> assertNotNull(employee.firstName.getReadableValue()); <ide> assertNotNull(employee.lastName.getReadableValue()); <ide> assertNotNull(employee.salary.getReadableValue()); <ide> assertNotNull(employee.extra.getReadableValue()); <ide> assertNotNull(employee.phones.getReadableValue()); <ide> } <del> <add> <ide> }
Java
apache-2.0
e2367fafc8c447220dc49dfa39b9f4a9078182f4
0
justinjose28/Hystrix,daveray/Hystrix,gorcz/Hystrix,mattrjacobs/Hystrix,eunmin/Hystrix,thomasandersen77/Hystrix,yshaojie/Hystrix,sasrin/Hystrix,yshaojie/Hystrix,sasrin/Hystrix,mebigfatguy/Hystrix,sposam/Hystrix,thomasandersen77/Hystrix,yshaojie/Hystrix,jordancheah/Hystrix,sensaid/Hystrix,wangsan/Hystrix,thomasandersen77/Hystrix,rukor/Hystrix,sposam/Hystrix,agentgt/Hystrix,fredboutin/Hystrix,loop-jazz/Hystrix,pcssi/Hystrix,KoltonAndrus/Hystrix,wangsan/Hystrix,sasrin/Hystrix,robertroeser/Hystrix,Siddartha07/Hystrix,ianynchen/Hystrix,Fsero/Hystrix,daveray/Hystrix,robertroeser/Hystrix,justinjose28/Hystrix,reboss/Hystrix,gorcz/Hystrix,fredboutin/Hystrix,mantofast/Hystrix,Siddartha07/Hystrix,liyuqi/Hystrix,dmgcodevil/Hystrix,Netflix/Hystrix,jforge/Hystrix,reboss/Hystrix,npccsb/Hystrix,JayhJung/Hystrix,dmgcodevil/Hystrix,tvaughan77/Hystrix,manwithharmonica/Hystrix,davidkarlsen/Hystrix,mauricionr/Hystrix,loop-jazz/Hystrix,Muktesh01/Hystrix,fabcipriano/Hystrix,ouyangkongtong/Hystrix,fredboutin/Hystrix,sensaid/Hystrix,manwithharmonica/Hystrix,liyuqi/Hystrix,davidkarlsen/Hystrix,Fsero/Hystrix,tvaughan77/Hystrix,gorcz/Hystrix,reboss/Hystrix,Muktesh01/Hystrix,fengshao0907/Hystrix,pcssi/Hystrix,justinjose28/Hystrix,coopsource/Hystrix,mickdwyer/Hystrix,mantofast/Hystrix,mantofast/Hystrix,ouyangkongtong/Hystrix,rukor/Hystrix,fabcipriano/Hystrix,mattrjacobs/Hystrix,coopsource/Hystrix,agentgt/Hystrix,robertroeser/Hystrix,eunmin/Hystrix,Muktesh01/Hystrix,jforge/Hystrix,dmgcodevil/Hystrix,ruhkopf/Hystrix,sposam/Hystrix,liyuqi/Hystrix,ruhkopf/Hystrix,Fsero/Hystrix,hcheung/Hystrix,ouyangkongtong/Hystrix,KoltonAndrus/Hystrix,mauricionr/Hystrix,npccsb/Hystrix,KoltonAndrus/Hystrix,coopsource/Hystrix,wangsan/Hystrix,ruhkopf/Hystrix,pcssi/Hystrix,tvaughan77/Hystrix,manwithharmonica/Hystrix,agentgt/Hystrix,hcheung/Hystrix,davidkarlsen/Hystrix,jforge/Hystrix,mebigfatguy/Hystrix,JayhJung/Hystrix,fengshao0907/Hystrix,hcheung/Hystrix,npccsb/Hystrix,mauricionr/Hystrix,sensaid/Hystrix,fabcipriano/Hystrix,fengshao0907/Hystrix,JayhJung/Hystrix,mickdwyer/Hystrix,eunmin/Hystrix,mattrjacobs/Hystrix,loop-jazz/Hystrix,rukor/Hystrix,jordancheah/Hystrix,jordancheah/Hystrix,mebigfatguy/Hystrix,Siddartha07/Hystrix,mickdwyer/Hystrix
/** * Copyright 2012 Netflix, 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.netflix.hystrix; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import org.junit.Test; import static org.junit.Assert.*; /** * ThreadPool used to executed {@link HystrixCommand#run()} on separate threads when configured to do so with {@link HystrixCommandProperties#executionIsolationStrategy()}. * <p> * Typically each {@link HystrixCommandGroupKey} has its own thread-pool so that any one group of commands can not starve others from being able to run. * <p> * A {@link HystrixCommand} can be configured with a thread-pool explicitly by injecting a {@link HystrixThreadPoolKey} or via the * {@link HystrixCommandProperties#executionIsolationThreadPoolKeyOverride()} otherwise it * will derive a {@link HystrixThreadPoolKey} from the injected {@link HystrixCommandGroupKey}. * <p> * The pool should be sized large enough to handle normal healthy traffic but small enough that it will constrain concurrent execution if backend calls become latent. * <p> * For more information see the Github Wiki: https://github.com/Netflix/Hystrix/wiki/Configuration#wiki-ThreadPool and https://github.com/Netflix/Hystrix/wiki/How-it-Works#wiki-Isolation */ public interface HystrixThreadPool { /** * Implementation of {@link ThreadPoolExecutor}. * * @return ThreadPoolExecutor */ public ThreadPoolExecutor getExecutor(); /** * Mark when a thread begins executing a command. */ public void markThreadExecution(); /** * Mark when a thread completes executing a command. */ public void markThreadCompletion(); /** * Whether the queue will allow adding an item to it. * <p> * This allows dynamic control of the max queueSize versus whatever the actual max queueSize is so that dynamic changes can be done via property changes rather than needing an app * restart to adjust when commands should be rejected from queuing up. * * @return boolean whether there is space on the queue */ public boolean isQueueSpaceAvailable(); /** * @ExcludeFromJavadoc */ /* package */static class Factory { /* * Use the String from HystrixThreadPoolKey.name() instead of the HystrixThreadPoolKey instance as it's just an interface and we can't ensure the object * we receive implements hashcode/equals correctly and do not want the default hashcode/equals which would create a new threadpool for every object we get even if the name is the same */ private static ConcurrentHashMap<String, HystrixThreadPool> threadPools = new ConcurrentHashMap<String, HystrixThreadPool>(); /** * Get the {@link HystrixThreadPool} instance for a given {@link HystrixThreadPoolKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixThreadPool} per {@link HystrixThreadPoolKey}. * * @return {@link HystrixThreadPool} instance */ /* package */static HystrixThreadPool getInstance(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesBuilder) { // get the key to use instead of using the object itself so that if people forget to implement equals/hashcode things will still work String key = threadPoolKey.name(); // this should find it for all but the first time HystrixThreadPool previouslyCached = threadPools.get(key); if (previouslyCached != null) { return previouslyCached; } // if we get here this is the first time so we need to initialize // Create and add to the map ... use putIfAbsent to atomically handle the possible race-condition of // 2 threads hitting this point at the same time and let ConcurrentHashMap provide us our thread-safety // If 2 threads hit here only one will get added and the other will get a non-null response instead. HystrixThreadPool poolForKey = threadPools.putIfAbsent(key, new HystrixThreadPoolDefault(threadPoolKey, propertiesBuilder)); if (poolForKey == null) { // this means the putIfAbsent step just created a new one so let's retrieve and return it HystrixThreadPool threadPoolJustCreated = threadPools.get(key); // return it return threadPoolJustCreated; } else { // this means a race occurred and while attempting to 'put' another one got there before // and we instead retrieved it and will now return it return poolForKey; } } /** * Initiate the shutdown of all {@link HystrixThreadPool} instances. * <p> * NOTE: This is NOT thread-safe if HystrixCommands are concurrently being executed * and causing thread-pools to initialize while also trying to shutdown. * </p> */ /* package */ static synchronized void shutdown() { for (HystrixThreadPool pool : threadPools.values()) { pool.getExecutor().shutdown(); } threadPools.clear(); } /** * Initiate the shutdown of all {@link HystrixThreadPool} instances and wait up to the given time on each pool to complete. * <p> * NOTE: This is NOT thread-safe if HystrixCommands are concurrently being executed * and causing thread-pools to initialize while also trying to shutdown. * </p> */ /* package */ static synchronized void shutdown(long timeout, TimeUnit unit) { for (HystrixThreadPool pool : threadPools.values()) { pool.getExecutor().shutdown(); } for (HystrixThreadPool pool : threadPools.values()) { try { pool.getExecutor().awaitTermination(timeout, unit); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting for thread-pools to terminate. Pools may not be correctly shutdown or cleared.", e); } } threadPools.clear(); } } /** * @ExcludeFromJavadoc */ @ThreadSafe /* package */ static class HystrixThreadPoolDefault implements HystrixThreadPool { private final HystrixThreadPoolProperties properties; private final BlockingQueue<Runnable> queue; private final ThreadPoolExecutor threadPool; private final HystrixThreadPoolMetrics metrics; public HystrixThreadPoolDefault(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesDefaults) { this.properties = HystrixPropertiesFactory.getThreadPoolProperties(threadPoolKey, propertiesDefaults); HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); this.queue = concurrencyStrategy.getBlockingQueue(properties.maxQueueSize().get()); this.threadPool = concurrencyStrategy.getThreadPool(threadPoolKey, properties.coreSize(), properties.coreSize(), properties.keepAliveTimeMinutes(), TimeUnit.MINUTES, queue); this.metrics = HystrixThreadPoolMetrics.getInstance(threadPoolKey, threadPool, properties); /* strategy: HystrixMetricsPublisherThreadPool */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForThreadPool(threadPoolKey, this.metrics, this.properties); } @Override public ThreadPoolExecutor getExecutor() { // allow us to change things via fast-properties by setting it each time threadPool.setCorePoolSize(properties.coreSize().get()); threadPool.setMaximumPoolSize(properties.coreSize().get()); // we always want maxSize the same as coreSize, we are not using a dynamically resizing pool threadPool.setKeepAliveTime(properties.keepAliveTimeMinutes().get(), TimeUnit.MINUTES); // this doesn't really matter since we're not resizing return threadPool; } @Override public void markThreadExecution() { metrics.markThreadExecution(); } @Override public void markThreadCompletion() { metrics.markThreadCompletion(); } /** * Whether the threadpool queue has space available according to the <code>queueSizeRejectionThreshold</code> settings. * <p> * If a SynchronousQueue implementation is used (<code>maxQueueSize</code> == -1), it always returns 0 as the size so this would always return true. */ @Override public boolean isQueueSpaceAvailable() { if (properties.maxQueueSize().get() < 0) { // we don't have a queue so we won't look for space but instead // let the thread-pool reject or not return true; } else { return threadPool.getQueue().size() < properties.queueSizeRejectionThreshold().get(); } } } public static class UnitTest { @Test public void testShutdown() { // other unit tests will probably have run before this so get the count int count = Factory.threadPools.size(); HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"), HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder()); assertEquals(count + 1, Factory.threadPools.size()); assertFalse(pool.getExecutor().isShutdown()); Factory.shutdown(); // ensure all pools were removed from the cache assertEquals(0, Factory.threadPools.size()); assertTrue(pool.getExecutor().isShutdown()); } @Test public void testShutdownWithWait() { // other unit tests will probably have run before this so get the count int count = Factory.threadPools.size(); HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"), HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder()); assertEquals(count + 1, Factory.threadPools.size()); assertFalse(pool.getExecutor().isShutdown()); Factory.shutdown(1, TimeUnit.SECONDS); // ensure all pools were removed from the cache assertEquals(0, Factory.threadPools.size()); assertTrue(pool.getExecutor().isShutdown()); } } }
hystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPool.java
/** * Copyright 2012 Netflix, 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.netflix.hystrix; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import org.junit.Test; import static org.junit.Assert.*; /** * ThreadPool used to executed {@link HystrixCommand#run()} on separate threads when configured to do so with {@link HystrixCommandProperties#executionIsolationStrategy()}. * <p> * Typically each {@link HystrixCommandGroupKey} has its own thread-pool so that any one group of commands can not starve others from being able to run. * <p> * A {@link HystrixCommand} can be configured with a thread-pool explicitly by injecting a {@link HystrixThreadPoolKey} or via the * {@link HystrixCommandProperties#executionIsolationThreadPoolKeyOverride()} otherwise it * will derive a {@link HystrixThreadPoolKey} from the injected {@link HystrixCommandGroupKey}. * <p> * The pool should be sized large enough to handle normal healthy traffic but small enough that it will constrain concurrent execution if backend calls become latent. * <p> * For more information see the Github Wiki: https://github.com/Netflix/Hystrix/wiki/Configuration#wiki-ThreadPool and https://github.com/Netflix/Hystrix/wiki/How-it-Works#wiki-Isolation */ public interface HystrixThreadPool { /** * Implementation of {@link ThreadPoolExecutor}. * * @return ThreadPoolExecutor */ public ThreadPoolExecutor getExecutor(); /** * Mark when a thread begins executing a command. */ public void markThreadExecution(); /** * Mark when a thread completes executing a command. */ public void markThreadCompletion(); /** * Whether the queue will allow adding an item to it. * <p> * This allows dynamic control of the max queueSize versus whatever the actual max queueSize is so that dynamic changes can be done via property changes rather than needing an app * restart to adjust when commands should be rejected from queuing up. * * @return boolean whether there is space on the queue */ public boolean isQueueSpaceAvailable(); /** * @ExcludeFromJavadoc */ /* package */static class Factory { /* * Use the String from HystrixThreadPoolKey.name() instead of the HystrixThreadPoolKey instance as it's just an interface and we can't ensure the object * we receive implements hashcode/equals correctly and do not want the default hashcode/equals which would create a new threadpool for every object we get even if the name is the same */ private static ConcurrentHashMap<String, HystrixThreadPool> threadPools = new ConcurrentHashMap<String, HystrixThreadPool>(); /** * Get the {@link HystrixThreadPool} instance for a given {@link HystrixThreadPoolKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixThreadPool} per {@link HystrixThreadPoolKey}. * * @return {@link HystrixThreadPool} instance */ /* package */static HystrixThreadPool getInstance(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesBuilder) { // get the key to use instead of using the object itself so that if people forget to implement equals/hashcode things will still work String key = threadPoolKey.name(); // this should find it for all but the first time HystrixThreadPool previouslyCached = threadPools.get(key); if (previouslyCached != null) { return previouslyCached; } // if we get here this is the first time so we need to initialize // Create and add to the map ... use putIfAbsent to atomically handle the possible race-condition of // 2 threads hitting this point at the same time and let ConcurrentHashMap provide us our thread-safety // If 2 threads hit here only one will get added and the other will get a non-null response instead. HystrixThreadPool poolForKey = threadPools.putIfAbsent(key, new HystrixThreadPoolDefault(threadPoolKey, propertiesBuilder)); if (poolForKey == null) { // this means the putIfAbsent step just created a new one so let's retrieve and return it HystrixThreadPool threadPoolJustCreated = threadPools.get(key); // return it return threadPoolJustCreated; } else { // this means a race occurred and while attempting to 'put' another one got there before // and we instead retrieved it and will now return it return poolForKey; } } /** * Initiate the shutdown of all {@link HystrixThreadPool} instances. * <p> * NOTE: This is NOT thread-safe if HystrixCommands are concurrently being executed * and causing thread-pools to initialize while also trying to shutdown. * </p> */ public static synchronized void shutdown() { for (HystrixThreadPool pool : threadPools.values()) { pool.getExecutor().shutdown(); } threadPools.clear(); } /** * Initiate the shutdown of all {@link HystrixThreadPool} instances and wait up to the given time on each pool to complete. * <p> * NOTE: This is NOT thread-safe if HystrixCommands are concurrently being executed * and causing thread-pools to initialize while also trying to shutdown. * </p> */ public static synchronized void shutdown(long timeout, TimeUnit unit) { for (HystrixThreadPool pool : threadPools.values()) { pool.getExecutor().shutdown(); } for (HystrixThreadPool pool : threadPools.values()) { try { pool.getExecutor().awaitTermination(timeout, unit); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting for thread-pools to terminate. Pools may not be correctly shutdown or cleared.", e); } } threadPools.clear(); } } /** * @ExcludeFromJavadoc */ @ThreadSafe /* package */ static class HystrixThreadPoolDefault implements HystrixThreadPool { private final HystrixThreadPoolProperties properties; private final BlockingQueue<Runnable> queue; private final ThreadPoolExecutor threadPool; private final HystrixThreadPoolMetrics metrics; public HystrixThreadPoolDefault(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesDefaults) { this.properties = HystrixPropertiesFactory.getThreadPoolProperties(threadPoolKey, propertiesDefaults); HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); this.queue = concurrencyStrategy.getBlockingQueue(properties.maxQueueSize().get()); this.threadPool = concurrencyStrategy.getThreadPool(threadPoolKey, properties.coreSize(), properties.coreSize(), properties.keepAliveTimeMinutes(), TimeUnit.MINUTES, queue); this.metrics = HystrixThreadPoolMetrics.getInstance(threadPoolKey, threadPool, properties); /* strategy: HystrixMetricsPublisherThreadPool */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForThreadPool(threadPoolKey, this.metrics, this.properties); } @Override public ThreadPoolExecutor getExecutor() { // allow us to change things via fast-properties by setting it each time threadPool.setCorePoolSize(properties.coreSize().get()); threadPool.setMaximumPoolSize(properties.coreSize().get()); // we always want maxSize the same as coreSize, we are not using a dynamically resizing pool threadPool.setKeepAliveTime(properties.keepAliveTimeMinutes().get(), TimeUnit.MINUTES); // this doesn't really matter since we're not resizing return threadPool; } @Override public void markThreadExecution() { metrics.markThreadExecution(); } @Override public void markThreadCompletion() { metrics.markThreadCompletion(); } /** * Whether the threadpool queue has space available according to the <code>queueSizeRejectionThreshold</code> settings. * <p> * If a SynchronousQueue implementation is used (<code>maxQueueSize</code> == -1), it always returns 0 as the size so this would always return true. */ @Override public boolean isQueueSpaceAvailable() { if (properties.maxQueueSize().get() < 0) { // we don't have a queue so we won't look for space but instead // let the thread-pool reject or not return true; } else { return threadPool.getQueue().size() < properties.queueSizeRejectionThreshold().get(); } } } public static class UnitTest { @Test public void testShutdown() { // other unit tests will probably have run before this so get the count int count = Factory.threadPools.size(); HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"), HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder()); assertEquals(count + 1, Factory.threadPools.size()); assertFalse(pool.getExecutor().isShutdown()); Factory.shutdown(); // ensure all pools were removed from the cache assertEquals(0, Factory.threadPools.size()); assertTrue(pool.getExecutor().isShutdown()); } @Test public void testShutdownWithWait() { // other unit tests will probably have run before this so get the count int count = Factory.threadPools.size(); HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"), HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder()); assertEquals(count + 1, Factory.threadPools.size()); assertFalse(pool.getExecutor().isShutdown()); Factory.shutdown(1, TimeUnit.SECONDS); // ensure all pools were removed from the cache assertEquals(0, Factory.threadPools.size()); assertTrue(pool.getExecutor().isShutdown()); } } }
make reset methods package private not public
hystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPool.java
make reset methods package private not public
<ide><path>ystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPool.java <ide> * and causing thread-pools to initialize while also trying to shutdown. <ide> * </p> <ide> */ <del> public static synchronized void shutdown() { <add> /* package */ static synchronized void shutdown() { <ide> for (HystrixThreadPool pool : threadPools.values()) { <ide> pool.getExecutor().shutdown(); <ide> } <ide> * and causing thread-pools to initialize while also trying to shutdown. <ide> * </p> <ide> */ <del> public static synchronized void shutdown(long timeout, TimeUnit unit) { <add> /* package */ static synchronized void shutdown(long timeout, TimeUnit unit) { <ide> for (HystrixThreadPool pool : threadPools.values()) { <ide> pool.getExecutor().shutdown(); <ide> }
Java
epl-1.0
1cb055a94d0be6592f772701e9d73d66322c6253
0
rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt
/*********************************************************************** * Copyright (c) 2005, 2006 IBM Corporation. * 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: * IBM Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.device.svg; import java.awt.Image; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.birt.chart.computation.DataPointHints; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IUpdateNotifier; import org.eclipse.birt.chart.device.extension.i18n.Messages; import org.eclipse.birt.chart.device.plugin.ChartDeviceExtensionPlugin; import org.eclipse.birt.chart.device.svg.plugin.ChartDeviceSVGPlugin; import org.eclipse.birt.chart.device.swing.SwingRendererImpl; import org.eclipse.birt.chart.event.ArcRenderEvent; import org.eclipse.birt.chart.event.AreaRenderEvent; import org.eclipse.birt.chart.event.ImageRenderEvent; import org.eclipse.birt.chart.event.InteractionEvent; import org.eclipse.birt.chart.event.LineRenderEvent; import org.eclipse.birt.chart.event.OvalRenderEvent; import org.eclipse.birt.chart.event.PolygonRenderEvent; import org.eclipse.birt.chart.event.PrimitiveRenderEvent; import org.eclipse.birt.chart.event.RectangleRenderEvent; import org.eclipse.birt.chart.event.StructureChangeEvent; import org.eclipse.birt.chart.event.TextRenderEvent; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.Location; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.Trigger; import org.eclipse.birt.chart.model.layout.LabelBlock; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.model.layout.Plot; import org.eclipse.birt.chart.model.layout.TitleBlock; import org.eclipse.birt.chart.util.PluginSettings; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; /** * Provides a reference implementation of a SVG device renderer. It translates * chart primitives into standard SVG v1.1 rendering primitives. */ public class SVGRendererImpl extends SwingRendererImpl { protected List scriptRefList = null; protected List scriptCodeList = null; private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.device.svg/trace" ); //$NON-NLS-1$ /** * */ private IUpdateNotifier _iun = null; protected SVGInteractiveRenderer ivRenderer; /** * */ public SVGRendererImpl( ) { if ( System.getProperty( "STANDALONE" ) == null ) //$NON-NLS-1$ { final PluginSettings ps = PluginSettings.instance( ); try { _ids = ps.getDisplayServer( "ds.SVG" ); //$NON-NLS-1$ } catch ( ChartException pex ) { logger.log( pex ); } } else _ids = new SVGDisplayServer( ); ivRenderer = new SVGInteractiveRenderer( getULocale( ) ); } /** * The SVG version is "-//W3C//DTD SVG 1.0//EN". */ static private final String SVG_VERSION = "-//W3C//DTD SVG 1.0//EN"; //$NON-NLS-1$ /** * The SVG DTD is * "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd". */ static private final String SVG_DTD = "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"; //$NON-NLS-1$ /** * The SVG namespace http://www.w3.org/2000/svg */ static private final String XMLNS = "http://www.w3.org/2000/svg"; //$NON-NLS-1$ /** * The xmlns:xlink is "http://www.w3.org/1999/xlink". */ static private final String XMLNSXINK = "http://www.w3.org/1999/xlink"; //$NON-NLS-1$ /** * */ protected Object oOutputIdentifier = null; /** * Document object that represents the SVG */ protected Document dom; /** * SVG Graphic context */ protected SVGGraphics2D svggc; /** * Property that determins if the SVG should resize to the containing * element dimensions. */ protected boolean _resizeSVG = false; /* * (non-Javadoc) * * @see org.eclipse.birt.chart.device.IDeviceRenderer#setProperty(java.lang.String, * java.lang.Object) */ public void setProperty( String sProperty, Object oValue ) { super.setProperty( sProperty, oValue ); if ( sProperty.equals( IDeviceRenderer.UPDATE_NOTIFIER ) ) { _iun = (IUpdateNotifier) oValue; ivRenderer.setIUpdateNotifier( _iun ); } else if ( sProperty.equals( IDeviceRenderer.EXPECTED_BOUNDS ) ) { final Bounds bo = (Bounds) oValue; try { dom = createSvgDocument( bo.getWidth( ), bo.getHeight( ) ); svggc = new SVGGraphics2D( dom ); ivRenderer.setSVG2D( svggc ); // Create the hotspot layer ivRenderer.createHotspotLayer( dom ); super.setProperty( IDeviceRenderer.GRAPHICS_CONTEXT, svggc ); } catch ( Exception e ) { e.printStackTrace( ); } } else if ( sProperty.equals( IDeviceRenderer.FILE_IDENTIFIER ) ) { oOutputIdentifier = oValue; } else if ( sProperty.equals( ISVGConstants.JAVASCRIPT_CODE_LIST ) ) { scriptCodeList = (List) oValue; } else if ( sProperty.equals( ISVGConstants.JAVASCRIPT_URL_REF_LIST ) ) { scriptRefList = (List) oValue; } else if ( sProperty.equals( ISVGConstants.RESIZE_SVG ) ) { _resizeSVG = ( (Boolean) oValue ).booleanValue( ); } } protected void addScripts( ) { if ( this.scriptCodeList != null ) { for ( int x = 0; x < scriptCodeList.size( ); x++ ) { String code = (String) scriptCodeList.get( x ); ( (SVGGraphics2D) _g2d ).addScript( code ); } } if ( this.scriptRefList != null ) { for ( int x = 0; x < scriptRefList.size( ); x++ ) { String ref = (String) scriptRefList.get( x ); ( (SVGGraphics2D) _g2d ).addScriptRef( ref ); } } } /** * * @param os * @throws RenderingException */ public void after( ) throws ChartException { super.after( ); ivRenderer.addInteractivity( ); addScripts( ); ( (SVGGraphics2D) _g2d ).flush( ); // make sure we add the hotspot layer to the bottom layer of the svg dom.getDocumentElement( ).appendChild( ivRenderer.getHotspotLayer( ) ); if ( oOutputIdentifier instanceof OutputStream ) // OUTPUT STREAM { try { writeDocumentToOutputStream( dom, (OutputStream) oOutputIdentifier ); } catch ( Exception ex ) { throw new ChartException( ChartDeviceSVGPlugin.ID, ChartException.RENDERING, ex ); } } else if ( oOutputIdentifier instanceof String ) { FileOutputStream fos = null; try { fos = new FileOutputStream( (String) oOutputIdentifier ); writeDocumentToOutputStream( dom, fos ); fos.close( ); } catch ( Exception ex ) { throw new ChartException( ChartDeviceSVGPlugin.ID, ChartException.RENDERING, ex ); } } else { throw new ChartException( ChartDeviceSVGPlugin.ID, ChartException.RENDERING, "SVGRendererImpl.exception.UnableToWriteChartImage", //$NON-NLS-1$ new Object[]{ oOutputIdentifier }, null ); } ivRenderer.clear( ); } /** * Writes the XML document to an output stream * * @param svgDocument * @param outputStream * @throws Exception */ private void writeDocumentToOutputStream( Document svgDocument, OutputStream outputStream ) throws Exception { if ( svgDocument != null && outputStream != null ) { OutputStreamWriter writer = null; writer = new OutputStreamWriter( outputStream, "UTF-8" ); //$NON-NLS-1$ DOMSource source = new DOMSource( svgDocument ); StreamResult result = new StreamResult( writer ); // need to check if we should use sun's implementation of the // transform factory. This is needed to work with jdk1.4 and jdk1.5 // with tomcat checkForTransformFactoryImpl( ); TransformerFactory transFactory = TransformerFactory.newInstance( ); Transformer transformer = transFactory.newTransformer( ); transformer.transform( source, result ); } } /** * Check to see if we should change the implementation of the * TransformFactory. * */ private void checkForTransformFactoryImpl( ) { try { Class.forName( "org.apache.xalan.processor.TransformerFactoryImpl" ); //$NON-NLS-1$ } catch ( ClassNotFoundException e ) { // Force using sun's implementation System.setProperty( "javax.xml.transform.TransformerFactory", //$NON-NLS-1$ "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl" ); //$NON-NLS-1$ } } /** * Creates an SVG document and assigns width and height to the root "svg" * element. * * @return Document the SVG document * @throws Exception */ protected Document createSvgDocument( ) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance( ); DocumentBuilder builder; builder = factory.newDocumentBuilder( ); DOMImplementation domImpl = builder.getDOMImplementation( ); DocumentType dType = domImpl.createDocumentType( "svg", //$NON-NLS-1$ SVG_VERSION, SVG_DTD ); Document svgDocument = domImpl.createDocument( XMLNS, "svg", dType ); //$NON-NLS-1$ svgDocument.getDocumentElement( ).setAttribute( "xmlns", XMLNS ); //$NON-NLS-1$ svgDocument.getDocumentElement( ) .setAttribute( "xmlns:xlink", XMLNSXINK ); //$NON-NLS-1$ if ( _resizeSVG ) { svgDocument.getDocumentElement( ) .setAttribute( "onload", "resizeSVG(evt)" ); //$NON-NLS-1$ //$NON-NLS-2$ // the onload() effect could be inaccurate, call onreisze again to // ensure, Note onload() is still needed, because onresize may never // be called. svgDocument.getDocumentElement( ) .setAttribute( "onresize", "resizeSVG(evt)" ); //$NON-NLS-1$ //$NON-NLS-2$ } return svgDocument; } protected Document createSvgDocument( double width, double height ) throws Exception { Document svgDocument = createSvgDocument( ); svgDocument.getDocumentElement( ).setAttribute( "width", //$NON-NLS-1$ Double.toString( width ) ); svgDocument.getDocumentElement( ).setAttribute( "height", //$NON-NLS-1$ Double.toString( height ) ); return svgDocument; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.device.IStructureDefinitionListener#changeStructure(org.eclipse.birt.chart.event.StructureChangeEvent) */ public void changeStructure( StructureChangeEvent scev ) { // Object sourceObj = scev.getSource( ); // switch ( scev.getEventType( ) ) // { // case StructureChangeEvent.BEFORE : // addGroupStructure( sourceObj ); // break; // case StructureChangeEvent.AFTER : // removeGroupStructure( sourceObj ); // break; // // } } protected void removeGroupStructure( Object block ) { if ( ( block instanceof TitleBlock ) || ( block instanceof Legend ) || ( block instanceof Plot ) || ( block instanceof LabelBlock ) || ( block instanceof Series ) || ( block instanceof DataPointHints ) ) svggc.popParent( ); } protected void addGroupStructure( Object block ) { if ( block instanceof TitleBlock ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "title" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof Legend ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "legend" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof Plot ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "plot" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof LabelBlock ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "label" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof Series ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "series" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof DataPointHints ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "dp" + block.hashCode( ) ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.device.IPrimitiveRenderer#enableInteraction(org.eclipse.birt.chart.event.InteractionEvent) */ public void enableInteraction( InteractionEvent ie ) throws ChartException { if ( _iun == null ) { logger.log( ILogger.WARNING, Messages.getString( "exception.missing.component.interaction", getULocale( ) ) ); //$NON-NLS-1$ return; } Trigger[] triggers = ie.getTriggers( ); if ( triggers == null ) { return; } // ///////////////////////////////////////////// // Create the hotspot and add the hotspot on // the SVG hotspot layer // ///////////////////////////////////////////// final PrimitiveRenderEvent pre = ie.getHotSpot( ); Element elm = null; if ( pre instanceof PolygonRenderEvent ) { final Location[] loa = ( (PolygonRenderEvent) pre ).getPoints( ); int[][] pa = getCoordinatesAsInts( loa ); elm = svggc.createPolygon( pa[0], pa[1], pa[0].length ); } else if ( pre instanceof OvalRenderEvent ) { final Bounds boEllipse = ( (OvalRenderEvent) pre ).getBounds( ); elm = svggc.createOval( boEllipse.getLeft( ), boEllipse.getTop( ), boEllipse.getWidth( ), boEllipse.getHeight( ) ); } else if ( pre instanceof RectangleRenderEvent ) { final Bounds boRect = ( (RectangleRenderEvent) pre ).getBounds( ); elm = svggc.createRect( boRect.getLeft( ), boRect.getTop( ), boRect.getWidth( ), boRect.getHeight( ) ); } else if ( pre instanceof AreaRenderEvent ) { AreaRenderEvent are = (AreaRenderEvent) pre; final GeneralPath gp = new GeneralPath( ); PrimitiveRenderEvent subPre; for ( int i = 0; i < are.getElementCount( ); i++ ) { subPre = are.getElement( i ); if ( subPre instanceof ArcRenderEvent ) { final ArcRenderEvent acre = (ArcRenderEvent) subPre; final Arc2D.Double a2d = new Arc2D.Double( acre.getTopLeft( ) .getX( ), acre.getTopLeft( ).getY( ), acre.getWidth( ), acre.getHeight( ), acre.getStartAngle( ), acre.getAngleExtent( ), toSwingArcType( acre.getStyle( ) ) ); gp.append( a2d, true ); } else if ( subPre instanceof LineRenderEvent ) { final LineRenderEvent lre = (LineRenderEvent) subPre; final Line2D.Double l2d = new Line2D.Double( lre.getStart( ) .getX( ), lre.getStart( ).getY( ), lre.getEnd( ) .getX( ), lre.getEnd( ).getY( ) ); gp.append( l2d, true ); } } elm = svggc.createGeneralPath( gp ); } else if ( pre instanceof ArcRenderEvent ) { final ArcRenderEvent are = (ArcRenderEvent) pre; if ( are.getInnerRadius( ) >= 0 && are.getOuterRadius( ) > 0 && are.getInnerRadius( ) < are.getOuterRadius( ) ) { Shape outerArc = new Arc2D.Double( are.getTopLeft( ).getX( ) + ( are.getWidth( ) - 2 * are.getOuterRadius( ) ) / 2, are.getTopLeft( ).getY( ) + ( are.getHeight( ) - 2 * are.getOuterRadius( ) ) / 2, 2 * are.getOuterRadius( ), 2 * are.getOuterRadius( ), are.getStartAngle( ), are.getAngleExtent( ), Arc2D.PIE ); Shape innerArc = new Arc2D.Double( are.getTopLeft( ).getX( ) + ( are.getWidth( ) - 2 * are.getInnerRadius( ) ) / 2, are.getTopLeft( ).getY( ) + ( are.getHeight( ) - 2 * are.getInnerRadius( ) ) / 2, 2 * are.getInnerRadius( ), 2 * are.getInnerRadius( ), are.getStartAngle( ), are.getAngleExtent( ), Arc2D.PIE ); Area fArea = new Area( outerArc ); fArea.exclusiveOr( new Area( innerArc ) ); // Shape prevClip = _g2d.getClip( ); // _g2d.setClip( fArea ); elm = svggc.createGeneralPath( fArea ); // _g2d.setClip( prevClip ); } else { elm = svggc.createGeneralPath( new Arc2D.Double( are.getTopLeft( ) .getX( ), are.getTopLeft( ).getY( ), are.getWidth( ), are.getHeight( ), are.getStartAngle( ), are.getAngleExtent( ), toSwingArcType( are.getStyle( ) ) ) ); } } ivRenderer.prepareInteractiveEvent( elm, ie, triggers ); } /** * * @param iArcStyle * @return */ private static final int toSwingArcType( int iArcStyle ) { switch ( iArcStyle ) { case ArcRenderEvent.OPEN : return Arc2D.OPEN; case ArcRenderEvent.CLOSED : return Arc2D.CHORD; case ArcRenderEvent.SECTOR : return Arc2D.PIE; } return -1; } public void drawArc( ArcRenderEvent are ) throws ChartException { ivRenderer.groupPrimitive( are, false ); super.drawArc( are ); ivRenderer.ungroupPrimitive( are, false ); } public void drawArea( AreaRenderEvent are ) throws ChartException { ivRenderer.groupPrimitive( are, false ); super.drawArea( are ); ivRenderer.ungroupPrimitive( are, false ); } public void drawImage( ImageRenderEvent pre ) throws ChartException { ivRenderer.groupPrimitive( pre, false ); super.drawImage( pre ); ivRenderer.ungroupPrimitive( pre, false ); } protected Image createImage( byte[] data ) { return new SVGImage( super.createImage( data ), null, data ); } public void drawLine( LineRenderEvent lre ) throws ChartException { ivRenderer.groupPrimitive( lre, false ); super.drawLine( lre ); ivRenderer.ungroupPrimitive( lre, false ); } public void drawOval( OvalRenderEvent ore ) throws ChartException { ivRenderer.groupPrimitive( ore, false ); super.drawOval( ore ); ivRenderer.ungroupPrimitive( ore, false ); } public void drawPolygon( PolygonRenderEvent pre ) throws ChartException { ivRenderer.groupPrimitive( pre, false ); super.drawPolygon( pre ); ivRenderer.ungroupPrimitive( pre, false ); } public void drawRectangle( RectangleRenderEvent rre ) throws ChartException { ivRenderer.groupPrimitive( rre, false ); super.drawRectangle( rre ); ivRenderer.ungroupPrimitive( rre, false ); } public void fillArc( ArcRenderEvent are ) throws ChartException { ivRenderer.groupPrimitive( are, false ); super.fillArc( are ); ivRenderer.ungroupPrimitive( are, false ); } public void fillArea( AreaRenderEvent are ) throws ChartException { ivRenderer.groupPrimitive( are, false ); super.fillArea( are ); ivRenderer.ungroupPrimitive( are, false ); } public void fillOval( OvalRenderEvent ore ) throws ChartException { ivRenderer.groupPrimitive( ore, false ); super.fillOval( ore ); ivRenderer.ungroupPrimitive( ore, false ); } public void fillPolygon( PolygonRenderEvent pre ) throws ChartException { ivRenderer.groupPrimitive( pre, false ); super.fillPolygon( pre ); ivRenderer.ungroupPrimitive( pre, false ); } public void fillRectangle( RectangleRenderEvent rre ) throws ChartException { ivRenderer.groupPrimitive( rre, false ); super.fillRectangle( rre ); ivRenderer.ungroupPrimitive( rre, false ); } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.event.IPrimitiveRenderListener#drawText(org.eclipse.birt.chart.event.TextRenderEvent) */ public void drawText( TextRenderEvent tre ) throws ChartException { ivRenderer.groupPrimitive( tre, true ); SVGTextRenderer tr = SVGTextRenderer.instance( (SVGDisplayServer) _ids ); switch ( tre.getAction( ) ) { case TextRenderEvent.UNDEFINED : throw new ChartException( ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, "exception.missing.text.render.action", //$NON-NLS-1$ Messages.getResourceBundle( getULocale( ) ) ); case TextRenderEvent.RENDER_SHADOW_AT_LOCATION : tr.renderShadowAtLocation( this, tre.getTextPosition( ), tre.getLocation( ), tre.getLabel( ) ); break; case TextRenderEvent.RENDER_TEXT_AT_LOCATION : tr.renderTextAtLocation( this, tre.getTextPosition( ), tre.getLocation( ), tre.getLabel( ) ); break; case TextRenderEvent.RENDER_TEXT_IN_BLOCK : tr.renderTextInBlock( this, tre.getBlockBounds( ), tre.getBlockAlignment( ), tre.getLabel( ) ); break; } ivRenderer.ungroupPrimitive( tre, true ); } }
chart/org.eclipse.birt.chart.device.svg/src/org/eclipse/birt/chart/device/svg/SVGRendererImpl.java
/*********************************************************************** * Copyright (c) 2005, 2006 IBM Corporation. * 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: * IBM Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.device.svg; import java.awt.Image; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.birt.chart.computation.DataPointHints; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IUpdateNotifier; import org.eclipse.birt.chart.device.extension.i18n.Messages; import org.eclipse.birt.chart.device.plugin.ChartDeviceExtensionPlugin; import org.eclipse.birt.chart.device.svg.plugin.ChartDeviceSVGPlugin; import org.eclipse.birt.chart.device.swing.SwingRendererImpl; import org.eclipse.birt.chart.event.ArcRenderEvent; import org.eclipse.birt.chart.event.AreaRenderEvent; import org.eclipse.birt.chart.event.ImageRenderEvent; import org.eclipse.birt.chart.event.InteractionEvent; import org.eclipse.birt.chart.event.LineRenderEvent; import org.eclipse.birt.chart.event.OvalRenderEvent; import org.eclipse.birt.chart.event.PolygonRenderEvent; import org.eclipse.birt.chart.event.PrimitiveRenderEvent; import org.eclipse.birt.chart.event.RectangleRenderEvent; import org.eclipse.birt.chart.event.StructureChangeEvent; import org.eclipse.birt.chart.event.TextRenderEvent; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.Location; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.Trigger; import org.eclipse.birt.chart.model.layout.LabelBlock; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.model.layout.Plot; import org.eclipse.birt.chart.model.layout.TitleBlock; import org.eclipse.birt.chart.util.PluginSettings; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; /** * Provides a reference implementation of a SVG device renderer. It translates * chart primitives into standard SVG v1.1 rendering primitives. */ public class SVGRendererImpl extends SwingRendererImpl { protected List scriptRefList = null; protected List scriptCodeList = null; private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.device.svg/trace" ); //$NON-NLS-1$ /** * */ private IUpdateNotifier _iun = null; protected SVGInteractiveRenderer ivRenderer; /** * */ public SVGRendererImpl( ) { if ( System.getProperty( "STANDALONE" ) == null ) //$NON-NLS-1$ { final PluginSettings ps = PluginSettings.instance( ); try { _ids = ps.getDisplayServer( "ds.SVG" ); //$NON-NLS-1$ } catch ( ChartException pex ) { logger.log( pex ); } } else _ids = new SVGDisplayServer( ); ivRenderer = new SVGInteractiveRenderer( getULocale( ) ); } /** * The SVG version is "-//W3C//DTD SVG 1.0//EN". */ static private final String SVG_VERSION = "-//W3C//DTD SVG 1.0//EN"; //$NON-NLS-1$ /** * The SVG DTD is * "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd". */ static private final String SVG_DTD = "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"; //$NON-NLS-1$ /** * The SVG namespace http://www.w3.org/2000/svg */ static private final String XMLNS = "http://www.w3.org/2000/svg"; //$NON-NLS-1$ /** * The xmlns:xlink is * "http://www.w3.org/1999/xlink". */ static private final String XMLNSXINK = "http://www.w3.org/1999/xlink"; //$NON-NLS-1$ /** * */ protected Object oOutputIdentifier = null; /** * Document object that represents the SVG */ protected Document dom; /** * SVG Graphic context */ protected SVGGraphics2D svggc; /** * Property that determins if the SVG should resize to the containing element dimensions. */ protected boolean _resizeSVG = false; /* * (non-Javadoc) * * @see org.eclipse.birt.chart.device.IDeviceRenderer#setProperty(java.lang.String, * java.lang.Object) */ public void setProperty( String sProperty, Object oValue ) { super.setProperty( sProperty, oValue ); if ( sProperty.equals( IDeviceRenderer.UPDATE_NOTIFIER ) ) { _iun = (IUpdateNotifier) oValue; ivRenderer.setIUpdateNotifier( _iun ); } else if ( sProperty.equals( IDeviceRenderer.EXPECTED_BOUNDS ) ) { final Bounds bo = (Bounds) oValue; try { dom = createSvgDocument( bo.getWidth( ), bo.getHeight( ) ); svggc = new SVGGraphics2D( dom ); ivRenderer.setSVG2D( svggc ); //Create the hotspot layer ivRenderer.createHotspotLayer(dom); super.setProperty( IDeviceRenderer.GRAPHICS_CONTEXT, svggc ); } catch ( Exception e ) { e.printStackTrace( ); } } else if ( sProperty.equals( IDeviceRenderer.FILE_IDENTIFIER ) ) { oOutputIdentifier = oValue; } else if ( sProperty.equals( ISVGConstants.JAVASCRIPT_CODE_LIST ) ) { scriptCodeList = (List)oValue; } else if ( sProperty.equals( ISVGConstants.JAVASCRIPT_URL_REF_LIST ) ) { scriptRefList = (List)oValue; } else if ( sProperty.equals( ISVGConstants.RESIZE_SVG ) ) { _resizeSVG = ((Boolean)oValue).booleanValue(); } } protected void addScripts(){ if (this.scriptCodeList != null){ for (int x = 0; x< scriptCodeList.size(); x++){ String code = (String)scriptCodeList.get(x); ((SVGGraphics2D)_g2d).addScript(code); } } if (this.scriptRefList != null){ for (int x = 0; x< scriptRefList.size(); x++){ String ref = (String)scriptRefList.get(x); ((SVGGraphics2D)_g2d).addScriptRef(ref); } } } /** * * @param os * @throws RenderingException */ public void after( ) throws ChartException { super.after( ); ivRenderer.addInteractivity( ); addScripts(); ((SVGGraphics2D)_g2d).flush(); //make sure we add the hotspot layer to the bottom layer of the svg dom.getDocumentElement().appendChild(ivRenderer.getHotspotLayer( )); if ( oOutputIdentifier instanceof OutputStream ) // OUTPUT STREAM { try { writeDocumentToOutputStream( dom, (OutputStream) oOutputIdentifier ); } catch ( Exception ex ) { throw new ChartException( ChartDeviceSVGPlugin.ID, ChartException.RENDERING, ex ); } } else if ( oOutputIdentifier instanceof String ) { FileOutputStream fos = null; try { fos = new FileOutputStream( (String) oOutputIdentifier ); writeDocumentToOutputStream( dom, fos ); fos.close( ); } catch ( Exception ex ) { throw new ChartException( ChartDeviceSVGPlugin.ID, ChartException.RENDERING, ex ); } } else { throw new ChartException( ChartDeviceSVGPlugin.ID, ChartException.RENDERING, "SVGRendererImpl.exception.UnableToWriteChartImage", //$NON-NLS-1$ new Object[]{ oOutputIdentifier }, null ); } ivRenderer.clear( ); } /** * Writes the XML document to an output stream * * @param svgDocument * @param outputStream * @throws Exception */ private void writeDocumentToOutputStream( Document svgDocument, OutputStream outputStream ) throws Exception { if ( svgDocument != null && outputStream != null ) { OutputStreamWriter writer = null; writer = new OutputStreamWriter( outputStream, "UTF-8" ); //$NON-NLS-1$ DOMSource source = new DOMSource( svgDocument ); StreamResult result = new StreamResult( writer ); //need to check if we should use sun's implementation of the transform factory. This is needed to work with jdk1.4 and jdk1.5 with tomcat checkForTransformFactoryImpl(); TransformerFactory transFactory = TransformerFactory.newInstance( ); Transformer transformer = transFactory.newTransformer( ); transformer.transform( source, result ); } } /** * Check to see if we should change the implementation of the TransformFactory. * */ private void checkForTransformFactoryImpl(){ try { Class.forName("org.apache.xalan.processor.TransformerFactoryImpl"); } catch (ClassNotFoundException e) { //Force using sun's implementation System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); } } /** * Creates an SVG document and assigns width and height to the root "svg" * element. * * @return Document the SVG document * @throws Exception */ protected Document createSvgDocument( ) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance( ); DocumentBuilder builder; builder = factory.newDocumentBuilder( ); DOMImplementation domImpl = builder.getDOMImplementation( ); DocumentType dType = domImpl.createDocumentType( "svg", //$NON-NLS-1$ SVG_VERSION, SVG_DTD ); Document svgDocument = domImpl.createDocument( XMLNS, "svg", dType ); //$NON-NLS-1$ svgDocument.getDocumentElement().setAttribute("xmlns", XMLNS); //$NON-NLS-1$ svgDocument.getDocumentElement().setAttribute("xmlns:xlink", XMLNSXINK); //$NON-NLS-1$ if (_resizeSVG) svgDocument.getDocumentElement().setAttribute("onload","resizeSVG(evt)"); //$NON-NLS-1$ //$NON-NLS-2$ return svgDocument; } protected Document createSvgDocument( double width, double height ) throws Exception { Document svgDocument = createSvgDocument( ); svgDocument.getDocumentElement( ).setAttribute( "width", //$NON-NLS-1$ Double.toString( width ) ); svgDocument.getDocumentElement( ).setAttribute( "height", //$NON-NLS-1$ Double.toString( height ) ); return svgDocument; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.device.IStructureDefinitionListener#changeStructure(org.eclipse.birt.chart.event.StructureChangeEvent) */ public void changeStructure( StructureChangeEvent scev ) { // Object sourceObj = scev.getSource( ); // switch ( scev.getEventType( ) ) // { // case StructureChangeEvent.BEFORE : // addGroupStructure( sourceObj ); // break; // case StructureChangeEvent.AFTER : // removeGroupStructure( sourceObj ); // break; // // } } protected void removeGroupStructure( Object block ) { if ( ( block instanceof TitleBlock ) || ( block instanceof Legend ) || ( block instanceof Plot ) || ( block instanceof LabelBlock ) || ( block instanceof Series ) || ( block instanceof DataPointHints ) ) svggc.popParent( ); } protected void addGroupStructure( Object block ) { if ( block instanceof TitleBlock ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "title" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof Legend ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "legend" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof Plot ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "plot" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof LabelBlock ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "label" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof Series ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "series" ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } else if ( block instanceof DataPointHints ) { Element group = svggc.dom.createElement( "g" ); //$NON-NLS-1$ group.setAttribute( "id", "dp" + block.hashCode( ) ); //$NON-NLS-1$ //$NON-NLS-2$ svggc.pushParent( group ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.device.IPrimitiveRenderer#enableInteraction(org.eclipse.birt.chart.event.InteractionEvent) */ public void enableInteraction( InteractionEvent ie ) throws ChartException { if ( _iun == null ) { logger.log( ILogger.WARNING, Messages.getString( "exception.missing.component.interaction", getULocale( ) ) ); //$NON-NLS-1$ return; } Trigger[] triggers = ie.getTriggers( ); if ( triggers == null ) { return; } /////////////////////////////////////////////// //Create the hotspot and add the hotspot on //the SVG hotspot layer /////////////////////////////////////////////// final PrimitiveRenderEvent pre = ie.getHotSpot( ); Element elm = null; if ( pre instanceof PolygonRenderEvent ) { final Location[] loa = ( (PolygonRenderEvent) pre ).getPoints( ); int[][] pa = getCoordinatesAsInts( loa ); elm = svggc.createPolygon( pa[0], pa[1], pa[0].length ); } else if ( pre instanceof OvalRenderEvent ) { final Bounds boEllipse = ( (OvalRenderEvent) pre ).getBounds( ); elm = svggc.createOval( boEllipse.getLeft( ), boEllipse.getTop( ), boEllipse.getWidth( ), boEllipse.getHeight( ) ); } else if ( pre instanceof RectangleRenderEvent ) { final Bounds boRect = ( (RectangleRenderEvent) pre ).getBounds( ); elm = svggc.createRect(boRect.getLeft(), boRect.getTop(), boRect.getWidth(), boRect.getHeight()); } else if ( pre instanceof AreaRenderEvent ) { AreaRenderEvent are = (AreaRenderEvent)pre; final GeneralPath gp = new GeneralPath( ); PrimitiveRenderEvent subPre; for ( int i = 0; i < are.getElementCount( ); i++ ) { subPre = are.getElement( i ); if ( subPre instanceof ArcRenderEvent ) { final ArcRenderEvent acre = (ArcRenderEvent) subPre; final Arc2D.Double a2d = new Arc2D.Double( acre.getTopLeft( ) .getX( ), acre.getTopLeft( ).getY( ), acre.getWidth( ), acre.getHeight( ), acre.getStartAngle( ), acre.getAngleExtent( ), toSwingArcType( acre.getStyle( ) ) ); gp.append( a2d, true ); } else if ( subPre instanceof LineRenderEvent ) { final LineRenderEvent lre = (LineRenderEvent) subPre; final Line2D.Double l2d = new Line2D.Double( lre.getStart( ) .getX( ), lre.getStart( ).getY( ), lre.getEnd( ).getX( ), lre.getEnd( ).getY( ) ); gp.append( l2d, true ); } } elm = svggc.createGeneralPath(gp); } else if ( pre instanceof ArcRenderEvent ) { final ArcRenderEvent are = (ArcRenderEvent) pre; if ( are.getInnerRadius( ) >= 0 && are.getOuterRadius( ) > 0 && are.getInnerRadius( ) < are.getOuterRadius( ) ) { Shape outerArc = new Arc2D.Double( are.getTopLeft( ).getX( ) + ( are.getWidth( ) - 2 * are.getOuterRadius( ) ) / 2, are.getTopLeft( ).getY( ) + ( are.getHeight( ) - 2 * are.getOuterRadius( ) ) / 2, 2 * are.getOuterRadius( ), 2 * are.getOuterRadius( ), are.getStartAngle( ), are.getAngleExtent( ), Arc2D.PIE ); Shape innerArc = new Arc2D.Double( are.getTopLeft( ).getX( ) + ( are.getWidth( ) - 2 * are.getInnerRadius( ) ) / 2, are.getTopLeft( ).getY( ) + ( are.getHeight( ) - 2 * are.getInnerRadius( ) ) / 2, 2 * are.getInnerRadius( ), 2 * are.getInnerRadius( ), are.getStartAngle( ), are.getAngleExtent( ), Arc2D.PIE ); Area fArea = new Area( outerArc ); fArea.exclusiveOr( new Area( innerArc ) ); // Shape prevClip = _g2d.getClip( ); // _g2d.setClip( fArea ); elm = svggc.createGeneralPath( fArea ); // _g2d.setClip( prevClip ); } else { elm = svggc.createGeneralPath( new Arc2D.Double( are.getTopLeft( ).getX( ), are.getTopLeft( ).getY( ), are.getWidth( ), are.getHeight( ), are.getStartAngle( ), are.getAngleExtent( ), toSwingArcType( are.getStyle( ) ) ) ); } } ivRenderer.prepareInteractiveEvent( elm, ie, triggers ); } /** * * @param iArcStyle * @return */ private static final int toSwingArcType( int iArcStyle ) { switch ( iArcStyle ) { case ArcRenderEvent.OPEN : return Arc2D.OPEN; case ArcRenderEvent.CLOSED : return Arc2D.CHORD; case ArcRenderEvent.SECTOR : return Arc2D.PIE; } return -1; } public void drawArc(ArcRenderEvent are) throws ChartException { ivRenderer.groupPrimitive(are, false); super.drawArc(are); ivRenderer.ungroupPrimitive(are, false); } public void drawArea(AreaRenderEvent are) throws ChartException { ivRenderer.groupPrimitive(are, false); super.drawArea(are); ivRenderer.ungroupPrimitive(are, false); } public void drawImage(ImageRenderEvent pre) throws ChartException { ivRenderer.groupPrimitive(pre, false); super.drawImage(pre); ivRenderer.ungroupPrimitive(pre, false); } protected Image createImage( byte[] data ) { return new SVGImage(super.createImage(data), null, data ); } public void drawLine(LineRenderEvent lre) throws ChartException { ivRenderer.groupPrimitive(lre, false); super.drawLine(lre); ivRenderer.ungroupPrimitive(lre, false); } public void drawOval(OvalRenderEvent ore) throws ChartException { ivRenderer.groupPrimitive(ore, false); super.drawOval(ore); ivRenderer.ungroupPrimitive(ore, false); } public void drawPolygon(PolygonRenderEvent pre) throws ChartException { ivRenderer.groupPrimitive(pre, false); super.drawPolygon(pre); ivRenderer.ungroupPrimitive(pre, false); } public void drawRectangle(RectangleRenderEvent rre) throws ChartException { ivRenderer.groupPrimitive(rre, false); super.drawRectangle(rre); ivRenderer.ungroupPrimitive(rre, false); } public void fillArc(ArcRenderEvent are) throws ChartException { ivRenderer.groupPrimitive(are, false); super.fillArc(are); ivRenderer.ungroupPrimitive(are, false); } public void fillArea(AreaRenderEvent are) throws ChartException { ivRenderer.groupPrimitive(are, false); super.fillArea(are); ivRenderer.ungroupPrimitive(are, false); } public void fillOval(OvalRenderEvent ore) throws ChartException { ivRenderer.groupPrimitive(ore, false); super.fillOval(ore); ivRenderer.ungroupPrimitive(ore, false); } public void fillPolygon(PolygonRenderEvent pre) throws ChartException { ivRenderer.groupPrimitive(pre, false); super.fillPolygon(pre); ivRenderer.ungroupPrimitive(pre, false); } public void fillRectangle(RectangleRenderEvent rre) throws ChartException { ivRenderer.groupPrimitive(rre, false); super.fillRectangle(rre); ivRenderer.ungroupPrimitive(rre, false); } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.event.IPrimitiveRenderListener#drawText(org.eclipse.birt.chart.event.TextRenderEvent) */ public void drawText( TextRenderEvent tre ) throws ChartException { ivRenderer.groupPrimitive(tre, true); SVGTextRenderer tr = SVGTextRenderer.instance( (SVGDisplayServer) _ids ); switch ( tre.getAction( ) ) { case TextRenderEvent.UNDEFINED : throw new ChartException( ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, "exception.missing.text.render.action", //$NON-NLS-1$ Messages.getResourceBundle( getULocale( ) ) ); case TextRenderEvent.RENDER_SHADOW_AT_LOCATION : tr.renderShadowAtLocation( this, tre.getTextPosition( ), tre.getLocation( ), tre.getLabel( ) ); break; case TextRenderEvent.RENDER_TEXT_AT_LOCATION : tr.renderTextAtLocation( this, tre.getTextPosition( ), tre.getLocation( ), tre.getLabel( ) ); break; case TextRenderEvent.RENDER_TEXT_IN_BLOCK : tr.renderTextInBlock( this, tre.getBlockBounds( ), tre.getBlockAlignment( ), tre.getLabel( ) ); break; } ivRenderer.ungroupPrimitive(tre, true); } }
- Summary: fix rc6 bug148172:[regression]Plot size of chart is incorrect in attached report - Bugzilla Bug (s) Resolved: 148172 - Description: added onresize handler to make svg chart correctly resized. - Tests Description : Manual test - Notes to Build Team: - Notes to Developers: - Notes to QA: - Notes to Documentation: - Files Edited: @changelist - Files Added: @addlist - Files Deleted @deletelist
chart/org.eclipse.birt.chart.device.svg/src/org/eclipse/birt/chart/device/svg/SVGRendererImpl.java
- Summary: fix rc6 bug148172:[regression]Plot size of chart is incorrect in attached report - Bugzilla Bug (s) Resolved: 148172 - Description: added onresize handler to make svg chart correctly resized. - Tests Description : Manual test - Notes to Build Team:
<ide><path>hart/org.eclipse.birt.chart.device.svg/src/org/eclipse/birt/chart/device/svg/SVGRendererImpl.java <ide> */ <ide> public class SVGRendererImpl extends SwingRendererImpl <ide> { <add> <ide> protected List scriptRefList = null; <ide> protected List scriptCodeList = null; <ide> private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.device.svg/trace" ); //$NON-NLS-1$ <ide> * <ide> */ <ide> private IUpdateNotifier _iun = null; <del> <del> <del> <ide> <ide> protected SVGInteractiveRenderer ivRenderer; <del> <add> <ide> /** <ide> * <ide> */ <ide> } <ide> else <ide> _ids = new SVGDisplayServer( ); <del> <add> <ide> ivRenderer = new SVGInteractiveRenderer( getULocale( ) ); <ide> } <ide> /** <ide> * "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd". <ide> */ <ide> static private final String SVG_DTD = "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"; //$NON-NLS-1$ <del> <add> <ide> /** <ide> * The SVG namespace http://www.w3.org/2000/svg <ide> */ <ide> static private final String XMLNS = "http://www.w3.org/2000/svg"; //$NON-NLS-1$ <ide> /** <del> * The xmlns:xlink is <del> * "http://www.w3.org/1999/xlink". <add> * The xmlns:xlink is "http://www.w3.org/1999/xlink". <ide> */ <ide> static private final String XMLNSXINK = "http://www.w3.org/1999/xlink"; //$NON-NLS-1$ <del> <add> <ide> /** <ide> * <ide> */ <ide> * Document object that represents the SVG <ide> */ <ide> protected Document dom; <del> <add> <ide> /** <ide> * SVG Graphic context <ide> */ <ide> protected SVGGraphics2D svggc; <del> <del> <del> <del> /** <del> * Property that determins if the SVG should resize to the containing element dimensions. <add> <add> /** <add> * Property that determins if the SVG should resize to the containing <add> * element dimensions. <ide> */ <ide> protected boolean _resizeSVG = false; <ide> <ide> { <ide> _iun = (IUpdateNotifier) oValue; <ide> ivRenderer.setIUpdateNotifier( _iun ); <del> <del> } <add> <add> } <ide> else if ( sProperty.equals( IDeviceRenderer.EXPECTED_BOUNDS ) ) <ide> { <ide> final Bounds bo = (Bounds) oValue; <ide> dom = createSvgDocument( bo.getWidth( ), bo.getHeight( ) ); <ide> svggc = new SVGGraphics2D( dom ); <ide> ivRenderer.setSVG2D( svggc ); <del> //Create the hotspot layer <del> ivRenderer.createHotspotLayer(dom); <add> // Create the hotspot layer <add> ivRenderer.createHotspotLayer( dom ); <ide> super.setProperty( IDeviceRenderer.GRAPHICS_CONTEXT, svggc ); <ide> } <ide> catch ( Exception e ) <ide> } <ide> else if ( sProperty.equals( ISVGConstants.JAVASCRIPT_CODE_LIST ) ) <ide> { <del> scriptCodeList = (List)oValue; <add> scriptCodeList = (List) oValue; <ide> } <ide> else if ( sProperty.equals( ISVGConstants.JAVASCRIPT_URL_REF_LIST ) ) <ide> { <del> scriptRefList = (List)oValue; <add> scriptRefList = (List) oValue; <ide> } <ide> else if ( sProperty.equals( ISVGConstants.RESIZE_SVG ) ) <ide> { <del> _resizeSVG = ((Boolean)oValue).booleanValue(); <del> } <del> } <del> <del> <del> <del> protected void addScripts(){ <del> if (this.scriptCodeList != null){ <del> for (int x = 0; x< scriptCodeList.size(); x++){ <del> String code = (String)scriptCodeList.get(x); <del> ((SVGGraphics2D)_g2d).addScript(code); <del> } <del> } <del> if (this.scriptRefList != null){ <del> for (int x = 0; x< scriptRefList.size(); x++){ <del> String ref = (String)scriptRefList.get(x); <del> ((SVGGraphics2D)_g2d).addScriptRef(ref); <add> _resizeSVG = ( (Boolean) oValue ).booleanValue( ); <add> } <add> } <add> <add> protected void addScripts( ) <add> { <add> if ( this.scriptCodeList != null ) <add> { <add> for ( int x = 0; x < scriptCodeList.size( ); x++ ) <add> { <add> String code = (String) scriptCodeList.get( x ); <add> ( (SVGGraphics2D) _g2d ).addScript( code ); <add> } <add> } <add> if ( this.scriptRefList != null ) <add> { <add> for ( int x = 0; x < scriptRefList.size( ); x++ ) <add> { <add> String ref = (String) scriptRefList.get( x ); <add> ( (SVGGraphics2D) _g2d ).addScriptRef( ref ); <ide> } <ide> } <ide> } <ide> public void after( ) throws ChartException <ide> { <ide> super.after( ); <del> <add> <ide> ivRenderer.addInteractivity( ); <del> addScripts(); <del> ((SVGGraphics2D)_g2d).flush(); <del> <del> //make sure we add the hotspot layer to the bottom layer of the svg <del> dom.getDocumentElement().appendChild(ivRenderer.getHotspotLayer( )); <del> <add> addScripts( ); <add> ( (SVGGraphics2D) _g2d ).flush( ); <add> <add> // make sure we add the hotspot layer to the bottom layer of the svg <add> dom.getDocumentElement( ).appendChild( ivRenderer.getHotspotLayer( ) ); <add> <ide> if ( oOutputIdentifier instanceof OutputStream ) // OUTPUT STREAM <ide> { <ide> try <ide> }, <ide> null ); <ide> } <del> <add> <ide> ivRenderer.clear( ); <del> <add> <ide> } <ide> <ide> /** <ide> DOMSource source = new DOMSource( svgDocument ); <ide> StreamResult result = new StreamResult( writer ); <ide> <del> //need to check if we should use sun's implementation of the transform factory. This is needed to work with jdk1.4 and jdk1.5 with tomcat <del> checkForTransformFactoryImpl(); <add> // need to check if we should use sun's implementation of the <add> // transform factory. This is needed to work with jdk1.4 and jdk1.5 <add> // with tomcat <add> checkForTransformFactoryImpl( ); <ide> TransformerFactory transFactory = TransformerFactory.newInstance( ); <ide> Transformer transformer = transFactory.newTransformer( ); <ide> <ide> } <ide> <ide> /** <del> * Check to see if we should change the implementation of the TransformFactory. <del> * <del> */ <del> private void checkForTransformFactoryImpl(){ <del> try { <del> Class.forName("org.apache.xalan.processor.TransformerFactoryImpl"); <del> } catch (ClassNotFoundException e) { <del> //Force using sun's implementation <del> System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); <del> } <del> } <add> * Check to see if we should change the implementation of the <add> * TransformFactory. <add> * <add> */ <add> private void checkForTransformFactoryImpl( ) <add> { <add> try <add> { <add> Class.forName( "org.apache.xalan.processor.TransformerFactoryImpl" ); //$NON-NLS-1$ <add> } <add> catch ( ClassNotFoundException e ) <add> { <add> // Force using sun's implementation <add> System.setProperty( "javax.xml.transform.TransformerFactory", //$NON-NLS-1$ <add> "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl" ); //$NON-NLS-1$ <add> } <add> } <add> <ide> /** <ide> * Creates an SVG document and assigns width and height to the root "svg" <ide> * element. <ide> builder = factory.newDocumentBuilder( ); <ide> DOMImplementation domImpl = builder.getDOMImplementation( ); <ide> DocumentType dType = domImpl.createDocumentType( "svg", //$NON-NLS-1$ <del> SVG_VERSION, SVG_DTD ); <add> SVG_VERSION, <add> SVG_DTD ); <ide> Document svgDocument = domImpl.createDocument( XMLNS, "svg", dType ); //$NON-NLS-1$ <del> svgDocument.getDocumentElement().setAttribute("xmlns", XMLNS); //$NON-NLS-1$ <del> svgDocument.getDocumentElement().setAttribute("xmlns:xlink", XMLNSXINK); //$NON-NLS-1$ <del> <del> if (_resizeSVG) <del> svgDocument.getDocumentElement().setAttribute("onload","resizeSVG(evt)"); //$NON-NLS-1$ //$NON-NLS-2$ <del> <add> svgDocument.getDocumentElement( ).setAttribute( "xmlns", XMLNS ); //$NON-NLS-1$ <add> svgDocument.getDocumentElement( ) <add> .setAttribute( "xmlns:xlink", XMLNSXINK ); //$NON-NLS-1$ <add> <add> if ( _resizeSVG ) <add> { <add> svgDocument.getDocumentElement( ) <add> .setAttribute( "onload", "resizeSVG(evt)" ); //$NON-NLS-1$ //$NON-NLS-2$ <add> // the onload() effect could be inaccurate, call onreisze again to <add> // ensure, Note onload() is still needed, because onresize may never <add> // be called. <add> svgDocument.getDocumentElement( ) <add> .setAttribute( "onresize", "resizeSVG(evt)" ); //$NON-NLS-1$ //$NON-NLS-2$ <add> } <add> <ide> return svgDocument; <ide> } <ide> <ide> */ <ide> public void changeStructure( StructureChangeEvent scev ) <ide> { <del>// Object sourceObj = scev.getSource( ); <del>// switch ( scev.getEventType( ) ) <del>// { <del>// case StructureChangeEvent.BEFORE : <del>// addGroupStructure( sourceObj ); <del>// break; <del>// case StructureChangeEvent.AFTER : <del>// removeGroupStructure( sourceObj ); <del>// break; <del>// <del>// } <add> // Object sourceObj = scev.getSource( ); <add> // switch ( scev.getEventType( ) ) <add> // { <add> // case StructureChangeEvent.BEFORE : <add> // addGroupStructure( sourceObj ); <add> // break; <add> // case StructureChangeEvent.AFTER : <add> // removeGroupStructure( sourceObj ); <add> // break; <add> // <add> // } <ide> } <ide> <ide> protected void removeGroupStructure( Object block ) <ide> Messages.getString( "exception.missing.component.interaction", getULocale( ) ) ); //$NON-NLS-1$ <ide> return; <ide> } <del> <add> <ide> Trigger[] triggers = ie.getTriggers( ); <ide> if ( triggers == null ) <ide> { <ide> return; <ide> } <ide> <del> /////////////////////////////////////////////// <del> //Create the hotspot and add the hotspot on <del> //the SVG hotspot layer <del> /////////////////////////////////////////////// <add> // ///////////////////////////////////////////// <add> // Create the hotspot and add the hotspot on <add> // the SVG hotspot layer <add> // ///////////////////////////////////////////// <ide> final PrimitiveRenderEvent pre = ie.getHotSpot( ); <ide> Element elm = null; <ide> <ide> { <ide> final Bounds boRect = ( (RectangleRenderEvent) pre ).getBounds( ); <ide> <del> elm = svggc.createRect(boRect.getLeft(), boRect.getTop(), boRect.getWidth(), boRect.getHeight()); <add> elm = svggc.createRect( boRect.getLeft( ), <add> boRect.getTop( ), <add> boRect.getWidth( ), <add> boRect.getHeight( ) ); <ide> } <ide> else if ( pre instanceof AreaRenderEvent ) <del> { <del> AreaRenderEvent are = (AreaRenderEvent)pre; <del> <add> { <add> AreaRenderEvent are = (AreaRenderEvent) pre; <add> <ide> final GeneralPath gp = new GeneralPath( ); <ide> PrimitiveRenderEvent subPre; <del> <add> <ide> for ( int i = 0; i < are.getElementCount( ); i++ ) <ide> { <ide> subPre = are.getElement( i ); <ide> { <ide> final LineRenderEvent lre = (LineRenderEvent) subPre; <ide> final Line2D.Double l2d = new Line2D.Double( lre.getStart( ) <del> .getX( ), <del> lre.getStart( ).getY( ), <del> lre.getEnd( ).getX( ), <del> lre.getEnd( ).getY( ) ); <add> .getX( ), lre.getStart( ).getY( ), lre.getEnd( ) <add> .getX( ), lre.getEnd( ).getY( ) ); <ide> gp.append( l2d, true ); <ide> } <ide> } <del> elm = svggc.createGeneralPath(gp); <del> } <add> elm = svggc.createGeneralPath( gp ); <add> } <ide> else if ( pre instanceof ArcRenderEvent ) <ide> { <ide> final ArcRenderEvent are = (ArcRenderEvent) pre; <del> <add> <ide> if ( are.getInnerRadius( ) >= 0 <ide> && are.getOuterRadius( ) > 0 <ide> && are.getInnerRadius( ) < are.getOuterRadius( ) ) <ide> Area fArea = new Area( outerArc ); <ide> fArea.exclusiveOr( new Area( innerArc ) ); <ide> <del>// Shape prevClip = _g2d.getClip( ); <del>// _g2d.setClip( fArea ); <add> // Shape prevClip = _g2d.getClip( ); <add> // _g2d.setClip( fArea ); <ide> elm = svggc.createGeneralPath( fArea ); <del>// _g2d.setClip( prevClip ); <del> } <add> // _g2d.setClip( prevClip ); <add> } <ide> else <ide> { <del> elm = svggc.createGeneralPath( new Arc2D.Double( are.getTopLeft( ).getX( ), <add> elm = svggc.createGeneralPath( new Arc2D.Double( are.getTopLeft( ) <add> .getX( ), <ide> are.getTopLeft( ).getY( ), <ide> are.getWidth( ), <ide> are.getHeight( ), <ide> are.getAngleExtent( ), <ide> toSwingArcType( are.getStyle( ) ) ) ); <ide> } <del> <del> } <del> <add> <add> } <add> <ide> ivRenderer.prepareInteractiveEvent( elm, ie, triggers ); <ide> } <del> <del> <del> <del> <del> <ide> <ide> /** <ide> * <ide> } <ide> return -1; <ide> } <del> <del> <del> <del> <del> <del> public void drawArc(ArcRenderEvent are) throws ChartException { <del> ivRenderer.groupPrimitive(are, false); <del> super.drawArc(are); <del> ivRenderer.ungroupPrimitive(are, false); <del> } <del> <del> public void drawArea(AreaRenderEvent are) throws ChartException { <del> ivRenderer.groupPrimitive(are, false); <del> super.drawArea(are); <del> ivRenderer.ungroupPrimitive(are, false); <del> } <del> <del> public void drawImage(ImageRenderEvent pre) throws ChartException { <del> ivRenderer.groupPrimitive(pre, false); <del> super.drawImage(pre); <del> ivRenderer.ungroupPrimitive(pre, false); <del> } <del> <add> <add> public void drawArc( ArcRenderEvent are ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( are, false ); <add> super.drawArc( are ); <add> ivRenderer.ungroupPrimitive( are, false ); <add> } <add> <add> public void drawArea( AreaRenderEvent are ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( are, false ); <add> super.drawArea( are ); <add> ivRenderer.ungroupPrimitive( are, false ); <add> } <add> <add> public void drawImage( ImageRenderEvent pre ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( pre, false ); <add> super.drawImage( pre ); <add> ivRenderer.ungroupPrimitive( pre, false ); <add> } <add> <ide> protected Image createImage( byte[] data ) <ide> { <del> return new SVGImage(super.createImage(data), null, data ); <del> } <del> <del> <del> public void drawLine(LineRenderEvent lre) throws ChartException { <del> ivRenderer.groupPrimitive(lre, false); <del> super.drawLine(lre); <del> ivRenderer.ungroupPrimitive(lre, false); <del> } <del> <del> public void drawOval(OvalRenderEvent ore) throws ChartException { <del> ivRenderer.groupPrimitive(ore, false); <del> super.drawOval(ore); <del> ivRenderer.ungroupPrimitive(ore, false); <del> } <del> <del> public void drawPolygon(PolygonRenderEvent pre) throws ChartException { <del> ivRenderer.groupPrimitive(pre, false); <del> super.drawPolygon(pre); <del> ivRenderer.ungroupPrimitive(pre, false); <del> } <del> <del> public void drawRectangle(RectangleRenderEvent rre) throws ChartException { <del> ivRenderer.groupPrimitive(rre, false); <del> super.drawRectangle(rre); <del> ivRenderer.ungroupPrimitive(rre, false); <del> } <del> <del> public void fillArc(ArcRenderEvent are) throws ChartException { <del> ivRenderer.groupPrimitive(are, false); <del> super.fillArc(are); <del> ivRenderer.ungroupPrimitive(are, false); <del> } <del> <del> public void fillArea(AreaRenderEvent are) throws ChartException { <del> ivRenderer.groupPrimitive(are, false); <del> super.fillArea(are); <del> ivRenderer.ungroupPrimitive(are, false); <del> } <del> <del> public void fillOval(OvalRenderEvent ore) throws ChartException { <del> ivRenderer.groupPrimitive(ore, false); <del> super.fillOval(ore); <del> ivRenderer.ungroupPrimitive(ore, false); <del> } <del> <del> public void fillPolygon(PolygonRenderEvent pre) throws ChartException { <del> ivRenderer.groupPrimitive(pre, false); <del> super.fillPolygon(pre); <del> ivRenderer.ungroupPrimitive(pre, false); <del> } <del> <del> public void fillRectangle(RectangleRenderEvent rre) throws ChartException { <del> ivRenderer.groupPrimitive(rre, false); <del> super.fillRectangle(rre); <del> ivRenderer.ungroupPrimitive(rre, false); <del> } <del> <add> return new SVGImage( super.createImage( data ), null, data ); <add> } <add> <add> public void drawLine( LineRenderEvent lre ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( lre, false ); <add> super.drawLine( lre ); <add> ivRenderer.ungroupPrimitive( lre, false ); <add> } <add> <add> public void drawOval( OvalRenderEvent ore ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( ore, false ); <add> super.drawOval( ore ); <add> ivRenderer.ungroupPrimitive( ore, false ); <add> } <add> <add> public void drawPolygon( PolygonRenderEvent pre ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( pre, false ); <add> super.drawPolygon( pre ); <add> ivRenderer.ungroupPrimitive( pre, false ); <add> } <add> <add> public void drawRectangle( RectangleRenderEvent rre ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( rre, false ); <add> super.drawRectangle( rre ); <add> ivRenderer.ungroupPrimitive( rre, false ); <add> } <add> <add> public void fillArc( ArcRenderEvent are ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( are, false ); <add> super.fillArc( are ); <add> ivRenderer.ungroupPrimitive( are, false ); <add> } <add> <add> public void fillArea( AreaRenderEvent are ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( are, false ); <add> super.fillArea( are ); <add> ivRenderer.ungroupPrimitive( are, false ); <add> } <add> <add> public void fillOval( OvalRenderEvent ore ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( ore, false ); <add> super.fillOval( ore ); <add> ivRenderer.ungroupPrimitive( ore, false ); <add> } <add> <add> public void fillPolygon( PolygonRenderEvent pre ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( pre, false ); <add> super.fillPolygon( pre ); <add> ivRenderer.ungroupPrimitive( pre, false ); <add> } <add> <add> public void fillRectangle( RectangleRenderEvent rre ) throws ChartException <add> { <add> ivRenderer.groupPrimitive( rre, false ); <add> super.fillRectangle( rre ); <add> ivRenderer.ungroupPrimitive( rre, false ); <add> } <add> <ide> /* <ide> * (non-Javadoc) <ide> * <ide> */ <ide> public void drawText( TextRenderEvent tre ) throws ChartException <ide> { <del> ivRenderer.groupPrimitive(tre, true); <add> ivRenderer.groupPrimitive( tre, true ); <ide> SVGTextRenderer tr = SVGTextRenderer.instance( (SVGDisplayServer) _ids ); <ide> switch ( tre.getAction( ) ) <ide> { <ide> tre.getLabel( ) ); <ide> break; <ide> } <del> ivRenderer.ungroupPrimitive(tre, true); <del> } <del> <add> ivRenderer.ungroupPrimitive( tre, true ); <add> } <ide> <ide> }
JavaScript
mit
319a580c3d715666e6174cea41bd83e1ad057a65
0
officert/mongotron,officert/mongotron
'use strict'; angular.module('app').directive('codemirror', [ '$window', '$timeout', function($window, $timeout) { return { restrict: 'A', require: 'ngModel', scope: { codemirror: '=', hasFocus: '=', handle: '=', customData: '=' }, link: function(scope, element, attrs, ngModelCtrl) { var editor; var options = scope.codemirror || {}; scope.handle = scope.handle || {}; scope.handle.autoformat = function() { _autoFormatSelection(editor); }; const TAB = ' '; //2 spaces options.lineNumbers = options.lineNumbers || true; options.extraKeys = options.extraKeys || {}; options.tabSize = TAB.length; options.indentWithTabs = false; options.mode = { name: 'javascript', globalVars: true }; init(); //take initial model value and set editor with it ngModelCtrl.$formatters.push(function(modelValue) { $timeout(function() { editor.setValue(modelValue); }); return modelValue; }); function init() { editor = new $window.CodeMirror(function(editorElement) { element.append(editorElement); }, options); _.extend(editor, { customData: scope.customData }); element.data('CodeMirrorInstance', editor); //make the instance available from the DOM editor.setOption('extraKeys', { Tab: function(cm) { //use spaces instead of tabs var spaces = new Array(cm.getOption('indentUnit') + 1).join(' '); cm.replaceSelection(spaces); } }); _registerEditorEvents(); editor.refresh(); } function _autoFormatSelection(codeMirrorEditor) { if (!codeMirrorEditor) return; var totalLines = codeMirrorEditor.lineCount(); var totalChars = codeMirrorEditor.getValue().length; codeMirrorEditor.autoFormatRange({ line: 0, ch: 0 }, { line: totalLines, ch: totalChars }); } function _showAutoComplete(cm, event) { if (cm.state.completionActive) return; if (event && event.keyCode === 13) return; CodeMirror.commands.autocomplete(cm, null, { completeSingle: false }); } function _registerEditorEvents() { editor.on('keyup', function(cm, event) { $timeout(function() { _showAutoComplete(cm, event); }); }); editor.on('change', function() { $timeout(function() { var value = editor.getValue(); value = value && value.trim ? value.trim() : value; ngModelCtrl.$setViewValue(value); }); }); editor.on('focus', function(cm, event) { $timeout(function() { scope.hasFocus = true; var value = editor.getValue(); if (!value) { _showAutoComplete(cm, event); } }); }); editor.on('blur', function() { $timeout(function() { scope.hasFocus = false; }); }); } } }; } ]); (() => { const hinter = require('lib/modules/query/hinter'); CodeMirror.registerHelper('hint', 'javascript', function(codemirror) { var currentValue = codemirror.getValue(); let customData = codemirror.customData || []; let results = hinter.getHintsByValue(currentValue, { collectionNames: customData.collectionNames }); let inner = { from: codemirror.getCursor(), to: codemirror.getCursor(), list: null }; inner.list = results.hints || []; // inner.list = _filterAutoCompleteHintsByInput(results.value, results.hints || []) || []; return inner; }); // https://github.com/codemirror/CodeMirror/issues/3092 let javascriptHint = CodeMirror.hint.javascript; CodeMirror.hint.javascript = function(codemirror, options) { var codemirrorInstance = codemirror; var result = javascriptHint(codemirror, options); if (result) { CodeMirror.on(result, 'pick', function(selectedHint) { var currentValue = codemirrorInstance.getValue(); var previousValue = currentValue.substring(0, currentValue.indexOf(selectedHint)); var parts = previousValue.split('.'); parts.pop(); parts.push(selectedHint); var newValue = parts.length > 1 ? parts.join('.') : parts[0]; codemirrorInstance.setValue(newValue); }); } return result; }; // function _filterAutoCompleteHintsByInput(input, hints) { // if (!input) return null; // if (!hints || !hints.length) return null; // // var term = $.ui.autocomplete.escapeRegex(input); // // var startsWithMatcher = new RegExp('^' + term, 'i'); // var startsWith = $.grep(hints, function(value) { // return startsWithMatcher.test(value.label || value.value || value); // }); // // var containsMatcher = new RegExp(term, 'i'); // var contains = $.grep(hints, function(value) { // return $.inArray(value, startsWith) < 0 && // containsMatcher.test(value.label || value.value || value); // }); // // return startsWith.concat(contains); // } }());
src/ui/directives/codemirror/codemirror.js
'use strict'; angular.module('app').directive('codemirror', [ '$window', '$timeout', function($window, $timeout) { return { restrict: 'A', require: 'ngModel', scope: { codemirror: '=', hasFocus: '=', handle: '=', customData: '=' }, link: function(scope, element, attrs, ngModelCtrl) { var editor; var options = scope.codemirror || {}; scope.handle = scope.handle || {}; scope.handle.autoformat = function() { _autoFormatSelection(editor); }; const TAB = ' '; //2 spaces options.lineNumbers = options.lineNumbers || true; options.extraKeys = options.extraKeys || {}; options.tabSize = TAB.length; options.indentWithTabs = false; options.mode = { name: 'javascript', globalVars: true }; init(); //take initial model value and set editor with it ngModelCtrl.$formatters.push(function(modelValue) { $timeout(function() { editor.setValue(modelValue); }); return modelValue; }); function init() { editor = new $window.CodeMirror(function(editorElement) { element.append(editorElement); }, options); _.extend(editor, { customData: scope.customData }); element.data('CodeMirrorInstance', editor); //make the instance available from the DOM editor.setOption('extraKeys', { Tab: function(cm) { //use spaces instead of tabs var spaces = new Array(cm.getOption('indentUnit') + 1).join(' '); cm.replaceSelection(spaces); } }); _registerEditorEvents(); editor.refresh(); } function _autoFormatSelection(codeMirrorEditor) { if (!codeMirrorEditor) return; var totalLines = codeMirrorEditor.lineCount(); var totalChars = codeMirrorEditor.getValue().length; codeMirrorEditor.autoFormatRange({ line: 0, ch: 0 }, { line: totalLines, ch: totalChars }); } function _showAutoComplete(cm, event) { if (cm.state.completionActive) return; if (event && event.keyCode === 13) return; CodeMirror.commands.autocomplete(cm, null, { completeSingle: false }); } function _registerEditorEvents() { editor.on('keyup', function(cm, event) { $timeout(function() { _showAutoComplete(cm, event); }); }); editor.on('change', function() { $timeout(function() { var value = editor.getValue(); value = value && value.trim ? value.trim() : value; ngModelCtrl.$setViewValue(value); }); }); editor.on('focus', function(cm, event) { $timeout(function() { scope.hasFocus = true; var value = editor.getValue(); if (!value) { _showAutoComplete(cm, event); } }); }); editor.on('blur', function() { $timeout(function() { scope.hasFocus = false; }); }); editor.on('endCompletion', function() { console.log('AUTOCOMPLETE FINISHED', arguments); var editorValue = editor.getValue(); console.log('editorValue', editorValue); // var value = getFullValue(editorValue); // // if (value) { // codemirror.setValue(value); // codemirror.setCursor(1, 4); // } }); } } }; } ]); (() => { const hinter = require('lib/modules/query/hinter'); CodeMirror.registerHelper('hint', 'javascript', function(codemirror) { var currentValue = codemirror.getValue(); let customData = codemirror.customData || []; console.log(customData); // var collectionNames = currentCollection && currentCollection.database ? _.pluck(currentCollection.database.collections, 'name') : []; let results = hinter.getHintsByValue(currentValue, { collectionNames : customData.collectionNames }); let inner = { from: codemirror.getCursor(), to: codemirror.getCursor(), list: null }; inner.list = results.hints || []; // inner.list = _filterAutoCompleteHintsByInput(results.value, results.hints) || []; return inner; }); }());
hook into the autocomplete ‘select’ event to replace the code mirror instance value with the autocomplete selection
src/ui/directives/codemirror/codemirror.js
hook into the autocomplete ‘select’ event to replace the code mirror instance value with the autocomplete selection
<ide><path>rc/ui/directives/codemirror/codemirror.js <ide> scope.hasFocus = false; <ide> }); <ide> }); <del> <del> editor.on('endCompletion', function() { <del> console.log('AUTOCOMPLETE FINISHED', arguments); <del> <del> var editorValue = editor.getValue(); <del> <del> console.log('editorValue', editorValue); <del> <del> // var value = getFullValue(editorValue); <del> // <del> // if (value) { <del> // codemirror.setValue(value); <del> // codemirror.setCursor(1, 4); <del> // } <del> }); <ide> } <ide> } <ide> }; <ide> <ide> let customData = codemirror.customData || []; <ide> <del> console.log(customData); <del> <del> // var collectionNames = currentCollection && currentCollection.database ? _.pluck(currentCollection.database.collections, 'name') : []; <del> <ide> let results = hinter.getHintsByValue(currentValue, { <del> collectionNames : customData.collectionNames <add> collectionNames: customData.collectionNames <ide> }); <ide> <ide> let inner = { <ide> }; <ide> <ide> inner.list = results.hints || []; <del> // inner.list = _filterAutoCompleteHintsByInput(results.value, results.hints) || []; <add> // inner.list = _filterAutoCompleteHintsByInput(results.value, results.hints || []) || []; <ide> <ide> return inner; <ide> }); <add> <add> <add> // https://github.com/codemirror/CodeMirror/issues/3092 <add> let javascriptHint = CodeMirror.hint.javascript; <add> CodeMirror.hint.javascript = function(codemirror, options) { <add> var codemirrorInstance = codemirror; <add> <add> var result = javascriptHint(codemirror, options); <add> <add> if (result) { <add> CodeMirror.on(result, 'pick', function(selectedHint) { <add> var currentValue = codemirrorInstance.getValue(); <add> <add> var previousValue = currentValue.substring(0, currentValue.indexOf(selectedHint)); <add> <add> var parts = previousValue.split('.'); <add> parts.pop(); <add> parts.push(selectedHint); <add> <add> var newValue = parts.length > 1 ? parts.join('.') : parts[0]; <add> <add> codemirrorInstance.setValue(newValue); <add> }); <add> } <add> return result; <add> }; <add> <add> // function _filterAutoCompleteHintsByInput(input, hints) { <add> // if (!input) return null; <add> // if (!hints || !hints.length) return null; <add> // <add> // var term = $.ui.autocomplete.escapeRegex(input); <add> // <add> // var startsWithMatcher = new RegExp('^' + term, 'i'); <add> // var startsWith = $.grep(hints, function(value) { <add> // return startsWithMatcher.test(value.label || value.value || value); <add> // }); <add> // <add> // var containsMatcher = new RegExp(term, 'i'); <add> // var contains = $.grep(hints, function(value) { <add> // return $.inArray(value, startsWith) < 0 && <add> // containsMatcher.test(value.label || value.value || value); <add> // }); <add> // <add> // return startsWith.concat(contains); <add> // } <ide> }());
JavaScript
agpl-3.0
53612ca467ebd585efcbd8b0f0f6649a0124c8a8
0
denkbar/step,denkbar/step,denkbar/step,denkbar/step,denkbar/step
function getVizDashboardList(){ return [["WikimediaDemo"], ["PerformanceDashboard"], ["RealtimePerformanceDashboard"]]; } var overtimeFillBlanksTransformFn = function(response, args) { var metric = args.metric; var retData = [], series = []; var payload = response.data.payload.stream.streamData; var payloadKeys = Object.keys(payload); for (i = 0; i < payloadKeys.length; i++) { var series_ = payload[payloadKeys[i]]; var serieskeys = Object.keys(series_ ) for (j = 0; j < serieskeys.length; j++) { if(!series.includes(serieskeys[j])){ series.push(serieskeys[j]); } } } for (i = 0; i < payloadKeys.length; i++) { var series_ = payload[payloadKeys[i]]; var serieskeys = Object.keys(series) for (j = 0; j < serieskeys.length; j++) { var key = series[serieskeys[j]]; var yval; if(series_[key] && series_[key][metric]){ yval = series_[key][metric]; }else{ yval = 0; } retData.push({ x: payloadKeys[i], y: yval, z: key }); } } return retData; }; function RealtimeSelfMonitoring() { var widgetsArray = []; var freeTokenTransform = function (response, args) { var array = [] $.each(response.data, function(index, item){ array.push({ x : new Date().getTime(), y : item.tokensCapacity.countByState.FREE, z : item.agentRef.agentUrl.split('http://')[1] }); }); return array; } var baseAgentQuery = new SimpleQuery("Raw", new Service("", "Get","",new DefaultPreproc(),new Postproc("", freeTokenTransform.toString(), [], {}, ""))); var agentQueryTemplate = new TemplatedQuery("Plain",baseAgentQuery,new DefaultPaging(),new Controls(new Template("","/rest/grid/agent",[]))); var options = new EffectiveChartOptions('lineChart'); options.showLegend = true; var widget1 = new Widget(getUniqueId(), new WidgetState('col-md-6', false, true), new DashletState("Free tokens per agent", false, 0, {}, options, new Config('On', false, false, '', 1000, 500, 'On', 20), agentQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(widget1); var executionsTransform = function (response, args) { return [{x: new Date().getTime(), y:response.data.recordsFiltered, z:'Ongoing executions'}]; }; var baseExecQuery = new SimpleQuery("Raw", new Service("", "Get","",new DefaultPreproc(),new Postproc("", executionsTransform.toString(), [], {}, ""))); var execQueryTemplate = new TemplatedQuery("Plain",baseExecQuery,new DefaultPaging(),new Controls(new Template("","rest/datatable/executions/data?ignoreContext=true&draw=__draw__&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=4&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=5&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=6&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=(INITIALIZING%7CIMPORTING%7CRUNNING%7CABORTING%7CEXPORTING)&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=true&columns%5B7%5D%5Bdata%5D=7&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B8%5D%5Bdata%5D=8&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=true&columns%5B8%5D%5Borderable%5D=true&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B9%5D%5Bdata%5D=9&columns%5B9%5D%5Bname%5D=&columns%5B9%5D%5Bsearchable%5D=true&columns%5B9%5D%5Borderable%5D=true&columns%5B9%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B9%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B10%5D%5Bdata%5D=10&columns%5B10%5D%5Bname%5D=&columns%5B10%5D%5Bsearchable%5D=true&columns%5B10%5D%5Borderable%5D=true&columns%5B10%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B10%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=2&order%5B0%5D%5Bdir%5D=desc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&undefined",[new Placeholder("__dayFrom__", "20151010", false), new Placeholder("__draw__", "Math.random().toString().split('.')[1].substring(0,8)", true)]))); var options = new EffectiveChartOptions('lineChart'); options.showLegend = true; var widget2 = new Widget(getUniqueId(), new WidgetState('col-md-6', false, true), new DashletState("Global number of on-going executions", false, 0, {}, options, new Config('On', false, false, '', 1000, 500, 'On', 20), execQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(widget2); var dashboardObject = new Dashboard('Instance Activity',new DashboardState(new GlobalSettings([],false,false,'Global Settings',1000), widgetsArray,'SelfMonitoring Dashboard','aggregated',new DefaultDashboardGui()) ); return dashboardObject; } function WikimediaDemo() { var widgetsArray = []; var wikimediaTransformFunction = function (response, args) { var ret = []; var items = response.data.items; for(var i=0; i < items.length; i++){ ret.push({x: items[i].timestamp, y: items[i].views, z: 'views'}); } return ret; }; var wikimediaBaseQuery = new SimpleQuery( "Raw", new Service( "", "Get","", new DefaultPreproc(), new Postproc("", wikimediaTransformFunction.toString(), [], {}, "") ) ); var wikimediaQueryTemplate = new TemplatedQuery( "Plain", wikimediaBaseQuery, new DefaultPaging(), new Controls(new Template("","https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Foo/daily/__dayFrom__/__dayTo__", [new Placeholder("__dayFrom__", "20151010", false), new Placeholder("__dayTo__", "20151030", false)])) ); var xAxisFn = function(d) { var str = d.toString(); var year = str.substring(0,4); var month = str.substring(4, 6); var day = str.substring(6, 8); return year + '-' + month + '-' + day; }; var options = new EffectiveChartOptions('lineChart', xAxisFn.toString()); options.showLegend = true; var widget = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(" Daily wikimedia stats", false, 0, {}, options, new Config('Off', false, false, ''), wikimediaQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(widget); var dashboardObject = new Dashboard( 'Daily Stats', new DashboardState( new GlobalSettings( [new Placeholder("__businessobjectid__", "", false)], false, false, 'Global Settings', 3000 ), widgetsArray, 'Wikimedia Dashboard', 'aggregated', new DefaultDashboardGui() ) ); return dashboardObject; } function ProjectOverview() { var widgetsArray = []; var executionsTransform = function (response, args) { var array = []; var min = new Date().getTime() - 604800000; var max = new Date().getTime(); var nbIntervals = 7; var interval = Math.round((max - min -1) / nbIntervals); var groupArray = []; var groupStats = {}; for(i=0; i< nbIntervals; i++){ var from_ = min + (i * interval); groupArray.push({from: from_, to: min + ((i+1)*interval)}); groupStats[from_] = 0; } $.each(response.data, function(index, item){ $.each(groupArray, function(index, item2){ if(item.startTime >= item2.from && item.startTime < item2.to){ groupStats[item2.from]+=1; } }); }); $.each(Object.keys(groupStats), function(index, item){ array.push({x: item, y: groupStats[item], z: 'Nb executions'}); }); return array; }; var xAxisFn = function (d) { var value; if ((typeof d) === "string") { value = parseInt(d); } else { value = d; } return d3.time.format("%Y-%m-%d")(new Date(value)); }; var baseExecQuery = new SimpleQuery("Raw", new Service("", "Post","",new DefaultPreproc(),new Postproc("", executionsTransform.toString(), [], {}, ""))); var execQueryTemplate = new TemplatedQuery("Plain",baseExecQuery,new DefaultPaging(),new Controls(new Template("{ \"criteria\": { \"attributes.project\": \"__businessobjectid__\"}, \"start\" : __from__, \"end\" : __to__}","/rest/controller/executions/findByCritera",[new Placeholder("__from__", "new Date().getTime()-604800000", true), new Placeholder("__to__", "new Date().getTime()", true)]))); var options = new EffectiveChartOptions('lineChart', xAxisFn.toString()); options.showLegend = true; var widget1 = new Widget(getUniqueId(), new WidgetState('col-md-6', false, true), new DashletState("Executions per day over last week", false, 0, {}, options, new Config('Off', false, false, '', 1000, 500, 'Off', 20), execQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(widget1); var entityName = "keyword"; var timeFrame = 604800000; var granularity_ = 86400000; var timeField = "begin"; var timeFormat = "long"; var valueField = "value"; var groupby = "name"; var textFilters = "[{ \"key\": \"project\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"keyword\", \"regex\": \"false\" }]"; var numericalFilters = "[]"; var overtimeTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n z: serieskeys[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; var config = getMasterSlaveConfig("raw", "Nb Keyword executions per day over last week", ""); var widget2 = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('stackedAreaChart', xAxisFn.toString(), timeFrame), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", granularity_, overtimeFillBlanksTransformFn.toString(), entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(widget2); var dashboardObject = new Dashboard('Weekly project overview',new DashboardState(new GlobalSettings([],false,false,'Global Settings',1000), widgetsArray,'Project stats','aggregated',new DefaultDashboardGui()) ); return dashboardObject; } function RealtimePerformanceDashboard(executionId, measurementType, entity, autorefresh) { var widgetsArray = []; var entityName = ''; if(measurementType && measurementType === 'keyword'){ entityName = 'Keyword'; }else{ entityName = 'Custom Transaction'; } var timeFrame = 30000; var timeField = "begin"; var timeFormat = "long"; var valueField = "value"; var groupby = "name"; var textFilters = "[{ \"key\": \"eId\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }]"; var numericalFilters = "[{ \"key\": \"begin\", \"minValue\": \"__from__\", \"maxValue\": \"__to__\" }]"; addAggregatesOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addErrorsOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addLastMeasurementsTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); //addErrorsSummary(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addAggregatesSummaryTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); var dashboardObject = new Dashboard( entityName + ' Performance', new DashboardState( new GlobalSettings( [new Placeholder("__businessobjectid__", executionId, false), new Placeholder("__measurementType__", measurementType?measurementType:'custom', false), new Placeholder("__from__", "new Date(new Date().getTime() - "+timeFrame+").getTime()", true), new Placeholder("__to__", "new Date().getTime()", true) ], autorefresh?autorefresh:true, false, 'Global Settings', 3000 ), widgetsArray, entityName + ' Dashboard', 'aggregated', new DefaultDashboardGui() ) ); dashboardObject.oid = "realTimePerfDashboardId"; return dashboardObject; }; function PerformanceDashboard(executionId, measurementType, entity) { var widgetsArray = []; var entityName = ''; if(measurementType && measurementType === 'keyword'){ entityName = 'Keyword'; }else{ entityName = 'Custom Transaction'; } var timeFrame = null; var timeField = "begin"; var timeFormat = "long"; var valueField = "value"; var groupby = "name"; var textFilters = "[{ \"key\": \"eId\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }]"; var numericalFilters = "[]"; addAggregatesOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addErrorsOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addLastMeasurementsTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); //addErrorsSummary(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addAggregatesSummaryTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); var dashboardObject = new Dashboard( entityName + ' Performance', new DashboardState( new GlobalSettings( [new Placeholder("__businessobjectid__", executionId, false), new Placeholder("__measurementType__", measurementType?measurementType:'custom', false)], false, false, 'Global Settings', 3000 ), widgetsArray, entityName + ' Dashboard', 'aggregated', new DefaultDashboardGui() ) ); dashboardObject.oid = "perfDashboardId"; return dashboardObject; }; function EffectiveChartOptions(charType, xAxisOverride, timeFrame, yAxisOverride){ var opts = new ChartOptions(charType, true, false, xAxisOverride?xAxisOverride:'function (d) {\r\n var value;\r\n if ((typeof d) === \"string\") {\r\n value = parseInt(d);\r\n } else {\r\n value = d;\r\n }\r\n\r\n return d3.time.format(\"%H:%M:%S\")(new Date(value));\r\n}', yAxisOverride?yAxisOverride:'function (d) { return d.toFixed(1); }', timeFrame?'[new Date(new Date().getTime() - '+timeFrame+').getTime(), new Date().getTime()]':undefined ); opts.margin.left = 75; return opts; } function RTMAggBaseQueryTmpl(metric, transform){ return new AsyncQuery( null, new Service(//service "/rtm/rest/aggregate/get", "Post", "",//templated new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"), new Postproc("", "",[], "function(response){if(!response.data.payload){console.log('No payload ->' + JSON.stringify(response)); return null;}return [{ placeholder : '__streamedSessionId__', value : response.data.payload.streamedSessionId, isDynamic : false }];}", "") ), new Service(//callback "/rtm/rest/aggregate/refresh", "Post", "{\"streamedSessionId\": \"__streamedSessionId__\"}", new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].placeholder, workData[i].value);}return newRequestFragment;}"), new Postproc("function(response){return response.data.payload.stream.complete;}", transform ,[{"key" : "metric", "value" : metric, "isDynamic" : false}], {}, "")) ); }; function RTMAggBaseTemplatedQueryTmpl(metric, pGranularity, transform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ return new TemplatedQuery( "Plain", new RTMAggBaseQueryTmpl(metric, transform), new DefaultPaging(), new Controls( new Template( "{ \"selectors1\": [{ \"textFilters\": "+textFilters+", \"numericalFilters\": "+numericalFilters+" }], \"serviceParams\": { \"measurementService.nextFactor\": \"0\", \"aggregateService.timeField\" : \""+timeField+"\", \"aggregateService.timeFormat\" : \""+timeFormat+"\", \"aggregateService.valueField\" : \""+valueField+"\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"__granularity__\", \"aggregateService.groupby\": \""+groupby+"\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }", "", [new Placeholder("__granularity__", pGranularity, false)] ) ) ); }; var addAggregatesSummaryTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var summaryTransform = "function (response) {\r\n //var metrics = response.data.payload.metricList;\r\n var metrics = [\"cnt\",\"avg\", \"min\", \"max\", \"tpm\", \"tps\", \"90th pcl\"];\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n if (payload && payloadKeys.length > 0) {\r\n var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n for (i = 0; i < metrics.length; i++) {\r\n var metric = metrics[i];\r\n if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n retData.push({\r\n x: metric,\r\n y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n z: serieskeys[j]\r\n });\r\n }else{\r\n retData.push({ x: metric, y: 0, z: serieskeys[j]});\r\n }\r\n }\r\n }\r\n }\r\n return retData;\r\n}"; var standalone = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(entityName + " stats summary", false, 0, {}, new EffectiveChartOptions('seriesTable', 'function(d) { return d; }', timeFrame), new Config('Off', false, false, '', 3000, 1000, 'Off', 8, 'On'), new RTMAggBaseTemplatedQueryTmpl("sum", "max", summaryTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(standalone); }; var addAggregatesOverTimeTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var overtimeTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n z: serieskeys[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; var config = getMasterSlaveConfig("raw", "Average "+entityName+" Duration (ms)", "Nb " + entityName + "s per second"); var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('lineChart', null, timeFrame), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("avg", "auto", overtimeTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); //var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('lineChart'), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", overtimeTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('stackedAreaChart', null, timeFrame), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("tps", "auto", overtimeFillBlanksTransformFn.toString(), entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(master); widgetsArray.push(slave); }; //No paging: FACTOR 100 via template var addLastMeasurementsTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ function RTMLatestMeasurementBaseQueryTmpl(){ return new SimpleQuery( "Raw", new Service( "/rtm/rest/measurement/latest", "Post", "", new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"), new Postproc("", "function (response, args) {\r\n var x = '"+timeField+"', y = '"+valueField+"', z = '"+groupby+"';\r\n var retData = [], index = {};\r\n var payload = response.data.payload;\r\n for (var i = 0; i < payload.length; i++) {\r\n retData.push({\r\n x: payload[i][x],\r\n y: payload[i][y],\r\n z: payload[i][z]\r\n });\r\n }\r\n return retData;\r\n}", [], {}, "") ) ); }; function RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ return new TemplatedQuery( "Plain", new RTMLatestMeasurementBaseQueryTmpl(), new DefaultPaging(), //new Paging("On", new Offset("__FACTOR__", "return 0;", "return value + 1;", "if(value > 0){return value - 1;} else{return 0;}"), null), new Controls( new Template( "{ \"selectors1\": [{ \"textFilters\": "+textFilters+", \"numericalFilters\": "+numericalFilters+" }], \"serviceParams\": { \"measurementService.nextFactor\": \"__FACTOR__\", \"aggregateService.timeField\" : \""+timeField+"\", \"aggregateService.timeFormat\" : \""+timeFormat+"\", \"aggregateService.valueField\" : \""+valueField+"\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"auto\", \"aggregateService.groupby\": \""+groupby+"\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }", "", [new Placeholder("__FACTOR__", "100", false)] ) ) ); }; var config = getMasterSlaveConfig("transformed", "Last 100 " + entityName +"s - Individual duration (ms)", "Last 100 "+entityName+"s - Value table (ms)"); var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('scatterChart', null, null), config.masterconfig, new RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo()) ); var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('seriesTable', null, null), config.slaveconfig, new RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo()) ); widgetsArray.push(master); //widgetsArray.push(slave); }; //No paging: hardcoded simple query var addLastMeasurements = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ function RTMLatestMeasurementBaseQuery(){ return new SimpleQuery( "Raw", new Service( "/rtm/rest/measurement/latest", "Post", "{\"selectors1\": [{ \"textFilters\": "+textFilters+", \"numericalFilters\": "+numericalFilters+" }],\"serviceParams\": { \"measurementService.nextFactor\": \"100\", \"aggregateService.timeField\" : \""+timeField+"\", \"aggregateService.timeFormat\" : \""+timeFormat+"\", \"aggregateService.valueField\" : \""+valueField+"\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"auto\", \"aggregateService.groupby\": \""+groupby+"\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" }\}", new Preproc(""), new Postproc("", "function (response, args) {\r\n var x = '"+timeField+"', y = '"+valueField+"', z = '"+groupby+"';\r\n var retData = [], index = {};\r\n var payload = response.data.payload;\r\n for (var i = 0; i < payload.length; i++) {\r\n retData.push({\r\n x: payload[i][x],\r\n y: payload[i][y],\r\n z: payload[i][z]\r\n });\r\n }\r\n return retData;\r\n}", [], {}, "") ) ); }; var config = getMasterSlaveConfig("raw", "Last 100 Measurements - Scattered values (ms)", "Last 100 Measurements - Value table (ms)"); var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('scatterChart', null, timeFrame), config.masterconfig, new RTMLatestMeasurementBaseQuery(), new DefaultGuiClosed(), new DefaultInfo()) ); var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('seriesTable', null, timeFrame), config.slaveconfig, new RTMLatestMeasurementBaseQuery(), new DefaultGuiClosed(), new DefaultInfo()) ); widgetsArray.push(master); widgetsArray.push(slave); }; var addErrorsSummary = function(widgetsArray, entityName, timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var summaryTransform = "function (response) {\r\n //var metrics = response.data.payload.metricList;\r\n var metrics = [\"cnt\"];\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n if (payload && payloadKeys.length > 0) {\r\n var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n for (i = 0; i < metrics.length; i++) {\r\n var metric = metrics[i];\r\n if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n retData.push({\r\n x: metric,\r\n y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n z: '\u0020' + serieskeys[j].split('_')[0]\r\n });\r\n }else{\r\n retData.push({ x: metric, y: 0, z: serieskeys[j]});\r\n }\r\n }\r\n }\r\n }\r\n return retData;\r\n}"; var standalone = new Widget(getUniqueId(), new DefaultWidgetState(), new DashletState(entityName + " status summary", false, 0, {}, new EffectiveChartOptions('singleValueTable', 'function(d) { return d; }', timeFrame), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("cnt", "max", summaryTransform, entityName,timeField, timeFormat, valueField, "rnStatus", textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(standalone); }; var addErrorsOverTimeTpl = function(widgetsArray, entityName, timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var summaryTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = [];\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n if(!serieskeys[j].includes(';PASSED') && !series.includes(serieskeys[j])){\r\n series.push(serieskeys[j]);\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n for (j = 0; j < series.length; j++) {\r\n var yval;\r\n if(payload[payloadKeys[i]][series[j]] && payload[payloadKeys[i]][series[j]][metric]){\r\n yval = payload[payloadKeys[i]][series[j]][metric];\r\n }else{\r\n //console.log('missing dot: x=' + payloadKeys[i] + '; series=' + series[j]);\r\n yval = 0;\r\n }\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: yval,\r\n z: series[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; var standalone = new Widget(getUniqueId(), new DefaultWidgetState(), new DashletState(entityName + " errors over time", false, 0, {}, new EffectiveChartOptions('stackedAreaChart', null, timeFrame), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", summaryTransform, entityName,timeField, timeFormat, valueField, "name;rnStatus", textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(standalone); }; var getMasterSlaveConfig = function(rawOrTransformed, masterTitle, slaveTitle){ var masterId, slaveId, masterTitle, slaveTitle, masterConfig, slaveConfig, datatype; if(rawOrTransformed === 'raw'){ datatype = 'state.data.rawresponse'; }else{ datatype = 'state.data.transformed'; } var random = getUniqueId(); masterId = random + "-master"; slaveId = random + "-slave"; masterConfig = new Config('Off', true, false, 'unnecessaryAsMaster'); slaveConfig = new Config('Off', false, true, datatype); slaveConfig.currentmaster = { oid: masterId, title: masterTitle }; return {masterid: masterId, slaveid: slaveId, mastertitle: masterTitle, slavetitle: slaveTitle, masterconfig : masterConfig, slaveconfig: slaveConfig}; }; function StaticPresets() { return { queries: [], controls: { templates: [] }, configs: [] }; }
step-controller/step-controller-server-webapp/src/main/resources/webapp/js/viz-presets.js
function getVizDashboardList(){ return [["WikimediaDemo"], ["PerformanceDashboard"], ["RealtimePerformanceDashboard"]]; } function WikimediaDemo() { var widgetsArray = []; var wikimediaTransformFunction = function (response, args) { var ret = []; var items = response.data.items; for(var i=0; i < items.length; i++){ ret.push({x: items[i].timestamp, y: items[i].views, z: 'views'}); } return ret; }; var wikimediaBaseQuery = new SimpleQuery( "Raw", new Service( "", "Get","", new DefaultPreproc(), new Postproc("", wikimediaTransformFunction.toString(), [], {}, "") ) ); var wikimediaQueryTemplate = new TemplatedQuery( "Template", wikimediaBaseQuery, new DefaultPaging(), new Controls(new Template("","https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Foo/daily/__dayFrom__/__dayTo__", [new Placeholder("__dayFrom__", "20151010", false), new Placeholder("__dayTo__", "20151030", false)])) ); var xAxisFn = function(d) { var str = d.toString(); var year = str.substring(0,4); var month = str.substring(4, 6); var day = str.substring(6, 8); return year + '-' + month + '-' + day; }; var options = new EffectiveChartOptions('lineChart', xAxisFn); options.showLegend = true; var widget = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(" Daily wikimedia stats", false, 0, {}, options, new Config('Off', false, false, ''), wikimediaQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(widget); var dashboardObject = new Dashboard( 'Daily Stats', new DashboardState( new GlobalSettings( [], false, false, 'Global Settings', 5000 ), widgetsArray, 'Wikimedia Dashboard', 'aggregated', new DefaultDashboardGui() ) ); return dashboardObject; } function RealtimePerformanceDashboard(executionId, measurementType, entity) { var widgetsArray = []; var entityName = ''; if(measurementType && measurementType === 'keyword'){ entityName = 'Keyword'; }else{ entityName = 'Custom Transaction'; } var timeFrame = 10000; var timeField = "begin"; var timeFormat = "long"; var valueField = "value"; var groupby = "name"; var textFilters = "[{ \"key\": \"eId\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }]"; var numericalFilters = "[{ \"key\": \"begin\", \"minValue\": \"__from__\", \"maxValue\": \"__to__\" }]"; addAggregatesOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addErrorsOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addLastMeasurementsTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); //addErrorsSummary(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addAggregatesSummaryTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); var dashboardObject = new Dashboard( entityName + ' Performance', new DashboardState( new GlobalSettings( [new Placeholder("__businessobjectid__", executionId, false), new Placeholder("__measurementType__", measurementType?measurementType:'custom', false), new Placeholder("__from__", "new Date(new Date().getTime() - "+timeFrame+").getTime()", true), new Placeholder("__to__", "new Date().getTime()", true) ], false, false, 'Global Settings', 3000 ), widgetsArray, entityName + ' Dashboard', 'aggregated', new DefaultDashboardGui() ) ); dashboardObject.oid = "perfDashboardId"; return dashboardObject; }; function PerformanceDashboard(executionId, measurementType, entity) { var widgetsArray = []; var entityName = ''; if(measurementType && measurementType === 'keyword'){ entityName = 'Keyword'; }else{ entityName = 'Custom Transaction'; } var timeFrame = null; var timeField = "begin"; var timeFormat = "long"; var valueField = "value"; var groupby = "name"; var textFilters = "[{ \"key\": \"eId\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }]"; var numericalFilters = "[]"; addAggregatesOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addErrorsOverTimeTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addLastMeasurementsTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); //addErrorsSummary(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); addAggregatesSummaryTpl(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame); var dashboardObject = new Dashboard( entityName + ' Performance', new DashboardState( new GlobalSettings( [new Placeholder("__businessobjectid__", executionId, false), new Placeholder("__measurementType__", measurementType?measurementType:'custom', false)], false, false, 'Global Settings', 3000 ), widgetsArray, entityName + ' Dashboard', 'aggregated', new DefaultDashboardGui() ) ); dashboardObject.oid = "perfDashboardId"; return dashboardObject; }; function EffectiveChartOptions(charType, xAxisOverride, timeFrame){ var opts = new ChartOptions(charType, false, false, xAxisOverride?xAxisOverride:'function (d) {\r\n var value;\r\n if ((typeof d) === \"string\") {\r\n value = parseInt(d);\r\n } else {\r\n value = d;\r\n }\r\n\r\n return d3.time.format(\"%H:%M:%S\")(new Date(value));\r\n}', xAxisOverride?xAxisOverride:'function (d) { return d.toFixed(1); }', timeFrame?'[new Date(new Date().getTime() - '+timeFrame+').getTime(), new Date().getTime()]':undefined ); opts.margin.left = 75; return opts; } function RTMAggBaseQueryTmpl(metric, transform){ return new AsyncQuery( null, new Service(//service "/rtm/rest/aggregate/get", "Post", "",//templated new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"), new Postproc("", "",[], "function(response){if(!response.data.payload){console.log('No payload ->' + JSON.stringify(response)); return null;}return [{ placeholder : '__streamedSessionId__', value : response.data.payload.streamedSessionId, isDynamic : false }];}", "") ), new Service(//callback "/rtm/rest/aggregate/refresh", "Post", "{\"streamedSessionId\": \"__streamedSessionId__\"}", new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].placeholder, workData[i].value);}return newRequestFragment;}"), new Postproc("function(response){return response.data.payload.stream.complete;}", transform ,[{"key" : "metric", "value" : metric, "isDynamic" : false}], {}, "")) ); }; function RTMAggBaseTemplatedQueryTmpl(metric, pGranularity, transform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ return new TemplatedQuery( "Template", new RTMAggBaseQueryTmpl(metric, transform), new DefaultPaging(), new Controls( new Template( "{ \"selectors1\": [{ \"textFilters\": "+textFilters+", \"numericalFilters\": "+numericalFilters+" }], \"serviceParams\": { \"measurementService.nextFactor\": \"0\", \"aggregateService.timeField\" : \""+timeField+"\", \"aggregateService.timeFormat\" : \""+timeFormat+"\", \"aggregateService.valueField\" : \""+valueField+"\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"__granularity__\", \"aggregateService.groupby\": \""+groupby+"\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }", "", [new Placeholder("__granularity__", pGranularity, false)] ) ) ); }; var addAggregatesSummaryTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var summaryTransform = "function (response) {\r\n //var metrics = response.data.payload.metricList;\r\n var metrics = [\"cnt\",\"avg\", \"min\", \"max\", \"tpm\", \"tps\", \"90th pcl\"];\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n if (payload && payloadKeys.length > 0) {\r\n var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n for (i = 0; i < metrics.length; i++) {\r\n var metric = metrics[i];\r\n if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n retData.push({\r\n x: metric,\r\n y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n z: serieskeys[j]\r\n });\r\n }else{\r\n retData.push({ x: metric, y: 0, z: serieskeys[j]});\r\n }\r\n }\r\n }\r\n }\r\n return retData;\r\n}"; var standalone = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(entityName + " stats summary", false, 0, {}, new EffectiveChartOptions('seriesTable', 'function(d) { return d; }', timeFrame), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("sum", "max", summaryTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(standalone); }; var addAggregatesOverTimeTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var overtimeTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n z: serieskeys[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; var overtimeFillBlanksTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = [];\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n if(!series.includes(serieskeys[j])){\r\n series.push(serieskeys[j]);\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < series.length; j++) {\r\n var yval;\r\n if(payload[payloadKeys[i]][serieskeys[j]] && payload[payloadKeys[i]][serieskeys[j]][metric]){\r\n yval = payload[payloadKeys[i]][serieskeys[j]][metric];\r\n }else{\r\n //console.log('missing dot: x=' + payloadKeys[i] + '; series=' + series[j]);\r\n yval = 0;\r\n }\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: yval,\r\n z: series[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; var config = getMasterSlaveConfig("raw", "Average "+entityName+" Duration (ms)", "Nb " + entityName + "s per second"); var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('lineChart', null, timeFrame), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("avg", "auto", overtimeTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); //var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('lineChart'), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", overtimeTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('stackedAreaChart', null, timeFrame), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("tps", "auto", overtimeFillBlanksTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(master); widgetsArray.push(slave); }; //No paging: FACTOR 100 via template var addLastMeasurementsTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ function RTMLatestMeasurementBaseQueryTmpl(){ return new SimpleQuery( "Raw", new Service( "/rtm/rest/measurement/latest", "Post", "", new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"), new Postproc("", "function (response, args) {\r\n var x = '"+timeField+"', y = '"+valueField+"', z = '"+groupby+"';\r\n var retData = [], index = {};\r\n var payload = response.data.payload;\r\n for (var i = 0; i < payload.length; i++) {\r\n retData.push({\r\n x: payload[i][x],\r\n y: payload[i][y],\r\n z: payload[i][z]\r\n });\r\n }\r\n return retData;\r\n}", [], {}, "") ) ); }; function RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ return new TemplatedQuery( "Template", new RTMLatestMeasurementBaseQueryTmpl(), new DefaultPaging(), //new Paging("On", new Offset("__FACTOR__", "return 0;", "return value + 1;", "if(value > 0){return value - 1;} else{return 0;}"), null), new Controls( new Template( "{ \"selectors1\": [{ \"textFilters\": "+textFilters+", \"numericalFilters\": "+numericalFilters+" }], \"serviceParams\": { \"measurementService.nextFactor\": \"__FACTOR__\", \"aggregateService.timeField\" : \""+timeField+"\", \"aggregateService.timeFormat\" : \""+timeFormat+"\", \"aggregateService.valueField\" : \""+valueField+"\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"auto\", \"aggregateService.groupby\": \""+groupby+"\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }", "", [new Placeholder("__FACTOR__", "100", false)] ) ) ); }; var config = getMasterSlaveConfig("transformed", "Last 100 " + entityName +"s - Individual duration (ms)", "Last 100 "+entityName+"s - Value table (ms)"); var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('scatterChart', null, null), config.masterconfig, new RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo()) ); var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('seriesTable', null, null), config.slaveconfig, new RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo()) ); widgetsArray.push(master); //widgetsArray.push(slave); }; //No paging: hardcoded simple query var addLastMeasurements = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ function RTMLatestMeasurementBaseQuery(){ return new SimpleQuery( "Raw", new Service( "/rtm/rest/measurement/latest", "Post", "{\"selectors1\": [{ \"textFilters\": "+textFilters+", \"numericalFilters\": "+numericalFilters+" }],\"serviceParams\": { \"measurementService.nextFactor\": \"100\", \"aggregateService.timeField\" : \""+timeField+"\", \"aggregateService.timeFormat\" : \""+timeFormat+"\", \"aggregateService.valueField\" : \""+valueField+"\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"auto\", \"aggregateService.groupby\": \""+groupby+"\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" }\}", new Preproc(""), new Postproc("", "function (response, args) {\r\n var x = '"+timeField+"', y = '"+valueField+"', z = '"+groupby+"';\r\n var retData = [], index = {};\r\n var payload = response.data.payload;\r\n for (var i = 0; i < payload.length; i++) {\r\n retData.push({\r\n x: payload[i][x],\r\n y: payload[i][y],\r\n z: payload[i][z]\r\n });\r\n }\r\n return retData;\r\n}", [], {}, "") ) ); }; var config = getMasterSlaveConfig("raw", "Last 100 Measurements - Scattered values (ms)", "Last 100 Measurements - Value table (ms)"); var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('scatterChart', null, timeFrame), config.masterconfig, new RTMLatestMeasurementBaseQuery(), new DefaultGuiClosed(), new DefaultInfo()) ); var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('seriesTable', null, timeFrame), config.slaveconfig, new RTMLatestMeasurementBaseQuery(), new DefaultGuiClosed(), new DefaultInfo()) ); widgetsArray.push(master); widgetsArray.push(slave); }; var addErrorsSummary = function(widgetsArray, entityName, timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var summaryTransform = "function (response) {\r\n //var metrics = response.data.payload.metricList;\r\n var metrics = [\"cnt\"];\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n if (payload && payloadKeys.length > 0) {\r\n var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n for (i = 0; i < metrics.length; i++) {\r\n var metric = metrics[i];\r\n if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n retData.push({\r\n x: metric,\r\n y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n z: '\u0020' + serieskeys[j].split('_')[0]\r\n });\r\n }else{\r\n retData.push({ x: metric, y: 0, z: serieskeys[j]});\r\n }\r\n }\r\n }\r\n }\r\n return retData;\r\n}"; var standalone = new Widget(getUniqueId(), new DefaultWidgetState(), new DashletState(entityName + " status summary", false, 0, {}, new EffectiveChartOptions('singleValueTable', 'function(d) { return d; }', timeFrame), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("cnt", "max", summaryTransform, entityName,timeField, timeFormat, valueField, "rnStatus", textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(standalone); }; var addErrorsOverTimeTpl = function(widgetsArray, entityName, timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ var summaryTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = [];\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n if(!serieskeys[j].includes(';PASSED') && !series.includes(serieskeys[j])){\r\n series.push(serieskeys[j]);\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n for (j = 0; j < series.length; j++) {\r\n var yval;\r\n if(payload[payloadKeys[i]][series[j]] && payload[payloadKeys[i]][series[j]][metric]){\r\n yval = payload[payloadKeys[i]][series[j]][metric];\r\n }else{\r\n //console.log('missing dot: x=' + payloadKeys[i] + '; series=' + series[j]);\r\n yval = 0;\r\n }\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: yval,\r\n z: series[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; var standalone = new Widget(getUniqueId(), new DefaultWidgetState(), new DashletState(entityName + " errors over time", false, 0, {}, new EffectiveChartOptions('stackedAreaChart', null, timeFrame), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", summaryTransform, entityName,timeField, timeFormat, valueField, "name;rnStatus", textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); widgetsArray.push(standalone); }; var getMasterSlaveConfig = function(rawOrTransformed, masterTitle, slaveTitle){ var masterId, slaveId, masterTitle, slaveTitle, masterConfig, slaveConfig, datatype; if(rawOrTransformed === 'raw'){ datatype = 'state.data.rawresponse'; }else{ datatype = 'state.data.transformed'; } var random = getUniqueId(); masterId = random + "-master"; slaveId = random + "-slave"; masterConfig = new Config('Off', true, false, 'unnecessaryAsMaster'); slaveConfig = new Config('Off', false, true, datatype); slaveConfig.currentmaster = { oid: masterId, title: masterTitle }; return {masterid: masterId, slaveid: slaveId, mastertitle: masterTitle, slavetitle: slaveTitle, masterconfig : masterConfig, slaveconfig: slaveConfig}; }; function StaticPresets() { return { queries: [], controls: { templates: [] }, configs: [] }; }
Upgrading preset-dashboards
step-controller/step-controller-server-webapp/src/main/resources/webapp/js/viz-presets.js
Upgrading preset-dashboards
<ide><path>tep-controller/step-controller-server-webapp/src/main/resources/webapp/js/viz-presets.js <ide> function getVizDashboardList(){ <ide> return [["WikimediaDemo"], ["PerformanceDashboard"], ["RealtimePerformanceDashboard"]]; <ide> } <add> <add>var overtimeFillBlanksTransformFn = function(response, args) { <add> var metric = args.metric; <add> var retData = [], series = []; <add> <add> var payload = response.data.payload.stream.streamData; <add> var payloadKeys = Object.keys(payload); <add> <add> for (i = 0; i < payloadKeys.length; i++) { <add> var series_ = payload[payloadKeys[i]]; <add> var serieskeys = Object.keys(series_ ) <add> for (j = 0; j < serieskeys.length; j++) { <add> if(!series.includes(serieskeys[j])){ <add> series.push(serieskeys[j]); <add> } <add> } <add> } <add> <add> for (i = 0; i < payloadKeys.length; i++) { <add> var series_ = payload[payloadKeys[i]]; <add> var serieskeys = Object.keys(series) <add> for (j = 0; j < serieskeys.length; j++) { <add> var key = series[serieskeys[j]]; <add> var yval; <add> if(series_[key] && series_[key][metric]){ <add> yval = series_[key][metric]; <add> }else{ <add> yval = 0; <add> } <add> retData.push({ <add> x: payloadKeys[i], <add> y: yval, <add> z: key <add> }); <add> } <add> } <add> return retData; <add>}; <add> <add>function RealtimeSelfMonitoring() { <add> <add> var widgetsArray = []; <add> <add> var freeTokenTransform = function (response, args) { <add> var array = [] <add> $.each(response.data, function(index, item){ <add> array.push({ <add> x : new Date().getTime(), <add> y : item.tokensCapacity.countByState.FREE, <add> z : item.agentRef.agentUrl.split('http://')[1] <add> }); <add> }); <add> return array; <add> } <add> <add> var baseAgentQuery = new SimpleQuery("Raw", new Service("", "Get","",new DefaultPreproc(),new Postproc("", freeTokenTransform.toString(), [], {}, ""))); <add> var agentQueryTemplate = new TemplatedQuery("Plain",baseAgentQuery,new DefaultPaging(),new Controls(new Template("","/rest/grid/agent",[]))); <add> <add> var options = new EffectiveChartOptions('lineChart'); <add> options.showLegend = true; <add> <add> var widget1 = new Widget(getUniqueId(), new WidgetState('col-md-6', false, true), new DashletState("Free tokens per agent", false, 0, {}, options, new Config('On', false, false, '', 1000, 500, 'On', 20), agentQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); <add> widgetsArray.push(widget1); <add> <add> var executionsTransform = function (response, args) { <add> return [{x: new Date().getTime(), y:response.data.recordsFiltered, z:'Ongoing executions'}]; <add> }; <add> <add> var baseExecQuery = new SimpleQuery("Raw", new Service("", "Get","",new DefaultPreproc(),new Postproc("", executionsTransform.toString(), [], {}, ""))); <add> var execQueryTemplate = new TemplatedQuery("Plain",baseExecQuery,new DefaultPaging(),new Controls(new Template("","rest/datatable/executions/data?ignoreContext=true&draw=__draw__&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=4&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=5&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=6&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=(INITIALIZING%7CIMPORTING%7CRUNNING%7CABORTING%7CEXPORTING)&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=true&columns%5B7%5D%5Bdata%5D=7&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B8%5D%5Bdata%5D=8&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=true&columns%5B8%5D%5Borderable%5D=true&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B9%5D%5Bdata%5D=9&columns%5B9%5D%5Bname%5D=&columns%5B9%5D%5Bsearchable%5D=true&columns%5B9%5D%5Borderable%5D=true&columns%5B9%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B9%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B10%5D%5Bdata%5D=10&columns%5B10%5D%5Bname%5D=&columns%5B10%5D%5Bsearchable%5D=true&columns%5B10%5D%5Borderable%5D=true&columns%5B10%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B10%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=2&order%5B0%5D%5Bdir%5D=desc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&undefined",[new Placeholder("__dayFrom__", "20151010", false), new Placeholder("__draw__", "Math.random().toString().split('.')[1].substring(0,8)", true)]))); <add> <add> var options = new EffectiveChartOptions('lineChart'); <add> options.showLegend = true; <add> <add> var widget2 = new Widget(getUniqueId(), new WidgetState('col-md-6', false, true), new DashletState("Global number of on-going executions", false, 0, {}, options, new Config('On', false, false, '', 1000, 500, 'On', 20), execQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); <add> widgetsArray.push(widget2); <add> <add> var dashboardObject = new Dashboard('Instance Activity',new DashboardState(new GlobalSettings([],false,false,'Global Settings',1000), <add> widgetsArray,'SelfMonitoring Dashboard','aggregated',new DefaultDashboardGui()) <add> ); <add> <add> return dashboardObject; <add>} <add> <ide> function WikimediaDemo() { <ide> <ide> var widgetsArray = []; <ide> ) <ide> ); <ide> var wikimediaQueryTemplate = new TemplatedQuery( <del> "Template", <add> "Plain", <ide> wikimediaBaseQuery, <ide> new DefaultPaging(), <ide> new Controls(new Template("","https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Foo/daily/__dayFrom__/__dayTo__", <ide> [new Placeholder("__dayFrom__", "20151010", false), new Placeholder("__dayTo__", "20151030", false)])) <ide> ); <del> <add> <ide> var xAxisFn = function(d) { <del> var str = d.toString(); <del> var year = str.substring(0,4); <del> var month = str.substring(4, 6); <del> var day = str.substring(6, 8); <del> return year + '-' + month + '-' + day; <del> }; <del> <del> var options = new EffectiveChartOptions('lineChart', xAxisFn); <add> var str = d.toString(); <add> var year = str.substring(0,4); <add> var month = str.substring(4, 6); <add> var day = str.substring(6, 8); <add> return year + '-' + month + '-' + day; <add> }; <add> <add> var options = new EffectiveChartOptions('lineChart', xAxisFn.toString()); <ide> options.showLegend = true; <ide> <ide> var widget = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(" Daily wikimedia stats", false, 0, {}, options, new Config('Off', false, false, ''), wikimediaQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); <ide> 'Daily Stats', <ide> new DashboardState( <ide> new GlobalSettings( <del> [], <add> [new Placeholder("__businessobjectid__", "", false)], <ide> false, <ide> false, <ide> 'Global Settings', <del> 5000 <add> 3000 <ide> ), <ide> widgetsArray, <ide> 'Wikimedia Dashboard', <ide> return dashboardObject; <ide> } <ide> <del> <del>function RealtimePerformanceDashboard(executionId, measurementType, entity) { <add>function ProjectOverview() { <add> var widgetsArray = []; <add> <add> var executionsTransform = function (response, args) { <add> var array = []; <add> var min = new Date().getTime() - 604800000; <add> var max = new Date().getTime(); <add> var nbIntervals = 7; <add> var interval = Math.round((max - min -1) / nbIntervals); <add> var groupArray = []; <add> var groupStats = {}; <add> for(i=0; i< nbIntervals; i++){ <add> var from_ = min + (i * interval); <add> groupArray.push({from: from_, to: min + ((i+1)*interval)}); <add> groupStats[from_] = 0; <add> } <add> $.each(response.data, function(index, item){ <add> $.each(groupArray, function(index, item2){ <add> if(item.startTime >= item2.from && item.startTime < item2.to){ <add> groupStats[item2.from]+=1; <add> } <add> }); <add> }); <add> $.each(Object.keys(groupStats), function(index, item){ <add> array.push({x: item, y: groupStats[item], z: 'Nb executions'}); <add> }); <add> return array; <add> }; <add> <add> var xAxisFn = function (d) { <add> var value; <add> if ((typeof d) === "string") { <add> value = parseInt(d); <add> } else { <add> value = d; <add> } <add> <add> return d3.time.format("%Y-%m-%d")(new Date(value)); <add> }; <add> <add> var baseExecQuery = new SimpleQuery("Raw", new Service("", "Post","",new DefaultPreproc(),new Postproc("", executionsTransform.toString(), [], {}, ""))); <add> var execQueryTemplate = new TemplatedQuery("Plain",baseExecQuery,new DefaultPaging(),new Controls(new Template("{ \"criteria\": { \"attributes.project\": \"__businessobjectid__\"}, \"start\" : __from__, \"end\" : __to__}","/rest/controller/executions/findByCritera",[new Placeholder("__from__", "new Date().getTime()-604800000", true), new Placeholder("__to__", "new Date().getTime()", true)]))); <add> <add> var options = new EffectiveChartOptions('lineChart', xAxisFn.toString()); <add> options.showLegend = true; <add> <add> var widget1 = new Widget(getUniqueId(), new WidgetState('col-md-6', false, true), new DashletState("Executions per day over last week", false, 0, {}, options, new Config('Off', false, false, '', 1000, 500, 'Off', 20), execQueryTemplate, new DefaultGuiClosed(), new DefaultInfo())); <add> widgetsArray.push(widget1); <add> <add> var entityName = "keyword"; <add> var timeFrame = 604800000; <add> var granularity_ = 86400000; <add> var timeField = "begin"; <add> var timeFormat = "long"; <add> var valueField = "value"; <add> var groupby = "name"; <add> <add> var textFilters = "[{ \"key\": \"project\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"keyword\", \"regex\": \"false\" }]"; <add> var numericalFilters = "[]"; <add> <add> var overtimeTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n z: serieskeys[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; <add> var config = getMasterSlaveConfig("raw", "Nb Keyword executions per day over last week", ""); <add> <add> var widget2 = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('stackedAreaChart', xAxisFn.toString(), timeFrame), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", granularity_, overtimeFillBlanksTransformFn.toString(), entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <add> widgetsArray.push(widget2); <add> <add> var dashboardObject = new Dashboard('Weekly project overview',new DashboardState(new GlobalSettings([],false,false,'Global Settings',1000), <add> widgetsArray,'Project stats','aggregated',new DefaultDashboardGui()) <add> ); <add> return dashboardObject; <add>} <add> <add>function RealtimePerformanceDashboard(executionId, measurementType, entity, autorefresh) { <ide> <ide> var widgetsArray = []; <ide> var entityName = ''; <ide> }else{ <ide> entityName = 'Custom Transaction'; <ide> } <del> <del> var timeFrame = 10000; <del> <add> <add> var timeFrame = 30000; <add> <ide> var timeField = "begin"; <ide> var timeFormat = "long"; <ide> var valueField = "value"; <ide> var groupby = "name"; <del> <add> <ide> var textFilters = "[{ \"key\": \"eId\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }]"; <ide> var numericalFilters = "[{ \"key\": \"begin\", \"minValue\": \"__from__\", \"maxValue\": \"__to__\" }]"; <ide> <ide> new DashboardState( <ide> new GlobalSettings( <ide> [new Placeholder("__businessobjectid__", executionId, false), new Placeholder("__measurementType__", measurementType?measurementType:'custom', false), <del> new Placeholder("__from__", "new Date(new Date().getTime() - "+timeFrame+").getTime()", true), <del> new Placeholder("__to__", "new Date().getTime()", true) <add> new Placeholder("__from__", "new Date(new Date().getTime() - "+timeFrame+").getTime()", true), <add> new Placeholder("__to__", "new Date().getTime()", true) <ide> ], <del> false, <add> autorefresh?autorefresh:true, <ide> false, <ide> 'Global Settings', <ide> 3000 <ide> ) <ide> ); <ide> <del> dashboardObject.oid = "perfDashboardId"; <add> dashboardObject.oid = "realTimePerfDashboardId"; <ide> return dashboardObject; <ide> }; <ide> <ide> }else{ <ide> entityName = 'Custom Transaction'; <ide> } <del> <add> <ide> var timeFrame = null; <del> <add> <ide> var timeField = "begin"; <ide> var timeFormat = "long"; <ide> var valueField = "value"; <ide> var groupby = "name"; <del> <add> <ide> var textFilters = "[{ \"key\": \"eId\", \"value\": \"__businessobjectid__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }]"; <ide> var numericalFilters = "[]"; <ide> <ide> return dashboardObject; <ide> }; <ide> <del>function EffectiveChartOptions(charType, xAxisOverride, timeFrame){ <del> var opts = new ChartOptions(charType, false, false, <add>function EffectiveChartOptions(charType, xAxisOverride, timeFrame, yAxisOverride){ <add> var opts = new ChartOptions(charType, true, false, <ide> xAxisOverride?xAxisOverride:'function (d) {\r\n var value;\r\n if ((typeof d) === \"string\") {\r\n value = parseInt(d);\r\n } else {\r\n value = d;\r\n }\r\n\r\n return d3.time.format(\"%H:%M:%S\")(new Date(value));\r\n}', <del> xAxisOverride?xAxisOverride:'function (d) { return d.toFixed(1); }', <del> timeFrame?'[new Date(new Date().getTime() - '+timeFrame+').getTime(), new Date().getTime()]':undefined <add> yAxisOverride?yAxisOverride:'function (d) { return d.toFixed(1); }', <add> timeFrame?'[new Date(new Date().getTime() - '+timeFrame+').getTime(), new Date().getTime()]':undefined <ide> ); <ide> opts.margin.left = 75; <ide> return opts; <ide> <ide> function RTMAggBaseTemplatedQueryTmpl(metric, pGranularity, transform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ <ide> return new TemplatedQuery( <del> "Template", <add> "Plain", <ide> new RTMAggBaseQueryTmpl(metric, transform), <ide> new DefaultPaging(), <ide> new Controls( <ide> <ide> var addAggregatesSummaryTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ <ide> var summaryTransform = "function (response) {\r\n //var metrics = response.data.payload.metricList;\r\n var metrics = [\"cnt\",\"avg\", \"min\", \"max\", \"tpm\", \"tps\", \"90th pcl\"];\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n if (payload && payloadKeys.length > 0) {\r\n var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n for (i = 0; i < metrics.length; i++) {\r\n var metric = metrics[i];\r\n if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n retData.push({\r\n x: metric,\r\n y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n z: serieskeys[j]\r\n });\r\n }else{\r\n retData.push({ x: metric, y: 0, z: serieskeys[j]});\r\n }\r\n }\r\n }\r\n }\r\n return retData;\r\n}"; <del> var standalone = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(entityName + " stats summary", false, 0, {}, new EffectiveChartOptions('seriesTable', 'function(d) { return d; }', timeFrame), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("sum", "max", summaryTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <add> var standalone = new Widget(getUniqueId(), new WidgetState('col-md-12', false, true), new DashletState(entityName + " stats summary", false, 0, {}, new EffectiveChartOptions('seriesTable', 'function(d) { return d; }', timeFrame), new Config('Off', false, false, '', 3000, 1000, 'Off', 8, 'On'), new RTMAggBaseTemplatedQueryTmpl("sum", "max", summaryTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <ide> widgetsArray.push(standalone); <ide> }; <ide> <ide> var addAggregatesOverTimeTpl = function(widgetsArray, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ <ide> var overtimeTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = {};\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n z: serieskeys[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; <del> var overtimeFillBlanksTransform = "function (response, args) {\r\n var metric = args.metric;\r\n var retData = [], series = [];\r\n\r\n var payload = response.data.payload.stream.streamData;\r\n var payloadKeys = Object.keys(payload);\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < serieskeys.length; j++) {\r\n if(!series.includes(serieskeys[j])){\r\n series.push(serieskeys[j]);\r\n }\r\n }\r\n }\r\n\r\n for (i = 0; i < payloadKeys.length; i++) {\r\n var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n for (j = 0; j < series.length; j++) {\r\n var yval;\r\n if(payload[payloadKeys[i]][serieskeys[j]] && payload[payloadKeys[i]][serieskeys[j]][metric]){\r\n yval = payload[payloadKeys[i]][serieskeys[j]][metric];\r\n }else{\r\n //console.log('missing dot: x=' + payloadKeys[i] + '; series=' + series[j]);\r\n yval = 0;\r\n }\r\n retData.push({\r\n x: payloadKeys[i],\r\n y: yval,\r\n z: series[j]\r\n });\r\n }\r\n }\r\n return retData;\r\n}"; <ide> var config = getMasterSlaveConfig("raw", "Average "+entityName+" Duration (ms)", "Nb " + entityName + "s per second"); <ide> <ide> var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new EffectiveChartOptions('lineChart', null, timeFrame), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("avg", "auto", overtimeTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <ide> //var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('lineChart'), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", overtimeTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <del> var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('stackedAreaChart', null, timeFrame), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("tps", "auto", overtimeFillBlanksTransform, entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <add> var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new EffectiveChartOptions('stackedAreaChart', null, timeFrame), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("tps", "auto", overtimeFillBlanksTransformFn.toString(), entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame), new DefaultGuiClosed(), new DefaultInfo())); <ide> <ide> widgetsArray.push(master); <ide> widgetsArray.push(slave); <ide> <ide> function RTMLatestMeasurementTemplatedQuery(entityName,timeField, timeFormat, valueField, groupby, textFilters, numericalFilters, timeFrame){ <ide> return new TemplatedQuery( <del> "Template", <add> "Plain", <ide> new RTMLatestMeasurementBaseQueryTmpl(), <ide> new DefaultPaging(), <ide> //new Paging("On", new Offset("__FACTOR__", "return 0;", "return value + 1;", "if(value > 0){return value - 1;} else{return 0;}"), null),
JavaScript
mit
d1b74f319a374f7e9f28839fb1d0fa214c30d02d
0
meep-meep/test-runner,meep-meep/test-runner
var fs = require('fs'); var path = require('path'); var express = require('express'); var ejs = require('ejs'); var RSVP = require('rsvp'); var queryString = require('querystring'); var shallowExtend = require('shallow-extend'); var ALL_TAGS = '#all#'; var _testRenderers = {}; var _dataAdapter = null; var app = express(); app.set('views', path.join(__dirname, '../templates')); app.engine('html', ejs.renderFile); function setDataAdapter(dataAdapter) { _dataAdapter = dataAdapter; } function rawContentToTag(rawContent) { if(/\.css$/.test(rawContent)) { return '<link rel="stylesheet" type="text/css" href="' + rawContent+ '"/>'; } else if(/\.js$/.test(rawContent)) { return '<script type="text/javascript" src="' + rawContent + '"></script>'; } } function getPageElement(pageElementName, params) { if(pageElementName in _testRenderers) { return _testRenderers[pageElementName].render(params); } return new RSVP.Promise(function(resolve, reject) { if(!params.rawContent) { reject(new Error('missing content in ' + pageElementName)); return; } resolve(rawContentToTag(params.rawContent)); }); } function _formatPageElementData(pageElementData) { var result = {}; var elementName; if(!pageElementData) { return null; } if(typeof pageElementData === 'string') { if(pageElementData in _testRenderers) { result = { name: pageElementData, params: {} }; } else { result = { params: {rawContent: pageElementData} }; } } else if(typeof pageElementData === 'object') { for(elementName in pageElementData) { result.name = elementName; result.params = pageElementData[elementName]; } } return result; } function getTestSuitePageElements(pageElements, qs) { return RSVP.hash({ 'before-all': _dataAdapter.get('tests/before-all'), 'after-all': _dataAdapter.get('tests/after-all') }) .then(function(hash) { var preList = hash['before-all']; var postList = hash['after-all']; var fullElementList = preList.concat(pageElements.slice()).concat(postList); return RSVP.all( fullElementList.map(function(pageElementData) { pageElementData = _formatPageElementData(pageElementData); var params = shallowExtend({}, pageElementData.params, qs); return getPageElement(pageElementData.name, params); }) ); }); } function renderResponse(response, templateName, templateData) { return new RSVP.Promise(function(resolve, reject) { response.render( templateName, templateData, function(error, renderedView) { if(error) { reject(error); return; } resolve(renderedView); } ); }); } function formatTags(tagString) { if(typeof(tagString) !== 'string') { return []; } return tagString .split(',') .map(function(tag) {return tag.trim().toLowerCase();}); } function matchTags(candidates, reference) { if(candidates === ALL_TAGS) { return true; } return candidates.every(function(candidate) { return reference.indexOf(candidate) !== -1; }); } function getfilteredTests(tags) { return _dataAdapter.get('tests/library') .then(function(testLibrary) { return testLibrary.filter(function(test) { for(var testTags in test) { if(tags === ALL_TAGS || matchTags(tags, formatTags(testTags))) { return true; } } }) .map(function(test) { var transformedTest; for(var testTags in test) { transformedTest = { tags: testTags, elements: test[testTags] }; } return transformedTest; }); }); } function fillQueryString(qs) { return _dataAdapter.get('reporter-url') .then(function(reporterUrl) { if(!qs.testRunnerSession) { qs.testRunnerSession = +(new Date()); } if(!qs.testIndex) { qs.testIndex = 0; } qs.reporterUrl = reporterUrl + '?testRunnerSession=' + qs.testRunnerSession + '&testIndex=' + qs.testIndex; }); } function addTestRenderers(newTestRenderers) { for(var name in newTestRenderers) { _testRenderers[name] = newTestRenderers[name]; } } function addTestSuites(newTestDefinition) { config.testSuites = newTestDefinition; } var testSuiteRequest = '/tests'; app.get( testSuiteRequest, function (request, response, next) { var qs = queryString.parse(request.url.split('?')[1]); var tags = formatTags(qs.tags); if(!tags.length) { tags = ALL_TAGS; } fillQueryString(qs) .then(function() { return getfilteredTests(tags); }) .then(function(filteredTests) { if(qs.testIndex >= filteredTests.length) { return renderResponse( response, '../templates/done.html', qs ) .then(function(renderedView) { response.send(renderedView); }) .catch(function(error) { console.error(error); response.res.sendStatus(500); }); } else { return getTestSuitePageElements(filteredTests[qs.testIndex].elements, qs) .then(function(pageElements) { return renderResponse( response, '../templates/template.html', { pageElements: pageElements, tags: filteredTests[qs.testIndex].tags, qs: qs } ); }) .then(function(renderedView) { response.send(renderedView); }) .catch(function(error) { console.error(error); response.res.sendStatus(500); }); } }) .catch(function(error) { console.error(error); }) } ); module.exports = { setDataAdapter: setDataAdapter, middleware: app, addTestRenderers: addTestRenderers };
src/index.js
var fs = require('fs'); var path = require('path'); var express = require('express'); var ejs = require('ejs'); var RSVP = require('rsvp'); var queryString = require('querystring'); var shallowExtend = require('shallow-extend'); var ALL_TAGS = '#all#'; var _testRenderers = {}; var _dataAdapter = null; var app = express(); app.set('views', path.join(__dirname, '../templates')); app.engine('html', ejs.renderFile); function setDataAdapter(dataAdapter) { _dataAdapter = dataAdapter; } function rawContentToTag(rawContent) { if(/\.css$/.test(rawContent)) { return '<link rel="stylesheet" type="text/css" href="' + rawContent+ '"/>'; } else if(/\.js$/.test(rawContent)) { return '<script type="text/javascript" src="' + rawContent + '"></script>'; } } function getPageElement(pageElementName, params) { if(pageElementName in _testRenderers) { return _testRenderers[pageElementName].render(params); } return new RSVP.Promise(function(resolve, reject) { if(!params.rawContent) { reject(new Error('missing content in ' + pageElementName)); return; } resolve(rawContentToTag(params.rawContent)); }); } function _formatPageElementData(pageElementData) { var result = {}; if(!pageElementData) { return null; } if(typeof pageElementData === 'string') { if(pageElementData in _testRenderers) { result = { name: pageElementData, params: {} }; } else { result = { params: {rawContent: pageElementData} }; } } else if(typeof pageElementData === 'object') { for(elementName in pageElementData) { result.name = elementName; result.params = pageElementData[elementName]; } } return result; } function getTestSuitePageElements(pageElements, qs) { return RSVP.hash({ 'before-all': _dataAdapter.get('tests/before-all'), 'after-all': _dataAdapter.get('tests/after-all') }) .then(function(hash) { var preList = hash['before-all']; var postList = hash['after-all']; var fullElementList = preList.concat(pageElements.slice()).concat(postList); return RSVP.all( fullElementList.map(function(pageElementData) { pageElementData = _formatPageElementData(pageElementData); var params = shallowExtend({}, pageElementData.params, qs); return getPageElement(pageElementData.name, params); }) ); }) } function renderResponse(response, templateName, templateData) { return new RSVP.Promise(function(resolve, reject) { response.render( templateName, templateData, function(error, renderedView) { if(error) { reject(error); return; } resolve(renderedView); } ); }); } function formatTags(tagString) { if(typeof(tagString) !== 'string') { return []; } return tagString .split(',') .map(function(tag) {return tag.trim().toLowerCase()}); } function matchTags(candidates, reference) { if(candidates === ALL_TAGS) { return true; } return candidates.every(function(candidate) { return reference.indexOf(candidate) !== -1; }); } function getfilteredTests(tags) { return _dataAdapter.get('tests/library') .then(function(testLibrary) { return testLibrary.filter(function(test) { for(var testTags in test) { if(tags === ALL_TAGS || matchTags(tags, formatTags(testTags))) { return true; } } }) .map(function(test) { var transformedTest; for(var testTags in test) { transformedTest = { tags: testTags, elements: test[testTags] }; } return transformedTest; }); }); } function fillQueryString(qs) { return _dataAdapter.get('reporter-url') .then(function(reporterUrl) { if(!qs.testRunnerSession) { qs.testRunnerSession = +(new Date()); } if(!qs.testIndex) { qs.testIndex = 0; } qs.reporterUrl = reporterUrl + '?testRunnerSession=' + qs.testRunnerSession + '&testIndex=' + qs.testIndex; }); } function addTestRenderers(newTestRenderers) { for(var name in newTestRenderers) { _testRenderers[name] = newTestRenderers[name]; } } function addTestSuites(newTestDefinition) { config.testSuites = newTestDefinition; } var testSuiteRequest = '/tests'; app.get( testSuiteRequest, function (request, response, next) { var qs = queryString.parse(request.url.split('?')[1]); var tags = formatTags(qs.tags); if(!tags.length) { tags = ALL_TAGS; } fillQueryString(qs) .then(function() { return getfilteredTests(tags); }) .then(function(filteredTests) { if(qs.testIndex >= filteredTests.length) { return renderResponse( response, '../templates/done.html', qs ) .then(function(renderedView) { response.send(renderedView); }) .catch(function(error) { console.error(error); response.res.sendStatus(500); }); } else { return getTestSuitePageElements(filteredTests[qs.testIndex].elements, qs) .then(function(pageElements) { return renderResponse( response, '../templates/template.html', { pageElements: pageElements, tags: filteredTests[qs.testIndex].tags, qs: qs } ); }) .then(function(renderedView) { response.send(renderedView); }) .catch(function(error) { console.error(error); response.res.sendStatus(500); }); } }) .catch(function(error) { console.error(error); }) } ); module.exports = { setDataAdapter: setDataAdapter, middleware: app, addTestRenderers: addTestRenderers };
linting
src/index.js
linting
<ide><path>rc/index.js <ide> <ide> function _formatPageElementData(pageElementData) { <ide> var result = {}; <add> var elementName; <add> <ide> if(!pageElementData) { <ide> return null; <ide> } <ide> return getPageElement(pageElementData.name, params); <ide> }) <ide> ); <del> <del> }) <add> }); <ide> } <ide> <ide> function renderResponse(response, templateName, templateData) { <ide> } <ide> return tagString <ide> .split(',') <del> .map(function(tag) {return tag.trim().toLowerCase()}); <add> .map(function(tag) {return tag.trim().toLowerCase();}); <ide> } <ide> <ide> function matchTags(candidates, reference) {
JavaScript
mit
3aee0d0ac0d8085b32d0a6d90533815fae858517
0
poldracklab/crn_server,poldracklab/crn_server
/*eslint no-console: ["error", { allow: ["log"] }] */ /* eslint-disable no-unused-vars*/ // dependencies ---------------------------------------------------- import express from 'express'; import async from 'async'; import config from './config'; import routes from './routes'; import bodyParser from 'body-parser'; import morgan from 'morgan'; import mongo from './libs/mongo'; //Handlers (need access to AwS Jobs handler to kickoff server side polling) import awsJobs from './handlers/awsJobs'; // import events lib to instantiate CRN Emitter import events from './libs/events'; // configuration --------------------------------------------------- mongo.connect(() => { //Start job polling let c = mongo.collections; let interval = let interval = 300000; // 5 minute interval for server side polling let pollJobs = () => { c.crn.jobs.find({ $or: [{ 'analysis.status':{$ne: 'SUCCEEDED'} } , { 'analysis.status':{$ne: 'FAILED'} }, { 'analysis.status':{$ne: 'REJECTED'} }] }).toArray((err, jobs) => { async.each(jobs, (job, cb) => { awsJobs.getJobStatus(job, job.userId, cb); }, (err) => { setTimeout(pollJobs, interval); }); }); }; pollJobs(); }); let app = express(); app.use((req, res, next) => { res.set(config.headers); res.type('application/json'); next(); }); app.use(morgan('short')); app.use(bodyParser.json()); // routing --------------------------------------------------------- app.use(config.apiPrefix, routes); // error handling -------------------------------------------------- app.use(function(err, req, res, next) { res.header('Content-Type', 'application/json'); var send = {'error' : ''}; var http_code = (typeof err.http_code === 'undefined') ? 500 : err.http_code; if (typeof err.message !== 'undefined' && err.message !== '') { send.error = err.message; } else { if(err.http_code == 400){ send.error = 'there was something wrong with that request'; }else if(err.http_code == 401){ send.error = 'you are not authorized to do that'; }else if(err.http_code == 404){ send.error = 'that resource was not found'; }else{ send.error = 'there was a problem'; } } res.status(http_code).send(send); }); // start server ---------------------------------------------------- app.listen(config.port, () => { console.log('Server is listening on port ' + config.port); });
server.js
/*eslint no-console: ["error", { allow: ["log"] }] */ /* eslint-disable no-unused-vars*/ // dependencies ---------------------------------------------------- import express from 'express'; import async from 'async'; import config from './config'; import routes from './routes'; import bodyParser from 'body-parser'; import morgan from 'morgan'; import mongo from './libs/mongo'; //Handlers (need access to AwS Jobs handler to kickoff server side polling) import awsJobs from './handlers/awsJobs'; // import events lib to instantiate CRN Emitter import events from './libs/events'; // configuration --------------------------------------------------- mongo.connect(() => { //Start job polling let c = mongo.collections; let interval = let interval = 300000; // 5 minute interval for server side polling let pollJobs = () => { c.crn.jobs.find({ $or: [{ 'analysis.status':{$ne: 'SUCCEEDED'} } , { 'analysis.status':{$ne: 'FAILED'} }, { 'analysis.status':{$ne: 'REJECTED'} }] }).toArray((err, jobs) => { async.each(jobs, (job, cb) => { awsJobs.getJobStatus(job, job.userId, cb); }, (err) { setTimeout(pollJobs, interval); }); }); }; pollJobs(); }); let app = express(); app.use((req, res, next) => { res.set(config.headers); res.type('application/json'); next(); }); app.use(morgan('short')); app.use(bodyParser.json()); // routing --------------------------------------------------------- app.use(config.apiPrefix, routes); // error handling -------------------------------------------------- app.use(function(err, req, res, next) { res.header('Content-Type', 'application/json'); var send = {'error' : ''}; var http_code = (typeof err.http_code === 'undefined') ? 500 : err.http_code; if (typeof err.message !== 'undefined' && err.message !== '') { send.error = err.message; } else { if(err.http_code == 400){ send.error = 'there was something wrong with that request'; }else if(err.http_code == 401){ send.error = 'you are not authorized to do that'; }else if(err.http_code == 404){ send.error = 'that resource was not found'; }else{ send.error = 'there was a problem'; } } res.status(http_code).send(send); }); // start server ---------------------------------------------------- app.listen(config.port, () => { console.log('Server is listening on port ' + config.port); });
missing arrow on arrown function
server.js
missing arrow on arrown function
<ide><path>erver.js <ide> }).toArray((err, jobs) => { <ide> async.each(jobs, (job, cb) => { <ide> awsJobs.getJobStatus(job, job.userId, cb); <del> }, (err) { <add> }, (err) => { <ide> setTimeout(pollJobs, interval); <ide> }); <ide> });
Java
lgpl-2.1
c4603c6a933b6f19234ba828a078ed6ef7561a6b
0
opensagres/xdocreport.eclipse,opensagres/xdocreport.eclipse
package org.dynaresume.dao.mock; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.dynaresume.dao.ResumeDao; import org.dynaresume.dao.mock.resume.AmineBoustaResume; import org.dynaresume.dao.mock.resume.AngeloZerrResume; import org.dynaresume.dao.mock.resume.DinoCosmasResume; import org.dynaresume.dao.mock.resume.LarsVogelResume; import org.dynaresume.dao.mock.resume.NicolasRaymondResume; import org.dynaresume.dao.mock.resume.PascalLeclercqResume; import org.dynaresume.dao.mock.resume.RalfSternbergResume; import org.dynaresume.domain.core.Address; import org.dynaresume.domain.core.NaturalPerson; import org.dynaresume.domain.hr.Education; import org.dynaresume.domain.hr.Experience; import org.dynaresume.domain.hr.Hobby; import org.dynaresume.domain.hr.Resume; import org.dynaresume.domain.hr.SkillResume; import org.springframework.stereotype.Repository; @Repository("resumeDao") public class MockResumeDao extends AbstractDaoMock<Resume> implements ResumeDao { private static final Map<Long, Resume> resumes; static long currentId = 0; static { resumes = new LinkedHashMap<Long, Resume>(); addResume(new AngeloZerrResume()); addResume(new PascalLeclercqResume()); addResume(new AmineBoustaResume()); addResume(new RalfSternbergResume()); addResume(new LarsVogelResume()); addResume(new DinoCosmasResume()); addResume(new NicolasRaymondResume()); } private static void addResume(Resume resume) { resumes.put(resume.getId(), resume); } public Iterable<Resume> findAll() { return resumes.values(); } public Resume findOne(Long id) { Resume Resume = resumes.get(id); if (Resume != null) { return clone(Resume); } return resumes.get(id); } public Resume save(Resume resume) { if (resume.getId() == null) { resume.setId(currentId++); } resumes.put(resume.getId(), resume); return clone(resume); } private Resume clone(Resume resume) { NaturalPerson person = resume.getOwner(); NaturalPerson newPerson = clone(person); Resume newResume = new Resume(); newResume.setId(resume.getId()); newResume.setTitle(resume.getTitle()); newResume.setOwner(newPerson); newResume.setPicture(resume.getPicture()); // Diplomas Set<Education> educations = resume.getEducations(); if (educations != null) { Set<Education> newDiplomas = new HashSet<Education>(); for (Education diploma : educations) { newDiplomas.add(clone(diploma)); } newResume.setEducations(educations); } // Experiences Set<Experience> experiences = resume.getExperiences(); if (experiences != null) { Set<Experience> newExperiences = new HashSet<Experience>(); for (Experience experience : experiences) { newExperiences.add(clone(experience)); } newResume.setExperiences(newExperiences); } // Hobbies Set<SkillResume> skills = resume.getSkills(); if (skills != null) { Set<SkillResume> newSkills = new HashSet<SkillResume>(); for (SkillResume skill : skills) { newSkills.add(clone(skill)); } newResume.setSkills(newSkills); } // Hobbies Set<Hobby> hobbies = resume.getHobbies(); if (hobbies != null) { Set<Hobby> newHobbies = new HashSet<Hobby>(); for (Hobby hobby : hobbies) { newHobbies.add(clone(hobby)); } newResume.setHobbies(newHobbies); } return newResume; } private NaturalPerson clone(NaturalPerson person) { NaturalPerson newPerson = new NaturalPerson(); newPerson.setId(person.getId()); newPerson.setLastName(person.getLastName()); newPerson.setFirstName(person.getFirstName()); newPerson.setBirthDate(person.getBirthDate()); newPerson.setEmail(person.getEmail()); newPerson.setAddress(clone(person.getAddress())); return newPerson; } private Experience clone(Experience experience) { Experience newExperience = new Experience(); Long id = experience.getId(); if (id == null) { id = currentId++; } newExperience.setId(id); newExperience.setTitle(experience.getTitle()); newExperience.setDetail(experience.getDetail()); newExperience.setMission(experience.getMission()); newExperience.setEndDate(experience.getEndDate()); newExperience.setStartDate(experience.getStartDate()); return newExperience; } private Education clone(Education diploma) { Education newDiploma = new Education(); Long id = diploma.getId(); if (id == null) { id = currentId++; } newDiploma.setId(id); newDiploma.setLabel(diploma.getLabel()); newDiploma.setInstitute(diploma.getInstitute()); return newDiploma; } private Hobby clone(Hobby hobby) { Hobby newHobby = new Hobby(); Long id = hobby.getId(); if (id == null) { id = currentId++; } newHobby.setId(id); newHobby.setLabel(hobby.getLabel()); return newHobby; } private SkillResume clone(SkillResume skill) { SkillResume newSkill = new SkillResume(); newSkill.setCategory(skill.getCategory()); newSkill.setSkill(skill.getSkill()); newSkill.setFreeSkill(skill.getFreeSkill()); return newSkill; } private Address clone(Address address) { if (address == null) { return null; } Address newAddress = new Address(); Long id = address.getId(); if (id == null) { id = currentId++; } newAddress.setId(id); newAddress.setCity(address.getCity()); newAddress.setCountry(address.getCountry()); newAddress.setFax(address.getFax()); newAddress.setStreet(address.getStreet()); newAddress.setTelephone(address.getTelephone()); newAddress.setZipCode(address.getZipCode()); return newAddress; } }
dynaresume/org.dynaresume.dao.mock/src/main/java/org/dynaresume/dao/mock/MockResumeDao.java
package org.dynaresume.dao.mock; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.dynaresume.dao.ResumeDao; import org.dynaresume.dao.mock.resume.AmineBoustaResume; import org.dynaresume.dao.mock.resume.AngeloZerrResume; import org.dynaresume.dao.mock.resume.DinoCosmasResume; import org.dynaresume.dao.mock.resume.LarsVogelResume; import org.dynaresume.dao.mock.resume.NicolasRaymondResume; import org.dynaresume.dao.mock.resume.PascalLeclercqResume; import org.dynaresume.domain.core.Address; import org.dynaresume.domain.core.NaturalPerson; import org.dynaresume.domain.hr.Education; import org.dynaresume.domain.hr.Experience; import org.dynaresume.domain.hr.Hobby; import org.dynaresume.domain.hr.Resume; import org.dynaresume.domain.hr.SkillResume; import org.springframework.stereotype.Repository; @Repository("resumeDao") public class MockResumeDao extends AbstractDaoMock<Resume> implements ResumeDao { private static final Map<Long, Resume> resumes; static long currentId = 0; static { resumes = new LinkedHashMap<Long, Resume>(); addResume(new AngeloZerrResume()); addResume(new PascalLeclercqResume()); addResume(new AmineBoustaResume()); addResume(new LarsVogelResume()); addResume(new DinoCosmasResume()); addResume(new NicolasRaymondResume()); } private static void addResume(Resume resume) { resumes.put(resume.getId(), resume); } public Iterable<Resume> findAll() { return resumes.values(); } public Resume findOne(Long id) { Resume Resume = resumes.get(id); if (Resume != null) { return clone(Resume); } return resumes.get(id); } public Resume save(Resume resume) { if (resume.getId() == null) { resume.setId(currentId++); } resumes.put(resume.getId(), resume); return clone(resume); } private Resume clone(Resume resume) { NaturalPerson person = resume.getOwner(); NaturalPerson newPerson = clone(person); Resume newResume = new Resume(); newResume.setId(resume.getId()); newResume.setTitle(resume.getTitle()); newResume.setOwner(newPerson); newResume.setPicture(resume.getPicture()); // Diplomas Set<Education> educations = resume.getEducations(); if (educations != null) { Set<Education> newDiplomas = new HashSet<Education>(); for (Education diploma : educations) { newDiplomas.add(clone(diploma)); } newResume.setEducations(educations); } // Experiences Set<Experience> experiences = resume.getExperiences(); if (experiences != null) { Set<Experience> newExperiences = new HashSet<Experience>(); for (Experience experience : experiences) { newExperiences.add(clone(experience)); } newResume.setExperiences(newExperiences); } // Hobbies Set<SkillResume> skills = resume.getSkills(); if (skills != null) { Set<SkillResume> newSkills = new HashSet<SkillResume>(); for (SkillResume skill : skills) { newSkills.add(clone(skill)); } newResume.setSkills(newSkills); } // Hobbies Set<Hobby> hobbies = resume.getHobbies(); if (hobbies != null) { Set<Hobby> newHobbies = new HashSet<Hobby>(); for (Hobby hobby : hobbies) { newHobbies.add(clone(hobby)); } newResume.setHobbies(newHobbies); } return newResume; } private NaturalPerson clone(NaturalPerson person) { NaturalPerson newPerson = new NaturalPerson(); newPerson.setId(person.getId()); newPerson.setLastName(person.getLastName()); newPerson.setFirstName(person.getFirstName()); newPerson.setBirthDate(person.getBirthDate()); newPerson.setEmail(person.getEmail()); newPerson.setAddress(clone(person.getAddress())); return newPerson; } private Experience clone(Experience experience) { Experience newExperience = new Experience(); Long id = experience.getId(); if (id == null) { id = currentId++; } newExperience.setId(id); newExperience.setTitle(experience.getTitle()); newExperience.setDetail(experience.getDetail()); newExperience.setMission(experience.getMission()); newExperience.setEndDate(experience.getEndDate()); newExperience.setStartDate(experience.getStartDate()); return newExperience; } private Education clone(Education diploma) { Education newDiploma = new Education(); Long id = diploma.getId(); if (id == null) { id = currentId++; } newDiploma.setId(id); newDiploma.setLabel(diploma.getLabel()); newDiploma.setInstitute(diploma.getInstitute()); return newDiploma; } private Hobby clone(Hobby hobby) { Hobby newHobby = new Hobby(); Long id = hobby.getId(); if (id == null) { id = currentId++; } newHobby.setId(id); newHobby.setLabel(hobby.getLabel()); return newHobby; } private SkillResume clone(SkillResume skill) { SkillResume newSkill = new SkillResume(); newSkill.setCategory(skill.getCategory()); newSkill.setSkill(skill.getSkill()); newSkill.setFreeSkill(skill.getFreeSkill()); return newSkill; } private Address clone(Address address) { if (address == null) { return null; } Address newAddress = new Address(); Long id = address.getId(); if (id == null) { id = currentId++; } newAddress.setId(id); newAddress.setCity(address.getCity()); newAddress.setCountry(address.getCountry()); newAddress.setFax(address.getFax()); newAddress.setStreet(address.getStreet()); newAddress.setTelephone(address.getTelephone()); newAddress.setZipCode(address.getZipCode()); return newAddress; } }
Add Ralf Sternberg resume.
dynaresume/org.dynaresume.dao.mock/src/main/java/org/dynaresume/dao/mock/MockResumeDao.java
Add Ralf Sternberg resume.
<ide><path>ynaresume/org.dynaresume.dao.mock/src/main/java/org/dynaresume/dao/mock/MockResumeDao.java <ide> import org.dynaresume.dao.mock.resume.LarsVogelResume; <ide> import org.dynaresume.dao.mock.resume.NicolasRaymondResume; <ide> import org.dynaresume.dao.mock.resume.PascalLeclercqResume; <add>import org.dynaresume.dao.mock.resume.RalfSternbergResume; <ide> import org.dynaresume.domain.core.Address; <ide> import org.dynaresume.domain.core.NaturalPerson; <ide> import org.dynaresume.domain.hr.Education; <ide> addResume(new AngeloZerrResume()); <ide> addResume(new PascalLeclercqResume()); <ide> addResume(new AmineBoustaResume()); <add> addResume(new RalfSternbergResume()); <ide> addResume(new LarsVogelResume()); <ide> addResume(new DinoCosmasResume()); <ide> addResume(new NicolasRaymondResume());
Java
apache-2.0
46455d1773fd8b52cccff495c359c51d206b855f
0
webfirmframework/wff,webfirmframework/wff
/* * Copyright 2014-2016 Web Firm Framework * * 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. * @author WFF */ package com.webfirmframework.wffweb.tag.html; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import com.webfirmframework.wffweb.clone.CloneUtil; import com.webfirmframework.wffweb.streamer.WffBinaryMessageOutputStreamer; import com.webfirmframework.wffweb.tag.core.AbstractTagBase; import com.webfirmframework.wffweb.tag.html.attribute.core.AbstractAttribute; import com.webfirmframework.wffweb.tag.html.attribute.core.AttributeUtil; import com.webfirmframework.wffweb.tag.html.core.TagRegistry; import com.webfirmframework.wffweb.tag.html.model.AbstractHtml5SharedObject; import com.webfirmframework.wffweb.util.WffBinaryMessageUtil; import com.webfirmframework.wffweb.util.data.NameValue; /** * @author WFF * @since 1.0.0 * @version 1.0.0 * */ public abstract class AbstractHtml extends AbstractTagBase { private static final long serialVersionUID = 1_0_0L; protected static int tagNameIndex; private AbstractHtml parent; private List<AbstractHtml> children; private String openingTag; // should be initialized with empty string private String closingTag = ""; private StringBuilder htmlStartSB; private StringBuilder htmlMiddleSB; private StringBuilder htmlEndSB; private String tagName; private StringBuilder tagBuilder; private AbstractAttribute[] attributes; private AbstractHtml5SharedObject sharedObject; private boolean htmlStartSBAsFirst; private OutputStream outputStream; // for future development private WffBinaryMessageOutputStreamer wffBinaryMessageOutputStreamer; private transient Charset charset = Charset.defaultCharset(); public static enum TagType { OPENING_CLOSING, SELF_CLOSING, NON_CLOSING; private TagType() { } } private TagType tagType = TagType.OPENING_CLOSING; { init(); } @SuppressWarnings("unused") private AbstractHtml() { throw new AssertionError(); } public AbstractHtml(final AbstractHtml base, final Collection<? extends AbstractHtml> children) { initInConstructor(); this.children.addAll(children); buildOpeningTag(false); buildClosingTag(); if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } } /** * @param base * @param childContent * any text, it can also be html text. */ public AbstractHtml(final AbstractHtml base, final String childContent) { initInConstructor(); htmlStartSBAsFirst = true; getHtmlMiddleSB().append(childContent); buildOpeningTag(false); buildClosingTag(); if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } setRebuild(true); } /** * should be invoked to generate opening and closing tag base class * containing the functionalities to generate html string. * * @param tagName * TODO * @param base * TODO * @author WFF */ public AbstractHtml(final String tagName, final AbstractHtml base, final AbstractAttribute[] attributes) { this.tagName = tagName; this.attributes = attributes; initInConstructor(); markOwnerTag(attributes); buildOpeningTag(false); buildClosingTag(); if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } } /** * should be invoked to generate opening and closing tag base class * containing the functionalities to generate html string. * * @param tagType * * @param tagName * TODO * @param base * TODO * @author WFF */ protected AbstractHtml(final TagType tagType, final String tagName, final AbstractHtml base, final AbstractAttribute[] attributes) { this.tagType = tagType; this.tagName = tagName; this.attributes = attributes; initInConstructor(); markOwnerTag(attributes); buildOpeningTag(false); if (tagType == TagType.OPENING_CLOSING) { buildClosingTag(); } if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } } /** * marks the owner tag in the attributes * * @param attributes * @since 1.0.0 * @author WFF */ private void markOwnerTag(final AbstractAttribute[] attributes) { if (attributes == null) { return; } for (final AbstractAttribute abstractAttribute : attributes) { abstractAttribute.setOwnerTag(this); } } private void init() { children = new LinkedList<AbstractHtml>(); tagBuilder = new StringBuilder(); setRebuild(true); } /** * to initialize objects in the constructor * * @since 1.0.0 * @author WFF */ private void initInConstructor() { htmlStartSB = new StringBuilder(tagName == null ? 0 : tagName.length() + 2 + ((attributes == null ? 0 : attributes.length) * 16)); htmlEndSB = new StringBuilder( tagName == null ? 16 : tagName.length() + 3); } public AbstractHtml getParent() { return parent; } public void setParent(final AbstractHtml parent) { this.parent = parent; } public List<AbstractHtml> getChildren() { return children; } public void setChildren(final List<AbstractHtml> children) { this.children = children; } public String getOpeningTag() { if (isRebuild() || isModified()) { buildOpeningTag(true); } return openingTag; } public String getClosingTag() { return closingTag; } /** * @return {@code String} equalent to the html string of the tag including * the child tags. * @since 1.0.0 * @author WFF */ protected String getPrintStructure() { String printStructure = null; if (isRebuild() || isModified()) { printStructure = getPrintStructure(true); setRebuild(false); } else { printStructure = tagBuilder.toString(); } return printStructure; } /** * @param rebuild * @return * @since 1.0.0 * @author WFF */ protected String getPrintStructure(final boolean rebuild) { if (rebuild || isRebuild() || isModified()) { beforePrintStructure(); tagBuilder.delete(0, tagBuilder.length()); recurChildren(Arrays.asList(this), true); setRebuild(false); } tagBuilder.trimToSize(); return tagBuilder.toString(); } /** * @param rebuild * @since 1.0.0 * @author WFF * @throws IOException */ protected void writePrintStructureToOutputStream(final boolean rebuild) throws IOException { beforeWritePrintStructureToOutputStream(); recurChildrenToOutputStream(Arrays.asList(this), true); } // for future development /** * @param rebuild * @since 1.2.0 * @author WFF * @throws IOException */ protected void writePrintStructureToWffBinaryMessageOutputStream( final boolean rebuild) throws IOException { beforeWritePrintStructureToWffBinaryMessageOutputStream(); recurChildrenToWffBinaryMessageOutputStream(Arrays.asList(this), true); } /** * to form html string from the children * * @param children * @param rebuild * TODO * @since 1.0.0 * @author WFF */ private void recurChildren(final List<AbstractHtml> children, final boolean rebuild) { if (children != null && children.size() > 0) { for (final AbstractHtml child : children) { child.setRebuild(rebuild); tagBuilder.append(child.getOpeningTag()); // tagBuilder.append("\n");// TODO should be removed later if (isHtmlStartSBAsFirst() && htmlMiddleSB != null) { tagBuilder.append(getHtmlMiddleSB()); } final List<AbstractHtml> childrenOfChildren = child.children; if (!isHtmlStartSBAsFirst() && htmlMiddleSB != null) { tagBuilder.append(getHtmlMiddleSB()); } recurChildren(childrenOfChildren, rebuild); tagBuilder.append(child.closingTag); // tagBuilder.append("\n");// TODO should be removed later } } } /** * to form html string from the children * * @param children * @param rebuild * TODO * @since 1.0.0 * @author WFF * @throws IOException */ private void recurChildrenToOutputStream(final List<AbstractHtml> children, final boolean rebuild) throws IOException { if (children != null && children.size() > 0) { for (final AbstractHtml child : children) { child.setRebuild(rebuild); outputStream.write(child.getOpeningTag().getBytes(charset)); if (isHtmlStartSBAsFirst() && htmlMiddleSB != null) { outputStream.write( getHtmlMiddleSB().toString().getBytes(charset)); } final List<AbstractHtml> childrenOfChildren = child.children; if (!isHtmlStartSBAsFirst() && htmlMiddleSB != null) { outputStream.write( getHtmlMiddleSB().toString().getBytes(charset)); } recurChildrenToOutputStream(childrenOfChildren, rebuild); outputStream.write(child.closingTag.getBytes(charset)); } } } // for future development /** * to form html string from the children * * @param children * @param rebuild * TODO * @since 1.2.0 * @author WFF * @throws IOException */ private void recurChildrenToWffBinaryMessageOutputStream( final List<AbstractHtml> children, final boolean rebuild) throws IOException { if (children != null && children.size() > 0) { for (final AbstractHtml child : children) { child.setRebuild(rebuild); // wffBinaryMessageOutputStreamer // outputStream.write(child.getOpeningTag().getBytes(charset)); final NameValue nameValue = new NameValue(); final int tagNameIndex = TagRegistry.getTagNames() .indexOf(child.getTagName()); // if the tag index is -1 i.e. it's not indexed then the tag // name prepended with 0 value byte should be set. // If the first byte == 0 and length is greater than 1 then it's // a tag name, if the first byte is greater than 0 then it is // index bytes byte[] closingTagNameConvertedBytes = null; if (tagNameIndex == -1) { final byte[] tagNameBytes = child.getTagName() .getBytes(charset); final byte[] nameBytes = new byte[tagNameBytes.length + 1]; nameBytes[0] = 0; System.arraycopy(tagNameBytes, 0, nameBytes, 1, tagNameBytes.length); nameValue.setName(nameBytes); closingTagNameConvertedBytes = nameBytes; } else { final byte[] indexBytes = WffBinaryMessageUtil .getOptimizedBytesFromInt(tagNameIndex); nameValue.setName(indexBytes); closingTagNameConvertedBytes = WffBinaryMessageUtil .getOptimizedBytesFromInt((tagNameIndex * (-1))); } nameValue.setValues( child.getAttributeHtmlBytesCompressedByIndex(rebuild, charset)); wffBinaryMessageOutputStreamer.write(nameValue); if (isHtmlStartSBAsFirst() && htmlMiddleSB != null) { final NameValue closingTagNameValue = new NameValue(); closingTagNameValue.setName(new byte[0]); closingTagNameValue.setValues(new byte[][] { getHtmlMiddleSB().toString().getBytes(charset) }); wffBinaryMessageOutputStreamer.write(closingTagNameValue); // outputStream.write( // getHtmlMiddleSB().toString().getBytes(charset)); } final List<AbstractHtml> childrenOfChildren = child.children; if (!isHtmlStartSBAsFirst() && htmlMiddleSB != null) { final NameValue closingTagNameValue = new NameValue(); closingTagNameValue.setName(new byte[0]); closingTagNameValue.setValues(new byte[][] { getHtmlMiddleSB().toString().getBytes(charset) }); wffBinaryMessageOutputStreamer.write(closingTagNameValue); // outputStream.write( // getHtmlMiddleSB().toString().getBytes(charset)); } recurChildrenToWffBinaryMessageOutputStream(childrenOfChildren, rebuild); final NameValue closingTagNameValue = new NameValue(); closingTagNameValue.setName(closingTagNameConvertedBytes); closingTagNameValue.setValues(new byte[0][0]); wffBinaryMessageOutputStreamer.write(closingTagNameValue); // outputStream.write(child.closingTag.getBytes(charset)); } } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.TagBase#toHtmlString() * * @since 1.0.0 * * @author WFF */ @Override public String toHtmlString() { final String printStructure = getPrintStructure( getSharedObject().isChildModified() && !getSharedObject().getRebuiltTags().contains(this)); if (parent == null) { getSharedObject().setChildModified(false); } else { getSharedObject().getRebuiltTags().add(this); } return printStructure; } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(java.nio. * charset.Charset) */ @Override public String toHtmlString(final Charset charset) { final Charset previousCharset = this.charset; try { this.charset = charset; // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(); return htmlString; } finally { this.charset = previousCharset; } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(java.lang. * String) */ @Override public String toHtmlString(final String charset) { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(); return htmlString; } finally { this.charset = previousCharset; } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.TagBase#toHtmlString(boolean) * * @since 1.0.0 * * @author WFF */ @Override public String toHtmlString(final boolean rebuild) { return getPrintStructure(rebuild); } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(boolean, * java.nio.charset.Charset) */ @Override public String toHtmlString(final boolean rebuild, final Charset charset) { final Charset previousCharset = this.charset; try { this.charset = charset; // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(rebuild); return htmlString; } finally { this.charset = previousCharset; } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(boolean, * java.lang.String) */ @Override public String toHtmlString(final boolean rebuild, final String charset) { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(rebuild); return htmlString; } finally { this.charset = previousCharset; } } // TODO for future implementation /** * @param os * the object of {@code OutputStream} to write to. * @throws IOException * @Deprecated this method is for future implementation so it should not be * consumed */ @Deprecated void toOutputStream(final boolean asWffBinaryMessage, final OutputStream os) throws IOException { if (asWffBinaryMessage) { System.out.println("asWffBinaryMessage " + asWffBinaryMessage); try { wffBinaryMessageOutputStreamer = new WffBinaryMessageOutputStreamer( os); writePrintStructureToWffBinaryMessageOutputStream(true); } finally { wffBinaryMessageOutputStreamer = null; } } else { toOutputStream(os); } } /** * @param os * the object of {@code OutputStream} to write to. * @throws IOException */ public void toOutputStream(final OutputStream os) throws IOException { try { outputStream = os; writePrintStructureToOutputStream(true); } finally { outputStream = null; } } /** * @param os * the object of {@code OutputStream} to write to. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final Charset charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = charset; outputStream = os; writePrintStructureToOutputStream(true); } finally { outputStream = null; this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final String charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); outputStream = os; writePrintStructureToOutputStream(true); } finally { outputStream = null; this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @param rebuild * true to rebuild & false to write previously built bytes. * * @throws IOException */ public void toOutputStream(final OutputStream os, final boolean rebuild) throws IOException { try { outputStream = os; writePrintStructureToOutputStream(rebuild); } finally { outputStream = null; } } /** * @param os * the object of {@code OutputStream} to write to. * @param rebuild * true to rebuild & false to write previously built bytes. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final boolean rebuild, final Charset charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = charset; outputStream = os; writePrintStructureToOutputStream(rebuild); } finally { outputStream = null; this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @param rebuild * true to rebuild & false to write previously built bytes. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final boolean rebuild, final String charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); outputStream = os; writePrintStructureToOutputStream(rebuild); } finally { outputStream = null; this.charset = previousCharset; } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ // it is not a best practice to print html string by this method because if // it is used in ThreadLocal class it may cause memory leak. @Override public String toString() { return super.toString(); } /** * Eg tag names :- html, body, div table, input, button etc... * * @return the tagName set by {@code AbstractHtml5#setTagName(String)} * method. * @since 1.0.0 * @author WFF */ public String getTagName() { return tagName; } public byte[][] getAttributeHtmlBytesCompressedByIndex( final boolean rebuild, final Charset charset) throws IOException { return AttributeUtil.getAttributeHtmlBytesCompressedByIndex(rebuild, charset, attributes); } /** * * @param rebuild * TODO * @since 1.0.0 * @author WFF */ private void buildOpeningTag(final boolean rebuild) { final String attributeHtmlString = AttributeUtil .getAttributeHtmlString(rebuild, charset, attributes); htmlStartSB.delete(0, htmlStartSB.length()); if (tagName != null) { htmlStartSB.append('<'); htmlStartSB.append(tagName); htmlStartSB.append(attributeHtmlString); if (tagType == TagType.OPENING_CLOSING) { htmlStartSB.append('>'); } else if (tagType == TagType.SELF_CLOSING) { htmlStartSB.append(new char[] { '/', '>' }); } else { // here it will be tagType == TagType.NON_CLOSING as there are // three types in TagType class htmlStartSB.append('>'); } htmlStartSB.trimToSize(); openingTag = htmlStartSB.toString(); } else { htmlStartSB.trimToSize(); openingTag = ""; } } /** * * @since 1.0.0 * @author WFF */ private void buildClosingTag() { htmlEndSB.delete(0, htmlEndSB.length()); if (tagName != null) { htmlEndSB.append(new char[] { '<', '/' }); htmlEndSB.append(tagName); htmlEndSB.append('>'); } else { if (htmlStartSB != null) { htmlEndSB.append(getHtmlMiddleSB()); } } htmlEndSB.trimToSize(); closingTag = htmlEndSB.toString(); } /** * @return the sharedObject * @since 1.0.0 * @author WFF */ public AbstractHtml5SharedObject getSharedObject() { return sharedObject; } /** * @return the htmlMiddleSB * @since 1.0.0 * @author WFF */ protected StringBuilder getHtmlMiddleSB() { if (htmlMiddleSB == null) { htmlMiddleSB = new StringBuilder(); } return htmlMiddleSB; } /** * @return the htmlStartSBAsFirst * @since 1.0.0 * @author WFF */ public boolean isHtmlStartSBAsFirst() { return htmlStartSBAsFirst; } protected AbstractHtml deepClone(final AbstractHtml objectToBeClonned) throws CloneNotSupportedException { return CloneUtil.<AbstractHtml> deepClone(objectToBeClonned); } /** * invokes just before {@code getPrintStructure(final boolean} method and * only if the getPrintStructure(final boolean} rebuilds the structure. * * @since 1.0.0 * @author WFF */ protected void beforePrintStructure() { // TODO override and use } /** * invokes just before * {@code writePrintStructureToOutputStream(final OutputStream} method. * * @since 1.0.0 * @author WFF */ protected void beforeWritePrintStructureToOutputStream() { // TODO override and use } /** * invokes just before * {@code writePrintStructureToWffBinaryMessageOutputStream(final OutputStream} * method. * * @since 1.2.0 * @author WFF */ protected void beforeWritePrintStructureToWffBinaryMessageOutputStream() { // TODO override and use } /** * Creates and returns a deeply cloned copy of this object. The precise * meaning of "copy" may depend on the class of the object. The general * intent is that, for any object {@code x}, the expression: <blockquote> * * <pre> * x.clone() != x * </pre> * * </blockquote> will be true, and that the expression: <blockquote> * * <pre> * x.clone().getClass() == x.getClass() * </pre> * * </blockquote> will be {@code true}, but these are not absolute * requirements. While it is typically the case that: <blockquote> * * <pre> * x.clone().equals(x) * </pre> * * </blockquote> will be {@code true}, this is not an absolute requirement. * <p> * By convention, the returned object should be obtained by calling * {@code super.clone}. If a class and all of its superclasses (except * {@code Object}) obey this convention, it will be the case that * {@code x.clone().getClass() == x.getClass()}. * <p> * By convention, the object returned by this method should be independent * of this object (which is being cloned). To achieve this independence, it * may be necessary to modify one or more fields of the object returned by * {@code super.clone} before returning it. Typically, this means copying * any mutable objects that comprise the internal "deep structure" of the * object being cloned and replacing the references to these objects with * references to the copies. If a class contains only primitive fields or * references to immutable objects, then it is usually the case that no * fields in the object returned by {@code super.clone} need to be modified. * <p> * The method {@code clone} for class {@code AbstractHtml} performs a * specific cloning operation. First, if the class of this object does not * implement the interfaces {@code Cloneable} and {@code Serializable}, then * a {@code CloneNotSupportedException} is thrown. Note that all arrays are * considered to implement the interface {@code Cloneable} and that the * return type of the {@code clone} method of an array type {@code T[]} is * {@code T[]} where T is any reference or primitive type. Otherwise, this * method creates a new instance of the class of this object and initializes * all its fields with exactly the contents of the corresponding fields of * this object, as if by assignment; the contents of the fields are not * themselves cloned. Thus, this method performs a "shallow copy" of this * object, not a "deep copy" operation. * * @return a deep clone of this instance. * @exception CloneNotSupportedException * if the object's class does not support the * {@code Cloneable} and {@code Serializable} interfaces. * Subclasses that override the {@code clone} method can also * throw this exception to indicate that an instance cannot * be cloned. * @see java.lang.Cloneable * @see java.io.Serializable * @author WFF */ @Override public AbstractHtml clone() throws CloneNotSupportedException { return deepClone(this); } /** * @return the charset */ public Charset getCharset() { return charset; } /** * @param charset * the charset to set */ public void setCharset(final Charset charset) { this.charset = charset; } }
wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/AbstractHtml.java
/* * Copyright 2014-2016 Web Firm Framework * * 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. * @author WFF */ package com.webfirmframework.wffweb.tag.html; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import com.webfirmframework.wffweb.clone.CloneUtil; import com.webfirmframework.wffweb.tag.core.AbstractTagBase; import com.webfirmframework.wffweb.tag.html.attribute.core.AbstractAttribute; import com.webfirmframework.wffweb.tag.html.attribute.core.AttributeUtil; import com.webfirmframework.wffweb.tag.html.model.AbstractHtml5SharedObject; /** * @author WFF * @since 1.0.0 * @version 1.0.0 * */ public abstract class AbstractHtml extends AbstractTagBase { private static final long serialVersionUID = 1_0_0L; private AbstractHtml parent; private List<AbstractHtml> children; private String openingTag; // should be initialized with empty string private String closingTag = ""; private StringBuilder htmlStartSB; private StringBuilder htmlMiddleSB; private StringBuilder htmlEndSB; private String tagName; private StringBuilder tagBuilder; private AbstractAttribute[] attributes; private AbstractHtml5SharedObject sharedObject; private boolean htmlStartSBAsFirst; private OutputStream outputStream; private transient Charset charset = Charset.defaultCharset(); public static enum TagType { OPENING_CLOSING, SELF_CLOSING, NON_CLOSING; private TagType() { } } private TagType tagType = TagType.OPENING_CLOSING; { init(); } @SuppressWarnings("unused") private AbstractHtml() { throw new AssertionError(); } public AbstractHtml(final AbstractHtml base, final Collection<? extends AbstractHtml> children) { initInConstructor(); this.children.addAll(children); buildOpeningTag(false); buildClosingTag(); if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } } /** * @param base * @param childContent * any text, it can also be html text. */ public AbstractHtml(final AbstractHtml base, final String childContent) { initInConstructor(); htmlStartSBAsFirst = true; getHtmlMiddleSB().append(childContent); buildOpeningTag(false); buildClosingTag(); if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } setRebuild(true); } /** * should be invoked to generate opening and closing tag base class * containing the functionalities to generate html string. * * @param tagName * TODO * @param base * TODO * @author WFF */ public AbstractHtml(final String tagName, final AbstractHtml base, final AbstractAttribute[] attributes) { this.tagName = tagName; this.attributes = attributes; initInConstructor(); markOwnerTag(attributes); buildOpeningTag(false); buildClosingTag(); if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } } /** * should be invoked to generate opening and closing tag base class * containing the functionalities to generate html string. * * @param tagType * * @param tagName * TODO * @param base * TODO * @author WFF */ protected AbstractHtml(final TagType tagType, final String tagName, final AbstractHtml base, final AbstractAttribute[] attributes) { this.tagType = tagType; this.tagName = tagName; this.attributes = attributes; initInConstructor(); markOwnerTag(attributes); buildOpeningTag(false); if (tagType == TagType.OPENING_CLOSING) { buildClosingTag(); } if (base != null) { parent = base; sharedObject = base.sharedObject; base.children.add(this); } else { sharedObject = new AbstractHtml5SharedObject(); } } /** * marks the owner tag in the attributes * * @param attributes * @since 1.0.0 * @author WFF */ private void markOwnerTag(final AbstractAttribute[] attributes) { if (attributes == null) { return; } for (final AbstractAttribute abstractAttribute : attributes) { abstractAttribute.setOwnerTag(this); } } private void init() { children = new LinkedList<AbstractHtml>(); tagBuilder = new StringBuilder(); setRebuild(true); } /** * to initialize objects in the constructor * * @since 1.0.0 * @author WFF */ private void initInConstructor() { htmlStartSB = new StringBuilder(tagName == null ? 0 : tagName.length() + 2 + ((attributes == null ? 0 : attributes.length) * 16)); htmlEndSB = new StringBuilder( tagName == null ? 16 : tagName.length() + 3); } public AbstractHtml getParent() { return parent; } public void setParent(final AbstractHtml parent) { this.parent = parent; } public List<AbstractHtml> getChildren() { return children; } public void setChildren(final List<AbstractHtml> children) { this.children = children; } public String getOpeningTag() { if (isRebuild() || isModified()) { buildOpeningTag(true); } return openingTag; } public String getClosingTag() { return closingTag; } /** * @return {@code String} equalent to the html string of the tag including * the child tags. * @since 1.0.0 * @author WFF */ protected String getPrintStructure() { String printStructure = null; if (isRebuild() || isModified()) { printStructure = getPrintStructure(true); setRebuild(false); } else { printStructure = tagBuilder.toString(); } return printStructure; } /** * @param rebuild * @return * @since 1.0.0 * @author WFF */ protected String getPrintStructure(final boolean rebuild) { if (rebuild || isRebuild() || isModified()) { beforePrintStructure(); tagBuilder.delete(0, tagBuilder.length()); recurChildren(Arrays.asList(this), true); setRebuild(false); } tagBuilder.trimToSize(); return tagBuilder.toString(); } /** * @param rebuild * @since 1.0.0 * @author WFF * @throws IOException */ protected void writePrintStructureToOutputStream(final boolean rebuild) throws IOException { beforeWritePrintStructureToOutputStream(); recurChildrenToOutputStream(Arrays.asList(this), true); } /** * to form html string from the children * * @param children * @param rebuild * TODO * @since 1.0.0 * @author WFF */ private void recurChildren(final List<AbstractHtml> children, final boolean rebuild) { if (children != null && children.size() > 0) { for (final AbstractHtml child : children) { child.setRebuild(rebuild); tagBuilder.append(child.getOpeningTag()); // tagBuilder.append("\n");// TODO should be removed later if (isHtmlStartSBAsFirst() && htmlMiddleSB != null) { tagBuilder.append(getHtmlMiddleSB()); } final List<AbstractHtml> childrenOfChildren = child.children; if (!isHtmlStartSBAsFirst() && htmlMiddleSB != null) { tagBuilder.append(getHtmlMiddleSB()); } recurChildren(childrenOfChildren, rebuild); tagBuilder.append(child.closingTag); // tagBuilder.append("\n");// TODO should be removed later } } } /** * to form html string from the children * * @param children * @param rebuild * TODO * @since 1.0.0 * @author WFF * @throws IOException */ private void recurChildrenToOutputStream(final List<AbstractHtml> children, final boolean rebuild) throws IOException { if (children != null && children.size() > 0) { for (final AbstractHtml child : children) { child.setRebuild(rebuild); outputStream.write(child.getOpeningTag().getBytes(charset)); if (isHtmlStartSBAsFirst() && htmlMiddleSB != null) { outputStream.write( getHtmlMiddleSB().toString().getBytes(charset)); } final List<AbstractHtml> childrenOfChildren = child.children; if (!isHtmlStartSBAsFirst() && htmlMiddleSB != null) { outputStream.write( getHtmlMiddleSB().toString().getBytes(charset)); } recurChildrenToOutputStream(childrenOfChildren, rebuild); outputStream.write(child.closingTag.getBytes(charset)); } } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.TagBase#toHtmlString() * * @since 1.0.0 * * @author WFF */ @Override public String toHtmlString() { final String printStructure = getPrintStructure( getSharedObject().isChildModified() && !getSharedObject().getRebuiltTags().contains(this)); if (parent == null) { getSharedObject().setChildModified(false); } else { getSharedObject().getRebuiltTags().add(this); } return printStructure; } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(java.nio. * charset.Charset) */ @Override public String toHtmlString(final Charset charset) { final Charset previousCharset = this.charset; try { this.charset = charset; // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(); return htmlString; } finally { this.charset = previousCharset; } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(java.lang. * String) */ @Override public String toHtmlString(final String charset) { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(); return htmlString; } finally { this.charset = previousCharset; } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.TagBase#toHtmlString(boolean) * * @since 1.0.0 * * @author WFF */ @Override public String toHtmlString(final boolean rebuild) { return getPrintStructure(rebuild); } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(boolean, * java.nio.charset.Charset) */ @Override public String toHtmlString(final boolean rebuild, final Charset charset) { final Charset previousCharset = this.charset; try { this.charset = charset; // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(rebuild); return htmlString; } finally { this.charset = previousCharset; } } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.tag.core.TagBase#toHtmlString(boolean, * java.lang.String) */ @Override public String toHtmlString(final boolean rebuild, final String charset) { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); // assigning it to new variable is very important here as this // line of code should invoke before finally block final String htmlString = toHtmlString(rebuild); return htmlString; } finally { this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @throws IOException */ public void toOutputStream(final OutputStream os) throws IOException { try { outputStream = os; writePrintStructureToOutputStream(true); } finally { outputStream = null; } } /** * @param os * the object of {@code OutputStream} to write to. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final Charset charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = charset; outputStream = os; writePrintStructureToOutputStream(true); } finally { outputStream = null; this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final String charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); outputStream = os; writePrintStructureToOutputStream(true); } finally { outputStream = null; this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @param rebuild * true to rebuild & false to write previously built bytes. * * @throws IOException */ public void toOutputStream(final OutputStream os, final boolean rebuild) throws IOException { try { outputStream = os; writePrintStructureToOutputStream(rebuild); } finally { outputStream = null; } } /** * @param os * the object of {@code OutputStream} to write to. * @param rebuild * true to rebuild & false to write previously built bytes. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final boolean rebuild, final Charset charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = charset; outputStream = os; writePrintStructureToOutputStream(rebuild); } finally { outputStream = null; this.charset = previousCharset; } } /** * @param os * the object of {@code OutputStream} to write to. * @param rebuild * true to rebuild & false to write previously built bytes. * @param charset * the charset * @throws IOException */ public void toOutputStream(final OutputStream os, final boolean rebuild, final String charset) throws IOException { final Charset previousCharset = this.charset; try { this.charset = Charset.forName(charset); outputStream = os; writePrintStructureToOutputStream(rebuild); } finally { outputStream = null; this.charset = previousCharset; } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ // it is not a best practice to print html string by this method because if // it is used in ThreadLocal class it may cause memory leak. @Override public String toString() { return super.toString(); } /** * Eg tag names :- html, body, div table, input, button etc... * * @return the tagName set by {@code AbstractHtml5#setTagName(String)} * method. * @since 1.0.0 * @author WFF */ public String getTagName() { return tagName; } /** * * @param rebuild * TODO * @since 1.0.0 * @author WFF */ private void buildOpeningTag(final boolean rebuild) { final String attributeHtmlString = AttributeUtil .getAttributeHtmlString(rebuild, charset, attributes); htmlStartSB.delete(0, htmlStartSB.length()); if (tagName != null) { htmlStartSB.append('<'); htmlStartSB.append(tagName); htmlStartSB.append(attributeHtmlString); if (tagType == TagType.OPENING_CLOSING) { htmlStartSB.append('>'); } else if (tagType == TagType.SELF_CLOSING) { htmlStartSB.append(new char[] { '/', '>' }); } else { // here it will be tagType == TagType.NON_CLOSING as there are // three types in TagType class htmlStartSB.append('>'); } htmlStartSB.trimToSize(); openingTag = htmlStartSB.toString(); } else { htmlStartSB.trimToSize(); openingTag = ""; } } /** * * @since 1.0.0 * @author WFF */ private void buildClosingTag() { htmlEndSB.delete(0, htmlEndSB.length()); if (tagName != null) { htmlEndSB.append(new char[] { '<', '/' }); htmlEndSB.append(tagName); htmlEndSB.append('>'); } else { if (htmlStartSB != null) { htmlEndSB.append(getHtmlMiddleSB()); } } htmlEndSB.trimToSize(); closingTag = htmlEndSB.toString(); } /** * @return the sharedObject * @since 1.0.0 * @author WFF */ public AbstractHtml5SharedObject getSharedObject() { return sharedObject; } /** * @return the htmlMiddleSB * @since 1.0.0 * @author WFF */ protected StringBuilder getHtmlMiddleSB() { if (htmlMiddleSB == null) { htmlMiddleSB = new StringBuilder(); } return htmlMiddleSB; } /** * @return the htmlStartSBAsFirst * @since 1.0.0 * @author WFF */ public boolean isHtmlStartSBAsFirst() { return htmlStartSBAsFirst; } protected AbstractHtml deepClone(final AbstractHtml objectToBeClonned) throws CloneNotSupportedException { return CloneUtil.<AbstractHtml> deepClone(objectToBeClonned); } /** * invokes just before {@code getPrintStructure(final boolean} method and * only if the getPrintStructure(final boolean} rebuilds the structure. * * @since 1.0.0 * @author WFF */ protected void beforePrintStructure() { // TODO override and use } /** * invokes just before * {@code writePrintStructureToOutputStream(final OutputStream} method. * * @since 1.0.0 * @author WFF */ protected void beforeWritePrintStructureToOutputStream() { // TODO override and use } /** * Creates and returns a deeply cloned copy of this object. The precise * meaning of "copy" may depend on the class of the object. The general * intent is that, for any object {@code x}, the expression: <blockquote> * * <pre> * x.clone() != x * </pre> * * </blockquote> will be true, and that the expression: <blockquote> * * <pre> * x.clone().getClass() == x.getClass() * </pre> * * </blockquote> will be {@code true}, but these are not absolute * requirements. While it is typically the case that: <blockquote> * * <pre> * x.clone().equals(x) * </pre> * * </blockquote> will be {@code true}, this is not an absolute requirement. * <p> * By convention, the returned object should be obtained by calling * {@code super.clone}. If a class and all of its superclasses (except * {@code Object}) obey this convention, it will be the case that * {@code x.clone().getClass() == x.getClass()}. * <p> * By convention, the object returned by this method should be independent * of this object (which is being cloned). To achieve this independence, it * may be necessary to modify one or more fields of the object returned by * {@code super.clone} before returning it. Typically, this means copying * any mutable objects that comprise the internal "deep structure" of the * object being cloned and replacing the references to these objects with * references to the copies. If a class contains only primitive fields or * references to immutable objects, then it is usually the case that no * fields in the object returned by {@code super.clone} need to be modified. * <p> * The method {@code clone} for class {@code AbstractHtml} performs a * specific cloning operation. First, if the class of this object does not * implement the interfaces {@code Cloneable} and {@code Serializable}, then * a {@code CloneNotSupportedException} is thrown. Note that all arrays are * considered to implement the interface {@code Cloneable} and that the * return type of the {@code clone} method of an array type {@code T[]} is * {@code T[]} where T is any reference or primitive type. Otherwise, this * method creates a new instance of the class of this object and initializes * all its fields with exactly the contents of the corresponding fields of * this object, as if by assignment; the contents of the fields are not * themselves cloned. Thus, this method performs a "shallow copy" of this * object, not a "deep copy" operation. * * @return a deep clone of this instance. * @exception CloneNotSupportedException * if the object's class does not support the * {@code Cloneable} and {@code Serializable} interfaces. * Subclasses that override the {@code clone} method can also * throw this exception to indicate that an instance cannot * be cloned. * @see java.lang.Cloneable * @see java.io.Serializable * @author WFF */ @Override public AbstractHtml clone() throws CloneNotSupportedException { return deepClone(this); } /** * @return the charset */ public Charset getCharset() { return charset; } /** * @param charset * the charset to set */ public void setCharset(final Charset charset) { this.charset = charset; } }
Future implementation for few methods for network transfer
wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/AbstractHtml.java
Future implementation for few methods for network transfer
<ide><path>ffweb/src/main/java/com/webfirmframework/wffweb/tag/html/AbstractHtml.java <ide> import java.util.List; <ide> <ide> import com.webfirmframework.wffweb.clone.CloneUtil; <add>import com.webfirmframework.wffweb.streamer.WffBinaryMessageOutputStreamer; <ide> import com.webfirmframework.wffweb.tag.core.AbstractTagBase; <ide> import com.webfirmframework.wffweb.tag.html.attribute.core.AbstractAttribute; <ide> import com.webfirmframework.wffweb.tag.html.attribute.core.AttributeUtil; <add>import com.webfirmframework.wffweb.tag.html.core.TagRegistry; <ide> import com.webfirmframework.wffweb.tag.html.model.AbstractHtml5SharedObject; <add>import com.webfirmframework.wffweb.util.WffBinaryMessageUtil; <add>import com.webfirmframework.wffweb.util.data.NameValue; <ide> <ide> /** <ide> * @author WFF <ide> <ide> private static final long serialVersionUID = 1_0_0L; <ide> <add> protected static int tagNameIndex; <add> <ide> private AbstractHtml parent; <ide> private List<AbstractHtml> children; <ide> private String openingTag; <ide> private boolean htmlStartSBAsFirst; <ide> <ide> private OutputStream outputStream; <add> <add> // for future development <add> private WffBinaryMessageOutputStreamer wffBinaryMessageOutputStreamer; <ide> <ide> private transient Charset charset = Charset.defaultCharset(); <ide> <ide> recurChildrenToOutputStream(Arrays.asList(this), true); <ide> } <ide> <add> // for future development <add> /** <add> * @param rebuild <add> * @since 1.2.0 <add> * @author WFF <add> * @throws IOException <add> */ <add> protected void writePrintStructureToWffBinaryMessageOutputStream( <add> final boolean rebuild) throws IOException { <add> beforeWritePrintStructureToWffBinaryMessageOutputStream(); <add> recurChildrenToWffBinaryMessageOutputStream(Arrays.asList(this), true); <add> } <add> <ide> /** <ide> * to form html string from the children <ide> * <ide> */ <ide> private void recurChildrenToOutputStream(final List<AbstractHtml> children, <ide> final boolean rebuild) throws IOException { <add> <ide> if (children != null && children.size() > 0) { <ide> for (final AbstractHtml child : children) { <ide> child.setRebuild(rebuild); <ide> } <ide> recurChildrenToOutputStream(childrenOfChildren, rebuild); <ide> outputStream.write(child.closingTag.getBytes(charset)); <add> } <add> } <add> } <add> <add> // for future development <add> /** <add> * to form html string from the children <add> * <add> * @param children <add> * @param rebuild <add> * TODO <add> * @since 1.2.0 <add> * @author WFF <add> * @throws IOException <add> */ <add> private void recurChildrenToWffBinaryMessageOutputStream( <add> final List<AbstractHtml> children, final boolean rebuild) <add> throws IOException { <add> if (children != null && children.size() > 0) { <add> for (final AbstractHtml child : children) { <add> child.setRebuild(rebuild); <add> // wffBinaryMessageOutputStreamer <add> <add> // outputStream.write(child.getOpeningTag().getBytes(charset)); <add> <add> final NameValue nameValue = new NameValue(); <add> <add> final int tagNameIndex = TagRegistry.getTagNames() <add> .indexOf(child.getTagName()); <add> <add> // if the tag index is -1 i.e. it's not indexed then the tag <add> // name prepended with 0 value byte should be set. <add> // If the first byte == 0 and length is greater than 1 then it's <add> // a tag name, if the first byte is greater than 0 then it is <add> // index bytes <add> <add> byte[] closingTagNameConvertedBytes = null; <add> if (tagNameIndex == -1) { <add> <add> final byte[] tagNameBytes = child.getTagName() <add> .getBytes(charset); <add> <add> final byte[] nameBytes = new byte[tagNameBytes.length + 1]; <add> <add> nameBytes[0] = 0; <add> <add> System.arraycopy(tagNameBytes, 0, nameBytes, 1, <add> tagNameBytes.length); <add> nameValue.setName(nameBytes); <add> closingTagNameConvertedBytes = nameBytes; <add> } else { <add> final byte[] indexBytes = WffBinaryMessageUtil <add> .getOptimizedBytesFromInt(tagNameIndex); <add> nameValue.setName(indexBytes); <add> closingTagNameConvertedBytes = WffBinaryMessageUtil <add> .getOptimizedBytesFromInt((tagNameIndex * (-1))); <add> } <add> <add> nameValue.setValues( <add> child.getAttributeHtmlBytesCompressedByIndex(rebuild, <add> charset)); <add> <add> wffBinaryMessageOutputStreamer.write(nameValue); <add> <add> if (isHtmlStartSBAsFirst() && htmlMiddleSB != null) { <add> <add> final NameValue closingTagNameValue = new NameValue(); <add> closingTagNameValue.setName(new byte[0]); <add> closingTagNameValue.setValues(new byte[][] { <add> getHtmlMiddleSB().toString().getBytes(charset) }); <add> wffBinaryMessageOutputStreamer.write(closingTagNameValue); <add> <add> // outputStream.write( <add> // getHtmlMiddleSB().toString().getBytes(charset)); <add> } <add> <add> final List<AbstractHtml> childrenOfChildren = child.children; <add> <add> if (!isHtmlStartSBAsFirst() && htmlMiddleSB != null) { <add> <add> final NameValue closingTagNameValue = new NameValue(); <add> closingTagNameValue.setName(new byte[0]); <add> closingTagNameValue.setValues(new byte[][] { <add> getHtmlMiddleSB().toString().getBytes(charset) }); <add> wffBinaryMessageOutputStreamer.write(closingTagNameValue); <add> <add> // outputStream.write( <add> // getHtmlMiddleSB().toString().getBytes(charset)); <add> } <add> <add> recurChildrenToWffBinaryMessageOutputStream(childrenOfChildren, <add> rebuild); <add> <add> final NameValue closingTagNameValue = new NameValue(); <add> closingTagNameValue.setName(closingTagNameConvertedBytes); <add> closingTagNameValue.setValues(new byte[0][0]); <add> wffBinaryMessageOutputStreamer.write(closingTagNameValue); <add> <add> // outputStream.write(child.closingTag.getBytes(charset)); <ide> } <ide> } <ide> } <ide> } <ide> } <ide> <add> // TODO for future implementation <add> /** <add> * @param os <add> * the object of {@code OutputStream} to write to. <add> * @throws IOException <add> * @Deprecated this method is for future implementation so it should not be <add> * consumed <add> */ <add> @Deprecated <add> void toOutputStream(final boolean asWffBinaryMessage, final OutputStream os) <add> throws IOException { <add> if (asWffBinaryMessage) { <add> System.out.println("asWffBinaryMessage " + asWffBinaryMessage); <add> try { <add> wffBinaryMessageOutputStreamer = new WffBinaryMessageOutputStreamer( <add> os); <add> writePrintStructureToWffBinaryMessageOutputStream(true); <add> } finally { <add> wffBinaryMessageOutputStreamer = null; <add> } <add> } else { <add> toOutputStream(os); <add> } <add> } <add> <ide> /** <ide> * @param os <ide> * the object of {@code OutputStream} to write to. <ide> */ <ide> public String getTagName() { <ide> return tagName; <add> } <add> <add> public byte[][] getAttributeHtmlBytesCompressedByIndex( <add> final boolean rebuild, final Charset charset) throws IOException { <add> return AttributeUtil.getAttributeHtmlBytesCompressedByIndex(rebuild, <add> charset, attributes); <ide> } <ide> <ide> /** <ide> * @author WFF <ide> */ <ide> protected void beforeWritePrintStructureToOutputStream() { <add> // TODO override and use <add> } <add> <add> /** <add> * invokes just before <add> * {@code writePrintStructureToWffBinaryMessageOutputStream(final OutputStream} <add> * method. <add> * <add> * @since 1.2.0 <add> * @author WFF <add> */ <add> protected void beforeWritePrintStructureToWffBinaryMessageOutputStream() { <ide> // TODO override and use <ide> } <ide>
Java
apache-2.0
4e82bf30c6b1fe144f9581cf277c381f03f8a2f9
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2017 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.transaction.support; import java.io.Flushable; /** * Interface for transaction synchronization callbacks. * Supported by AbstractPlatformTransactionManager. * * <p>TransactionSynchronization implementations can implement the Ordered interface * to influence their execution order. A synchronization that does not implement the * Ordered interface is appended to the end of the synchronization chain. * * <p>System synchronizations performed by Spring itself use specific order values, * allowing for fine-grained interaction with their execution order (if necessary). * * @author Juergen Hoeller * @since 02.06.2003 * @see TransactionSynchronizationManager * @see AbstractPlatformTransactionManager * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER */ public interface TransactionSynchronization extends Flushable { /** Completion status in case of proper commit */ int STATUS_COMMITTED = 0; /** Completion status in case of proper rollback */ int STATUS_ROLLED_BACK = 1; /** Completion status in case of heuristic mixed completion or system errors */ int STATUS_UNKNOWN = 2; /** * Suspend this synchronization. * Supposed to unbind resources from TransactionSynchronizationManager if managing any. * @see TransactionSynchronizationManager#unbindResource */ default void suspend() { } /** * Resume this synchronization. * Supposed to rebind resources to TransactionSynchronizationManager if managing any. * @see TransactionSynchronizationManager#bindResource */ default void resume() { } /** * Flush the underlying session to the datastore, if applicable: * for example, a Hibernate/JPA session. * @see org.springframework.transaction.TransactionStatus#flush() */ @Override default void flush() { } /** * Invoked before transaction commit (before "beforeCompletion"). * Can e.g. flush transactional O/R Mapping sessions to the database. * <p>This callback does <i>not</i> mean that the transaction will actually be committed. * A rollback decision can still occur after this method has been called. This callback * is rather meant to perform work that's only relevant if a commit still has a chance * to happen, such as flushing SQL statements to the database. * <p>Note that exceptions will get propagated to the commit caller and cause a * rollback of the transaction. * @param readOnly whether the transaction is defined as read-only transaction * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b> * (note: do not throw TransactionException subclasses here!) * @see #beforeCompletion */ default void beforeCommit(boolean readOnly) { } /** * Invoked before transaction commit/rollback. * Can perform resource cleanup <i>before</i> transaction completion. * <p>This method will be invoked after {@code beforeCommit}, even when * {@code beforeCommit} threw an exception. This callback allows for * closing resources before transaction completion, for any outcome. * @throws RuntimeException in case of errors; will be <b>logged but not propagated</b> * (note: do not throw TransactionException subclasses here!) * @see #beforeCommit * @see #afterCompletion */ default void beforeCompletion() { } /** * Invoked after transaction commit. Can perform further operations right * <i>after</i> the main transaction has <i>successfully</i> committed. * <p>Can e.g. commit further operations that are supposed to follow on a successful * commit of the main transaction, like confirmation messages or emails. * <p><b>NOTE:</b> The transaction will have been committed already, but the * transactional resources might still be active and accessible. As a consequence, * any data access code triggered at this point will still "participate" in the * original transaction, allowing to perform some cleanup (with no commit following * anymore!), unless it explicitly declares that it needs to run in a separate * transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW} for any * transactional operation that is called from here.</b> * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b> * (note: do not throw TransactionException subclasses here!) */ default void afterCommit() { } /** * Invoked after transaction commit/rollback. * Can perform resource cleanup <i>after</i> transaction completion. * <p><b>NOTE:</b> The transaction will have been committed or rolled back already, * but the transactional resources might still be active and accessible. As a * consequence, any data access code triggered at this point will still "participate" * in the original transaction, allowing to perform some cleanup (with no commit * following anymore!), unless it explicitly declares that it needs to run in a * separate transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW} * for any transactional operation that is called from here.</b> * @param status completion status according to the {@code STATUS_*} constants * @throws RuntimeException in case of errors; will be <b>logged but not propagated</b> * (note: do not throw TransactionException subclasses here!) * @see #STATUS_COMMITTED * @see #STATUS_ROLLED_BACK * @see #STATUS_UNKNOWN * @see #beforeCompletion */ default void afterCompletion(int status) { } }
spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronization.java
/* * Copyright 2002-2014 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.transaction.support; import java.io.Flushable; /** * Interface for transaction synchronization callbacks. * Supported by AbstractPlatformTransactionManager. * * <p>TransactionSynchronization implementations can implement the Ordered interface * to influence their execution order. A synchronization that does not implement the * Ordered interface is appended to the end of the synchronization chain. * * <p>System synchronizations performed by Spring itself use specific order values, * allowing for fine-grained interaction with their execution order (if necessary). * * @author Juergen Hoeller * @since 02.06.2003 * @see TransactionSynchronizationManager * @see AbstractPlatformTransactionManager * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER */ public interface TransactionSynchronization extends Flushable { /** Completion status in case of proper commit */ int STATUS_COMMITTED = 0; /** Completion status in case of proper rollback */ int STATUS_ROLLED_BACK = 1; /** Completion status in case of heuristic mixed completion or system errors */ int STATUS_UNKNOWN = 2; /** * Suspend this synchronization. * Supposed to unbind resources from TransactionSynchronizationManager if managing any. * @see TransactionSynchronizationManager#unbindResource */ void suspend(); /** * Resume this synchronization. * Supposed to rebind resources to TransactionSynchronizationManager if managing any. * @see TransactionSynchronizationManager#bindResource */ void resume(); /** * Flush the underlying session to the datastore, if applicable: * for example, a Hibernate/JPA session. * @see org.springframework.transaction.TransactionStatus#flush() */ @Override void flush(); /** * Invoked before transaction commit (before "beforeCompletion"). * Can e.g. flush transactional O/R Mapping sessions to the database. * <p>This callback does <i>not</i> mean that the transaction will actually be committed. * A rollback decision can still occur after this method has been called. This callback * is rather meant to perform work that's only relevant if a commit still has a chance * to happen, such as flushing SQL statements to the database. * <p>Note that exceptions will get propagated to the commit caller and cause a * rollback of the transaction. * @param readOnly whether the transaction is defined as read-only transaction * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b> * (note: do not throw TransactionException subclasses here!) * @see #beforeCompletion */ void beforeCommit(boolean readOnly); /** * Invoked before transaction commit/rollback. * Can perform resource cleanup <i>before</i> transaction completion. * <p>This method will be invoked after {@code beforeCommit}, even when * {@code beforeCommit} threw an exception. This callback allows for * closing resources before transaction completion, for any outcome. * @throws RuntimeException in case of errors; will be <b>logged but not propagated</b> * (note: do not throw TransactionException subclasses here!) * @see #beforeCommit * @see #afterCompletion */ void beforeCompletion(); /** * Invoked after transaction commit. Can perform further operations right * <i>after</i> the main transaction has <i>successfully</i> committed. * <p>Can e.g. commit further operations that are supposed to follow on a successful * commit of the main transaction, like confirmation messages or emails. * <p><b>NOTE:</b> The transaction will have been committed already, but the * transactional resources might still be active and accessible. As a consequence, * any data access code triggered at this point will still "participate" in the * original transaction, allowing to perform some cleanup (with no commit following * anymore!), unless it explicitly declares that it needs to run in a separate * transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW} for any * transactional operation that is called from here.</b> * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b> * (note: do not throw TransactionException subclasses here!) */ void afterCommit(); /** * Invoked after transaction commit/rollback. * Can perform resource cleanup <i>after</i> transaction completion. * <p><b>NOTE:</b> The transaction will have been committed or rolled back already, * but the transactional resources might still be active and accessible. As a * consequence, any data access code triggered at this point will still "participate" * in the original transaction, allowing to perform some cleanup (with no commit * following anymore!), unless it explicitly declares that it needs to run in a * separate transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW} * for any transactional operation that is called from here.</b> * @param status completion status according to the {@code STATUS_*} constants * @throws RuntimeException in case of errors; will be <b>logged but not propagated</b> * (note: do not throw TransactionException subclasses here!) * @see #STATUS_COMMITTED * @see #STATUS_ROLLED_BACK * @see #STATUS_UNKNOWN * @see #beforeCompletion */ void afterCompletion(int status); }
TransactionSynchronization declared with default methods Issue: SPR-14432
spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronization.java
TransactionSynchronization declared with default methods
<ide><path>pring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronization.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2017 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * Supposed to unbind resources from TransactionSynchronizationManager if managing any. <ide> * @see TransactionSynchronizationManager#unbindResource <ide> */ <del> void suspend(); <add> default void suspend() { <add> } <ide> <ide> /** <ide> * Resume this synchronization. <ide> * Supposed to rebind resources to TransactionSynchronizationManager if managing any. <ide> * @see TransactionSynchronizationManager#bindResource <ide> */ <del> void resume(); <add> default void resume() { <add> } <ide> <ide> /** <ide> * Flush the underlying session to the datastore, if applicable: <ide> * @see org.springframework.transaction.TransactionStatus#flush() <ide> */ <ide> @Override <del> void flush(); <add> default void flush() { <add> } <ide> <ide> /** <ide> * Invoked before transaction commit (before "beforeCompletion"). <ide> * (note: do not throw TransactionException subclasses here!) <ide> * @see #beforeCompletion <ide> */ <del> void beforeCommit(boolean readOnly); <add> default void beforeCommit(boolean readOnly) { <add> } <ide> <ide> /** <ide> * Invoked before transaction commit/rollback. <ide> * @see #beforeCommit <ide> * @see #afterCompletion <ide> */ <del> void beforeCompletion(); <add> default void beforeCompletion() { <add> } <ide> <ide> /** <ide> * Invoked after transaction commit. Can perform further operations right <ide> * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b> <ide> * (note: do not throw TransactionException subclasses here!) <ide> */ <del> void afterCommit(); <add> default void afterCommit() { <add> } <ide> <ide> /** <ide> * Invoked after transaction commit/rollback. <ide> * @see #STATUS_UNKNOWN <ide> * @see #beforeCompletion <ide> */ <del> void afterCompletion(int status); <add> default void afterCompletion(int status) { <add> } <ide> <ide> }
JavaScript
mit
36f8547a2a088e644fa004f252686141502944b1
0
ahatzz11/toolkit-for-ynab,falkencreative/toolkit-for-ynab,dbaldon/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,falkencreative/toolkit-for-ynab,falkencreative/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,blargity/toolkit-for-ynab,blargity/toolkit-for-ynab,falkencreative/toolkit-for-ynab,dbaldon/toolkit-for-ynab,dbaldon/toolkit-for-ynab,blargity/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,dbaldon/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,blargity/toolkit-for-ynab
import { isTransfer } from 'toolkit/extension/utils/transaction'; const isValidPayee = (payee) => { if (payee === null) { return true; } return payee.internalName !== 'StartingBalancePayee'; }; const isValidDate = (transactionTime, currentTime, historyLookupMonths) => { if (historyLookupMonths !== 0) { return (currentTime - transactionTime) / 3600 / 24 / 1000 / (365 / 12) < historyLookupMonths; } return true; }; export function outflowTransactionsFilter(historyLookupMonths) { const dateNow = Date.now(); return (transaction) => ( !transaction.isTombstone && transaction.transferAccountId === null && transaction.amount < 0 && isValidPayee(transaction.getPayee()) && transaction.getAccount().onBudget && !isTransfer(transaction) && isValidDate(transaction.getDate().getUTCTime(), dateNow, historyLookupMonths) ); } export function generateReport(transactions, totalBudget) { const transactionDates = transactions.map(t => t.getDate().getUTCTime()); const firstTransactionDate = Math.min(...transactionDates); const lastTransactionDate = Math.max(...transactionDates); const totalDays = (lastTransactionDate - firstTransactionDate) / 3600 / 24 / 1000; const totalOutflow = transactions.map(t => -t.amount).reduce((outflow, amount) => outflow + amount, 0); const avgDailyOutflow = totalOutflow / totalDays; const avgDailyTransactions = transactions.length / totalDays; let daysOfBuffering = Math.floor(totalBudget / avgDailyOutflow); if (daysOfBuffering < 10) { daysOfBuffering = (totalBudget / avgDailyOutflow).toFixed(1); } if (totalDays < 15) { return { ableToGenerate: false }; } return { daysOfBuffering, totalOutflow, totalDays, avgDailyOutflow, avgDailyTransactions, ableToGenerate: true }; }
src/extension/features/budget/days-of-buffering/helpers.js
import { isTransfer } from 'toolkit/extension/utils/transaction'; const isValidPayee = (payee) => { if (payee === null) { return true; } return payee.internalName !== 'StartingBalancePayee'; }; const isValidDate = (transactionTime, currentTime, historyLookupMonths) => { if (historyLookupMonths !== 0) { return (currentTime - transactionTime) / 3600 / 24 / 1000 / (365 / 12) < historyLookupMonths; } return true; }; export function outflowTransactionFilter(historyLookupMonths) { const dateNow = Date.now(); return (transaction) => ( !transaction.isTombstone && transaction.transferAccountId === null && transaction.amount < 0 && isValidPayee(transaction.getPayee()) && transaction.getAccount().onBudget && !isTransfer(transaction) && isValidDate(transaction.getDate().getUTCTime(), dateNow, historyLookupMonths) ); } export function generateReport(transactions, totalBudget) { const transactionDates = transactions.map(t => t.getDate().getUTCTime()); const firstTransactionDate = Math.min(...transactionDates); const lastTransactionDate = Math.max(...transactionDates); const totalDays = (lastTransactionDate - firstTransactionDate) / 3600 / 24 / 1000; const totalOutflow = transactions.map(t => -t.amount).reduce((outflow, amount) => outflow + amount, 0); const avgDailyOutflow = totalOutflow / totalDays; const avgDailyTransactions = transactions.length / totalDays; let daysOfBuffering = Math.floor(totalBudget / avgDailyOutflow); if (daysOfBuffering < 10) { daysOfBuffering = (totalBudget / avgDailyOutflow).toFixed(1); } if (totalDays < 15) { return { ableToGenerate: false }; } return { daysOfBuffering, totalOutflow, totalDays, avgDailyOutflow, avgDailyTransactions, ableToGenerate: true }; }
Fix import for days-of-buffering helper function
src/extension/features/budget/days-of-buffering/helpers.js
Fix import for days-of-buffering helper function
<ide><path>rc/extension/features/budget/days-of-buffering/helpers.js <ide> }; <ide> <ide> <del>export function outflowTransactionFilter(historyLookupMonths) { <add>export function outflowTransactionsFilter(historyLookupMonths) { <ide> const dateNow = Date.now(); <ide> <ide> return (transaction) => (
Java
apache-2.0
ddd2fa687bfa976921349e919bbbbb266e988cb7
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * 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.activemq.store.jdbc; /** * @version $Revision: 1.4 $ * * @org.apache.xbean.XBean element="statements" * */ public class Statements { protected String messageTableName = "ACTIVEMQ_MSGS"; protected String durableSubAcksTableName = "ACTIVEMQ_ACKS"; protected String lockTableName = "ACTIVEMQ_LOCK"; protected String binaryDataType = "BLOB"; protected String containerNameDataType = "VARCHAR(250)"; protected String msgIdDataType = "VARCHAR(250)"; protected String sequenceDataType = "INTEGER"; protected String longDataType = "BIGINT"; protected String stringIdDataType = "VARCHAR(250)"; protected boolean useExternalMessageReferences; private String tablePrefix = ""; private String addMessageStatement; private String updateMessageStatement; private String removeMessageStatment; private String findMessageSequenceIdStatement; private String findMessageStatement; private String findAllMessagesStatement; private String findLastSequenceIdInMsgsStatement; private String findLastSequenceIdInAcksStatement; private String createDurableSubStatement; private String findDurableSubStatement; private String findAllDurableSubsStatement; private String updateLastAckOfDurableSubStatement; private String deleteSubscriptionStatement; private String findAllDurableSubMessagesStatement; private String findDurableSubMessagesStatement; private String findAllDestinationsStatement; private String removeAllMessagesStatement; private String removeAllSubscriptionsStatement; private String deleteOldMessagesStatement; private String[] createSchemaStatements; private String[] dropSchemaStatements; private String lockCreateStatement; private String lockUpdateStatement; private String nextDurableSubscriberMessageStatement; private String durableSubscriberMessageCountStatement; private String lastAckedDurableSubscriberMessageStatement; private String destinationMessageCountStatement; private String findNextMessagesStatement; private boolean useLockCreateWhereClause; public String[] getCreateSchemaStatements() { if (createSchemaStatements == null) { createSchemaStatements = new String[] { "CREATE TABLE " + getFullMessageTableName() + "(" + "ID " + sequenceDataType + " NOT NULL" + ", CONTAINER " + containerNameDataType + ", MSGID_PROD " + msgIdDataType + ", MSGID_SEQ " + sequenceDataType + ", EXPIRATION " + longDataType + ", MSG " + (useExternalMessageReferences ? stringIdDataType : binaryDataType) + ", PRIMARY KEY ( ID ) )", "CREATE INDEX " + getFullMessageTableName() + "_MIDX ON " + getFullMessageTableName() + " (MSGID_PROD,MSGID_SEQ)", "CREATE INDEX " + getFullMessageTableName() + "_CIDX ON " + getFullMessageTableName() + " (CONTAINER)", "CREATE INDEX " + getFullMessageTableName() + "_EIDX ON " + getFullMessageTableName() + " (EXPIRATION)", "CREATE TABLE " + getFullAckTableName() + "(" + "CONTAINER " + containerNameDataType + " NOT NULL" + ", SUB_DEST " + stringIdDataType + ", CLIENT_ID " + stringIdDataType + " NOT NULL" + ", SUB_NAME " + stringIdDataType + " NOT NULL" + ", SELECTOR " + stringIdDataType + ", LAST_ACKED_ID " + sequenceDataType + ", PRIMARY KEY ( CONTAINER, CLIENT_ID, SUB_NAME))", "CREATE TABLE " + getFullLockTableName() + "( ID " + longDataType + " NOT NULL, TIME " + longDataType + ", BROKER_NAME " + stringIdDataType + ", PRIMARY KEY (ID) )", "INSERT INTO " + getFullLockTableName() + "(ID) VALUES (1)", }; } return createSchemaStatements; } public String[] getDropSchemaStatements() { if (dropSchemaStatements == null) { dropSchemaStatements = new String[] {"DROP TABLE " + getFullAckTableName() + "", "DROP TABLE " + getFullMessageTableName() + "", "DROP TABLE " + getFullLockTableName() + ""}; } return dropSchemaStatements; } public String getAddMessageStatement() { if (addMessageStatement == null) { addMessageStatement = "INSERT INTO " + getFullMessageTableName() + "(ID, MSGID_PROD, MSGID_SEQ, CONTAINER, EXPIRATION, MSG) VALUES (?, ?, ?, ?, ?, ?)"; } return addMessageStatement; } public String getUpdateMessageStatement() { if (updateMessageStatement == null) { updateMessageStatement = "UPDATE " + getFullMessageTableName() + " SET MSG=? WHERE ID=?"; } return updateMessageStatement; } public String getRemoveMessageStatment() { if (removeMessageStatment == null) { removeMessageStatment = "DELETE FROM " + getFullMessageTableName() + " WHERE ID=?"; } return removeMessageStatment; } public String getFindMessageSequenceIdStatement() { if (findMessageSequenceIdStatement == null) { findMessageSequenceIdStatement = "SELECT ID FROM " + getFullMessageTableName() + " WHERE MSGID_PROD=? AND MSGID_SEQ=?"; } return findMessageSequenceIdStatement; } public String getFindMessageStatement() { if (findMessageStatement == null) { findMessageStatement = "SELECT MSG FROM " + getFullMessageTableName() + " WHERE ID=?"; } return findMessageStatement; } public String getFindAllMessagesStatement() { if (findAllMessagesStatement == null) { findAllMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName() + " WHERE CONTAINER=? ORDER BY ID"; } return findAllMessagesStatement; } public String getFindLastSequenceIdInMsgsStatement() { if (findLastSequenceIdInMsgsStatement == null) { findLastSequenceIdInMsgsStatement = "SELECT MAX(ID) FROM " + getFullMessageTableName(); } return findLastSequenceIdInMsgsStatement; } public String getFindLastSequenceIdInAcksStatement() { if (findLastSequenceIdInAcksStatement == null) { findLastSequenceIdInAcksStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + getFullAckTableName(); } return findLastSequenceIdInAcksStatement; } public String getCreateDurableSubStatement() { if (createDurableSubStatement == null) { createDurableSubStatement = "INSERT INTO " + getFullAckTableName() + "(CONTAINER, CLIENT_ID, SUB_NAME, SELECTOR, LAST_ACKED_ID, SUB_DEST) " + "VALUES (?, ?, ?, ?, ?, ?)"; } return createDurableSubStatement; } public String getFindDurableSubStatement() { if (findDurableSubStatement == null) { findDurableSubStatement = "SELECT SELECTOR, SUB_DEST " + "FROM " + getFullAckTableName() + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return findDurableSubStatement; } public String getFindAllDurableSubsStatement() { if (findAllDurableSubsStatement == null) { findAllDurableSubsStatement = "SELECT SELECTOR, SUB_NAME, CLIENT_ID, SUB_DEST" + " FROM " + getFullAckTableName() + " WHERE CONTAINER=?"; } return findAllDurableSubsStatement; } public String getUpdateLastAckOfDurableSubStatement() { if (updateLastAckOfDurableSubStatement == null) { updateLastAckOfDurableSubStatement = "UPDATE " + getFullAckTableName() + " SET LAST_ACKED_ID=?" + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return updateLastAckOfDurableSubStatement; } public String getDeleteSubscriptionStatement() { if (deleteSubscriptionStatement == null) { deleteSubscriptionStatement = "DELETE FROM " + getFullAckTableName() + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return deleteSubscriptionStatement; } public String getFindAllDurableSubMessagesStatement() { if (findAllDurableSubMessagesStatement == null) { findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + " ORDER BY M.ID"; } return findAllDurableSubMessagesStatement; } public String getFindDurableSubMessagesStatement() { if (findDurableSubMessagesStatement == null) { findDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + " ORDER BY M.ID"; } return findDurableSubMessagesStatement; } public String findAllDurableSubMessagesStatement() { if (findAllDurableSubMessagesStatement == null) { findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + " ORDER BY M.ID"; } return findAllDurableSubMessagesStatement; } public String getNextDurableSubscriberMessageStatement() { if (nextDurableSubscriberMessageStatement == null) { nextDurableSubscriberMessageStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + " ORDER BY M.ID "; } return nextDurableSubscriberMessageStatement; } /** * @return the durableSubscriberMessageCountStatement */ public String getDurableSubscriberMessageCountStatement() { if (durableSubscriberMessageCountStatement == null) { durableSubscriberMessageCountStatement = "SELECT COUNT(*) FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"; } return durableSubscriberMessageCountStatement; } public String getFindAllDestinationsStatement() { if (findAllDestinationsStatement == null) { findAllDestinationsStatement = "SELECT DISTINCT CONTAINER FROM " + getFullMessageTableName(); } return findAllDestinationsStatement; } public String getRemoveAllMessagesStatement() { if (removeAllMessagesStatement == null) { removeAllMessagesStatement = "DELETE FROM " + getFullMessageTableName() + " WHERE CONTAINER=?"; } return removeAllMessagesStatement; } public String getRemoveAllSubscriptionsStatement() { if (removeAllSubscriptionsStatement == null) { removeAllSubscriptionsStatement = "DELETE FROM " + getFullAckTableName() + " WHERE CONTAINER=?"; } return removeAllSubscriptionsStatement; } public String getDeleteOldMessagesStatement() { if (deleteOldMessagesStatement == null) { deleteOldMessagesStatement = "DELETE FROM " + getFullMessageTableName() + " WHERE ( EXPIRATION<>0 AND EXPIRATION<?) OR ID <= " + "( SELECT min(" + getFullAckTableName() + ".LAST_ACKED_ID) " + "FROM " + getFullAckTableName() + " WHERE " + getFullAckTableName() + ".CONTAINER=" + getFullMessageTableName() + ".CONTAINER)"; } return deleteOldMessagesStatement; } public String getLockCreateStatement() { if (lockCreateStatement == null) { lockCreateStatement = "SELECT * FROM " + getFullLockTableName(); if (useLockCreateWhereClause) { lockCreateStatement += " WHERE ID = 1"; } lockCreateStatement += " FOR UPDATE"; } return lockCreateStatement; } public String getLockUpdateStatement() { if (lockUpdateStatement == null) { lockUpdateStatement = "UPDATE " + getFullLockTableName() + " SET TIME = ? WHERE ID = 1"; } return lockUpdateStatement; } /** * @return the destinationMessageCountStatement */ public String getDestinationMessageCountStatement() { if (destinationMessageCountStatement == null) { destinationMessageCountStatement = "SELECT COUNT(*) FROM " + getFullMessageTableName() + " WHERE CONTAINER=?"; } return destinationMessageCountStatement; } /** * @return the findNextMessagesStatement */ public String getFindNextMessagesStatement() { if (findNextMessagesStatement == null) { findNextMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName() + " WHERE CONTAINER=? AND ID > ? ORDER BY ID"; } return findNextMessagesStatement; } /** * @return the lastAckedDurableSubscriberMessageStatement */ public String getLastAckedDurableSubscriberMessageStatement() { if (lastAckedDurableSubscriberMessageStatement == null) { lastAckedDurableSubscriberMessageStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + getFullAckTableName() + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return lastAckedDurableSubscriberMessageStatement; } public String getFullMessageTableName() { return getTablePrefix() + getMessageTableName(); } public String getFullAckTableName() { return getTablePrefix() + getDurableSubAcksTableName(); } public String getFullLockTableName() { return getTablePrefix() + getLockTableName(); } /** * @return Returns the containerNameDataType. */ public String getContainerNameDataType() { return containerNameDataType; } /** * @param containerNameDataType The containerNameDataType to set. */ public void setContainerNameDataType(String containerNameDataType) { this.containerNameDataType = containerNameDataType; } /** * @return Returns the messageDataType. */ public String getBinaryDataType() { return binaryDataType; } /** * @param messageDataType The messageDataType to set. */ public void setBinaryDataType(String messageDataType) { this.binaryDataType = messageDataType; } /** * @return Returns the messageTableName. */ public String getMessageTableName() { return messageTableName; } /** * @param messageTableName The messageTableName to set. */ public void setMessageTableName(String messageTableName) { this.messageTableName = messageTableName; } /** * @return Returns the msgIdDataType. */ public String getMsgIdDataType() { return msgIdDataType; } /** * @param msgIdDataType The msgIdDataType to set. */ public void setMsgIdDataType(String msgIdDataType) { this.msgIdDataType = msgIdDataType; } /** * @return Returns the sequenceDataType. */ public String getSequenceDataType() { return sequenceDataType; } /** * @param sequenceDataType The sequenceDataType to set. */ public void setSequenceDataType(String sequenceDataType) { this.sequenceDataType = sequenceDataType; } /** * @return Returns the tablePrefix. */ public String getTablePrefix() { return tablePrefix; } /** * @param tablePrefix The tablePrefix to set. */ public void setTablePrefix(String tablePrefix) { this.tablePrefix = tablePrefix; } /** * @return Returns the durableSubAcksTableName. */ public String getDurableSubAcksTableName() { return durableSubAcksTableName; } /** * @param durableSubAcksTableName The durableSubAcksTableName to set. */ public void setDurableSubAcksTableName(String durableSubAcksTableName) { this.durableSubAcksTableName = durableSubAcksTableName; } public String getLockTableName() { return lockTableName; } public void setLockTableName(String lockTableName) { this.lockTableName = lockTableName; } public String getLongDataType() { return longDataType; } public void setLongDataType(String longDataType) { this.longDataType = longDataType; } public String getStringIdDataType() { return stringIdDataType; } public void setStringIdDataType(String stringIdDataType) { this.stringIdDataType = stringIdDataType; } public void setUseExternalMessageReferences(boolean useExternalMessageReferences) { this.useExternalMessageReferences = useExternalMessageReferences; } public boolean isUseExternalMessageReferences() { return useExternalMessageReferences; } public void setAddMessageStatement(String addMessageStatment) { this.addMessageStatement = addMessageStatment; } public void setCreateDurableSubStatement(String createDurableSubStatment) { this.createDurableSubStatement = createDurableSubStatment; } public void setCreateSchemaStatements(String[] createSchemaStatments) { this.createSchemaStatements = createSchemaStatments; } public void setDeleteOldMessagesStatement(String deleteOldMessagesStatment) { this.deleteOldMessagesStatement = deleteOldMessagesStatment; } public void setDeleteSubscriptionStatement(String deleteSubscriptionStatment) { this.deleteSubscriptionStatement = deleteSubscriptionStatment; } public void setDropSchemaStatements(String[] dropSchemaStatments) { this.dropSchemaStatements = dropSchemaStatments; } public void setFindAllDestinationsStatement(String findAllDestinationsStatment) { this.findAllDestinationsStatement = findAllDestinationsStatment; } public void setFindAllDurableSubMessagesStatement(String findAllDurableSubMessagesStatment) { this.findAllDurableSubMessagesStatement = findAllDurableSubMessagesStatment; } public void setFindAllDurableSubsStatement(String findAllDurableSubsStatment) { this.findAllDurableSubsStatement = findAllDurableSubsStatment; } public void setFindAllMessagesStatement(String findAllMessagesStatment) { this.findAllMessagesStatement = findAllMessagesStatment; } public void setFindDurableSubStatement(String findDurableSubStatment) { this.findDurableSubStatement = findDurableSubStatment; } public void setFindLastSequenceIdInAcksStatement(String findLastSequenceIdInAcks) { this.findLastSequenceIdInAcksStatement = findLastSequenceIdInAcks; } public void setFindLastSequenceIdInMsgsStatement(String findLastSequenceIdInMsgs) { this.findLastSequenceIdInMsgsStatement = findLastSequenceIdInMsgs; } public void setFindMessageSequenceIdStatement(String findMessageSequenceIdStatment) { this.findMessageSequenceIdStatement = findMessageSequenceIdStatment; } public void setFindMessageStatement(String findMessageStatment) { this.findMessageStatement = findMessageStatment; } public void setRemoveAllMessagesStatement(String removeAllMessagesStatment) { this.removeAllMessagesStatement = removeAllMessagesStatment; } public void setRemoveAllSubscriptionsStatement(String removeAllSubscriptionsStatment) { this.removeAllSubscriptionsStatement = removeAllSubscriptionsStatment; } public void setRemoveMessageStatment(String removeMessageStatment) { this.removeMessageStatment = removeMessageStatment; } public void setUpdateLastAckOfDurableSubStatement(String updateLastAckOfDurableSub) { this.updateLastAckOfDurableSubStatement = updateLastAckOfDurableSub; } public void setUpdateMessageStatement(String updateMessageStatment) { this.updateMessageStatement = updateMessageStatment; } public boolean isUseLockCreateWhereClause() { return useLockCreateWhereClause; } public void setUseLockCreateWhereClause(boolean useLockCreateWhereClause) { this.useLockCreateWhereClause = useLockCreateWhereClause; } public void setLockCreateStatement(String lockCreateStatement) { this.lockCreateStatement = lockCreateStatement; } public void setLockUpdateStatement(String lockUpdateStatement) { this.lockUpdateStatement = lockUpdateStatement; } /** * @param findDurableSubMessagesStatement the * findDurableSubMessagesStatement to set */ public void setFindDurableSubMessagesStatement(String findDurableSubMessagesStatement) { this.findDurableSubMessagesStatement = findDurableSubMessagesStatement; } /** * @param nextDurableSubscriberMessageStatement the nextDurableSubscriberMessageStatement to set */ public void setNextDurableSubscriberMessageStatement(String nextDurableSubscriberMessageStatement) { this.nextDurableSubscriberMessageStatement = nextDurableSubscriberMessageStatement; } /** * @param durableSubscriberMessageCountStatement the durableSubscriberMessageCountStatement to set */ public void setDurableSubscriberMessageCountStatement(String durableSubscriberMessageCountStatement) { this.durableSubscriberMessageCountStatement = durableSubscriberMessageCountStatement; } /** * @param findNextMessagesStatement the findNextMessagesStatement to set */ public void setFindNextMessagesStatement(String findNextMessagesStatement) { this.findNextMessagesStatement = findNextMessagesStatement; } /** * @param destinationMessageCountStatement the destinationMessageCountStatement to set */ public void setDestinationMessageCountStatement(String destinationMessageCountStatement) { this.destinationMessageCountStatement = destinationMessageCountStatement; } /** * @param lastAckedDurableSubscriberMessageStatement the lastAckedDurableSubscriberMessageStatement to set */ public void setLastAckedDurableSubscriberMessageStatement( String lastAckedDurableSubscriberMessageStatement) { this.lastAckedDurableSubscriberMessageStatement = lastAckedDurableSubscriberMessageStatement; } }
activemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java
/** * 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.activemq.store.jdbc; /** * @version $Revision: 1.4 $ * * @org.apache.xbean.XBean element="statements" * */ public class Statements { protected String messageTableName = "ACTIVEMQ_MSGS"; protected String durableSubAcksTableName = "ACTIVEMQ_ACKS"; protected String lockTableName = "ACTIVEMQ_LOCK"; protected String binaryDataType = "BLOB"; protected String containerNameDataType = "VARCHAR(250)"; protected String msgIdDataType = "VARCHAR(250)"; protected String sequenceDataType = "INTEGER"; protected String longDataType = "BIGINT"; protected String stringIdDataType = "VARCHAR(250)"; protected boolean useExternalMessageReferences; private String tablePrefix = ""; private String addMessageStatement; private String updateMessageStatement; private String removeMessageStatment; private String findMessageSequenceIdStatement; private String findMessageStatement; private String findAllMessagesStatement; private String findLastSequenceIdInMsgsStatement; private String findLastSequenceIdInAcksStatement; private String createDurableSubStatement; private String findDurableSubStatement; private String findAllDurableSubsStatement; private String updateLastAckOfDurableSubStatement; private String deleteSubscriptionStatement; private String findAllDurableSubMessagesStatement; private String findDurableSubMessagesStatement; private String findAllDestinationsStatement; private String removeAllMessagesStatement; private String removeAllSubscriptionsStatement; private String deleteOldMessagesStatement; private String[] createSchemaStatements; private String[] dropSchemaStatements; private String lockCreateStatement; private String lockUpdateStatement; private String nextDurableSubscriberMessageStatement; private String durableSubscriberMessageCountStatement; private String lastAckedDurableSubscriberMessageStatement; private String destinationMessageCountStatement; private String findNextMessagesStatement; private boolean useLockCreateWhereClause; public String[] getCreateSchemaStatements() { if (createSchemaStatements == null) { createSchemaStatements = new String[] { "CREATE TABLE " + getFullMessageTableName() + "(" + "ID " + sequenceDataType + " NOT NULL" + ", CONTAINER " + containerNameDataType + ", MSGID_PROD " + msgIdDataType + ", MSGID_SEQ " + sequenceDataType + ", EXPIRATION " + longDataType + ", MSG " + (useExternalMessageReferences ? stringIdDataType : binaryDataType) + ", PRIMARY KEY ( ID ) )", "CREATE INDEX " + getFullMessageTableName() + "_MIDX ON " + getFullMessageTableName() + " (MSGID_PROD,MSGID_SEQ)", "CREATE INDEX " + getFullMessageTableName() + "_CIDX ON " + getFullMessageTableName() + " (CONTAINER)", "CREATE INDEX " + getFullMessageTableName() + "_EIDX ON " + getFullMessageTableName() + " (EXPIRATION)", "CREATE TABLE " + getFullAckTableName() + "(" + "CONTAINER " + containerNameDataType + " NOT NULL" + ", SUB_DEST " + stringIdDataType + ", CLIENT_ID " + stringIdDataType + " NOT NULL" + ", SUB_NAME " + stringIdDataType + " NOT NULL" + ", SELECTOR " + stringIdDataType + ", LAST_ACKED_ID " + sequenceDataType + ", PRIMARY KEY ( CONTAINER, CLIENT_ID, SUB_NAME))", "CREATE TABLE " + getFullLockTableName() + "( ID " + longDataType + " NOT NULL, TIME " + longDataType + ", BROKER_NAME " + stringIdDataType + ", PRIMARY KEY (ID) )", "INSERT INTO " + getFullLockTableName() + "(ID) VALUES (1)", }; } return createSchemaStatements; } public String[] getDropSchemaStatements() { if (dropSchemaStatements == null) { dropSchemaStatements = new String[] {"DROP TABLE " + getFullAckTableName() + "", "DROP TABLE " + getFullMessageTableName() + ""}; } return dropSchemaStatements; } public String getAddMessageStatement() { if (addMessageStatement == null) { addMessageStatement = "INSERT INTO " + getFullMessageTableName() + "(ID, MSGID_PROD, MSGID_SEQ, CONTAINER, EXPIRATION, MSG) VALUES (?, ?, ?, ?, ?, ?)"; } return addMessageStatement; } public String getUpdateMessageStatement() { if (updateMessageStatement == null) { updateMessageStatement = "UPDATE " + getFullMessageTableName() + " SET MSG=? WHERE ID=?"; } return updateMessageStatement; } public String getRemoveMessageStatment() { if (removeMessageStatment == null) { removeMessageStatment = "DELETE FROM " + getFullMessageTableName() + " WHERE ID=?"; } return removeMessageStatment; } public String getFindMessageSequenceIdStatement() { if (findMessageSequenceIdStatement == null) { findMessageSequenceIdStatement = "SELECT ID FROM " + getFullMessageTableName() + " WHERE MSGID_PROD=? AND MSGID_SEQ=?"; } return findMessageSequenceIdStatement; } public String getFindMessageStatement() { if (findMessageStatement == null) { findMessageStatement = "SELECT MSG FROM " + getFullMessageTableName() + " WHERE ID=?"; } return findMessageStatement; } public String getFindAllMessagesStatement() { if (findAllMessagesStatement == null) { findAllMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName() + " WHERE CONTAINER=? ORDER BY ID"; } return findAllMessagesStatement; } public String getFindLastSequenceIdInMsgsStatement() { if (findLastSequenceIdInMsgsStatement == null) { findLastSequenceIdInMsgsStatement = "SELECT MAX(ID) FROM " + getFullMessageTableName(); } return findLastSequenceIdInMsgsStatement; } public String getFindLastSequenceIdInAcksStatement() { if (findLastSequenceIdInAcksStatement == null) { findLastSequenceIdInAcksStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + getFullAckTableName(); } return findLastSequenceIdInAcksStatement; } public String getCreateDurableSubStatement() { if (createDurableSubStatement == null) { createDurableSubStatement = "INSERT INTO " + getFullAckTableName() + "(CONTAINER, CLIENT_ID, SUB_NAME, SELECTOR, LAST_ACKED_ID, SUB_DEST) " + "VALUES (?, ?, ?, ?, ?, ?)"; } return createDurableSubStatement; } public String getFindDurableSubStatement() { if (findDurableSubStatement == null) { findDurableSubStatement = "SELECT SELECTOR, SUB_DEST " + "FROM " + getFullAckTableName() + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return findDurableSubStatement; } public String getFindAllDurableSubsStatement() { if (findAllDurableSubsStatement == null) { findAllDurableSubsStatement = "SELECT SELECTOR, SUB_NAME, CLIENT_ID, SUB_DEST" + " FROM " + getFullAckTableName() + " WHERE CONTAINER=?"; } return findAllDurableSubsStatement; } public String getUpdateLastAckOfDurableSubStatement() { if (updateLastAckOfDurableSubStatement == null) { updateLastAckOfDurableSubStatement = "UPDATE " + getFullAckTableName() + " SET LAST_ACKED_ID=?" + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return updateLastAckOfDurableSubStatement; } public String getDeleteSubscriptionStatement() { if (deleteSubscriptionStatement == null) { deleteSubscriptionStatement = "DELETE FROM " + getFullAckTableName() + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return deleteSubscriptionStatement; } public String getFindAllDurableSubMessagesStatement() { if (findAllDurableSubMessagesStatement == null) { findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + " ORDER BY M.ID"; } return findAllDurableSubMessagesStatement; } public String getFindDurableSubMessagesStatement() { if (findDurableSubMessagesStatement == null) { findDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + " ORDER BY M.ID"; } return findDurableSubMessagesStatement; } public String findAllDurableSubMessagesStatement() { if (findAllDurableSubMessagesStatement == null) { findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + " ORDER BY M.ID"; } return findAllDurableSubMessagesStatement; } public String getNextDurableSubscriberMessageStatement() { if (nextDurableSubscriberMessageStatement == null) { nextDurableSubscriberMessageStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + " ORDER BY M.ID "; } return nextDurableSubscriberMessageStatement; } /** * @return the durableSubscriberMessageCountStatement */ public String getDurableSubscriberMessageCountStatement() { if (durableSubscriberMessageCountStatement == null) { durableSubscriberMessageCountStatement = "SELECT COUNT(*) FROM " + getFullMessageTableName() + " M, " + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"; } return durableSubscriberMessageCountStatement; } public String getFindAllDestinationsStatement() { if (findAllDestinationsStatement == null) { findAllDestinationsStatement = "SELECT DISTINCT CONTAINER FROM " + getFullMessageTableName(); } return findAllDestinationsStatement; } public String getRemoveAllMessagesStatement() { if (removeAllMessagesStatement == null) { removeAllMessagesStatement = "DELETE FROM " + getFullMessageTableName() + " WHERE CONTAINER=?"; } return removeAllMessagesStatement; } public String getRemoveAllSubscriptionsStatement() { if (removeAllSubscriptionsStatement == null) { removeAllSubscriptionsStatement = "DELETE FROM " + getFullAckTableName() + " WHERE CONTAINER=?"; } return removeAllSubscriptionsStatement; } public String getDeleteOldMessagesStatement() { if (deleteOldMessagesStatement == null) { deleteOldMessagesStatement = "DELETE FROM " + getFullMessageTableName() + " WHERE ( EXPIRATION<>0 AND EXPIRATION<?) OR ID <= " + "( SELECT min(" + getFullAckTableName() + ".LAST_ACKED_ID) " + "FROM " + getFullAckTableName() + " WHERE " + getFullAckTableName() + ".CONTAINER=" + getFullMessageTableName() + ".CONTAINER)"; } return deleteOldMessagesStatement; } public String getLockCreateStatement() { if (lockCreateStatement == null) { lockCreateStatement = "SELECT * FROM " + getFullLockTableName(); if (useLockCreateWhereClause) { lockCreateStatement += " WHERE ID = 1"; } lockCreateStatement += " FOR UPDATE"; } return lockCreateStatement; } public String getLockUpdateStatement() { if (lockUpdateStatement == null) { lockUpdateStatement = "UPDATE " + getFullLockTableName() + " SET TIME = ? WHERE ID = 1"; } return lockUpdateStatement; } /** * @return the destinationMessageCountStatement */ public String getDestinationMessageCountStatement() { if (destinationMessageCountStatement == null) { destinationMessageCountStatement = "SELECT COUNT(*) FROM " + getFullMessageTableName() + " WHERE CONTAINER=?"; } return destinationMessageCountStatement; } /** * @return the findNextMessagesStatement */ public String getFindNextMessagesStatement() { if (findNextMessagesStatement == null) { findNextMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName() + " WHERE CONTAINER=? AND ID > ? ORDER BY ID"; } return findNextMessagesStatement; } /** * @return the lastAckedDurableSubscriberMessageStatement */ public String getLastAckedDurableSubscriberMessageStatement() { if (lastAckedDurableSubscriberMessageStatement == null) { lastAckedDurableSubscriberMessageStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + getFullAckTableName() + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return lastAckedDurableSubscriberMessageStatement; } public String getFullMessageTableName() { return getTablePrefix() + getMessageTableName(); } public String getFullAckTableName() { return getTablePrefix() + getDurableSubAcksTableName(); } public String getFullLockTableName() { return getTablePrefix() + getLockTableName(); } /** * @return Returns the containerNameDataType. */ public String getContainerNameDataType() { return containerNameDataType; } /** * @param containerNameDataType The containerNameDataType to set. */ public void setContainerNameDataType(String containerNameDataType) { this.containerNameDataType = containerNameDataType; } /** * @return Returns the messageDataType. */ public String getBinaryDataType() { return binaryDataType; } /** * @param messageDataType The messageDataType to set. */ public void setBinaryDataType(String messageDataType) { this.binaryDataType = messageDataType; } /** * @return Returns the messageTableName. */ public String getMessageTableName() { return messageTableName; } /** * @param messageTableName The messageTableName to set. */ public void setMessageTableName(String messageTableName) { this.messageTableName = messageTableName; } /** * @return Returns the msgIdDataType. */ public String getMsgIdDataType() { return msgIdDataType; } /** * @param msgIdDataType The msgIdDataType to set. */ public void setMsgIdDataType(String msgIdDataType) { this.msgIdDataType = msgIdDataType; } /** * @return Returns the sequenceDataType. */ public String getSequenceDataType() { return sequenceDataType; } /** * @param sequenceDataType The sequenceDataType to set. */ public void setSequenceDataType(String sequenceDataType) { this.sequenceDataType = sequenceDataType; } /** * @return Returns the tablePrefix. */ public String getTablePrefix() { return tablePrefix; } /** * @param tablePrefix The tablePrefix to set. */ public void setTablePrefix(String tablePrefix) { this.tablePrefix = tablePrefix; } /** * @return Returns the durableSubAcksTableName. */ public String getDurableSubAcksTableName() { return durableSubAcksTableName; } /** * @param durableSubAcksTableName The durableSubAcksTableName to set. */ public void setDurableSubAcksTableName(String durableSubAcksTableName) { this.durableSubAcksTableName = durableSubAcksTableName; } public String getLockTableName() { return lockTableName; } public void setLockTableName(String lockTableName) { this.lockTableName = lockTableName; } public String getLongDataType() { return longDataType; } public void setLongDataType(String longDataType) { this.longDataType = longDataType; } public String getStringIdDataType() { return stringIdDataType; } public void setStringIdDataType(String stringIdDataType) { this.stringIdDataType = stringIdDataType; } public void setUseExternalMessageReferences(boolean useExternalMessageReferences) { this.useExternalMessageReferences = useExternalMessageReferences; } public boolean isUseExternalMessageReferences() { return useExternalMessageReferences; } public void setAddMessageStatement(String addMessageStatment) { this.addMessageStatement = addMessageStatment; } public void setCreateDurableSubStatement(String createDurableSubStatment) { this.createDurableSubStatement = createDurableSubStatment; } public void setCreateSchemaStatements(String[] createSchemaStatments) { this.createSchemaStatements = createSchemaStatments; } public void setDeleteOldMessagesStatement(String deleteOldMessagesStatment) { this.deleteOldMessagesStatement = deleteOldMessagesStatment; } public void setDeleteSubscriptionStatement(String deleteSubscriptionStatment) { this.deleteSubscriptionStatement = deleteSubscriptionStatment; } public void setDropSchemaStatements(String[] dropSchemaStatments) { this.dropSchemaStatements = dropSchemaStatments; } public void setFindAllDestinationsStatement(String findAllDestinationsStatment) { this.findAllDestinationsStatement = findAllDestinationsStatment; } public void setFindAllDurableSubMessagesStatement(String findAllDurableSubMessagesStatment) { this.findAllDurableSubMessagesStatement = findAllDurableSubMessagesStatment; } public void setFindAllDurableSubsStatement(String findAllDurableSubsStatment) { this.findAllDurableSubsStatement = findAllDurableSubsStatment; } public void setFindAllMessagesStatement(String findAllMessagesStatment) { this.findAllMessagesStatement = findAllMessagesStatment; } public void setFindDurableSubStatement(String findDurableSubStatment) { this.findDurableSubStatement = findDurableSubStatment; } public void setFindLastSequenceIdInAcksStatement(String findLastSequenceIdInAcks) { this.findLastSequenceIdInAcksStatement = findLastSequenceIdInAcks; } public void setFindLastSequenceIdInMsgsStatement(String findLastSequenceIdInMsgs) { this.findLastSequenceIdInMsgsStatement = findLastSequenceIdInMsgs; } public void setFindMessageSequenceIdStatement(String findMessageSequenceIdStatment) { this.findMessageSequenceIdStatement = findMessageSequenceIdStatment; } public void setFindMessageStatement(String findMessageStatment) { this.findMessageStatement = findMessageStatment; } public void setRemoveAllMessagesStatement(String removeAllMessagesStatment) { this.removeAllMessagesStatement = removeAllMessagesStatment; } public void setRemoveAllSubscriptionsStatement(String removeAllSubscriptionsStatment) { this.removeAllSubscriptionsStatement = removeAllSubscriptionsStatment; } public void setRemoveMessageStatment(String removeMessageStatment) { this.removeMessageStatment = removeMessageStatment; } public void setUpdateLastAckOfDurableSubStatement(String updateLastAckOfDurableSub) { this.updateLastAckOfDurableSubStatement = updateLastAckOfDurableSub; } public void setUpdateMessageStatement(String updateMessageStatment) { this.updateMessageStatement = updateMessageStatment; } public boolean isUseLockCreateWhereClause() { return useLockCreateWhereClause; } public void setUseLockCreateWhereClause(boolean useLockCreateWhereClause) { this.useLockCreateWhereClause = useLockCreateWhereClause; } public void setLockCreateStatement(String lockCreateStatement) { this.lockCreateStatement = lockCreateStatement; } public void setLockUpdateStatement(String lockUpdateStatement) { this.lockUpdateStatement = lockUpdateStatement; } /** * @param findDurableSubMessagesStatement the * findDurableSubMessagesStatement to set */ public void setFindDurableSubMessagesStatement(String findDurableSubMessagesStatement) { this.findDurableSubMessagesStatement = findDurableSubMessagesStatement; } /** * @param nextDurableSubscriberMessageStatement the nextDurableSubscriberMessageStatement to set */ public void setNextDurableSubscriberMessageStatement(String nextDurableSubscriberMessageStatement) { this.nextDurableSubscriberMessageStatement = nextDurableSubscriberMessageStatement; } /** * @param durableSubscriberMessageCountStatement the durableSubscriberMessageCountStatement to set */ public void setDurableSubscriberMessageCountStatement(String durableSubscriberMessageCountStatement) { this.durableSubscriberMessageCountStatement = durableSubscriberMessageCountStatement; } /** * @param findNextMessagesStatement the findNextMessagesStatement to set */ public void setFindNextMessagesStatement(String findNextMessagesStatement) { this.findNextMessagesStatement = findNextMessagesStatement; } /** * @param destinationMessageCountStatement the destinationMessageCountStatement to set */ public void setDestinationMessageCountStatement(String destinationMessageCountStatement) { this.destinationMessageCountStatement = destinationMessageCountStatement; } /** * @param lastAckedDurableSubscriberMessageStatement the lastAckedDurableSubscriberMessageStatement to set */ public void setLastAckedDurableSubscriberMessageStatement( String lastAckedDurableSubscriberMessageStatement) { this.lastAckedDurableSubscriberMessageStatement = lastAckedDurableSubscriberMessageStatement; } }
Fix for https://issues.apache.org/activemq/browse/AMQ-1953 git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@698800 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java
Fix for https://issues.apache.org/activemq/browse/AMQ-1953
<ide><path>ctivemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java <ide> public String[] getDropSchemaStatements() { <ide> if (dropSchemaStatements == null) { <ide> dropSchemaStatements = new String[] {"DROP TABLE " + getFullAckTableName() + "", <del> "DROP TABLE " + getFullMessageTableName() + ""}; <add> "DROP TABLE " + getFullMessageTableName() + "", <add> "DROP TABLE " + getFullLockTableName() + ""}; <ide> } <ide> return dropSchemaStatements; <ide> }
JavaScript
mit
6c17718242cd284519ad32f186f4f55a5df27761
0
DavidAnson/markdownlint,DavidAnson/markdownlint
// @ts-check "use strict"; const { existsSync } = require("fs"); // eslint-disable-next-line unicorn/import-style const { join } = require("path"); const { promisify } = require("util"); const globby = require("globby"); const jsYaml = require("js-yaml"); const stripJsonComments = require("strip-json-comments"); const test = require("ava").default; const markdownlint = require("../lib/markdownlint"); const markdownlintPromise = promisify(markdownlint); const readConfigPromise = promisify(markdownlint.readConfig); /** * Parses JSONC text. * * @param {string} json JSON to parse. * @returns {Object} Object representation. */ function jsoncParse(json) { return JSON.parse(stripJsonComments(json)); } /** * Parses YAML text. * * @param {string} yaml YAML to parse. * @returns {Object} Object representation. */ function yamlParse(yaml) { return jsYaml.load(yaml); } /** * Lints a test repository. * * @param {Object} t Test instance. * @param {string[]} globPatterns Array of files to in/exclude. * @param {string} configPath Path to config file. * @returns {Promise} Test result. */ function lintTestRepo(t, globPatterns, configPath) { t.plan(1); return Promise.all([ globby(globPatterns), // @ts-ignore readConfigPromise(configPath, [ jsoncParse, yamlParse ]) ]).then((globbyAndReadConfigResults) => { const [ files, config ] = globbyAndReadConfigResults; const options = { files, config }; // eslint-disable-next-line no-console console.log(`${t.title}: Linting ${files.length} files...`); return markdownlintPromise(options).then((results) => { const resultsString = results.toString(); if (resultsString.length > 0) { // eslint-disable-next-line no-console console.log(resultsString); } t.is(resultsString.length, 0, "Unexpected linting violations"); }); }); } /** * Excludes a list of globs. * * @param {string} rootDir Root directory for globs. * @param {...string} globs Globs to exclude. * @returns {string[]} Array of excluded globs. */ function excludeGlobs(rootDir, ...globs) { return globs.map((glob) => "!" + join(rootDir, glob)); } // Run markdownlint the same way the corresponding repositories do test("https://github.com/eslint/eslint", (t) => { const rootDir = "./test-repos/eslint-eslint"; const globPatterns = [ join(rootDir, "docs/**/*.md"), ...excludeGlobs(rootDir, "docs/rules/array-callback-return.md") ]; const configPath = join(rootDir, ".markdownlint.yml"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/mkdocs/mkdocs", (t) => { const rootDir = "./test-repos/mkdocs-mkdocs"; const globPatterns = [ join(rootDir, "README.md"), join(rootDir, "CONTRIBUTING.md"), join(rootDir, "docs/**/*.md"), ...excludeGlobs(rootDir, "docs/CNAME") ]; const configPath = join(rootDir, ".markdownlintrc"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/mochajs/mocha", (t) => { const rootDir = "./test-repos/mochajs-mocha"; const globPatterns = [ join(rootDir, "*.md"), join(rootDir, "docs/**/*.md"), join(rootDir, ".github/*.md"), join(rootDir, "lib/**/*.md"), join(rootDir, "test/**/*.md"), join(rootDir, "example/**/*.md") ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/pi-hole/docs", (t) => { const rootDir = "./test-repos/pi-hole-docs"; const globPatterns = [ join(rootDir, "**/*.md"), ...excludeGlobs(rootDir, "docs/guides/dns/unbound.md", "docs/index.md", "docs/main/prerequisites.md" ) ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/webhintio/hint", (t) => { const rootDir = "./test-repos/webhintio-hint"; const globPatterns = [ join(rootDir, "**/*.md"), ...excludeGlobs(rootDir, "**/CHANGELOG.md") ]; const configPath = join(rootDir, ".markdownlintrc"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/webpack/webpack.js.org", (t) => { const rootDir = "./test-repos/webpack-webpack-js-org"; const globPatterns = [ join(rootDir, "**/*.md") ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); // Optional repositories (very large) const dotnetDocsDir = "./test-repos/dotnet-docs"; if (existsSync(dotnetDocsDir)) { test("https://github.com/dotnet/docs", (t) => { const rootDir = dotnetDocsDir; const globPatterns = [ join(rootDir, "**/*.md"), ...excludeGlobs(rootDir, "samples/**/*.md", /* eslint-disable max-len */ "docs/architecture/cloud-native/candidate-apps.md", "docs/architecture/containerized-lifecycle/docker-devops-workflow/docker-application-outer-loop-devops-workflow.md", "docs/architecture/dapr-for-net-developers/getting-started.md", "docs/architecture/grpc-for-wcf-developers/channel-credentials.md", "docs/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests.md", "docs/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot.md", "docs/architecture/modern-web-apps-azure/architectural-principles.md", "docs/architecture/modern-web-apps-azure/azure-hosting-recommendations-for-asp-net-web-apps.md", "docs/architecture/modern-web-apps-azure/common-client-side-web-technologies.md", "docs/architecture/modern-web-apps-azure/develop-asp-net-core-mvc-apps.md", "docs/architecture/modern-web-apps-azure/development-process-for-azure.md", "docs/architecture/modern-web-apps-azure/index.md", "docs/core/additional-tools/dotnet-svcutil-guide.md", "docs/core/dependency-loading/collect-details.md", "docs/core/deploying/single-file.md", "docs/core/deploying/trimming/trimming-options.md", "docs/core/extensions/cloud-service.md", "docs/core/extensions/configuration-providers.md", "docs/core/extensions/console-log-formatter.md", "docs/core/extensions/create-resource-files.md", "docs/core/extensions/localization.md", "docs/core/extensions/windows-service.md", "docs/core/install/linux-alpine.md", "docs/core/install/windows.md", "docs/core/porting/third-party-deps.md", "docs/core/project-sdk/msbuild-props-desktop.md", "docs/core/testing/unit-testing-code-coverage.md", "docs/core/tools/troubleshoot-usage-issues.md", "docs/core/tutorials/cli-templates-create-item-template.md", "docs/core/tutorials/cli-templates-create-project-template.md", "docs/core/tutorials/cli-templates-create-template-pack.md", "docs/core/tutorials/cli-templates-create-template-package.md", "docs/core/tutorials/cli-templates-create-item-template.md", "docs/core/tutorials/cli-templates-create-project-template.md", "docs/core/tutorials/cli-templates-create-template-pack.md", "docs/core/whats-new/dotnet-core-3-0.md", "docs/csharp/language-reference/compiler-options/code-generation.md", "docs/csharp/linq/query-expression-basics.md", "docs/csharp/programming-guide/classes-and-structs/named-and-optional-arguments.md", "docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md", "docs/csharp/tutorials/attributes.md", "docs/csharp/whats-new/csharp-version-history.md", "docs/framework/data/adonet/dataset-datatable-dataview/security-guidance.md", "docs/fsharp/language-reference/compiler-directives.md", "docs/fsharp/language-reference/exception-handling/the-try-with-expression.md", "docs/fsharp/language-reference/xml-documentation.md", "docs/fsharp/style-guide/conventions.md", "docs/fsharp/tutorials/async.md", "docs/fsharp/tutorials/asynchronous-and-concurrent-programming/async.md", "docs/fundamentals/code-analysis/configuration-files.md", "docs/fundamentals/code-analysis/style-rules/naming-rules.md", "docs/machine-learning/tutorials/health-violation-classification-model-builder.md", "docs/machine-learning/tutorials/object-detection-model-builder.md", "docs/machine-learning/tutorials/object-detection-onnx.md", "docs/machine-learning/tutorials/text-classification-tf.md", "docs/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview.md", "docs/standard/asynchronous-programming-patterns/implementing-the-event-based-asynchronous-pattern.md", "docs/standard/base-types/string-comparison-net-5-plus.md", "docs/standard/delegates-lambdas.md", "docs/standard/io/isolated-storage.md", "docs/standard/native-interop/tutorial-comwrappers.md", "docs/standard/serialization/xml-schema-definition-tool-xsd-exe.md", "docs/standard/serialization/xml-serializer-generator-tool-sgen-exe.md", "docs/standard/native-interop/best-practices.md", "docs/standard/serialization/binaryformatter-security-guide.md", "docs/framework/windows-workflow-foundation/authoring-workflows-activities-and-expressions-using-imperative-code.md", "docs/spark/how-to-guides/deploy-worker-udf-binaries.md" /* eslint-enable max-len */ ) ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); } const v8v8DevDir = "./test-repos/v8-v8-dev"; if (existsSync(v8v8DevDir)) { test("https://github.com/v8/v8.dev", (t) => { const rootDir = v8v8DevDir; const globPatterns = [ join(rootDir, "src/**/*.md"), ...excludeGlobs(rootDir, "src/blog/array-sort.md", "src/blog/code-caching-for-devs.md", "src/blog/fast-async.md", "src/blog/liftoff.md", "src/blog/pointer-compression.md", "src/blog/react-cliff.md", "src/blog/slack-tracking.md", "src/blog/v8-release-74.md", "src/features/bigint.md", "src/features/dynamic-import.md", "src/features/globalthis.md", "src/features/modules.md" ) ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); }
test/markdownlint-test-repos.js
// @ts-check "use strict"; const { existsSync } = require("fs"); // eslint-disable-next-line unicorn/import-style const { join } = require("path"); const { promisify } = require("util"); const globby = require("globby"); const jsYaml = require("js-yaml"); const stripJsonComments = require("strip-json-comments"); const test = require("ava").default; const markdownlint = require("../lib/markdownlint"); const markdownlintPromise = promisify(markdownlint); const readConfigPromise = promisify(markdownlint.readConfig); /** * Parses JSONC text. * * @param {string} json JSON to parse. * @returns {Object} Object representation. */ function jsoncParse(json) { return JSON.parse(stripJsonComments(json)); } /** * Parses YAML text. * * @param {string} yaml YAML to parse. * @returns {Object} Object representation. */ function yamlParse(yaml) { return jsYaml.load(yaml); } /** * Lints a test repository. * * @param {Object} t Test instance. * @param {string[]} globPatterns Array of files to in/exclude. * @param {string} configPath Path to config file. * @returns {Promise} Test result. */ function lintTestRepo(t, globPatterns, configPath) { t.plan(1); return Promise.all([ globby(globPatterns), // @ts-ignore readConfigPromise(configPath, [ jsoncParse, yamlParse ]) ]).then((globbyAndReadConfigResults) => { const [ files, config ] = globbyAndReadConfigResults; const options = { files, config }; // eslint-disable-next-line no-console console.log(`${t.title}: Linting ${files.length} files...`); return markdownlintPromise(options).then((results) => { const resultsString = results.toString(); if (resultsString.length > 0) { // eslint-disable-next-line no-console console.log(resultsString); } t.is(resultsString.length, 0, "Unexpected linting violations"); }); }); } /** * Excludes a list of globs. * * @param {string} rootDir Root directory for globs. * @param {...string} globs Globs to exclude. * @returns {string[]} Array of excluded globs. */ function excludeGlobs(rootDir, ...globs) { return globs.map((glob) => "!" + join(rootDir, glob)); } // Run markdownlint the same way the corresponding repositories do test("https://github.com/eslint/eslint", (t) => { const rootDir = "./test-repos/eslint-eslint"; const globPatterns = [ join(rootDir, "docs/**/*.md"), ...excludeGlobs(rootDir, "docs/rules/array-callback-return.md") ]; const configPath = join(rootDir, ".markdownlint.yml"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/mkdocs/mkdocs", (t) => { const rootDir = "./test-repos/mkdocs-mkdocs"; const globPatterns = [ join(rootDir, "README.md"), join(rootDir, "CONTRIBUTING.md"), join(rootDir, "docs/**/*.md"), ...excludeGlobs(rootDir, "docs/CNAME") ]; const configPath = join(rootDir, ".markdownlintrc"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/mochajs/mocha", (t) => { const rootDir = "./test-repos/mochajs-mocha"; const globPatterns = [ join(rootDir, "*.md"), join(rootDir, "docs/**/*.md"), join(rootDir, ".github/*.md"), join(rootDir, "lib/**/*.md"), join(rootDir, "test/**/*.md"), join(rootDir, "example/**/*.md") ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/pi-hole/docs", (t) => { const rootDir = "./test-repos/pi-hole-docs"; const globPatterns = [ join(rootDir, "**/*.md"), ...excludeGlobs(rootDir, "docs/guides/dns/unbound.md", "docs/index.md", "docs/main/prerequisites.md" ) ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/webhintio/hint", (t) => { const rootDir = "./test-repos/webhintio-hint"; const globPatterns = [ join(rootDir, "**/*.md"), ...excludeGlobs(rootDir, "**/CHANGELOG.md") ]; const configPath = join(rootDir, ".markdownlintrc"); return lintTestRepo(t, globPatterns, configPath); }); test("https://github.com/webpack/webpack.js.org", (t) => { const rootDir = "./test-repos/webpack-webpack-js-org"; const globPatterns = [ join(rootDir, "**/*.md") ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); // Optional repositories (very large) const dotnetDocsDir = "./test-repos/dotnet-docs"; if (existsSync(dotnetDocsDir)) { test("https://github.com/dotnet/docs", (t) => { const rootDir = dotnetDocsDir; const globPatterns = [ join(rootDir, "**/*.md"), ...excludeGlobs(rootDir, "samples/**/*.md", /* eslint-disable max-len */ "docs/architecture/cloud-native/candidate-apps.md", "docs/architecture/containerized-lifecycle/docker-devops-workflow/docker-application-outer-loop-devops-workflow.md", "docs/architecture/dapr-for-net-developers/getting-started.md", "docs/architecture/grpc-for-wcf-developers/channel-credentials.md", "docs/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests.md", "docs/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot.md", "docs/architecture/modern-web-apps-azure/architectural-principles.md", "docs/architecture/modern-web-apps-azure/azure-hosting-recommendations-for-asp-net-web-apps.md", "docs/architecture/modern-web-apps-azure/common-client-side-web-technologies.md", "docs/architecture/modern-web-apps-azure/develop-asp-net-core-mvc-apps.md", "docs/architecture/modern-web-apps-azure/development-process-for-azure.md", "docs/architecture/modern-web-apps-azure/index.md", "docs/core/additional-tools/dotnet-svcutil-guide.md", "docs/core/dependency-loading/collect-details.md", "docs/core/deploying/single-file.md", "docs/core/deploying/trimming/trimming-options.md", "docs/core/extensions/cloud-service.md", "docs/core/extensions/console-log-formatter.md", "docs/core/extensions/create-resource-files.md", "docs/core/extensions/localization.md", "docs/core/extensions/windows-service.md", "docs/core/install/linux-alpine.md", "docs/core/install/windows.md", "docs/core/porting/third-party-deps.md", "docs/core/project-sdk/msbuild-props-desktop.md", "docs/core/testing/unit-testing-code-coverage.md", "docs/core/tools/troubleshoot-usage-issues.md", "docs/core/tutorials/cli-templates-create-item-template.md", "docs/core/tutorials/cli-templates-create-project-template.md", "docs/core/tutorials/cli-templates-create-template-pack.md", "docs/core/tutorials/cli-templates-create-template-package.md", "docs/core/tutorials/cli-templates-create-item-template.md", "docs/core/tutorials/cli-templates-create-project-template.md", "docs/core/tutorials/cli-templates-create-template-pack.md", "docs/core/whats-new/dotnet-core-3-0.md", "docs/csharp/language-reference/compiler-options/code-generation.md", "docs/csharp/linq/query-expression-basics.md", "docs/csharp/programming-guide/classes-and-structs/named-and-optional-arguments.md", "docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md", "docs/csharp/tutorials/attributes.md", "docs/csharp/whats-new/csharp-version-history.md", "docs/framework/data/adonet/dataset-datatable-dataview/security-guidance.md", "docs/fsharp/language-reference/compiler-directives.md", "docs/fsharp/language-reference/exception-handling/the-try-with-expression.md", "docs/fsharp/language-reference/xml-documentation.md", "docs/fsharp/style-guide/conventions.md", "docs/fsharp/tutorials/async.md", "docs/fsharp/tutorials/asynchronous-and-concurrent-programming/async.md", "docs/fundamentals/code-analysis/configuration-files.md", "docs/fundamentals/code-analysis/style-rules/naming-rules.md", "docs/machine-learning/tutorials/health-violation-classification-model-builder.md", "docs/machine-learning/tutorials/object-detection-model-builder.md", "docs/machine-learning/tutorials/object-detection-onnx.md", "docs/machine-learning/tutorials/text-classification-tf.md", "docs/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview.md", "docs/standard/asynchronous-programming-patterns/implementing-the-event-based-asynchronous-pattern.md", "docs/standard/base-types/string-comparison-net-5-plus.md", "docs/standard/delegates-lambdas.md", "docs/standard/io/isolated-storage.md", "docs/standard/native-interop/tutorial-comwrappers.md", "docs/standard/serialization/xml-schema-definition-tool-xsd-exe.md", "docs/standard/serialization/xml-serializer-generator-tool-sgen-exe.md", "docs/standard/native-interop/best-practices.md", "docs/standard/serialization/binaryformatter-security-guide.md", "docs/framework/windows-workflow-foundation/authoring-workflows-activities-and-expressions-using-imperative-code.md", "docs/spark/how-to-guides/deploy-worker-udf-binaries.md" /* eslint-enable max-len */ ) ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); } const v8v8DevDir = "./test-repos/v8-v8-dev"; if (existsSync(v8v8DevDir)) { test("https://github.com/v8/v8.dev", (t) => { const rootDir = v8v8DevDir; const globPatterns = [ join(rootDir, "src/**/*.md"), ...excludeGlobs(rootDir, "src/blog/array-sort.md", "src/blog/code-caching-for-devs.md", "src/blog/fast-async.md", "src/blog/liftoff.md", "src/blog/pointer-compression.md", "src/blog/react-cliff.md", "src/blog/slack-tracking.md", "src/blog/v8-release-74.md", "src/features/bigint.md", "src/features/dynamic-import.md", "src/features/globalthis.md", "src/features/modules.md" ) ]; const configPath = join(rootDir, ".markdownlint.json"); return lintTestRepo(t, globPatterns, configPath); }); }
Add new test repo suppression for pre-release rule MD049.
test/markdownlint-test-repos.js
Add new test repo suppression for pre-release rule MD049.
<ide><path>est/markdownlint-test-repos.js <ide> "docs/core/deploying/single-file.md", <ide> "docs/core/deploying/trimming/trimming-options.md", <ide> "docs/core/extensions/cloud-service.md", <add> "docs/core/extensions/configuration-providers.md", <ide> "docs/core/extensions/console-log-formatter.md", <ide> "docs/core/extensions/create-resource-files.md", <ide> "docs/core/extensions/localization.md",
Java
lgpl-2.1
3e6a6ff36e5ef5f8717b8187405214f167f78308
0
rnveach/checkstyle,romani/checkstyle,rnveach/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,romani/checkstyle,romani/checkstyle,rnveach/checkstyle,rnveach/checkstyle,rnveach/checkstyle,romani/checkstyle,rnveach/checkstyle,checkstyle/checkstyle,romani/checkstyle,checkstyle/checkstyle,romani/checkstyle,checkstyle/checkstyle
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2019 the original author or authors. // // 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 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import java.util.Objects; import com.puppycrawl.tools.checkstyle.StatelessCheck; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * <p> * Check that the {@code default} is after all the cases in a {@code switch} statement. * </p> * <p> * Rationale: Java allows {@code default} anywhere within the * {@code switch} statement. But it is more readable if it comes after the last {@code case}. * </p> * <ul> * <li> * Property {@code skipIfLastAndSharedWithCase} - Control whether to allow {@code default} * along with {@code case} if they are not last. * Default value is {@code false}. * </li> * </ul> * <p> * To configure the check: * </p> * <pre> * &lt;module name=&quot;DefaultComesLast&quot;/&gt; * </pre> * <p> * To configure the check for skipIfLastAndSharedWithCase: * </p> * <pre> * &lt;module name=&quot;DefaultComesLast&quot;&gt; * &lt;property name=&quot;skipIfLastAndSharedWithCase&quot; value=&quot;true&quot;/&gt; * &lt;/module&gt; * </pre> * <p> * Example when skipIfLastAndSharedWithCase is set to true. * </p> * <pre> * switch (i) { * case 1: * break; * case 2: * default: // No violation with the new option is expected * break; * case 3: * break; * } * switch (i) { * case 1: * break; * default: // violation with the new option is expected * case 2: * break; * } * </pre> * * @since 3.4 */ @StatelessCheck public class DefaultComesLastCheck extends AbstractCheck { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "default.comes.last"; /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE = "default.comes.last.in.casegroup"; /** Control whether to allow {@code default} along with {@code case} if they are not last. */ private boolean skipIfLastAndSharedWithCase; @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.LITERAL_DEFAULT, }; } /** * Setter to control whether to allow {@code default} along with * {@code case} if they are not last. * @param newValue whether to ignore checking. */ public void setSkipIfLastAndSharedWithCase(boolean newValue) { skipIfLastAndSharedWithCase = newValue; } @Override public void visitToken(DetailAST ast) { final DetailAST defaultGroupAST = ast.getParent(); if (skipIfLastAndSharedWithCase) { if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) { log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE); } else if (ast.getPreviousSibling() == null && Objects.nonNull(findNextSibling(defaultGroupAST, TokenTypes.CASE_GROUP))) { log(ast, MSG_KEY); } } else if (Objects.nonNull(findNextSibling(defaultGroupAST, TokenTypes.CASE_GROUP))) { log(ast, MSG_KEY); } } /** * Return token type only if passed tokenType in argument is found or returns -1. * * @param ast root node. * @param tokenType tokentype to be processed. * @return token if desired token is found or else null. */ private static DetailAST findNextSibling(DetailAST ast, int tokenType) { DetailAST token = null; DetailAST node = ast.getNextSibling(); while (node != null) { if (node.getType() == tokenType) { token = node; break; } node = node.getNextSibling(); } return token; } }
src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.java
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2019 the original author or authors. // // 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 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import java.util.Objects; import com.puppycrawl.tools.checkstyle.StatelessCheck; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * <p> * Check that the {@code default} is after all the cases in a {@code switch} statement. * </p> * <p> * Rationale: Java allows {@code default} anywhere within the * {@code switch} statement. But it is more readable if it comes after the last {@code case}. * </p> * <ul> * <li> * Property {@code skipIfLastAndSharedWithCase} - Control whether to allow {@code default} * along with {@code case} if they are not last. * Default value is {@code false}. * </li> * </ul> * <p> * To configure the check: * </p> * <pre> * &lt;module name=&quot;DefaultComesLast&quot;/&gt; * </pre> * <p> * To configure the check for skipIfLastAndSharedWithCase: * </p> * <pre> * &lt;module name=&quot;DefaultComesLast&quot;&gt; * &lt;property name=&quot;skipIfLastAndSharedWithCase&quot; value=&quot;true&quot;/&gt; * &lt;/module&gt; * </pre> * <p> * Example when skipIfLastAndSharedWithCase is set to true. * </p> * <pre> * switch (i) { * case 1: * break; * case 2: * default: // No violation with the new option is expected * break; * case 3: * break; * } * switch (i) { * case 1: * break; * default: // violation with the new option is expected * case 2: * break; * } * </pre> * * @since 3.4 */ @StatelessCheck public class DefaultComesLastCheck extends AbstractCheck { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "default.comes.last"; /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE = "default.comes.last.in.casegroup"; /** Control whether to allow {@code default} along with {@code case} if they are not last. */ private boolean skipIfLastAndSharedWithCase; @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.LITERAL_DEFAULT, }; } /** * Setter to control whether to allow {@code default} along with * {@code case} if they are not last. * @param newValue whether to ignore checking. */ public void setSkipIfLastAndSharedWithCase(boolean newValue) { skipIfLastAndSharedWithCase = newValue; } @Override public void visitToken(DetailAST ast) { final DetailAST defaultGroupAST = ast.getParent(); //default keywords used in annotations too - not what we're //interested in if (defaultGroupAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF && defaultGroupAST.getType() != TokenTypes.MODIFIERS) { if (skipIfLastAndSharedWithCase) { if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) { log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE); } else if (ast.getPreviousSibling() == null && Objects.nonNull(findNextSibling(defaultGroupAST, TokenTypes.CASE_GROUP))) { log(ast, MSG_KEY); } } else if (Objects.nonNull(findNextSibling(defaultGroupAST, TokenTypes.CASE_GROUP))) { log(ast, MSG_KEY); } } } /** * Return token type only if passed tokenType in argument is found or returns -1. * * @param ast root node. * @param tokenType tokentype to be processed. * @return token if desired token is found or else null. */ private static DetailAST findNextSibling(DetailAST ast, int tokenType) { DetailAST token = null; DetailAST node = ast.getNextSibling(); while (node != null) { if (node.getType() == tokenType) { token = node; break; } node = node.getNextSibling(); } return token; } }
Issue #6320: resolve remove conditional for DefaultComesLastCheck
src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.java
Issue #6320: resolve remove conditional for DefaultComesLastCheck
<ide><path>rc/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.java <ide> @Override <ide> public void visitToken(DetailAST ast) { <ide> final DetailAST defaultGroupAST = ast.getParent(); <del> //default keywords used in annotations too - not what we're <del> //interested in <del> if (defaultGroupAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF <del> && defaultGroupAST.getType() != TokenTypes.MODIFIERS) { <del> if (skipIfLastAndSharedWithCase) { <del> if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) { <del> log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE); <del> } <del> else if (ast.getPreviousSibling() == null <del> && Objects.nonNull(findNextSibling(defaultGroupAST, <del> TokenTypes.CASE_GROUP))) { <del> log(ast, MSG_KEY); <del> } <add> if (skipIfLastAndSharedWithCase) { <add> if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) { <add> log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE); <ide> } <del> else if (Objects.nonNull(findNextSibling(defaultGroupAST, <del> TokenTypes.CASE_GROUP))) { <add> else if (ast.getPreviousSibling() == null <add> && Objects.nonNull(findNextSibling(defaultGroupAST, <add> TokenTypes.CASE_GROUP))) { <ide> log(ast, MSG_KEY); <ide> } <add> } <add> else if (Objects.nonNull(findNextSibling(defaultGroupAST, <add> TokenTypes.CASE_GROUP))) { <add> log(ast, MSG_KEY); <ide> } <ide> } <ide>
Java
apache-2.0
5a8ccc55ad906fde6c4ca21b0b38a8305dff28e6
0
rboese/prog,rboese/prog
package collections; import java.util.LinkedList; import java.util.Queue; class SchlangeTest { public static void main(String args[]) { if (args.length == 0) throw new IllegalArgumentException("Ein Argument ist notwendig."); Queue<Object> q = new LinkedList<>(); for (int i = 0; i < args[0].length(); i++) q.add(new Character(args[0].charAt(i))); System.out.println(); System.out.println(q); while (!q.isEmpty()) { Character c = (Character) q.remove(); System.out.print(c.charValue()); } System.out.println(); } }
collections/src/main/java/collections/SchlangeTest.java
package collections; class SchlangeTest { public static void main(String args[]) { if (args.length == 0) throw new IllegalArgumentException("Ein Argument ist notwendig."); SchlangeMitListe q = new SchlangeMitListe(); for (int i = 0; i < args[0].length(); i++) q.anfuege(new Character(args[0].charAt(i))); System.out.println(); q.durchlaufe(); while (!q.istLeer()) { Character c = (Character) q.abarbeite(); System.out.print(c.charValue()); } System.out.println(); } }
solution exercise 6
collections/src/main/java/collections/SchlangeTest.java
solution exercise 6
<ide><path>ollections/src/main/java/collections/SchlangeTest.java <ide> package collections; <add> <add>import java.util.LinkedList; <add>import java.util.Queue; <ide> <ide> class SchlangeTest { <ide> public static void main(String args[]) { <ide> if (args.length == 0) <ide> throw new IllegalArgumentException("Ein Argument ist notwendig."); <ide> <del> SchlangeMitListe q = new SchlangeMitListe(); <add> Queue<Object> q = new LinkedList<>(); <ide> <ide> for (int i = 0; i < args[0].length(); i++) <del> q.anfuege(new Character(args[0].charAt(i))); <add> q.add(new Character(args[0].charAt(i))); <ide> <ide> System.out.println(); <del> q.durchlaufe(); <add> System.out.println(q); <ide> <del> while (!q.istLeer()) { <del> Character c = (Character) q.abarbeite(); <add> while (!q.isEmpty()) { <add> Character c = (Character) q.remove(); <ide> System.out.print(c.charValue()); <ide> } <ide>
JavaScript
mit
d0eb36c6cf1b7c071140bf507c580ecd98ae7f97
0
hafeez-syed/coffeeify,jsdf/coffee-reactify,jnordberg/coffeeify,jsdf/coffee-reactify
var coffee = require('coffee-script'); var through = require('through'); var convert = require('convert-source-map'); function isCoffee (file) { return (/\.((lit)?coffee|coffee\.md)$/).test(file); } function isLiterate (file) { return (/\.(litcoffee|coffee\.md)$/).test(file); } function ParseError(error, src, file) { /* Creates a ParseError from a CoffeeScript SyntaxError modeled after substack's syntax-error module */ SyntaxError.call(this); this.message = error.message; this.line = error.location.first_line + 1; // cs linenums are 0-indexed this.column = error.location.first_column + 1; // same with columns var markerLen = 2; if(error.location.first_line === error.location.last_line) { markerLen += error.location.last_column - error.location.first_column; } this.annotated = [ file + ':' + this.line, src.split('\n')[this.line - 1], Array(this.column).join(' ') + Array(markerLen).join('^'), 'ParseError: ' + this.message ].join('\n'); } ParseError.prototype = Object.create(SyntaxError.prototype); ParseError.prototype.toString = function () { return this.annotated; }; ParseError.prototype.inspect = function () { return this.annotated; }; function compile(file, data, callback) { var compiled; try { compiled = coffee.compile(data, { sourceMap: true, generatedFile: file, inline: true, bare: true, literate: isLiterate(file) }); } catch (e) { var error = e; if (e.location) { error = new ParseError(e, data, file); } callback(error); return; } var map = convert.fromJSON(compiled.v3SourceMap); map.setProperty('sources', [file]); callback(null, compiled.js + '\n' + map.toComment() + '\n'); } function coffeeify(file) { if (!isCoffee(file)) return through(); var data = '', stream = through(write, end); return stream; function write(buf) { data += buf; } function end() { compile(file, data, function(error, result) { if (error) stream.emit('error', error); stream.queue(result); stream.queue(null); }); } } coffeeify.compile = compile; coffeeify.isCoffee = isCoffee; coffeeify.isLiterate = isLiterate; module.exports = coffeeify;
index.js
var coffee = require('coffee-script'); var through = require('through'); var convert = require('convert-source-map'); function isCoffee (file) { return (/\.((lit)?coffee|coffee\.md)$/).test(file); } function isLiterate (file) { return (/\.(litcoffee|coffee\.md)$/).test(file); } function ParseError(error, src, file) { /* Creates a ParseError from a CoffeeScript SyntaxError modeled after substack's syntax-error module */ SyntaxError.call(this); this.message = error.message; this.line = error.location.first_line + 1; // cs linenums are 0-indexed this.column = error.location.first_column + 1; // same with columns var markerLen = 2; if(error.location.first_line === error.location.last_line) { markerLen += error.location.last_column - error.location.first_column; } this.annotated = [ file + ':' + this.line, src.split('\n')[this.line - 1], Array(this.column).join(' ') + Array(markerLen).join('^'), 'ParseError: ' + this.message ].join('\n'); } ParseError.prototype = Object.create(SyntaxError.prototype); ParseError.prototype.toString = function () { return this.annotated; }; ParseError.prototype.inspect = function () { return this.annotated; }; function compile(file, data, callback) { var compiled; try { compiled = coffee.compile(data, { sourceMap: true, generatedFile: file, inline: true, bare: true, literate: isLiterate(file) }); } catch (e) { var error = e; if (e.location) { error = new ParseError(e, data, file); } callback(error); return; } var map = convert.fromJSON(compiled.v3SourceMap); map.setProperty('sources', [file]); callback(null, compiled.js + '\n' + map.toComment()); } function coffeeify(file) { if (!isCoffee(file)) return through(); var data = '', stream = through(write, end); return stream; function write(buf) { data += buf; } function end() { compile(file, data, function(error, result) { if (error) stream.emit('error', error); stream.queue(result); stream.queue(null); }); } } coffeeify.compile = compile; coffeeify.isCoffee = isCoffee; coffeeify.isLiterate = isLiterate; module.exports = coffeeify;
work around substack/insert-module-globals#29 Coffeeify and Browserify don't play nice right now due to substack/insert-module-globals#29 There seems to be no downside to adding a newline after the sourcemap comment to work around it.
index.js
work around substack/insert-module-globals#29
<ide><path>ndex.js <ide> var map = convert.fromJSON(compiled.v3SourceMap); <ide> map.setProperty('sources', [file]); <ide> <del> callback(null, compiled.js + '\n' + map.toComment()); <add> callback(null, compiled.js + '\n' + map.toComment() + '\n'); <ide> } <ide> <ide> function coffeeify(file) {
JavaScript
isc
26c18a7ddf3edf48e636735e8c309b53fc7c729d
0
jonatkins/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,mrmakeit/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,mrmakeit/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,mrmakeit/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,mrmakeit/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion
// SETUP ///////////////////////////////////////////////////////////// // these functions set up specific areas after the boot function // created a basic framework. All of these functions should only ever // be run once. window.setupLargeImagePreview = function() { $('#portaldetails').on('click', '.imgpreview', function() { var ex = $('#largepreview'); if(ex.length > 0) { ex.remove(); return; } var img = $(this).find('img')[0]; var w = img.naturalWidth/2; var h = img.naturalHeight/2; var c = $('#portaldetails').attr('class'); $('body').append( '<div id="largepreview" class="'+c+'" style="margin-left: '+(-SIDEBAR_WIDTH/2-w-2)+'px; margin-top: '+(-h-2)+'px">' + img.outerHTML + '</div>' ); $('#largepreview').click(function() { $(this).remove() }); }); } // adds listeners to the layer chooser such that a long press hides // all custom layers except the long pressed one. window.setupLayerChooserSelectOne = function() { $('.leaflet-control-layers-overlays').on('click', 'label', function(e) { if(!e || !(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)) return; var isChecked = $(this).find('input').is(':checked'); var checkSize = $('.leaflet-control-layers-overlays input:checked').length; if((isChecked && checkSize === 1) || checkSize === 0) { // if nothing is selected or the users long-clicks the only // selected element, assume all boxes should be checked again $('.leaflet-control-layers-overlays input:not(:checked)').click(); } else { // uncheck all $('.leaflet-control-layers-overlays input:checked').click(); $(this).find('input').click(); } }); } window.setupStyles = function() { $('head').append('<style>' + [ '#largepreview.enl img { border:2px solid '+COLORS[TEAM_ENL]+'; } ', '#largepreview.res img { border:2px solid '+COLORS[TEAM_RES]+'; } ', '#largepreview.none img { border:2px solid '+COLORS[TEAM_NONE]+'; } ', '#chatcontrols { bottom: '+(CHAT_SHRINKED+22)+'px; }', '#chat { height: '+CHAT_SHRINKED+'px; } ', '.leaflet-right { margin-right: '+(SIDEBAR_WIDTH+1)+'px } ', '#updatestatus { width:'+(SIDEBAR_WIDTH+2)+'px; } ', '#sidebar { width:'+(SIDEBAR_WIDTH + HIDDEN_SCROLLBAR_ASSUMED_WIDTH + 1 /*border*/)+'px; } ', '#sidebartoggle { right:'+(SIDEBAR_WIDTH+1)+'px; } ', '#scrollwrapper { width:'+(SIDEBAR_WIDTH + 2*HIDDEN_SCROLLBAR_ASSUMED_WIDTH)+'px; right:-'+(2*HIDDEN_SCROLLBAR_ASSUMED_WIDTH-2)+'px } ', '#sidebar > * { width:'+(SIDEBAR_WIDTH+1)+'px; }'].join("\n") + '</style>'); } window.setupMap = function() { $('#map').text(''); var osmOpt = {attribution: 'Map data © OpenStreetMap contributors', maxZoom: 18}; var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmOpt); var cmOpt = {attribution: 'Map data © OpenStreetMap contributors, Imagery © CloudMade', maxZoom: 18}; var cmMin = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/22677/256/{z}/{x}/{y}.png', cmOpt); var cmMid = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/999/256/{z}/{x}/{y}.png', cmOpt); var views = [cmMid, cmMin, osm, new L.Google('INGRESS'), new L.Google('ROADMAP'), new L.Google('SATELLITE'), new L.Google('HYBRID')]; window.map = new L.Map('map', $.extend(getPosition(), {zoomControl: !(localStorage['iitc.zoom.buttons'] === 'false')} )); var addLayers = {}; portalsLayers = []; for(var i = 0; i <= 8; i++) { portalsLayers[i] = L.layerGroup([]); map.addLayer(portalsLayers[i]); var t = (i === 0 ? 'Unclaimed' : 'Level ' + i) + ' Portals'; addLayers[t] = portalsLayers[i]; } fieldsLayer = L.layerGroup([]); map.addLayer(fieldsLayer, true); addLayers['Fields'] = fieldsLayer; linksLayer = L.layerGroup([]); map.addLayer(linksLayer, true); addLayers['Links'] = linksLayer; window.layerChooser = new L.Control.Layers({ 'OSM Cloudmade Midnight': views[0], 'OSM Cloudmade Minimal': views[1], 'OSM Mapnik': views[2], 'Google Roads Ingress Style': views[3], 'Google Roads': views[4], 'Google Satellite': views[5], 'Google Hybrid': views[6] }, addLayers); map.addControl(window.layerChooser); // set the map AFTER adding the layer chooser, or Chrome reorders the // layers. This likely leads to broken layer selection because the // views/cookie order does not match the layer chooser order. try { map.addLayer(views[readCookie('ingress.intelmap.type')]); } catch(e) { map.addLayer(views[0]); } map.attributionControl.setPrefix(''); // listen for changes and store them in cookies map.on('moveend', window.storeMapPosition); map.on('zoomend', function() { window.storeMapPosition(); // remove all resonators if zoom out to < RESONATOR_DISPLAY_ZOOM_LEVEL if(isResonatorsShow()) return; for(var i = 1; i < portalsLayers.length; i++) { portalsLayers[i].eachLayer(function(item) { var itemGuid = item.options.guid; // check if 'item' is a resonator if(getTypeByGuid(itemGuid) != TYPE_RESONATOR) return true; portalsLayers[i].removeLayer(item); }); } console.log('Remove all resonators'); }); map.on('baselayerchange', function () { var selInd = $('[name=leaflet-base-layers]:checked').parent().index(); writeCookie('ingress.intelmap.type', selInd); }); // map update status handling map.on('movestart zoomstart', function() { window.mapRunsUserAction = true }); map.on('moveend zoomend', function() { window.mapRunsUserAction = false }); // update map hooks map.on('movestart zoomstart', window.requests.abort); map.on('moveend zoomend', function() { window.startRefreshTimeout(500) }); // run once on init window.requestData(); window.startRefreshTimeout(); window.addResumeFunction(window.requestData); window.requests.addRefreshFunction(window.requestData); }; // renders player details into the website. Since the player info is // included as inline script in the original site, the data is static // and cannot be updated. window.setupPlayerStat = function() { PLAYER.guid = playerNameToGuid(PLAYER.nickname); var level; var ap = parseInt(PLAYER.ap); for(level = 0; level < MIN_AP_FOR_LEVEL.length; level++) { if(ap < MIN_AP_FOR_LEVEL[level]) break; } PLAYER.level = level; var thisLvlAp = MIN_AP_FOR_LEVEL[level-1]; var nextLvlAp = MIN_AP_FOR_LEVEL[level] || ap; var lvlUpAp = digits(nextLvlAp-ap); var lvlApProg = Math.round((ap-thisLvlAp)/(nextLvlAp-thisLvlAp)*100); var xmMax = MAX_XM_PER_LEVEL[level]; var xmRatio = Math.round(PLAYER.energy/xmMax*100); var cls = PLAYER.team === 'ALIENS' ? 'enl' : 'res'; var t = 'Level:\t' + level + '\n' + 'XM:\t' + PLAYER.energy + ' / ' + xmMax + '\n' + 'AP:\t' + digits(ap) + '\n' + (level < 8 ? 'level up in:\t' + lvlUpAp + ' AP' : 'Congrats! (neeeeerd)') + '\n\Invites:\t'+PLAYER.available_invites; + '\n\nNote: your player stats can only be updated by a full reload (F5)'; $('#playerstat').html('' + '<h2 title="'+t+'">'+level+'&nbsp;' + '<div id="name">' + '<span class="'+cls+'">'+PLAYER.nickname+'</span>' + '<a href="https://www.ingress.com/_ah/logout?continue=https://www.google.com/accounts/Logout%3Fcontinue%3Dhttps://appengine.google.com/_ah/logout%253Fcontinue%253Dhttps://www.ingress.com/intel%26service%3Dah" id="signout">sign out</a>' + '</div>' + '<div id="stats">' + '<sup>XM: '+xmRatio+'%</sup>' + '<sub>' + (level < 8 ? 'level: '+lvlApProg+'%' : 'max level') + '</sub>' + '</div>' + '</h2>' ); $('#name').mouseenter(function() { $('#signout').show(); }).mouseleave(function() { $('#signout').hide(); }); } window.setupSidebarToggle = function() { $('#sidebartoggle').on('click', function() { var toggle = $('#sidebartoggle'); var sidebar = $('#scrollwrapper'); if(sidebar.is(':visible')) { sidebar.hide().css('z-index', 1); $('.leaflet-right').css('margin-right','0'); toggle.html('<span class="toggle open"></span>'); toggle.css('right', '0'); } else { sidebar.css('z-index', 1001).show(); $('.leaflet-right').css('margin-right', SIDEBAR_WIDTH+1+'px'); toggle.html('<span class="toggle close"></span>'); toggle.css('right', SIDEBAR_WIDTH+1+'px'); } }); } window.setupTooltips = function(element) { element = element || $(document); element.tooltip({ // disable show/hide animation show: { effect: "hide", duration: 0 } , hide: false, open: function(event, ui) { ui.tooltip.delay(300).fadeIn(0); }, content: function() { var title = $(this).attr('title'); return window.convertTextToTableMagic(title); } }); if(!window.tooltipClearerHasBeenSetup) { window.tooltipClearerHasBeenSetup = true; $(document).on('click', '.ui-tooltip', function() { $(this).remove(); }); } } window.setupDialogs = function() { $('#dialog').dialog({ autoOpen: false, modal: true, buttons: [ { text: 'OK', click: function() { $(this).dialog('close'); } } ] }); window.alert = function(text, isHTML) { var h = isHTML ? text : window.convertTextToTableMagic(text); $('#dialog').html(h).dialog('open'); } } window.setupQRLoadLib = function() { @@INCLUDERAW:external/jquery.qrcode.min.js@@ } // BOOTING /////////////////////////////////////////////////////////// function boot() { window.debug.console.overwriteNativeIfRequired(); console.log('loading done, booting. Built: @@BUILDDATE@@'); if(window.deviceID) console.log('Your device ID: ' + window.deviceID); window.runOnSmartphonesBeforeBoot(); // overwrite default Leaflet Marker icon to be a neutral color var base = 'https://iitcserv.appspot.com/dist/images'; L.Icon.Default.imagePath = base; window.iconEnl = L.Icon.Default.extend({options: { iconUrl: base + '/marker-green.png' } }); window.iconRes = L.Icon.Default.extend({options: { iconUrl: base + '/marker-blue.png' } }); window.setupStyles(); window.setupDialogs(); window.setupMap(); window.setupGeosearch(); window.setupRedeem(); window.setupLargeImagePreview(); window.setupSidebarToggle(); window.updateGameScore(); window.setupPlayerStat(); window.setupTooltips(); window.chat.setup(); window.setupQRLoadLib(); window.setupLayerChooserSelectOne(); // read here ONCE, so the URL is only evaluated one time after the // necessary data has been loaded. urlPortal = getURLParam('pguid'); // load only once var n = window.PLAYER['nickname']; window.PLAYER['nickMatcher'] = new RegExp('\\b('+n+')\\b', 'ig'); $('#sidebar').show(); if(window.bootPlugins) $.each(window.bootPlugins, function(ind, ref) { ref(); }); // sidebar is now at final height. Adjust scrollwrapper so scrolling // is possible for small screens and it doesn’t block the area below // it. $('#scrollwrapper').css('max-height', ($('#sidebar').get(0).scrollHeight+3) + 'px'); window.runOnSmartphonesAfterBoot(); // workaround for #129. Not sure why this is required. setTimeout('window.map.invalidateSize(false);', 500); window.iitcLoaded = true; } // this is the minified load.js script that allows us to easily load // further javascript files async as well as in order. // https://github.com/chriso/load.js // Copyright (c) 2010 Chris O'Hara <[email protected]>. MIT Licensed function asyncLoadScript(a){return function(b,c){var d=document.createElement("script");d.type="text/javascript",d.src=a,d.onload=b,d.onerror=c,d.onreadystatechange=function(){var a=this.readyState;if(a==="loaded"||a==="complete")d.onreadystatechange=null,b()},head.insertBefore(d,head.firstChild)}}(function(a){a=a||{};var b={},c,d;c=function(a,d,e){var f=a.halt=!1;a.error=function(a){throw a},a.next=function(c){c&&(f=!1);if(!a.halt&&d&&d.length){var e=d.shift(),g=e.shift();f=!0;try{b[g].apply(a,[e,e.length,g])}catch(h){a.error(h)}}return a};for(var g in b){if(typeof a[g]=="function")continue;(function(e){a[e]=function(){var g=Array.prototype.slice.call(arguments);if(e==="onError"){if(d)return b.onError.apply(a,[g,g.length]),a;var h={};return b.onError.apply(h,[g,g.length]),c(h,null,"onError")}return g.unshift(e),d?(a.then=a[e],d.push(g),f?a:a.next()):c({},[g],e)}})(g)}return e&&(a.then=a[e]),a.call=function(b,c){c.unshift(b),d.unshift(c),a.next(!0)},a.next()},d=a.addMethod=function(d){var e=Array.prototype.slice.call(arguments),f=e.pop();for(var g=0,h=e.length;g<h;g++)typeof e[g]=="string"&&(b[e[g]]=f);--h||(b["then"+d.substr(0,1).toUpperCase()+d.substr(1)]=f),c(a)},d("chain",function(a){var b=this,c=function(){if(!b.halt){if(!a.length)return b.next(!0);try{null!=a.shift().call(b,c,b.error)&&c()}catch(d){b.error(d)}}};c()}),d("run",function(a,b){var c=this,d=function(){c.halt||--b||c.next(!0)},e=function(a){c.error(a)};for(var f=0,g=b;!c.halt&&f<g;f++)null!=a[f].call(c,d,e)&&d()}),d("defer",function(a){var b=this;setTimeout(function(){b.next(!0)},a.shift())}),d("onError",function(a,b){var c=this;this.error=function(d){c.halt=!0;for(var e=0;e<b;e++)a[e].call(c,d)}})})(this);var head=document.getElementsByTagName("head")[0]||document.documentElement;addMethod("load",function(a,b){for(var c=[],d=0;d<b;d++)(function(b){c.push(asyncLoadScript(a[b]))})(d);this.call("run",c)}) try { console.log('Loading included JS now'); } catch(e) {} @@INCLUDERAW:external/leaflet.js@@ // modified version of https://github.com/shramov/leaflet-plugins. Also // contains the default Ingress map style. @@INCLUDERAW:external/leaflet_google.js@@ @@INCLUDERAW:external/autolink.js@@ @@INCLUDERAW:external/oms.min.js@@ try { console.log('done loading included JS'); } catch(e) {} var JQUERY = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; var JQUERYUI = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js'; // after all scripts have loaded, boot the actual app load(JQUERY).then(JQUERYUI).thenRun(boot);
code/boot.js
// SETUP ///////////////////////////////////////////////////////////// // these functions set up specific areas after the boot function // created a basic framework. All of these functions should only ever // be run once. window.setupLargeImagePreview = function() { $('#portaldetails').on('click', '.imgpreview', function() { var ex = $('#largepreview'); if(ex.length > 0) { ex.remove(); return; } var img = $(this).find('img')[0]; var w = img.naturalWidth/2; var h = img.naturalHeight/2; var c = $('#portaldetails').attr('class'); $('body').append( '<div id="largepreview" class="'+c+'" style="margin-left: '+(-SIDEBAR_WIDTH/2-w-2)+'px; margin-top: '+(-h-2)+'px">' + img.outerHTML + '</div>' ); $('#largepreview').click(function() { $(this).remove() }); }); } // adds listeners to the layer chooser such that a long press hides // all custom layers except the long pressed one. window.setupLayerChooserSelectOne = function() { $('.leaflet-control-layers-overlays').on('click', 'label', function(e) { if(!e || !(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)) return; var isChecked = $(this).find('input').is(':checked'); var checkSize = $('.leaflet-control-layers-overlays input:checked').length; if((isChecked && checkSize === 1) || checkSize === 0) { // if nothing is selected or the users long-clicks the only // selected element, assume all boxes should be checked again $('.leaflet-control-layers-overlays input:not(:checked)').click(); } else { // uncheck all $('.leaflet-control-layers-overlays input:checked').click(); $(this).find('input').click(); } }); } window.setupStyles = function() { $('head').append('<style>' + [ '#largepreview.enl img { border:2px solid '+COLORS[TEAM_ENL]+'; } ', '#largepreview.res img { border:2px solid '+COLORS[TEAM_RES]+'; } ', '#largepreview.none img { border:2px solid '+COLORS[TEAM_NONE]+'; } ', '#chatcontrols { bottom: '+(CHAT_SHRINKED+22)+'px; }', '#chat { height: '+CHAT_SHRINKED+'px; } ', '.leaflet-right { margin-right: '+(SIDEBAR_WIDTH+1)+'px } ', '#updatestatus { width:'+(SIDEBAR_WIDTH+2)+'px; } ', '#sidebar { width:'+(SIDEBAR_WIDTH + HIDDEN_SCROLLBAR_ASSUMED_WIDTH + 1 /*border*/)+'px; } ', '#sidebartoggle { right:'+(SIDEBAR_WIDTH+1)+'px; } ', '#scrollwrapper { width:'+(SIDEBAR_WIDTH + 2*HIDDEN_SCROLLBAR_ASSUMED_WIDTH)+'px; right:-'+(2*HIDDEN_SCROLLBAR_ASSUMED_WIDTH-2)+'px } ', '#sidebar > * { width:'+(SIDEBAR_WIDTH+1)+'px; }'].join("\n") + '</style>'); } window.setupMap = function() { $('#map').text(''); var osmOpt = {attribution: 'Map data © OpenStreetMap contributors', maxZoom: 18}; var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmOpt); var cmOpt = {attribution: 'Map data © OpenStreetMap contributors, Imagery © CloudMade', maxZoom: 18}; var cmMin = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/22677/256/{z}/{x}/{y}.png', cmOpt); var cmMid = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/999/256/{z}/{x}/{y}.png', cmOpt); var views = [cmMid, cmMin, osm, new L.Google('INGRESS'), new L.Google('ROADMAP'), new L.Google('SATELLITE'), new L.Google('HYBRID')]; window.map = new L.Map('map', $.extend(getPosition(), {zoomControl: !(localStorage['iitc.zoom.buttons'] === 'false')} )); var addLayers = {}; portalsLayers = []; for(var i = 0; i <= 8; i++) { portalsLayers[i] = L.layerGroup([]); map.addLayer(portalsLayers[i]); var t = (i === 0 ? 'Unclaimed' : 'Level ' + i) + ' Portals'; addLayers[t] = portalsLayers[i]; } fieldsLayer = L.layerGroup([]); map.addLayer(fieldsLayer, true); addLayers['Fields'] = fieldsLayer; linksLayer = L.layerGroup([]); map.addLayer(linksLayer, true); addLayers['Links'] = linksLayer; window.layerChooser = new L.Control.Layers({ 'OSM Cloudmade Midnight': views[0], 'OSM Cloudmade Minimal': views[1], 'OSM Mapnik': views[2], 'Google Roads Ingress Style': views[3], 'Google Roads': views[4], 'Google Satellite': views[5], 'Google Hybrid': views[6] }, addLayers); map.addControl(window.layerChooser); // set the map AFTER adding the layer chooser, or Chrome reorders the // layers. This likely leads to broken layer selection because the // views/cookie order does not match the layer chooser order. try { map.addLayer(views[readCookie('ingress.intelmap.type')]); } catch(e) { map.addLayer(views[0]); } map.attributionControl.setPrefix(''); // listen for changes and store them in cookies map.on('moveend', window.storeMapPosition); map.on('zoomend', function() { window.storeMapPosition(); // remove all resonators if zoom out to < RESONATOR_DISPLAY_ZOOM_LEVEL if(isResonatorsShow()) return; for(var i = 1; i < portalsLayers.length; i++) { portalsLayers[i].eachLayer(function(item) { var itemGuid = item.options.guid; // check if 'item' is a resonator if(getTypeByGuid(itemGuid) != TYPE_RESONATOR) return true; portalsLayers[i].removeLayer(item); }); } console.log('Remove all resonators'); }); map.on('baselayerchange', function () { var selInd = $('[name=leaflet-base-layers]:checked').parent().index(); writeCookie('ingress.intelmap.type', selInd); }); // map update status handling map.on('movestart zoomstart', function() { window.mapRunsUserAction = true }); map.on('moveend zoomend', function() { window.mapRunsUserAction = false }); // update map hooks map.on('movestart zoomstart', window.requests.abort); map.on('moveend zoomend', function() { window.startRefreshTimeout(500) }); // run once on init window.requestData(); window.startRefreshTimeout(); window.addResumeFunction(window.requestData); window.requests.addRefreshFunction(window.requestData); }; // renders player details into the website. Since the player info is // included as inline script in the original site, the data is static // and cannot be updated. window.setupPlayerStat = function() { PLAYER.guid = playerNameToGuid(PLAYER.nickname); var level; var ap = parseInt(PLAYER.ap); for(level = 0; level < MIN_AP_FOR_LEVEL.length; level++) { if(ap < MIN_AP_FOR_LEVEL[level]) break; } PLAYER.level = level; var thisLvlAp = MIN_AP_FOR_LEVEL[level-1]; var nextLvlAp = MIN_AP_FOR_LEVEL[level] || ap; var lvlUpAp = digits(nextLvlAp-ap); var lvlApProg = Math.round((ap-thisLvlAp)/(nextLvlAp-thisLvlAp)*100); var xmMax = MAX_XM_PER_LEVEL[level]; var xmRatio = Math.round(PLAYER.energy/xmMax*100); var cls = PLAYER.team === 'ALIENS' ? 'enl' : 'res'; var t = 'Level:\t' + level + '\n' + 'XM:\t' + PLAYER.energy + ' / ' + xmMax + '\n' + 'AP:\t' + digits(ap) + '\n' + (level < 8 ? 'level up in:\t' + lvlUpAp + ' AP' : 'Congrats! (neeeeerd)') + '\n\Invites:\t'+PLAYER.available_invites; + '\n\nNote: your player stats can only be updated by a full reload (F5)'; $('#playerstat').html('' + '<h2 title="'+t+'">'+level+'&nbsp;' + '<div id="name">' + '<span class="'+cls+'">'+PLAYER.nickname+'</span>' + '<a href="https://www.ingress.com/_ah/logout?continue=https://www.google.com/accounts/Logout%3Fcontinue%3Dhttps://appengine.google.com/_ah/logout%253Fcontinue%253Dhttps://www.ingress.com/intel%26service%3Dah" id="signout">sign out</a>' + '</div>' + '<div id="stats">' + '<sup>XM: '+xmRatio+'%</sup>' + '<sub>' + (level < 8 ? 'level: '+lvlApProg+'%' : 'max level') + '</sub>' + '</div>' + '</h2>' ); $('#name').mouseenter(function() { $('#signout').show(); }).mouseleave(function() { $('#signout').hide(); }); } window.setupSidebarToggle = function() { $('#sidebartoggle').on('click', function() { var toggle = $('#sidebartoggle'); var sidebar = $('#scrollwrapper'); if(sidebar.is(':visible')) { sidebar.hide().css('z-index', 1); $('.leaflet-right').css('margin-right','0'); toggle.html('<span class="toggle open"></span>'); toggle.css('right', '0'); } else { sidebar.css('z-index', 1001).show(); $('.leaflet-right').css('margin-right', SIDEBAR_WIDTH+1+'px'); toggle.html('<span class="toggle close"></span>'); toggle.css('right', SIDEBAR_WIDTH+1+'px'); } }); } window.setupTooltips = function(element) { element = element || $(document); element.tooltip({ // disable show/hide animation show: { effect: "hide", duration: 0 } , hide: false, open: function(event, ui) { ui.tooltip.delay(300).fadeIn(0); }, content: function() { var title = $(this).attr('title'); return window.convertTextToTableMagic(title); } }); if(!window.tooltipClearerHasBeenSetup) { window.tooltipClearerHasBeenSetup = true; $(document).on('click', '.ui-tooltip', function() { $(this).remove(); }); } } window.setupDialogs = function() { $('#dialog').dialog({ autoOpen: false, modal: true, buttons: [ { text: 'OK', click: function() { $(this).dialog('close'); } } ] }); window.alert = function(text, isHTML) { var h = isHTML ? text : window.convertTextToTableMagic(text); $('#dialog').html(h).dialog('open'); } } window.setupQRLoadLib = function() { @@INCLUDERAW:external/jquery.qrcode.min.js@@ } // BOOTING /////////////////////////////////////////////////////////// function boot() { window.debug.console.overwriteNativeIfRequired(); console.log('loading done, booting. Built: @@BUILDDATE@@'); if(window.deviceID) console.log('Your device ID: ' + window.deviceID); window.runOnSmartphonesBeforeBoot(); // overwrite default Leaflet Marker icon to be a neutral color var base = 'https://iitcserv.appspot.com/dist/images/'; L.Icon.Default.imagePath = base; window.iconEnl = L.Icon.Default.extend({options: { iconUrl: base + 'marker-green.png' } }); window.iconRes = L.Icon.Default.extend({options: { iconUrl: base + 'marker-blue.png' } }); window.setupStyles(); window.setupDialogs(); window.setupMap(); window.setupGeosearch(); window.setupRedeem(); window.setupLargeImagePreview(); window.setupSidebarToggle(); window.updateGameScore(); window.setupPlayerStat(); window.setupTooltips(); window.chat.setup(); window.setupQRLoadLib(); window.setupLayerChooserSelectOne(); // read here ONCE, so the URL is only evaluated one time after the // necessary data has been loaded. urlPortal = getURLParam('pguid'); // load only once var n = window.PLAYER['nickname']; window.PLAYER['nickMatcher'] = new RegExp('\\b('+n+')\\b', 'ig'); $('#sidebar').show(); if(window.bootPlugins) $.each(window.bootPlugins, function(ind, ref) { ref(); }); // sidebar is now at final height. Adjust scrollwrapper so scrolling // is possible for small screens and it doesn’t block the area below // it. $('#scrollwrapper').css('max-height', ($('#sidebar').get(0).scrollHeight+3) + 'px'); window.runOnSmartphonesAfterBoot(); // workaround for #129. Not sure why this is required. setTimeout('window.map.invalidateSize(false);', 500); window.iitcLoaded = true; } // this is the minified load.js script that allows us to easily load // further javascript files async as well as in order. // https://github.com/chriso/load.js // Copyright (c) 2010 Chris O'Hara <[email protected]>. MIT Licensed function asyncLoadScript(a){return function(b,c){var d=document.createElement("script");d.type="text/javascript",d.src=a,d.onload=b,d.onerror=c,d.onreadystatechange=function(){var a=this.readyState;if(a==="loaded"||a==="complete")d.onreadystatechange=null,b()},head.insertBefore(d,head.firstChild)}}(function(a){a=a||{};var b={},c,d;c=function(a,d,e){var f=a.halt=!1;a.error=function(a){throw a},a.next=function(c){c&&(f=!1);if(!a.halt&&d&&d.length){var e=d.shift(),g=e.shift();f=!0;try{b[g].apply(a,[e,e.length,g])}catch(h){a.error(h)}}return a};for(var g in b){if(typeof a[g]=="function")continue;(function(e){a[e]=function(){var g=Array.prototype.slice.call(arguments);if(e==="onError"){if(d)return b.onError.apply(a,[g,g.length]),a;var h={};return b.onError.apply(h,[g,g.length]),c(h,null,"onError")}return g.unshift(e),d?(a.then=a[e],d.push(g),f?a:a.next()):c({},[g],e)}})(g)}return e&&(a.then=a[e]),a.call=function(b,c){c.unshift(b),d.unshift(c),a.next(!0)},a.next()},d=a.addMethod=function(d){var e=Array.prototype.slice.call(arguments),f=e.pop();for(var g=0,h=e.length;g<h;g++)typeof e[g]=="string"&&(b[e[g]]=f);--h||(b["then"+d.substr(0,1).toUpperCase()+d.substr(1)]=f),c(a)},d("chain",function(a){var b=this,c=function(){if(!b.halt){if(!a.length)return b.next(!0);try{null!=a.shift().call(b,c,b.error)&&c()}catch(d){b.error(d)}}};c()}),d("run",function(a,b){var c=this,d=function(){c.halt||--b||c.next(!0)},e=function(a){c.error(a)};for(var f=0,g=b;!c.halt&&f<g;f++)null!=a[f].call(c,d,e)&&d()}),d("defer",function(a){var b=this;setTimeout(function(){b.next(!0)},a.shift())}),d("onError",function(a,b){var c=this;this.error=function(d){c.halt=!0;for(var e=0;e<b;e++)a[e].call(c,d)}})})(this);var head=document.getElementsByTagName("head")[0]||document.documentElement;addMethod("load",function(a,b){for(var c=[],d=0;d<b;d++)(function(b){c.push(asyncLoadScript(a[b]))})(d);this.call("run",c)}) try { console.log('Loading included JS now'); } catch(e) {} @@INCLUDERAW:external/leaflet.js@@ // modified version of https://github.com/shramov/leaflet-plugins. Also // contains the default Ingress map style. @@INCLUDERAW:external/leaflet_google.js@@ @@INCLUDERAW:external/autolink.js@@ @@INCLUDERAW:external/oms.min.js@@ try { console.log('done loading included JS'); } catch(e) {} var JQUERY = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; var JQUERYUI = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js'; // after all scripts have loaded, boot the actual app load(JQUERY).then(JQUERYUI).thenRun(boot);
fix shadow handling in marker icons
code/boot.js
fix shadow handling in marker icons
<ide><path>ode/boot.js <ide> window.runOnSmartphonesBeforeBoot(); <ide> <ide> // overwrite default Leaflet Marker icon to be a neutral color <del> var base = 'https://iitcserv.appspot.com/dist/images/'; <add> var base = 'https://iitcserv.appspot.com/dist/images'; <ide> L.Icon.Default.imagePath = base; <ide> <del> window.iconEnl = L.Icon.Default.extend({options: { iconUrl: base + 'marker-green.png' } }); <del> window.iconRes = L.Icon.Default.extend({options: { iconUrl: base + 'marker-blue.png' } }); <add> window.iconEnl = L.Icon.Default.extend({options: { iconUrl: base + '/marker-green.png' } }); <add> window.iconRes = L.Icon.Default.extend({options: { iconUrl: base + '/marker-blue.png' } }); <ide> <ide> window.setupStyles(); <ide> window.setupDialogs();
JavaScript
bsd-3-clause
99e27f6d8f1f89d0ef0c5ae87a654efc85822b9d
0
FredXue/boomerang,lognormal/boomerang,FredXue/boomerang,lognormal/boomerang,yahoo/boomerang,levexis/boomerang,forcedotcom/kylie,levexis/boomerang,sdgdsffdsfff/boomerang,forcedotcom/kylie,sdgdsffdsfff/boomerang
/** \file boomerang.js boomerang measures various performance characteristics of your user's browsing experience and beacons it back to your server. \details To use this you'll need a web site, lots of users and the ability to do something with the data you collect. How you collect the data is up to you, but we have a few ideas. Copyright (c) 2010 Yahoo! Inc. All rights reserved. Code licensed under the BSD License. See the file LICENSE.txt for the full license text. */ // beaconing section // the two parameters are the window and document objects (function(w, d) { // don't allow this code to be included twice if(typeof BMR !== "undefined" && typeof BMR.version !== "undefined") { return; } // Short namespace because I don't want to keep typing BOOMERANG if(typeof w.BMR === "undefined" || !w.BMR) { BMR = {}; } BMR.version = "1.0"; // bmr is a private object not reachable from outside the impl // users can set properties by passing in to the init() method var bmr = { // properties beacon_url: "", site_domain: d.location.hostname.replace(/.*?([^.]+\.[^.]+)\.?$/, '$1').toLowerCase(), // strip out everything except last two parts of hostname. user_ip: '', //! User's ip address determined on the server events: { "script_load": [], "page_load": [], "page_unload": [], "before_beacon": [] }, vars: {} }; // O is the boomerang object. We merge it into BMR later. Do it this way so that plugins // may be defined before including the script. var O = { // Utility functions utils: { getCookie: function(name) { name = ' ' + name + '='; var i, cookies; cookies = ' ' + d.cookie + ';'; if ( (i=cookies.indexOf(name)) >= 0 ) { i += name.length; cookies = cookies.substring(i, cookies.indexOf(';', i)); return cookies; } return ""; }, setCookie: function(name, subcookies, max_age, path, domain, sec) { if(!name) { return; } var value = ""; for(var k in subcookies) { if(subcookies.hasOwnProperty(k)) { value += '&' + encodeURIComponent(k) + '=' + encodeURIComponent(subcookies[k]); } } value = value.replace(/^&/, ''); var exp = ""; if(max_age) { exp = new Date(); exp.setTime(exp.getTime() + max_age*1000); exp = exp.toGMTString(); } var nameval = name + '=' + value; var c = nameval + ((max_age) ? "; expires=" + exp : "" ) + ((path) ? "; path=" + path : "") + ((typeof domain !== "undefined") ? "; domain=" + (domain === null ? bmr.site_domain : domain) : "") + ((sec) ? "; secure" : ""); if ( nameval.length < 4000 ) { d.cookie = c; return ( value === getCookie(name) ); // confirm it was set (could be blocked by user's settings, etc.) } return false; }, getSubCookies: function(cookie) { if(!cookie) { return null; } var cookies_a = cookie.split('&'); if(cookies_a.length === 0) { return null; } var cookies = {}; for(var i=0, l=cookies_a.length; i<l; i++) { var kv = cookies_a[i].split('='); kv.push(""); // just in case there's no value cookies[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); } return cookies; }, removeCookie: function(name) { return setCookie(name, {}, 0, "/", null); }, addListener: function(el, sType, fn, capture) { if(w.addEventListener) { el.addEventListener(sType, fn, (capture)); } else if(w.attachEvent) { el.attachEvent("on" + sType, fn); } } }, init: function(config) { var i, k, properties = ["beacon_url", "site_domain", "user_ip"]; for(i=0; i<properties.length; i++) { if(typeof config[properties[i]] !== "undefined") { bmr[properties[i]] = config[properties[i]]; } } if(typeof config.log !== "undefined") { this.log = config.log; } for(k in this.plugins) { if(this.plugins.hasOwnProperty(k) && typeof this.plugins[k].init === "function") { this.plugins[k].init(config); } } // The developer can override onload by setting autorun to false if(typeof config.autorun === "undefined" || config.autorun !== false) { this.utils.addListener(w, "load", function() { this.page_loaded(); }); } this.utils.addListener(w, "beforeunload", function() { this.fireEvent("page_unload"); }); return this; }, // The page dev calls this method when they determine the page is usable. Only call this if autorun is explicitly set to false page_loaded: function() { this.fireEvent("page_load"); return this; }, subscribe: function(e, fn, cb_data, cb_scope) { if(bmr.events.hasOwnProperty(e)) { bmr.events[e].push([ fn, cb_data || {}, cb_scope || null ]) } return this; }, fireEvent: function(e) { var i; if(bmr.events.hasOwnProperty(e)) { for(i=0; i<bmr.events[e].length; i++) { _fireEvent(e, i); } } }, addVar: function(name, value) { bmr.vars[name] = value; return this; }, removeVar: function(name) { if(bmr.hasOwnProperty(name)) { delete bmr.name } return this; }, sendBeacon = function() { var i, k, url, img; // At this point someone is ready to send the beacon. We send // the beacon only if all plugins have finished doing what they // wanted to do for(k in this.plugins) { if(this.plugins.hasOwnProperty(k)) { if(!this.plugins[k].is_complete()) { return; } } } // If we reach here, all plugins have completed url = this.beacon_url + '?v=' + encodeURIComponent(BMR.version); for(k in bmr.vars) { if(bmr.vars.hasOwnProperty(k)) { url += "&" + encodeURIComponent(k) + "=" + encodeURIComponent(bmr.vars[k]); } } this.fireEvent("before_beacon"); img = new Image(); img.src=url; }, log: function(m,l,s) {} // create a logger - we'll try to use the YUI logger if it exists or firebug if it exists, or just fall back to nothing. }; if(typeof YAHOO !== "undefined" && typeof YAHOO.log !== "undefined") { O.log = YAHOO.log; } else if(typeof Y !== "undefined" && typeof Y.log !== "undefined") { O.log = Y.log; } else if(typeof console !== "undefined" && typeof console.log !== "undefined") { O.log = function(m,l,s) { console.log(s + ": [" + l + "] " + m); }; } // We fire events with a setTimeout so that they run asynchronously // and don't block each other. This is most useful on a multi-threaded // JS engine var _fireEvent = function(e, i) { setTimeout(function() { bmr.events[e][i][0].call(bmr.events[e][i][1], bmr.events[e][i][2]); }, 10); }; for(var k in O) { if(O.hasOwnProperty(k)) { BMR[k] = O[k]; } } if(typeof BMR.plugins === "undefined" || !BMR.plugins) { BMR.plugins = {}; } }(this, this.document)); // end of boomerang beaconing section // Now we start built in plugins. I might move them into separate source files at some point // This is the RT plugin // the two parameters are the window and document objects (function(w, d) { // private object var rt = { complete: false,//! Set when this plugin has completed timers: {}, //! Custom timers that the developer can use // Format for each timer is { start: XXX, end: YYY, delta: YYY-XXX } cookie: 'BRT', //! Name of the cookie that stores the start time and referrer cookie_exp:600, //! Cookie expiry in seconds }; BMR.plugins.RT = { // Methods init: function(config) { var i, properties = ["cookie", "cookie_exp"]; rt.complete = false; if(typeof config === "undefined" || typeof config.RT === "undefined") { return; } for(i=0; i<config.RT.length; i++) { if(typeof config.RT[properties[i]] !== "undefined") { rt[properties[i]] = config.RT[properties[i]]; } } }, // The start method is fired on page unload start: function() { var t_start = new Date().getTime(); BMR.utils.setCookie(rt.cookie, { s: t_start, r: d.location }, rt.cookie_exp, "/", null); if(new Date().getTime() - t_start > 20) { // It took > 20ms to set the cookie // Most likely user has cookie prompting turned on so t_start won't be the actual unload time // We bail at this point since we can't reliably tell t_done removeCookie(rt.cookie); // at some point we may want to log this info on the server side } return this; }, startTimer: function(timer_name) { rt.timers[timer_name] = { start: new Date().getTime() }; return this; }, endTimer: function(timer_name, time_value) { if(typeof rt.timers[timer_name] === "undefined") { rt.timers[timer_name] = {}; } rt.timers[timer_name].end = (typeof time_value === "number" ? time_value : new Date().getTime()); return this; }, setTimer: function(timer_name, time_delta) { rt.timers[timer_name] = { delta: time_delta }; return this; }, error: function(msg) { BMR.log(msg, "error", "boomerang.rt"); return this; }, // Called when the page has reached a "loaded" state. This may be when the onload event fires, // or it could be at some other moment during/after page load when the page is usable by the user done: function() { var t_start, u, r, r2, t_other=[]; if(rt.complete) { return this; } this.endTimer("t_done"); // A beacon may be fired automatically on page load or if the page dev fires it // manually with their own timers. It may not always contain a referrer (eg: XHR calls) // We set default values for these cases u = d.location.href.replace(/#.*/, ''); r = r2 = d.referrer.replace(/#.*/, ''); var subcookies = BMR.utils.getSubCookies(BMR.utils.getCookie(rt.cookie)); BMR.utils.removeCookie(rt.cookie); if(subcookies !== null && typeof subcookies.s !== "undefined" && typeof subcookies.r !== "undefined") { t_start = parseInt(subcookies.s, 10); r = subcookies.r; } var basic_timers = { t_done: 1, t_rtpage: 1, t_resp: 1 }; var ntimers = 0; for(var timer in rt.timers) { if(!rt.timers.hasOwnProperty(timer)) { continue; } if(typeof rt.timers[timer].delta !== "number") { rt.timers[timer].delta = rt.timers[timer].end - ( typeof rt.timers[timer].start === "number" ? rt.timers[timer].start : t_start ); } if(isNaN(rt.timers[timer].delta)) { continue; } if(basic_timers[timer]) { BMR.addVar(timer, rt.timers[timer].delta); } else { t_other.push(encodeURIComponent(timer) + "|" + encodeURIComponent(rt.timers[timer].delta)); } ntimers++; } // make sure an old t_other doesn't stick around BMR.removeVar('t_other'); // At this point we decide whether the beacon should be sent or not if(ntimers === 0) { return this.error("no timers"); } if(t_other.length > 0) { BMR.addVar("t_other", t_other.join(",")); } rt.timers = {}; BMR.addVar("u", u); BMR.addVar("r", r); BMR.removeVars('r2'); if(r2 !== r) { BMR.addVar("r2", r2); } rt.complete = true; BMR.sendBeacon(); return this; }, is_complete: function() { return rt.complete; } }; BMR.subscribe("page_load", BMR.RT.done, null, BMR.RT); BMR.subscribe("page_unload", BMR.RT.start, null, BMR.RT); }(this, this.document)); // End of RT plugin // This is the BW plugin // the two parameters are the window and document objects (function(w, d) { // private object var bw = { base_url: '', timeout: 15000, nruns: 5, latency_runs: 10 }; // We choose image sizes so that we can narrow down on a bandwidth range as soon as possible // the sizes chosen correspond to bandwidth values of 14-64kbps, 64-256kbps, 256-1024kbps, 1-2Mbps, 2-8Mbps, 8-30Mbps & 30Mbps+ // Anything below 14kbps will probably timeout before the test completes // Anything over 60Mbps will probably be unreliable since latency will make up the largest part of download time // If you want to extend this further to cover 100Mbps & 1Gbps networks, use image sizes of 19,200,000 & 153,600,000 bytes respectively // See https://spreadsheets.google.com/ccc?key=0AplxPyCzmQi6dDRBN2JEd190N1hhV1N5cHQtUVdBMUE&hl=en_GB for a spreadsheet with the details var images=[ { name: "image-0.png", size: 11483, timeout: 1400 }, { name: "image-1.png", size: 40658, timeout: 1200 }, { name: "image-2.png", size: 164897, timeout: 1300 }, { name: "image-3.png", size: 381756, timeout: 1500 }, { name: "image-4.png", size: 1234664, timeout: 1200 }, { name: "image-5.png", size: 4509613, timeout: 1200 }, { name: "image-6.png", size: 9084559, timeout: 1200 } ]; var nimages = images.length; var smallest_image = 0; // abuse arrays to do the latency test simply because it avoids a bunch of branches in the rest of the code images['l'] = { name: "image-l.gif", size: 35, timeout: 1000 }; var results = [], latencies = [], latency = null, runs_left = bw.nruns, aborted = false, complete = false, test_start = null; BMR.plugins.BW = { init: function(config) { var i, properties = ["base_url", "timeout", "nruns", "latency_runs"]; if(typeof config !== "undefined" && typeof config.BW !== "undefined") { for(i=0; i<config.BW.length; i++) { if(typeof config.BW[properties[i]] !== "undefined") { bw[properties[i]] = config.BW[properties[i]]; } } } runs_left = bw.nruns; latency_runs = 10; smallest_image = 0; results = []; latencies = []; latency = null; complete = false; aborted = false; test_start = null; }, run: function() { setTimeout(BMR.plugins.BW.abort, bw.timeout); test_start = new Date().getTime(); defer(iterate); }, abort: function() { aborted = true; finish(); // we don't defer this call because it might be called from onbeforeunload // and we want the entire chain to complete before we return }, is_complete: function() { return complete; } }; var ncmp = function(a, b) { return (a-b); }; var iqr = function(a) { var l = a.length-1; var q1 = (a[Math.floor(l*0.25)] + a[Math.ceil(l*0.25)])/2; var q3 = (a[Math.floor(l*0.75)] + a[Math.ceil(l*0.75)])/2; var fw = (q3-q1)*1.5; var b=[]; l++; for(var i=0; i<l && a[i] < q3+fw; i++) { if(a[i] > q1-fw) { b.push(a[i]); } } return b; }; var debug = function(msg) { BMR.log(msg, "debug", "boomerang.bw"); }; var defer = function(method) { return setTimeout(method, 10); }; var iterate = function() { if(aborted) { return false; } if(!runs_left) { finish(); } else if(latency_runs) { load_img('l', latency_runs--, lat_loaded); } else { results.push({r:[]}); load_img(smallest_image, runs_left--, img_loaded); } }; var load_img = function(i, run, callback) { var url = base_url + images[i].name + '?t=' + (new Date().getTime()) + Math.random(); var timer=0, tstart=0; var img = new Image(); img.onload=function() { img=null; clearTimeout(timer); if(callback) callback(i, tstart, run, true); callback=null; }; img.onerror=function() { img=null; clearTimeout(timer); if(callback) callback(i, tstart, run, false); callback=null; }; // the timeout does not abort download of the current image, it just sets an end of loop flag so we don't attempt download of the next image // we still need to wait until onload or onerror fire to be sure that the image download isn't using up bandwidth. // This also saves us if the timeout happens on the first image. If it didn't, we'd have nothing to measure. timer=setTimeout(function() { if(callback) callback(i, tstart, run, null); }, images[i].timeout + Math.min(400, latency ? latency.mean : 400)); tstart = new Date().getTime(); img.src=url; }; var lat_loaded = function(i, tstart, run, success) { if(run != latency_runs+1) return; if(success !== null) { var lat = new Date().getTime() - tstart; latencies.push(lat); } // if we've got all the latency images at this point, we can calculate latency if(latency_runs === 0) { latency = calc_latency(); } defer(iterate); }; var img_loaded = function(i, tstart, run, success) { if(run != runs_left+1) return; if(results[nruns-run].r[i]) // already called on this image return; if(success === null) { // if timeout, then we set the next image to the end of loop marker results[nruns-run].r[i+1] = {t:null, state: null, run: run}; return; } var result = { start: tstart, end: new Date().getTime(), t: null, state: success, run: run }; if(success) { result.t = result.end-result.start; } results[nruns-run].r[i] = result; // we terminate if an image timed out because that means the connection is too slow to go to the next image if(i >= nimages-1 || typeof results[nruns-run].r[i+1] !== 'undefined') { debug(results[nruns-run]); // First run is a pilot test to decide what the largest image that we can download is // All following runs only try to download this image if(run === nruns) { smallest_image = i; } defer(iterate); } else { load_img(i+1, run, img_loaded); } }; var calc_latency = function() { var i, n, sum=0, sumsq=0, amean, median, std_dev, std_err; // We first do IQR filtering and use the resulting data set for all calculations var lat_filtered = iqr(latencies.sort(ncmp)); n = lat_filtered.length; debug(lat_filtered); // First we get the arithmetic mean, standard deviation and standard error // We ignore the first since it paid the price of DNS lookup, TCP connect and slow start for(i=1; i<n; i++) { sum += lat_filtered[i]; sumsq += lat_filtered[i] * lat_filtered[i]; } n--; // Since we started the loop with 1 and not 0 amean = Math.round(sum / n); std_dev = Math.sqrt( sumsq/n - sum*sum/(n*n)); // See http://en.wikipedia.org/wiki/1.96 and http://en.wikipedia.org/wiki/Standard_error_%28statistics%29 std_err = (1.96 * std_dev/Math.sqrt(n)).toFixed(2); std_dev = std_dev.toFixed(2); n = lat_filtered.length-1; median = Math.round((lat_filtered[Math.floor(n/2)] + lat_filtered[Math.ceil(n/2)])/2); return { mean: amean, median: median, stddev: std_dev, stderr: std_err }; }; var calc_bw = function(latency) { var i, j, n=0, r, bandwidths=[], bandwidths_corrected=[], sum=0, sumsq=0, sum_corrected=0, sumsq_corrected=0, amean, std_dev, std_err, median, amean_corrected, std_dev_corrected, std_err_corrected, median_corrected; for(i=0; i<nruns; i++) { if(!results[i] || !results[i].r) { continue; } r=results[i].r; // the next loop we iterate through backwards and only consider the largest 3 images that succeeded // that way we don't consider small images that downloaded fast without really saturating the network var nimgs=0; for(j=r.length-1; j>=0 && nimgs<3; j--) { if(typeof r[j] === 'undefined') // if we hit an undefined image time, it means we skipped everything before this break; if(r[j].t === null) continue; n++; nimgs++; var bw = images[j].size*1000/r[j].t; bandwidths.push(bw); var bw_c = images[j].size*1000/(r[j].t - latency); bandwidths_corrected.push(bw_c); } } debug('got ' + n + ' readings'); debug('bandwidths: ' + bandwidths); debug('corrected: ' + bandwidths_corrected); // First do IQR filtering since we use the median here and should use the stddev after filtering. if(bandwidths.length > 3) { bandwidths = iqr(bandwidths.sort(ncmp)); bandwidths_corrected = iqr(bandwidths_corrected.sort(ncmp)); } else { bandwidths = bandwidths.sort(ncmp); bandwidths_corrected = bandwidths_corrected.sort(ncmp); } debug('after iqr: ' + bandwidths); debug('corrected: ' + bandwidths_corrected); // Now get the mean & median. Also get corrected values that eliminate latency n = Math.max(bandwidths.length, bandwidths_corrected.length); for(i=0; i<n; i++) { if(i<bandwidths.length) { sum += bandwidths[i]; sumsq += Math.pow(bandwidths[i], 2); } if(i<bandwidths_corrected.length) { sum_corrected += bandwidths_corrected[i]; sumsq_corrected += Math.pow(bandwidths_corrected[i], 2); } } n = bandwidths.length; amean = Math.round(sum/n); std_dev = Math.sqrt(sumsq/n - Math.pow(sum/n, 2)); std_err = Math.round(1.96 * std_dev/Math.sqrt(n)); std_dev = Math.round(std_dev); n = bandwidths.length-1; median = Math.round((bandwidths[Math.floor(n/2)] + bandwidths[Math.ceil(n/2)])/2); n = bandwidths_corrected.length; amean_corrected = Math.round(sum_corrected/n); std_dev_corrected = Math.sqrt(sumsq_corrected/n - Math.pow(sum_corrected/n, 2)); std_err_corrected = (1.96 * std_dev_corrected/Math.sqrt(n)).toFixed(2); std_dev_corrected = std_dev_corrected.toFixed(2); n = bandwidths_corrected.length-1; median_corrected = Math.round((bandwidths_corrected[Math.floor(n/2)] + bandwidths_corrected[Math.ceil(n/2)])/2); debug('amean: ' + amean + ', median: ' + median); debug('corrected amean: ' + amean_corrected + ', median: ' + median_corrected); return { mean: amean, stddev: std_dev, stderr: std_err, median: median, mean_corrected: amean_corrected, stddev_corrected: std_dev_corrected, stderr_corrected: std_err_corrected, median_corrected: median_corrected }; }; var finish = function() { if(!latency) latency = calc_latency(); var bw = calc_bw(latency.mean); var test_time = new Date().getTime() - test_start; var o = { bw: bw.median_corrected, bw_err: parseFloat(bw.stderr_corrected, 10), lat: latency.mean, lat_err: parseFloat(latency.stderr, 10) }; for(var k in o) { if(o.hasOwnProperty(k)) { BMR.addVar(k, o[k]); } } complete = true; BMR.sendBeacon(); }; BMR.subscribe("page_load", BMR.BW.run, null, BMR.BW); }(this, this.document)); // End of BW plugin BMR.fireEvent("script_load");
boomerang.js
/** \file boomerang.js boomerang measures various performance characteristics of your user's browsing experience and beacons it back to your server. \details To use this you'll need a web site, lots of users and the ability to do something with the data you collect. How you collect the data is up to you, but we have a few ideas. Copyright (c) 2010 Yahoo! Inc. All rights reserved. Code licensed under the BSD License. See the file LICENSE.txt for the full license text. */ // beaconing section // the two parameters are the window and document objects (function(w, d) { // don't allow this code to be included twice if(typeof BMR !== "undefined" && typeof BMR.version !== "undefined") { return; } // Short namespace because I don't want to keep typing BOOMERANG if(typeof w.BMR === "undefined" || !w.BMR) { BMR = {}; } BMR.version = "1.0"; // bmr is a private object not reachable from outside the impl // users can set properties by passing in to the init() method var bmr = { // properties beacon_url: "", site_domain: d.location.hostname.replace(/.*?([^.]+\.[^.]+)\.?$/, '$1').toLowerCase(), // strip out everything except last two parts of hostname. user_ip: '', //! User's ip address determined on the server events: { "script_load": [], "page_load": [], "page_unload": [], "before_beacon": [] }, vars: {} }; // O is the boomerang object. We merge it into BMR later. Do it this way so that plugins // may be defined before including the script. var O = { // Utility functions utils: { getCookie: function(name) { name = ' ' + name + '='; var i, cookies; cookies = ' ' + d.cookie + ';'; if ( (i=cookies.indexOf(name)) >= 0 ) { i += name.length; cookies = cookies.substring(i, cookies.indexOf(';', i)); return cookies; } return ""; }, setCookie: function(name, subcookies, max_age, path, domain, sec) { if(!name) { return; } var value = ""; for(var k in subcookies) { if(subcookies.hasOwnProperty(k)) { value += '&' + encodeURIComponent(k) + '=' + encodeURIComponent(subcookies[k]); } } value = value.replace(/^&/, ''); var exp = ""; if(max_age) { exp = new Date(); exp.setTime(exp.getTime() + max_age*1000); exp = exp.toGMTString(); } var nameval = name + '=' + value; var c = nameval + ((max_age) ? "; expires=" + exp : "" ) + ((path) ? "; path=" + path : "") + ((typeof domain !== "undefined") ? "; domain=" + (domain === null ? bmr.site_domain : domain) : "") + ((sec) ? "; secure" : ""); if ( nameval.length < 4000 ) { d.cookie = c; return ( value === getCookie(name) ); // confirm it was set (could be blocked by user's settings, etc.) } return false; }, getSubCookies: function(cookie) { if(!cookie) { return null; } var cookies_a = cookie.split('&'); if(cookies_a.length === 0) { return null; } var cookies = {}; for(var i=0, l=cookies_a.length; i<l; i++) { var kv = cookies_a[i].split('='); kv.push(""); // just in case there's no value cookies[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); } return cookies; }, removeCookie: function(name) { return setCookie(name, {}, 0, "/", null); }, addListener: function(el, sType, fn, capture) { if(w.addEventListener) { el.addEventListener(sType, fn, (capture)); } else if(w.attachEvent) { el.attachEvent("on" + sType, fn); } } }, init: function(config) { var i, k, properties = ["beacon_url", "site_domain", "user_ip"]; for(i=0; i<properties.length; i++) { if(typeof config[properties[i]] !== "undefined") { bmr[properties[i]] = config[properties[i]]; } } if(typeof config.log !== "undefined") { this.log = config.log; } for(k in this.plugins) { if(this.plugins.hasOwnProperty(k) && typeof this.plugins[k].init === "function") { this.plugins[k].init(config); } } // The developer can override onload by setting autorun to false if(typeof config.autorun === "undefined" || config.autorun !== false) { this.utils.addListener(w, "load", this.page_loaded); } this.utils.addListener(w, "beforeunload", function() { this.fireEvent("page_unload"); }); return this; }, // The page dev calls this method when they determine the page is usable. Only call this if autorun is explicitly set to false page_loaded: function() { this.fireEvent("page_load"); return this; }, subscribe: function(e, fn, cb_data, cb_scope) { if(bmr.events.hasOwnProperty(e)) { bmr.events[e].push([ fn, cb_data || {}, cb_scope || null ]) } return this; }, fireEvent: function(e) { var i; if(bmr.events.hasOwnProperty(e)) { for(i=0; i<bmr.events[e].length; i++) { _fireEvent(e, i); } } }, addVar: function(name, value) { bmr.vars[name] = value; return this; }, removeVar: function(name) { if(bmr.hasOwnProperty(name)) { delete bmr.name } return this; }, sendBeacon = function() { var i, k, url, img; // At this point someone is ready to send the beacon. We send // the beacon only if all plugins have finished doing what they // wanted to do for(k in this.plugins) { if(this.plugins.hasOwnProperty(k)) { if(!this.plugins[k].is_complete()) { return; } } } // If we reach here, all plugins have completed url = this.beacon_url + '?v=' + encodeURIComponent(BMR.version); for(k in bmr.vars) { if(bmr.vars.hasOwnProperty(k)) { url += "&" + encodeURIComponent(k) + "=" + encodeURIComponent(bmr.vars[k]); } } this.fireEvent("before_beacon"); img = new Image(); img.src=url; }, log: function(m,l,s) {} // create a logger - we'll try to use the YUI logger if it exists or firebug if it exists, or just fall back to nothing. }; if(typeof YAHOO !== "undefined" && typeof YAHOO.log !== "undefined") { O.log = YAHOO.log; } else if(typeof Y !== "undefined" && typeof Y.log !== "undefined") { O.log = Y.log; } else if(typeof console !== "undefined" && typeof console.log !== "undefined") { O.log = function(m,l,s) { console.log(s + ": [" + l + "] " + m); }; } // We fire events with a setTimeout so that they run asynchronously // and don't block each other. This is most useful on a multi-threaded // JS engine var _fireEvent = function(e, i) { setTimeout(function() { bmr.events[e][i][0].call(bmr.events[e][i][1], bmr.events[e][i][2]); }, 10); }; for(var k in O) { if(O.hasOwnProperty(k)) { BMR[k] = O[k]; } } if(typeof BMR.plugins === "undefined" || !BMR.plugins) { BMR.plugins = {}; } }(this, this.document)); // end of boomerang beaconing section // Now we start built in plugins. I might move them into separate source files at some point // This is the RT plugin // the two parameters are the window and document objects (function(w, d) { // private object var rt = { complete: false,//! Set when this plugin has completed timers: {}, //! Custom timers that the developer can use // Format for each timer is { start: XXX, end: YYY, delta: YYY-XXX } cookie: 'BRT', //! Name of the cookie that stores the start time and referrer cookie_exp:600, //! Cookie expiry in seconds }; BMR.plugins.RT = { // Methods init: function(config) { var i, properties = ["cookie", "cookie_exp"]; rt.complete = false; if(typeof config === "undefined" || typeof config.RT === "undefined") { return; } for(i=0; i<config.RT.length; i++) { if(typeof config.RT[properties[i]] !== "undefined") { rt[properties[i]] = config.RT[properties[i]]; } } }, // The start method is fired on page unload start: function() { var t_start = new Date().getTime(); BMR.utils.setCookie(rt.cookie, { s: t_start, r: d.location }, rt.cookie_exp, "/", null); if(new Date().getTime() - t_start > 20) { // It took > 20ms to set the cookie // Most likely user has cookie prompting turned on so t_start won't be the actual unload time // We bail at this point since we can't reliably tell t_done removeCookie(rt.cookie); // at some point we may want to log this info on the server side } return this; }, startTimer: function(timer_name) { rt.timers[timer_name] = { start: new Date().getTime() }; return this; }, endTimer: function(timer_name, time_value) { if(typeof rt.timers[timer_name] === "undefined") { rt.timers[timer_name] = {}; } rt.timers[timer_name].end = (typeof time_value === "number" ? time_value : new Date().getTime()); return this; }, setTimer: function(timer_name, time_delta) { rt.timers[timer_name] = { delta: time_delta }; return this; }, error: function(msg) { BMR.log(msg, "error", "boomerang.rt"); return this; }, // Called when the page has reached a "loaded" state. This may be when the onload event fires, // or it could be at some other moment during/after page load when the page is usable by the user done: function() { var t_start, u, r, r2, t_other=[]; if(rt.complete) { return this; } this.endTimer("t_done"); // A beacon may be fired automatically on page load or if the page dev fires it // manually with their own timers. It may not always contain a referrer (eg: XHR calls) // We set default values for these cases u = d.location.href.replace(/#.*/, ''); r = r2 = d.referrer.replace(/#.*/, ''); var subcookies = BMR.utils.getSubCookies(BMR.utils.getCookie(rt.cookie)); BMR.utils.removeCookie(rt.cookie); if(subcookies !== null && typeof subcookies.s !== "undefined" && typeof subcookies.r !== "undefined") { t_start = parseInt(subcookies.s, 10); r = subcookies.r; } var basic_timers = { t_done: 1, t_rtpage: 1, t_resp: 1 }; var ntimers = 0; for(var timer in rt.timers) { if(!rt.timers.hasOwnProperty(timer)) { continue; } if(typeof rt.timers[timer].delta !== "number") { rt.timers[timer].delta = rt.timers[timer].end - ( typeof rt.timers[timer].start === "number" ? rt.timers[timer].start : t_start ); } if(isNaN(rt.timers[timer].delta)) { continue; } if(basic_timers[timer]) { BMR.addVar(timer, rt.timers[timer].delta); } else { t_other.push(encodeURIComponent(timer) + "|" + encodeURIComponent(rt.timers[timer].delta)); } ntimers++; } // make sure an old t_other doesn't stick around BMR.removeVar('t_other'); // At this point we decide whether the beacon should be sent or not if(ntimers === 0) { return this.error("no timers"); } if(t_other.length > 0) { BMR.addVar("t_other", t_other.join(",")); } rt.timers = {}; BMR.addVar("u", u); BMR.addVar("r", r); BMR.removeVars('r2'); if(r2 !== r) { BMR.addVar("r2", r2); } rt.complete = true; BMR.sendBeacon(); return this; }, is_complete: function() { return rt.complete; } }; BMR.subscribe("page_load", BMR.RT.done, null, BMR.RT); BMR.subscribe("page_unload", BMR.RT.start, null, BMR.RT); }(this, this.document)); // End of RT plugin // This is the BW plugin // the two parameters are the window and document objects (function(w, d) { // private object var bw = { base_url: '', timeout: 15000, nruns: 5, latency_runs: 10 }; // We choose image sizes so that we can narrow down on a bandwidth range as soon as possible // the sizes chosen correspond to bandwidth values of 14-64kbps, 64-256kbps, 256-1024kbps, 1-2Mbps, 2-8Mbps, 8-30Mbps & 30Mbps+ // Anything below 14kbps will probably timeout before the test completes // Anything over 60Mbps will probably be unreliable since latency will make up the largest part of download time // If you want to extend this further to cover 100Mbps & 1Gbps networks, use image sizes of 19,200,000 & 153,600,000 bytes respectively // See https://spreadsheets.google.com/ccc?key=0AplxPyCzmQi6dDRBN2JEd190N1hhV1N5cHQtUVdBMUE&hl=en_GB for a spreadsheet with the details var images=[ { name: "image-0.png", size: 11483, timeout: 1400 }, { name: "image-1.png", size: 40658, timeout: 1200 }, { name: "image-2.png", size: 164897, timeout: 1300 }, { name: "image-3.png", size: 381756, timeout: 1500 }, { name: "image-4.png", size: 1234664, timeout: 1200 }, { name: "image-5.png", size: 4509613, timeout: 1200 }, { name: "image-6.png", size: 9084559, timeout: 1200 } ]; var nimages = images.length; var smallest_image = 0; // abuse arrays to do the latency test simply because it avoids a bunch of branches in the rest of the code images['l'] = { name: "image-l.gif", size: 35, timeout: 1000 }; var results = [], latencies = [], latency = null, runs_left = bw.nruns, aborted = false, complete = false, test_start = null; BMR.plugins.BW = { init: function(config) { var i, properties = ["base_url", "timeout", "nruns", "latency_runs"]; if(typeof config !== "undefined" && typeof config.BW !== "undefined") { for(i=0; i<config.BW.length; i++) { if(typeof config.BW[properties[i]] !== "undefined") { bw[properties[i]] = config.BW[properties[i]]; } } } runs_left = bw.nruns; latency_runs = 10; smallest_image = 0; results = []; latencies = []; latency = null; complete = false; aborted = false; test_start = null; }, run: function() { setTimeout(BMR.plugins.BW.abort, bw.timeout); test_start = new Date().getTime(); defer(iterate); }, abort: function() { aborted = true; finish(); // we don't defer this call because it might be called from onbeforeunload // and we want the entire chain to complete before we return }, is_complete: function() { return complete; } }; var ncmp = function(a, b) { return (a-b); }; var iqr = function(a) { var l = a.length-1; var q1 = (a[Math.floor(l*0.25)] + a[Math.ceil(l*0.25)])/2; var q3 = (a[Math.floor(l*0.75)] + a[Math.ceil(l*0.75)])/2; var fw = (q3-q1)*1.5; var b=[]; l++; for(var i=0; i<l && a[i] < q3+fw; i++) { if(a[i] > q1-fw) { b.push(a[i]); } } return b; }; var debug = function(msg) { BMR.log(msg, "debug", "boomerang.bw"); }; var defer = function(method) { return setTimeout(method, 10); }; var iterate = function() { if(aborted) { return false; } if(!runs_left) { finish(); } else if(latency_runs) { load_img('l', latency_runs--, lat_loaded); } else { results.push({r:[]}); load_img(smallest_image, runs_left--, img_loaded); } }; var load_img = function(i, run, callback) { var url = base_url + images[i].name + '?t=' + (new Date().getTime()) + Math.random(); var timer=0, tstart=0; var img = new Image(); img.onload=function() { img=null; clearTimeout(timer); if(callback) callback(i, tstart, run, true); callback=null; }; img.onerror=function() { img=null; clearTimeout(timer); if(callback) callback(i, tstart, run, false); callback=null; }; // the timeout does not abort download of the current image, it just sets an end of loop flag so we don't attempt download of the next image // we still need to wait until onload or onerror fire to be sure that the image download isn't using up bandwidth. // This also saves us if the timeout happens on the first image. If it didn't, we'd have nothing to measure. timer=setTimeout(function() { if(callback) callback(i, tstart, run, null); }, images[i].timeout + Math.min(400, latency ? latency.mean : 400)); tstart = new Date().getTime(); img.src=url; }; var lat_loaded = function(i, tstart, run, success) { if(run != latency_runs+1) return; if(success !== null) { var lat = new Date().getTime() - tstart; latencies.push(lat); } // if we've got all the latency images at this point, we can calculate latency if(latency_runs === 0) { latency = calc_latency(); } defer(iterate); }; var img_loaded = function(i, tstart, run, success) { if(run != runs_left+1) return; if(results[nruns-run].r[i]) // already called on this image return; if(success === null) { // if timeout, then we set the next image to the end of loop marker results[nruns-run].r[i+1] = {t:null, state: null, run: run}; return; } var result = { start: tstart, end: new Date().getTime(), t: null, state: success, run: run }; if(success) { result.t = result.end-result.start; } results[nruns-run].r[i] = result; // we terminate if an image timed out because that means the connection is too slow to go to the next image if(i >= nimages-1 || typeof results[nruns-run].r[i+1] !== 'undefined') { debug(results[nruns-run]); // First run is a pilot test to decide what the largest image that we can download is // All following runs only try to download this image if(run === nruns) { smallest_image = i; } defer(iterate); } else { load_img(i+1, run, img_loaded); } }; var calc_latency = function() { var i, n, sum=0, sumsq=0, amean, median, std_dev, std_err; // We first do IQR filtering and use the resulting data set for all calculations var lat_filtered = iqr(latencies.sort(ncmp)); n = lat_filtered.length; debug(lat_filtered); // First we get the arithmetic mean, standard deviation and standard error // We ignore the first since it paid the price of DNS lookup, TCP connect and slow start for(i=1; i<n; i++) { sum += lat_filtered[i]; sumsq += lat_filtered[i] * lat_filtered[i]; } n--; // Since we started the loop with 1 and not 0 amean = Math.round(sum / n); std_dev = Math.sqrt( sumsq/n - sum*sum/(n*n)); // See http://en.wikipedia.org/wiki/1.96 and http://en.wikipedia.org/wiki/Standard_error_%28statistics%29 std_err = (1.96 * std_dev/Math.sqrt(n)).toFixed(2); std_dev = std_dev.toFixed(2); n = lat_filtered.length-1; median = Math.round((lat_filtered[Math.floor(n/2)] + lat_filtered[Math.ceil(n/2)])/2); return { mean: amean, median: median, stddev: std_dev, stderr: std_err }; }; var calc_bw = function(latency) { var i, j, n=0, r, bandwidths=[], bandwidths_corrected=[], sum=0, sumsq=0, sum_corrected=0, sumsq_corrected=0, amean, std_dev, std_err, median, amean_corrected, std_dev_corrected, std_err_corrected, median_corrected; for(i=0; i<nruns; i++) { if(!results[i] || !results[i].r) { continue; } r=results[i].r; // the next loop we iterate through backwards and only consider the largest 3 images that succeeded // that way we don't consider small images that downloaded fast without really saturating the network var nimgs=0; for(j=r.length-1; j>=0 && nimgs<3; j--) { if(typeof r[j] === 'undefined') // if we hit an undefined image time, it means we skipped everything before this break; if(r[j].t === null) continue; n++; nimgs++; var bw = images[j].size*1000/r[j].t; bandwidths.push(bw); var bw_c = images[j].size*1000/(r[j].t - latency); bandwidths_corrected.push(bw_c); } } debug('got ' + n + ' readings'); debug('bandwidths: ' + bandwidths); debug('corrected: ' + bandwidths_corrected); // First do IQR filtering since we use the median here and should use the stddev after filtering. if(bandwidths.length > 3) { bandwidths = iqr(bandwidths.sort(ncmp)); bandwidths_corrected = iqr(bandwidths_corrected.sort(ncmp)); } else { bandwidths = bandwidths.sort(ncmp); bandwidths_corrected = bandwidths_corrected.sort(ncmp); } debug('after iqr: ' + bandwidths); debug('corrected: ' + bandwidths_corrected); // Now get the mean & median. Also get corrected values that eliminate latency n = Math.max(bandwidths.length, bandwidths_corrected.length); for(i=0; i<n; i++) { if(i<bandwidths.length) { sum += bandwidths[i]; sumsq += Math.pow(bandwidths[i], 2); } if(i<bandwidths_corrected.length) { sum_corrected += bandwidths_corrected[i]; sumsq_corrected += Math.pow(bandwidths_corrected[i], 2); } } n = bandwidths.length; amean = Math.round(sum/n); std_dev = Math.sqrt(sumsq/n - Math.pow(sum/n, 2)); std_err = Math.round(1.96 * std_dev/Math.sqrt(n)); std_dev = Math.round(std_dev); n = bandwidths.length-1; median = Math.round((bandwidths[Math.floor(n/2)] + bandwidths[Math.ceil(n/2)])/2); n = bandwidths_corrected.length; amean_corrected = Math.round(sum_corrected/n); std_dev_corrected = Math.sqrt(sumsq_corrected/n - Math.pow(sum_corrected/n, 2)); std_err_corrected = (1.96 * std_dev_corrected/Math.sqrt(n)).toFixed(2); std_dev_corrected = std_dev_corrected.toFixed(2); n = bandwidths_corrected.length-1; median_corrected = Math.round((bandwidths_corrected[Math.floor(n/2)] + bandwidths_corrected[Math.ceil(n/2)])/2); debug('amean: ' + amean + ', median: ' + median); debug('corrected amean: ' + amean_corrected + ', median: ' + median_corrected); return { mean: amean, stddev: std_dev, stderr: std_err, median: median, mean_corrected: amean_corrected, stddev_corrected: std_dev_corrected, stderr_corrected: std_err_corrected, median_corrected: median_corrected }; }; var finish = function() { if(!latency) latency = calc_latency(); var bw = calc_bw(latency.mean); var test_time = new Date().getTime() - test_start; var o = { bw: bw.median_corrected, bw_err: parseFloat(bw.stderr_corrected, 10), lat: latency.mean, lat_err: parseFloat(latency.stderr, 10) }; for(var k in o) { if(o.hasOwnProperty(k)) { BMR.addVar(k, o[k]); } } complete = true; BMR.sendBeacon(); }; BMR.subscribe("page_load", BMR.BW.run, null, BMR.BW); }(this, this.document)); // End of BW plugin BMR.fireEvent("script_load");
this is not passed from event handler
boomerang.js
this is not passed from event handler
<ide><path>oomerang.js <ide> <ide> // The developer can override onload by setting autorun to false <ide> if(typeof config.autorun === "undefined" || config.autorun !== false) { <del> this.utils.addListener(w, "load", this.page_loaded); <add> this.utils.addListener(w, "load", function() { this.page_loaded(); }); <ide> } <ide> this.utils.addListener(w, "beforeunload", function() { this.fireEvent("page_unload"); }); <ide>
Java
mit
74523cc07045cf5f48acef329e0e69d6f8760643
0
Bathlamos/RTDC,Bathlamos/RTDC,Bathlamos/RTDC
package rtdc.android.presenter; import android.app.ActionBar; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import rtdc.android.R; import rtdc.android.impl.AndroidUiDate; import rtdc.android.impl.AndroidUiDropdownList; import rtdc.android.impl.AndroidUiString; import rtdc.core.controller.AddActionController; import rtdc.core.impl.UiDropdownList; import rtdc.core.impl.UiElement; import rtdc.core.model.Action; import rtdc.core.util.Cache; import rtdc.core.view.AddActionView; import java.util.Date; public class CreateActionActivity extends AbstractActivity implements AddActionView { private AddActionController controller; private AndroidUiString roleEdit, targetEdit, descriptionEdit; private AndroidUiDate deadlineEdit; private AndroidUiDropdownList unitSpinner, statusSpinner, taskSpinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_action); roleEdit = (AndroidUiString) findViewById(R.id.roleEdit); targetEdit = (AndroidUiString) findViewById(R.id.targetEdit); deadlineEdit = (AndroidUiDate) findViewById(R.id.deadlineEdit); descriptionEdit = (AndroidUiString) findViewById(R.id.descriptionEdit); unitSpinner = (AndroidUiDropdownList) findViewById(R.id.unitSpinner); statusSpinner = (AndroidUiDropdownList) findViewById(R.id.statusSpinner); taskSpinner = (AndroidUiDropdownList) findViewById(R.id.actionSpinner); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); if(controller == null) controller = new AddActionController(this); } @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_create_action, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will switch (item.getItemId()) { case R.id.action_save_action: controller.addAction(); return true; case R.id.action_cancel_action: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public UiDropdownList<String> getUnitUiElement() { return unitSpinner; } @Override public UiDropdownList<String> getStatusUiElement() { return statusSpinner; } @Override public UiElement<String> getRoleUiElement() { return roleEdit; } @Override public UiDropdownList<String> getTaskUiElement() { return taskSpinner; } @Override public UiElement<String> getTargetUiElement() { return targetEdit; } @Override public UiElement<Date> getDeadlineUiElement() { return deadlineEdit; } @Override public UiElement<String> getDescriptionUiElement() { return descriptionEdit; } }
android/src/main/java/rtdc/android/presenter/CreateActionActivity.java
package rtdc.android.presenter; import android.app.ActionBar; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import rtdc.android.R; import rtdc.android.impl.AndroidUiDate; import rtdc.android.impl.AndroidUiDropdownList; import rtdc.android.impl.AndroidUiString; import rtdc.core.controller.AddActionController; import rtdc.core.impl.UiDropdownList; import rtdc.core.impl.UiElement; import rtdc.core.model.Action; import rtdc.core.util.Cache; import rtdc.core.view.AddActionView; import java.util.Date; public class CreateActionActivity extends AbstractActivity implements AddActionView { private AddActionController controller; private AndroidUiString roleEdit, targetEdit, descriptionEdit; private AndroidUiDate deadlineEdit; private AndroidUiDropdownList unitSpinner, statusSpinner, taskSpinner; private Action currentAction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_action); roleEdit = (AndroidUiString) findViewById(R.id.roleEdit); targetEdit = (AndroidUiString) findViewById(R.id.targetEdit); deadlineEdit = (AndroidUiDate) findViewById(R.id.deadlineEdit); descriptionEdit = (AndroidUiString) findViewById(R.id.descriptionEdit); unitSpinner = (AndroidUiDropdownList) findViewById(R.id.unitSpinner); statusSpinner = (AndroidUiDropdownList) findViewById(R.id.statusSpinner); taskSpinner = (AndroidUiDropdownList) findViewById(R.id.actionSpinner); currentAction = (Action) Cache.getInstance().retrieve("action"); if (currentAction != null) { getRoleUiElement().setValue(currentAction.getRoleResponsible()); getTargetUiElement().setValue(currentAction.getTarget()); getDeadlineUiElement().setValue(currentAction.getDeadline()); getDescriptionUiElement().setValue(currentAction.getDescription()); getUnitUiElement().setValue(currentAction.getUnit().getName()); getStatusUiElement().setValue(currentAction.getStatus()); getTaskUiElement().setValue(currentAction.getTask()); } ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); if(controller == null) controller = new AddActionController(this); } @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_create_action, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will Intent intent; switch (item.getItemId()) { case R.id.action_save_action: if (currentAction != null) Cache.getInstance().put("action", currentAction); controller.addAction(); intent = new Intent(this, ActionPlanActivity.class); startActivity(intent); return true; case R.id.action_cancel_action: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public UiDropdownList<String> getUnitUiElement() { return unitSpinner; } @Override public UiDropdownList<String> getStatusUiElement() { return statusSpinner; } @Override public UiElement<String> getRoleUiElement() { return roleEdit; } @Override public UiDropdownList<String> getTaskUiElement() { return taskSpinner; } @Override public UiElement<String> getTargetUiElement() { return targetEdit; } @Override public UiElement<Date> getDeadlineUiElement() { return deadlineEdit; } @Override public UiElement<String> getDescriptionUiElement() { return descriptionEdit; } }
Pour corriger le dernier merge
android/src/main/java/rtdc/android/presenter/CreateActionActivity.java
Pour corriger le dernier merge
<ide><path>ndroid/src/main/java/rtdc/android/presenter/CreateActionActivity.java <ide> private AndroidUiDate deadlineEdit; <ide> private AndroidUiDropdownList unitSpinner, statusSpinner, taskSpinner; <ide> <del> private Action currentAction; <del> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> unitSpinner = (AndroidUiDropdownList) findViewById(R.id.unitSpinner); <ide> statusSpinner = (AndroidUiDropdownList) findViewById(R.id.statusSpinner); <ide> taskSpinner = (AndroidUiDropdownList) findViewById(R.id.actionSpinner); <del> <del> currentAction = (Action) Cache.getInstance().retrieve("action"); <del> if (currentAction != null) { <del> getRoleUiElement().setValue(currentAction.getRoleResponsible()); <del> getTargetUiElement().setValue(currentAction.getTarget()); <del> getDeadlineUiElement().setValue(currentAction.getDeadline()); <del> getDescriptionUiElement().setValue(currentAction.getDescription()); <del> getUnitUiElement().setValue(currentAction.getUnit().getName()); <del> getStatusUiElement().setValue(currentAction.getStatus()); <del> getTaskUiElement().setValue(currentAction.getTask()); <del> } <ide> <ide> ActionBar actionBar = getActionBar(); <ide> actionBar.setDisplayHomeAsUpEnabled(true); <ide> @Override <ide> public boolean onOptionsItemSelected(MenuItem item) { <ide> // Handle action bar item clicks here. The action bar will <del> Intent intent; <ide> switch (item.getItemId()) { <ide> case R.id.action_save_action: <del> if (currentAction != null) <del> Cache.getInstance().put("action", currentAction); <ide> controller.addAction(); <del> intent = new Intent(this, ActionPlanActivity.class); <del> startActivity(intent); <ide> return true; <ide> case R.id.action_cancel_action: <ide> finish();
Java
lgpl-2.1
a3431b30388fde1e8a276d0934895de85e46cee4
0
Anaphory/beast2,tgvaughan/beast2,tgvaughan/beast2,tgvaughan/beast2,CompEvol/beast2,Anaphory/beast2,CompEvol/beast2,tgvaughan/beast2,Anaphory/beast2,CompEvol/beast2,CompEvol/beast2,Anaphory/beast2
package beast.app.beauti; import beast.app.draw.*; import beast.core.*; import beast.core.parameter.IntegerParameter; import beast.core.parameter.RealParameter; import beast.core.util.CompoundDistribution; import beast.evolution.alignment.Alignment; import beast.evolution.likelihood.GenericTreeLikelihood; import beast.evolution.operators.DeltaExchangeOperator; import beast.evolution.sitemodel.SiteModel; import beast.evolution.sitemodel.SiteModelInterface; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; public class SiteModelInputEditor extends BEASTObjectInputEditor { private static final long serialVersionUID = 1L; IntegerInputEditor categoryCountEditor; JTextField categoryCountEntry; InputEditor gammaShapeEditor; ParameterInputEditor inVarEditor; // vars for dealing with mean-rate delta exchange operator JCheckBox fixMeanRatesCheckBox; DeltaExchangeOperator operator; protected SmallLabel fixMeanRatesValidateLabel; public SiteModelInputEditor(BeautiDoc doc) { super(doc); } @Override public Class<?> type() { return SiteModelInterface.Base.class; } @Override public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) { fixMeanRatesCheckBox = new JCheckBox("Fix mean substitution rate"); fixMeanRatesCheckBox.setName("FixMeanMutationRate"); fixMeanRatesCheckBox.setEnabled(!doc.autoUpdateFixMeanSubstRate); super.init(input, beastObject, itemNr, isExpandOption, addButtons); List<Operator> operators = ((MCMC) doc.mcmc.get()).operatorsInput.get(); fixMeanRatesCheckBox.addActionListener(e -> { JCheckBox averageRatesBox = (JCheckBox) e.getSource(); doFixMeanRates(averageRatesBox.isSelected()); if (averageRatesBox.isSelected()) // set up relative weights setUpOperator(); }); operator = (DeltaExchangeOperator) doc.pluginmap.get("FixMeanMutationRatesOperator"); if (operator == null) { operator = new DeltaExchangeOperator(); try { operator.setID("FixMeanMutationRatesOperator"); operator.initByName("weight", 2.0, "delta", 0.75, "parameter", new RealParameter(new Double[] { 1., 1., 1., 1. })); } catch (Throwable e1) { // ignore initAndValidate exception } doc.addPlugin(operator); } fixMeanRatesCheckBox.setSelected(operators.contains(operator)); Box box = Box.createHorizontalBox(); box.add(fixMeanRatesCheckBox); box.add(Box.createHorizontalGlue()); fixMeanRatesValidateLabel = new SmallLabel("x", Color.GREEN); fixMeanRatesValidateLabel.setVisible(false); box.add(fixMeanRatesValidateLabel); if (doc.alignments.size() >= 1 && operator != null) { JComponent component = (JComponent) getComponents()[0]; component.add(box); } setUpOperator(); } // @Override // public Class<?> [] types() { // Class<?>[] types = {SiteModel.class, SiteModel.Base.class}; // return types; // } private void doFixMeanRates(boolean averageRates) { List<Operator> operators = ((MCMC) doc.mcmc.get()).operatorsInput.get(); if (averageRates) { // connect DeltaExchangeOperator if (!operators.contains(operator)) { operators.add(operator); } } else { operators.remove(operator); fixMeanRatesValidateLabel.setVisible(false); repaint(); } } public InputEditor createMutationRateEditor() { SiteModel sitemodel = ((SiteModel) m_input.get()); final Input<?> input = sitemodel.muParameterInput; ParameterInputEditor mutationRateEditor = new ParameterInputEditor(doc); mutationRateEditor.init(input, sitemodel, -1, ExpandOption.FALSE, true); mutationRateEditor.getEntry().setEnabled(!doc.autoUpdateFixMeanSubstRate); return mutationRateEditor; } public InputEditor createGammaCategoryCountEditor() { SiteModel sitemodel = ((SiteModel) m_input.get()); final Input<?> input = sitemodel.gammaCategoryCount; categoryCountEditor = new IntegerInputEditor(doc) { private static final long serialVersionUID = 1L; @Override public void validateInput() { super.validateInput(); SiteModel sitemodel = (SiteModel) m_beastObject; if (sitemodel.gammaCategoryCount.get() < 2 && sitemodel.shapeParameterInput.get().isEstimatedInput.get()) { m_validateLabel.m_circleColor = Color.orange; m_validateLabel.setToolTipText("shape parameter is estimated, but not used"); m_validateLabel.setVisible(true); } }; }; categoryCountEditor.init(input, sitemodel, -1, ExpandOption.FALSE, true); categoryCountEntry = categoryCountEditor.getEntry(); categoryCountEntry.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { processEntry2(); } @Override public void insertUpdate(DocumentEvent e) { processEntry2(); } @Override public void changedUpdate(DocumentEvent e) { processEntry2(); } }); categoryCountEditor.validateInput(); return categoryCountEditor; } void processEntry2() { String categories = categoryCountEntry.getText(); try { int categoryCount = Integer.parseInt(categories); RealParameter shapeParameter = ((SiteModel) m_input.get()).shapeParameterInput.get(); if (!gammaShapeEditor.getComponent().isVisible() && categoryCount >= 2) { // we are flipping from no gamma to gamma heterogeneity accross sites // so set the estimate flag on the shape parameter shapeParameter.isEstimatedInput.setValue(true, shapeParameter); } else if (gammaShapeEditor.getComponent().isVisible() && categoryCount < 2) { // we are flipping from with gamma to no gamma heterogeneity accross sites // so unset the estimate flag on the shape parameter shapeParameter.isEstimatedInput.setValue(false, shapeParameter); } Object o = ((ParameterInputEditor)gammaShapeEditor).getComponent(); if (o instanceof ParameterInputEditor) { ParameterInputEditor e = (ParameterInputEditor) o; e.m_isEstimatedBox.setSelected(shapeParameter.isEstimatedInput.get()); } gammaShapeEditor.getComponent().setVisible(categoryCount >= 2); repaint(); } catch (java.lang.NumberFormatException e) { // ignore. } } public InputEditor createShapeEditor() throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final Input<?> input = ((SiteModel) m_input.get()).shapeParameterInput; gammaShapeEditor = doc.getInputEditorFactory().createInputEditor(input, (BEASTInterface) m_input.get(), doc); gammaShapeEditor.getComponent().setVisible(((SiteModel) m_input.get()).gammaCategoryCount.get() >= 2); return gammaShapeEditor; } public InputEditor createProportionInvariantEditor() { final Input<?> input = ((SiteModel) m_input.get()).invarParameterInput; inVarEditor = new ParameterInputEditor(doc) { private static final long serialVersionUID = 1L; @Override public void validateInput() { RealParameter p = (RealParameter) m_input.get(); if (p.isEstimatedInput.get() && p.valuesInput.get().get(0) <= 0.0) { m_validateLabel.setVisible(true); m_validateLabel.setToolTipText("<html><p>Proportion invariant should be non-zero when estimating</p></html>"); return; } if (p.valuesInput.get().get(0) < 0.0 || p.valuesInput.get().get(0) >= 1.0) { m_validateLabel.setVisible(true); m_validateLabel.setToolTipText("<html><p>Proportion invariant should be from 0 to 1 (exclusive 1)</p></html>"); return; } super.validateInput(); } }; inVarEditor.init(input, (BEASTInterface) m_input.get(), -1, ExpandOption.FALSE, true); inVarEditor.addValidationListener(this); return inVarEditor; } public static boolean customConnector(BeautiDoc doc) { try { DeltaExchangeOperator operator = (DeltaExchangeOperator) doc.pluginmap.get("FixMeanMutationRatesOperator"); if (operator == null) { return false; } List<RealParameter> parameters = operator.parameterInput.get(); parameters.clear(); //String weights = ""; CompoundDistribution likelihood = (CompoundDistribution) doc.pluginmap.get("likelihood"); boolean hasOneEstimatedRate = false; List<String> rateIDs = new ArrayList<>(); List<Integer> weights = new ArrayList<>(); for (Distribution d : likelihood.pDistributions.get()) { GenericTreeLikelihood treelikelihood = (GenericTreeLikelihood) d; Alignment data = treelikelihood.dataInput.get(); int weight = data.getSiteCount(); if (data.isAscertained) { weight -= data.getExcludedPatternCount(); } if (treelikelihood.siteModelInput.get() instanceof SiteModel) { SiteModel siteModel = (SiteModel) treelikelihood.siteModelInput.get(); RealParameter mutationRate = siteModel.muParameterInput.get(); //clockRate.m_bIsEstimated.setValue(true, clockRate); if (mutationRate.isEstimatedInput.get()) { hasOneEstimatedRate = true; if (rateIDs.indexOf(mutationRate.getID()) == -1) { parameters.add(mutationRate); weights.add(weight); rateIDs.add(mutationRate.getID()); } else { int k = rateIDs.indexOf(mutationRate.getID()); weights.set(k, weights.get(k) + weight); } } } } IntegerParameter weightParameter; if (weights.size() == 0) { weightParameter = new IntegerParameter(); } else { String weightString = ""; for (int k : weights) { weightString += k + " "; } weightParameter = new IntegerParameter(weightString); weightParameter.setID("weightparameter"); } weightParameter.isEstimatedInput.setValue(false, weightParameter); operator.parameterWeightsInput.setValue(weightParameter, operator); return hasOneEstimatedRate; } catch (Exception e) { } return false; } /** set up relative weights and parameter input **/ public void setUpOperator() { boolean isAllClocksAreEqual = true; try { boolean hasOneEstimatedRate = customConnector(doc); if (doc.autoUpdateFixMeanSubstRate) { fixMeanRatesCheckBox.setSelected(hasOneEstimatedRate); doFixMeanRates(hasOneEstimatedRate); } try { double commonClockRate = -1; CompoundDistribution likelihood = (CompoundDistribution) doc.pluginmap.get("likelihood"); for (Distribution d : likelihood.pDistributions.get()) { GenericTreeLikelihood treelikelihood = (GenericTreeLikelihood) d; if (treelikelihood.siteModelInput.get() instanceof SiteModel) { SiteModel siteModel = (SiteModel) treelikelihood.siteModelInput.get(); RealParameter mutationRate = siteModel.muParameterInput.get(); //clockRate.m_bIsEstimated.setValue(true, clockRate); if (mutationRate.isEstimatedInput.get()) { if (commonClockRate < 0) { commonClockRate = mutationRate.valuesInput.get().get(0); } else { if (Math.abs(commonClockRate - mutationRate.valuesInput.get().get(0)) > 1e-10) { isAllClocksAreEqual = false; } } } } } } catch (Exception e) { } List<RealParameter> parameters = operator.parameterInput.get(); if (!fixMeanRatesCheckBox.isSelected()) { fixMeanRatesValidateLabel.setVisible(false); repaint(); return; } if (parameters.size() == 0) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.red; fixMeanRatesValidateLabel.setToolTipText("The model is invalid: At least one substitution rate should be estimated."); repaint(); return; } if (!isAllClocksAreEqual) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.orange; fixMeanRatesValidateLabel.setToolTipText("Not all substitution rates are equal. Are you sure this is what you want?"); } else if (parameters.size() == 1) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.orange; fixMeanRatesValidateLabel.setToolTipText("At least 2 clock models should have their rate estimated"); } else if (parameters.size() < doc.getPartitions("SiteModel").size()) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.orange; fixMeanRatesValidateLabel.setToolTipText("Not all partitions have their rate estimated"); } else { fixMeanRatesValidateLabel.setVisible(false); } repaint(); } catch (Exception e) { e.printStackTrace(); } } }
src/beast/app/beauti/SiteModelInputEditor.java
package beast.app.beauti; import java.awt.Color; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import beast.app.draw.BEASTObjectInputEditor; import beast.app.draw.InputEditor; import beast.app.draw.IntegerInputEditor; import beast.app.draw.ParameterInputEditor; import beast.app.draw.SmallLabel; import beast.core.BEASTInterface; import beast.core.Distribution; import beast.core.Input; import beast.core.MCMC; import beast.core.Operator; import beast.core.parameter.IntegerParameter; import beast.core.parameter.RealParameter; import beast.core.util.CompoundDistribution; import beast.evolution.alignment.Alignment; import beast.evolution.likelihood.GenericTreeLikelihood; import beast.evolution.operators.DeltaExchangeOperator; import beast.evolution.sitemodel.SiteModel; import beast.evolution.sitemodel.SiteModelInterface; public class SiteModelInputEditor extends BEASTObjectInputEditor { private static final long serialVersionUID = 1L; IntegerInputEditor categoryCountEditor; JTextField categoryCountEntry; InputEditor gammaShapeEditor; ParameterInputEditor inVarEditor; // vars for dealing with mean-rate delta exchange operator JCheckBox fixMeanRatesCheckBox; DeltaExchangeOperator operator; protected SmallLabel fixMeanRatesValidateLabel; public SiteModelInputEditor(BeautiDoc doc) { super(doc); } @Override public Class<?> type() { return SiteModelInterface.Base.class; } @Override public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) { fixMeanRatesCheckBox = new JCheckBox("Fix mean substitution rate"); fixMeanRatesCheckBox.setName("FixMeanMutationRate"); fixMeanRatesCheckBox.setEnabled(!doc.autoUpdateFixMeanSubstRate); super.init(input, beastObject, itemNr, isExpandOption, addButtons); List<Operator> operators = ((MCMC) doc.mcmc.get()).operatorsInput.get(); fixMeanRatesCheckBox.addActionListener(e -> { JCheckBox averageRatesBox = (JCheckBox) e.getSource(); doFixMeanRates(averageRatesBox.isSelected()); if (averageRatesBox.isSelected()) // set up relative weights setUpOperator(); }); operator = (DeltaExchangeOperator) doc.pluginmap.get("FixMeanMutationRatesOperator"); if (operator == null) { operator = new DeltaExchangeOperator(); try { operator.setID("FixMeanMutationRatesOperator"); operator.initByName("weight", 2.0, "delta", 0.75); } catch (Throwable e1) { // ignore initAndValidate exception } doc.addPlugin(operator); } fixMeanRatesCheckBox.setSelected(operators.contains(operator)); Box box = Box.createHorizontalBox(); box.add(fixMeanRatesCheckBox); box.add(Box.createHorizontalGlue()); fixMeanRatesValidateLabel = new SmallLabel("x", Color.GREEN); fixMeanRatesValidateLabel.setVisible(false); box.add(fixMeanRatesValidateLabel); if (doc.alignments.size() >= 1 && operator != null) { JComponent component = (JComponent) getComponents()[0]; component.add(box); } setUpOperator(); } // @Override // public Class<?> [] types() { // Class<?>[] types = {SiteModel.class, SiteModel.Base.class}; // return types; // } private void doFixMeanRates(boolean averageRates) { List<Operator> operators = ((MCMC) doc.mcmc.get()).operatorsInput.get(); if (averageRates) { // connect DeltaExchangeOperator if (!operators.contains(operator)) { operators.add(operator); } } else { operators.remove(operator); fixMeanRatesValidateLabel.setVisible(false); repaint(); } } public InputEditor createMutationRateEditor() { SiteModel sitemodel = ((SiteModel) m_input.get()); final Input<?> input = sitemodel.muParameterInput; ParameterInputEditor mutationRateEditor = new ParameterInputEditor(doc); mutationRateEditor.init(input, sitemodel, -1, ExpandOption.FALSE, true); mutationRateEditor.getEntry().setEnabled(!doc.autoUpdateFixMeanSubstRate); return mutationRateEditor; } public InputEditor createGammaCategoryCountEditor() { SiteModel sitemodel = ((SiteModel) m_input.get()); final Input<?> input = sitemodel.gammaCategoryCount; categoryCountEditor = new IntegerInputEditor(doc) { private static final long serialVersionUID = 1L; @Override public void validateInput() { super.validateInput(); SiteModel sitemodel = (SiteModel) m_beastObject; if (sitemodel.gammaCategoryCount.get() < 2 && sitemodel.shapeParameterInput.get().isEstimatedInput.get()) { m_validateLabel.m_circleColor = Color.orange; m_validateLabel.setToolTipText("shape parameter is estimated, but not used"); m_validateLabel.setVisible(true); } }; }; categoryCountEditor.init(input, sitemodel, -1, ExpandOption.FALSE, true); categoryCountEntry = categoryCountEditor.getEntry(); categoryCountEntry.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { processEntry2(); } @Override public void insertUpdate(DocumentEvent e) { processEntry2(); } @Override public void changedUpdate(DocumentEvent e) { processEntry2(); } }); categoryCountEditor.validateInput(); return categoryCountEditor; } void processEntry2() { String categories = categoryCountEntry.getText(); try { int categoryCount = Integer.parseInt(categories); RealParameter shapeParameter = ((SiteModel) m_input.get()).shapeParameterInput.get(); if (!gammaShapeEditor.getComponent().isVisible() && categoryCount >= 2) { // we are flipping from no gamma to gamma heterogeneity accross sites // so set the estimate flag on the shape parameter shapeParameter.isEstimatedInput.setValue(true, shapeParameter); } else if (gammaShapeEditor.getComponent().isVisible() && categoryCount < 2) { // we are flipping from with gamma to no gamma heterogeneity accross sites // so unset the estimate flag on the shape parameter shapeParameter.isEstimatedInput.setValue(false, shapeParameter); } Object o = ((ParameterInputEditor)gammaShapeEditor).getComponent(); if (o instanceof ParameterInputEditor) { ParameterInputEditor e = (ParameterInputEditor) o; e.m_isEstimatedBox.setSelected(shapeParameter.isEstimatedInput.get()); } gammaShapeEditor.getComponent().setVisible(categoryCount >= 2); repaint(); } catch (java.lang.NumberFormatException e) { // ignore. } } public InputEditor createShapeEditor() throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final Input<?> input = ((SiteModel) m_input.get()).shapeParameterInput; gammaShapeEditor = doc.getInputEditorFactory().createInputEditor(input, (BEASTInterface) m_input.get(), doc); gammaShapeEditor.getComponent().setVisible(((SiteModel) m_input.get()).gammaCategoryCount.get() >= 2); return gammaShapeEditor; } public InputEditor createProportionInvariantEditor() { final Input<?> input = ((SiteModel) m_input.get()).invarParameterInput; inVarEditor = new ParameterInputEditor(doc) { private static final long serialVersionUID = 1L; @Override public void validateInput() { RealParameter p = (RealParameter) m_input.get(); if (p.isEstimatedInput.get() && p.valuesInput.get().get(0) <= 0.0) { m_validateLabel.setVisible(true); m_validateLabel.setToolTipText("<html><p>Proportion invariant should be non-zero when estimating</p></html>"); return; } if (p.valuesInput.get().get(0) < 0.0 || p.valuesInput.get().get(0) >= 1.0) { m_validateLabel.setVisible(true); m_validateLabel.setToolTipText("<html><p>Proportion invariant should be from 0 to 1 (exclusive 1)</p></html>"); return; } super.validateInput(); } }; inVarEditor.init(input, (BEASTInterface) m_input.get(), -1, ExpandOption.FALSE, true); inVarEditor.addValidationListener(this); return inVarEditor; } public static boolean customConnector(BeautiDoc doc) { try { DeltaExchangeOperator operator = (DeltaExchangeOperator) doc.pluginmap.get("FixMeanMutationRatesOperator"); if (operator == null) { return false; } List<RealParameter> parameters = operator.parameterInput.get(); parameters.clear(); //String weights = ""; CompoundDistribution likelihood = (CompoundDistribution) doc.pluginmap.get("likelihood"); boolean hasOneEstimatedRate = false; List<String> rateIDs = new ArrayList<>(); List<Integer> weights = new ArrayList<>(); for (Distribution d : likelihood.pDistributions.get()) { GenericTreeLikelihood treelikelihood = (GenericTreeLikelihood) d; Alignment data = treelikelihood.dataInput.get(); int weight = data.getSiteCount(); if (data.isAscertained) { weight -= data.getExcludedPatternCount(); } if (treelikelihood.siteModelInput.get() instanceof SiteModel) { SiteModel siteModel = (SiteModel) treelikelihood.siteModelInput.get(); RealParameter mutationRate = siteModel.muParameterInput.get(); //clockRate.m_bIsEstimated.setValue(true, clockRate); if (mutationRate.isEstimatedInput.get()) { hasOneEstimatedRate = true; if (rateIDs.indexOf(mutationRate.getID()) == -1) { parameters.add(mutationRate); weights.add(weight); rateIDs.add(mutationRate.getID()); } else { int k = rateIDs.indexOf(mutationRate.getID()); weights.set(k, weights.get(k) + weight); } } } } IntegerParameter weightParameter; if (weights.size() == 0) { weightParameter = new IntegerParameter(); } else { String weightString = ""; for (int k : weights) { weightString += k + " "; } weightParameter = new IntegerParameter(weightString); weightParameter.setID("weightparameter"); } weightParameter.isEstimatedInput.setValue(false, weightParameter); operator.parameterWeightsInput.setValue(weightParameter, operator); return hasOneEstimatedRate; } catch (Exception e) { } return false; } /** set up relative weights and parameter input **/ public void setUpOperator() { boolean isAllClocksAreEqual = true; try { boolean hasOneEstimatedRate = customConnector(doc); if (doc.autoUpdateFixMeanSubstRate) { fixMeanRatesCheckBox.setSelected(hasOneEstimatedRate); doFixMeanRates(hasOneEstimatedRate); } try { double commonClockRate = -1; CompoundDistribution likelihood = (CompoundDistribution) doc.pluginmap.get("likelihood"); for (Distribution d : likelihood.pDistributions.get()) { GenericTreeLikelihood treelikelihood = (GenericTreeLikelihood) d; if (treelikelihood.siteModelInput.get() instanceof SiteModel) { SiteModel siteModel = (SiteModel) treelikelihood.siteModelInput.get(); RealParameter mutationRate = siteModel.muParameterInput.get(); //clockRate.m_bIsEstimated.setValue(true, clockRate); if (mutationRate.isEstimatedInput.get()) { if (commonClockRate < 0) { commonClockRate = mutationRate.valuesInput.get().get(0); } else { if (Math.abs(commonClockRate - mutationRate.valuesInput.get().get(0)) > 1e-10) { isAllClocksAreEqual = false; } } } } } } catch (Exception e) { } List<RealParameter> parameters = operator.parameterInput.get(); if (!fixMeanRatesCheckBox.isSelected()) { fixMeanRatesValidateLabel.setVisible(false); repaint(); return; } if (parameters.size() == 0) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.red; fixMeanRatesValidateLabel.setToolTipText("The model is invalid: At least one substitution rate should be estimated."); repaint(); return; } if (!isAllClocksAreEqual) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.orange; fixMeanRatesValidateLabel.setToolTipText("Not all substitution rates are equal. Are you sure this is what you want?"); } else if (parameters.size() == 1) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.orange; fixMeanRatesValidateLabel.setToolTipText("At least 2 clock models should have their rate estimated"); } else if (parameters.size() < doc.getPartitions("SiteModel").size()) { fixMeanRatesValidateLabel.setVisible(true); fixMeanRatesValidateLabel.m_circleColor = Color.orange; fixMeanRatesValidateLabel.setToolTipText("Not all partitions have their rate estimated"); } else { fixMeanRatesValidateLabel.setVisible(false); } repaint(); } catch (Exception e) { e.printStackTrace(); } } }
BEAUti SiteModelInputEditor DeltaExchangeOperator init exception #740
src/beast/app/beauti/SiteModelInputEditor.java
BEAUti SiteModelInputEditor DeltaExchangeOperator init exception #740
<ide><path>rc/beast/app/beauti/SiteModelInputEditor.java <ide> package beast.app.beauti; <ide> <ide> <del>import java.awt.Color; <del>import java.lang.reflect.InvocationTargetException; <del>import java.util.ArrayList; <del>import java.util.List; <del> <del>import javax.swing.Box; <del>import javax.swing.JCheckBox; <del>import javax.swing.JComponent; <del>import javax.swing.JTextField; <del>import javax.swing.event.DocumentEvent; <del>import javax.swing.event.DocumentListener; <del> <del>import beast.app.draw.BEASTObjectInputEditor; <del>import beast.app.draw.InputEditor; <del>import beast.app.draw.IntegerInputEditor; <del>import beast.app.draw.ParameterInputEditor; <del>import beast.app.draw.SmallLabel; <del>import beast.core.BEASTInterface; <del>import beast.core.Distribution; <del>import beast.core.Input; <del>import beast.core.MCMC; <del>import beast.core.Operator; <add>import beast.app.draw.*; <add>import beast.core.*; <ide> import beast.core.parameter.IntegerParameter; <ide> import beast.core.parameter.RealParameter; <ide> import beast.core.util.CompoundDistribution; <ide> import beast.evolution.operators.DeltaExchangeOperator; <ide> import beast.evolution.sitemodel.SiteModel; <ide> import beast.evolution.sitemodel.SiteModelInterface; <add> <add>import javax.swing.*; <add>import javax.swing.event.DocumentEvent; <add>import javax.swing.event.DocumentListener; <add>import java.awt.*; <add>import java.lang.reflect.InvocationTargetException; <add>import java.util.ArrayList; <add>import java.util.List; <ide> <ide> public class SiteModelInputEditor extends BEASTObjectInputEditor { <ide> private static final long serialVersionUID = 1L; <ide> operator = new DeltaExchangeOperator(); <ide> try { <ide> operator.setID("FixMeanMutationRatesOperator"); <del> operator.initByName("weight", 2.0, "delta", 0.75); <add> operator.initByName("weight", 2.0, "delta", 0.75, <add> "parameter", new RealParameter(new Double[] { 1., 1., 1., 1. })); <ide> } catch (Throwable e1) { <ide> // ignore initAndValidate exception <ide> }
Java
apache-2.0
e8836084e77341d54fd44eb4088c6211355047aa
0
opencb/opencga,opencb/opencga,opencb/opencga,opencb/opencga,opencb/opencga,opencb/opencga
package org.opencb.opencga.analysis.rga; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import org.apache.commons.lang3.time.StopWatch; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrException; import org.opencb.commons.datastore.core.*; import org.opencb.commons.utils.CollectionUtils; import org.opencb.opencga.analysis.rga.exceptions.RgaException; import org.opencb.opencga.analysis.rga.iterators.RgaIterator; import org.opencb.opencga.analysis.variant.manager.VariantStorageManager; import org.opencb.opencga.catalog.db.api.SampleDBAdaptor; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.AbstractManager; import org.opencb.opencga.catalog.managers.CatalogManager; import org.opencb.opencga.catalog.managers.FileManager; import org.opencb.opencga.catalog.managers.SampleManager; import org.opencb.opencga.catalog.utils.ParamUtils; import org.opencb.opencga.core.common.TimeUtils; import org.opencb.opencga.core.config.Configuration; import org.opencb.opencga.core.config.storage.StorageConfiguration; import org.opencb.opencga.core.models.analysis.knockout.*; import org.opencb.opencga.core.models.common.RgaIndex; import org.opencb.opencga.core.models.file.File; import org.opencb.opencga.core.models.sample.Sample; import org.opencb.opencga.core.models.sample.SampleAclEntry; import org.opencb.opencga.core.models.study.Study; import org.opencb.opencga.core.response.OpenCGAResult; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.io.managers.IOConnectorProvider; import org.opencb.opencga.storage.core.variant.adaptors.VariantField; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam; import org.opencb.opencga.storage.core.variant.adaptors.iterators.VariantDBIterator; import org.opencb.opencga.storage.core.variant.query.VariantQueryUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import static org.opencb.opencga.core.api.ParamConstants.ACL_PARAM; public class RgaManager implements AutoCloseable { private CatalogManager catalogManager; private StorageConfiguration storageConfiguration; private final RgaEngine rgaEngine; private final VariantStorageManager variantStorageManager; private IndividualRgaConverter individualRgaConverter; private GeneRgaConverter geneConverter; private VariantRgaConverter variantConverter; private final Logger logger; private static final int KNOCKOUT_INSERT_BATCH_SIZE = 25; private static ExecutorService executor; static { executor = Executors.newCachedThreadPool(); } public RgaManager(CatalogManager catalogManager, VariantStorageManager variantStorageManager, StorageEngineFactory storageEngineFactory) { this.catalogManager = catalogManager; this.storageConfiguration = storageEngineFactory.getStorageConfiguration(); this.rgaEngine = new RgaEngine(storageConfiguration); this.variantStorageManager = variantStorageManager; this.individualRgaConverter = new IndividualRgaConverter(); this.geneConverter = new GeneRgaConverter(); this.variantConverter = new VariantRgaConverter(); this.logger = LoggerFactory.getLogger(getClass()); } public RgaManager(Configuration configuration, StorageConfiguration storageConfiguration) throws CatalogException { this.catalogManager = new CatalogManager(configuration); this.storageConfiguration = storageConfiguration; StorageEngineFactory storageEngineFactory = StorageEngineFactory.get(storageConfiguration); this.variantStorageManager = new VariantStorageManager(catalogManager, storageEngineFactory); this.rgaEngine = new RgaEngine(storageConfiguration); this.individualRgaConverter = new IndividualRgaConverter(); this.geneConverter = new GeneRgaConverter(); this.variantConverter = new VariantRgaConverter(); this.logger = LoggerFactory.getLogger(getClass()); } public RgaManager(Configuration configuration, StorageConfiguration storageConfiguration, VariantStorageManager variantStorageManager, RgaEngine rgaEngine) throws CatalogException { this.catalogManager = new CatalogManager(configuration); this.storageConfiguration = storageConfiguration; this.rgaEngine = rgaEngine; this.variantStorageManager = variantStorageManager; this.individualRgaConverter = new IndividualRgaConverter(); this.geneConverter = new GeneRgaConverter(); this.variantConverter = new VariantRgaConverter(); this.logger = LoggerFactory.getLogger(getClass()); } public OpenCGAResult<KnockoutByIndividual> individualQuery(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); Preprocess preprocess; try { preprocess = individualQueryPreprocess(study, query, options, token); } catch (RgaException e) { if (RgaException.NO_RESULTS_FOUND.equals(e.getMessage())) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByIndividual.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } throw e; } catch (CatalogException | IOException e) { throw e; } RgaIterator rgaIterator = rgaEngine.individualQuery(collection, preprocess.getQuery(), QueryOptions.empty()); List<KnockoutByIndividual> knockoutByIndividuals = individualRgaConverter.convertToDataModelType(rgaIterator); int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByIndividual> result = new OpenCGAResult<>(time, Collections.emptyList(), knockoutByIndividuals.size(), knockoutByIndividuals, -1); if (preprocess.getQueryOptions().getBoolean(QueryOptions.COUNT)) { result.setNumMatches(preprocess.getNumTotalResults()); } if (preprocess.getEvent() != null) { result.setEvents(Collections.singletonList(preprocess.getEvent())); } return result; } public OpenCGAResult<RgaKnockoutByGene> geneQuery(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions queryOptions = setDefaultLimit(options); List<String> includeIndividuals = queryOptions.getAsStringList(RgaQueryParams.INCLUDE_INDIVIDUAL); Boolean isOwnerOrAdmin = catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); Query auxQuery = query != null ? new Query(query) : new Query(); // Get numTotalResults in a future Future<Integer> numTotalResults = null; if (queryOptions.getBoolean(QueryOptions.COUNT)) { numTotalResults = executor.submit(() -> { QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, "unique(" + RgaDataModel.GENE_ID + ")"); try { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); return ((Number) result.first().getAggregationValues().get(0)).intValue(); } catch (Exception e) { e.printStackTrace(); } return -1; }); } // If the user is querying by gene id, we don't need to do a facet first if (!auxQuery.containsKey(RgaDataModel.GENE_ID)) { // 1st. we perform a facet to get the different gene ids matching the user query and using the skip and limit values QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, RgaDataModel.GENE_ID); facetOptions.putIfNotNull(QueryOptions.LIMIT, queryOptions.get(QueryOptions.LIMIT)); facetOptions.putIfNotNull(QueryOptions.SKIP, queryOptions.get(QueryOptions.SKIP)); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(RgaKnockoutByGene.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> geneIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); auxQuery.put(RgaDataModel.GENE_ID, geneIds); } // Fetch all individuals matching the user query if (!auxQuery.containsKey("sampleId") && !auxQuery.containsKey("individualId") && includeIndividuals.isEmpty()) { // We perform a facet to get the different individual ids matching the user query DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, new QueryOptions(QueryOptions.FACET, RgaDataModel.INDIVIDUAL_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(RgaKnockoutByGene.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } includeIndividuals = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); } // Get the set of sample ids the user will be able to see Set<String> includeSampleIds; if (!isOwnerOrAdmin) { if (!includeIndividuals.isEmpty()) { // 3. Get list of indexed sample ids for which the user has permissions from the list of includeIndividuals provided Query sampleQuery = new Query() .append(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED) .append(SampleDBAdaptor.QueryParams.ID.key(), includeIndividuals); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } else { // 2. Check permissions DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, new QueryOptions(QueryOptions.FACET, RgaDataModel.SAMPLE_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(RgaKnockoutByGene.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> sampleIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); // 3. Get list of sample ids for which the user has permissions Query sampleQuery = new Query(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.ID.key(), sampleIds); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); // TODO: The number of samples to include could be really high includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } } else { // TODO: Check if samples or individuals are provided // Obtain samples Query sampleQuery = new Query(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED); if (!includeIndividuals.isEmpty()) { query.put(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), includeIndividuals); } else { // TODO: Include only the samples that will be necessary logger.warn("Include only the samples that are actually necessary"); } OpenCGAResult<?> sampleResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) sampleResult.getResults()); } RgaIterator rgaIterator = rgaEngine.geneQuery(collection, auxQuery, queryOptions); int skipIndividuals = queryOptions.getInt(RgaQueryParams.SKIP_INDIVIDUAL); int limitIndividuals = queryOptions.getInt(RgaQueryParams.LIMIT_INDIVIDUAL, RgaQueryParams.DEFAULT_INDIVIDUAL_LIMIT); // 4. Solr gene query List<RgaKnockoutByGene> knockoutResultList = geneConverter.convertToDataModelType(rgaIterator, includeIndividuals, skipIndividuals, limitIndividuals); int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<RgaKnockoutByGene> knockoutResult = new OpenCGAResult<>(time, Collections.emptyList(), knockoutResultList.size(), knockoutResultList, -1); knockoutResult.setTime((int) stopWatch.getTime(TimeUnit.MILLISECONDS)); try { knockoutResult.setNumMatches(numTotalResults != null ? numTotalResults.get() : -1); } catch (InterruptedException | ExecutionException e) { knockoutResult.setNumMatches(-1); } if (isOwnerOrAdmin && includeSampleIds.isEmpty()) { return knockoutResult; } else { // 5. Filter out individual or samples for which user does not have permissions for (RgaKnockoutByGene knockout : knockoutResult.getResults()) { List<RgaKnockoutByGene.KnockoutIndividual> individualList = new ArrayList<>(knockout.getIndividuals().size()); for (RgaKnockoutByGene.KnockoutIndividual individual : knockout.getIndividuals()) { if (includeSampleIds.contains(individual.getSampleId())) { individualList.add(individual); } } knockout.setIndividuals(individualList); } return knockoutResult; } } public OpenCGAResult<KnockoutByVariant> variantQuery(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions queryOptions = setDefaultLimit(options); List<String> includeIndividuals = queryOptions.getAsStringList(RgaQueryParams.INCLUDE_INDIVIDUAL); Boolean isOwnerOrAdmin = catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); Query auxQuery = query != null ? new Query(query) : new Query(); Future<Integer> numTotalResults = null; if (queryOptions.getBoolean(QueryOptions.COUNT)) { numTotalResults = executor.submit(() -> { QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, "unique(" + RgaDataModel.VARIANTS + ")"); try { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); return ((Number) result.first().getAggregationValues().get(0)).intValue(); } catch (Exception e) { logger.error("Could not obtain the count: {}", e.getMessage(), e); } return -1; }); } // If the user is querying by variant id, we don't need to do a facet first if (!auxQuery.containsKey(RgaDataModel.VARIANTS)) { // 1st. we perform a facet to get the different variant ids matching the user query and using the skip and limit values QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, RgaDataModel.VARIANTS); facetOptions.putIfNotNull(QueryOptions.LIMIT, queryOptions.get(QueryOptions.LIMIT)); facetOptions.putIfNotNull(QueryOptions.SKIP, queryOptions.get(QueryOptions.SKIP)); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByVariant.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> variantIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); auxQuery.put(RgaDataModel.VARIANTS, variantIds); } Set<String> includeSampleIds; if (!isOwnerOrAdmin) { if (!includeIndividuals.isEmpty()) { // 3. Get list of sample ids for which the user has permissions from the list of includeIndividuals provided Query sampleQuery = new Query() .append(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED) .append(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), includeIndividuals); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } else { // 2. Check permissions DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, new QueryOptions(QueryOptions.FACET, RgaDataModel.SAMPLE_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByVariant.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> sampleIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue) .collect(Collectors.toList()); // 3. Get list of individual ids for which the user has permissions Query sampleQuery = new Query() .append(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.ID.key(), sampleIds); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } } else { // Obtain samples Query sampleQuery = new Query(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED); if (!includeIndividuals.isEmpty()) { query.put(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), includeIndividuals); } else { // TODO: Include only the samples that will be necessary logger.warn("Include only the samples that are actually necessary"); } OpenCGAResult<?> sampleResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) sampleResult.getResults()); } Future<VariantDBIterator> variantFuture = executor.submit( () -> variantStorageQuery(study.getFqn(), new ArrayList<>(includeSampleIds), auxQuery, options, token) ); Future<RgaIterator> rgaIteratorFuture = executor.submit(() -> rgaEngine.variantQuery(collection, auxQuery, queryOptions)); VariantDBIterator variantDBIterator; try { variantDBIterator = variantFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } RgaIterator rgaIterator; try { rgaIterator = rgaIteratorFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } int skipIndividuals = queryOptions.getInt(RgaQueryParams.SKIP_INDIVIDUAL); int limitIndividuals = queryOptions.getInt(RgaQueryParams.LIMIT_INDIVIDUAL, RgaQueryParams.DEFAULT_INDIVIDUAL_LIMIT); // 4. Solr gene query List<KnockoutByVariant> knockoutResultList = variantConverter.convertToDataModelType(rgaIterator, variantDBIterator, auxQuery.getAsStringList(RgaQueryParams.VARIANTS.key()), includeIndividuals, skipIndividuals, limitIndividuals); int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByVariant> knockoutResult = new OpenCGAResult<>(time, Collections.emptyList(), knockoutResultList.size(), knockoutResultList, -1); knockoutResult.setTime((int) stopWatch.getTime(TimeUnit.MILLISECONDS)); try { knockoutResult.setNumMatches(numTotalResults != null ? numTotalResults.get() : -1); } catch (InterruptedException | ExecutionException e) { knockoutResult.setNumMatches(-1); } if (isOwnerOrAdmin && includeSampleIds.isEmpty()) { return knockoutResult; } else { // 5. Filter out individual or samples for which user does not have permissions for (KnockoutByVariant knockout : knockoutResult.getResults()) { List<KnockoutByIndividual> individualList = new ArrayList<>(knockout.getIndividuals().size()); for (KnockoutByIndividual individual : knockout.getIndividuals()) { if (includeSampleIds.contains(individual.getSampleId())) { individualList.add(individual); } } knockout.setIndividuals(individualList); } return knockoutResult; } } private VariantDBIterator variantStorageQuery(String study, List<String> sampleIds, Query query, QueryOptions options, String token) throws CatalogException, IOException, StorageEngineException, RgaException { String collection = getCollectionName(study); List<String> variantIds = query.getAsStringList(RgaDataModel.VARIANTS); if (variantIds.isEmpty()) { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, query, new QueryOptions(QueryOptions.FACET, RgaDataModel.VARIANTS).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { return VariantDBIterator.EMPTY_ITERATOR; } variantIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); } if (variantIds.size() > RgaQueryParams.DEFAULT_INDIVIDUAL_LIMIT) { throw new RgaException("Too many variants requested"); } Query variantQuery = new Query(VariantQueryParam.ID.key(), variantIds) .append(VariantQueryParam.STUDY.key(), study) .append(VariantQueryParam.INCLUDE_SAMPLE.key(), sampleIds) .append(VariantQueryParam.INCLUDE_SAMPLE_DATA.key(), "GT,DP"); QueryOptions queryOptions = new QueryOptions() .append(QueryOptions.EXCLUDE, Arrays.asList( // VariantField.ANNOTATION_POPULATION_FREQUENCIES, VariantField.ANNOTATION_CYTOBAND, VariantField.ANNOTATION_CONSERVATION, VariantField.ANNOTATION_DRUGS, VariantField.ANNOTATION_GENE_EXPRESSION )); return variantStorageManager.iterator(variantQuery, queryOptions, token); } public OpenCGAResult<Long> updateRgaInternalIndexStatus(String studyStr, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions facetOptions = new QueryOptions() .append(QueryOptions.FACET, RgaDataModel.SAMPLE_ID) .append(QueryOptions.LIMIT, -1); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, new Query(), facetOptions); int totalSamples = result.first().getBuckets().size(); int updatedSamples = 0; // Before doing anything, we first reset all the sample rga indexes OpenCGAResult<Sample> resetResult = catalogManager.getSampleManager().resetRgaIndexes(studyStr, token); logger.debug("Resetting RGA indexes for " + resetResult.getNumMatches() + " samples took " + resetResult.getTime() + " ms."); // Update samples in batches of 100 List<String> sampleIds = new ArrayList<>(100); RgaIndex rgaIndex = new RgaIndex(RgaIndex.Status.INDEXED, TimeUtils.getTime()); for (FacetField.Bucket bucket : result.first().getBuckets()) { sampleIds.add(bucket.getValue()); if (sampleIds.size() == 100) { OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), sampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); sampleIds = new ArrayList<>(100); } } if (!sampleIds.isEmpty()) { // Update last batch OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), sampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); } stopWatch.stop(); return new OpenCGAResult<>((int) stopWatch.getTime(TimeUnit.MILLISECONDS), null, totalSamples, 0, updatedSamples, 0); } public OpenCGAResult<Long> updateRgaInternalIndexStatus(String studyStr, List<String> sampleIds, RgaIndex.Status status, String token) throws CatalogException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); int updatedSamples = 0; // Update samples in batches of 100 List<String> tmpSampleIds = new ArrayList<>(100); RgaIndex rgaIndex = new RgaIndex(status, TimeUtils.getTime()); for (String sampleId : sampleIds) { tmpSampleIds.add(sampleId); if (tmpSampleIds.size() == 100) { OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), tmpSampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); tmpSampleIds = new ArrayList<>(100); } } if (!tmpSampleIds.isEmpty()) { // Update last batch OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), tmpSampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); } stopWatch.stop(); return new OpenCGAResult<>((int) stopWatch.getTime(TimeUnit.MILLISECONDS), null, sampleIds.size(), 0, updatedSamples, 0); } public OpenCGAResult<KnockoutByIndividualSummary> individualSummary(String studyStr, Query query, QueryOptions options, String token) throws RgaException, CatalogException, IOException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); Preprocess preprocess; try { preprocess = individualQueryPreprocess(study, query, options, token); } catch (RgaException e) { if (RgaException.NO_RESULTS_FOUND.equals(e.getMessage())) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByIndividualSummary.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } throw e; } catch (CatalogException | IOException e) { throw e; } List<String> sampleIds = preprocess.getQuery().getAsStringList(RgaQueryParams.SAMPLE_ID.key()); preprocess.getQuery().remove(RgaQueryParams.SAMPLE_ID.key()); List<KnockoutByIndividualSummary> knockoutByIndividualSummaryList = new ArrayList<>(sampleIds.size()); // Generate 4 batches to create 4 threads int batchSize = 4; List<List<String>> batchList = new ArrayList<>(batchSize); int size = (int) Math.ceil(sampleIds.size() / (double) batchSize); List<String> batch = null; for (int i = 0; i < sampleIds.size(); i++) { if (i % size == 0) { if (batch != null) { batchList.add(batch); } batch = new ArrayList<>(size); } batch.add(sampleIds.get(i)); } batchList.add(batch); List<Future<List<KnockoutByIndividualSummary>>> futureList = new ArrayList<>(batchSize); for (List<String> sampleIdList : batchList) { futureList.add(executor.submit(() -> calculateIndividualSummary(collection, preprocess.getQuery(), sampleIdList))); } try { for (Future<List<KnockoutByIndividualSummary>> summaryFuture : futureList) { knockoutByIndividualSummaryList.addAll(summaryFuture.get()); } } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByIndividualSummary> result = new OpenCGAResult<>(time, Collections.emptyList(), knockoutByIndividualSummaryList.size(), knockoutByIndividualSummaryList, -1); if (preprocess.getQueryOptions().getBoolean(QueryOptions.COUNT)) { result.setNumMatches(preprocess.getNumTotalResults()); } if (preprocess.getEvent() != null) { result.setEvents(Collections.singletonList(preprocess.getEvent())); } return result; } public OpenCGAResult<KnockoutByGeneSummary> geneSummary(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } catalogManager.getAuthorizationManager().checkCanViewStudy(study.getUid(), userId); StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions queryOptions = setDefaultLimit(options); Query auxQuery = query != null ? new Query(query) : new Query(); // Get numTotalResults in a future Future<Integer> numTotalResults = null; if (queryOptions.getBoolean(QueryOptions.COUNT)) { numTotalResults = executor.submit(() -> { QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, "unique(" + RgaDataModel.GENE_ID + ")"); try { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); return ((Number) result.first().getAggregationValues().get(0)).intValue(); } catch (Exception e) { e.printStackTrace(); } return -1; }); } List<String> geneIds = auxQuery.getAsStringList(RgaDataModel.GENE_ID); auxQuery.remove(RgaDataModel.GENE_ID); // If the user is querying by gene id, we don't need to do a facet first if (geneIds.isEmpty()) { // 1st. we perform a facet to get the different gene ids matching the user query and using the skip and limit values QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, RgaDataModel.GENE_ID); facetOptions.putIfNotNull(QueryOptions.LIMIT, queryOptions.get(QueryOptions.LIMIT)); facetOptions.putIfNotNull(QueryOptions.SKIP, queryOptions.get(QueryOptions.SKIP)); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByGeneSummary.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } geneIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); } // Generate 4 batches to create 4 threads int batchSize = 4; List<List<String>> batchList = new ArrayList<>(batchSize); int size = (int) Math.ceil(geneIds.size() / (double) batchSize); List<String> batch = null; for (int i = 0; i < geneIds.size(); i++) { if (i % size == 0) { if (batch != null) { batchList.add(batch); } batch = new ArrayList<>(size); } batch.add(geneIds.get(i)); } batchList.add(batch); List<Future<List<KnockoutByGeneSummary>>> geneSummaryFutureList = new ArrayList<>(batchSize); for (List<String> geneIdList : batchList) { geneSummaryFutureList.add(executor.submit(() -> calculateGeneSummary(collection, auxQuery, geneIdList))); } List<KnockoutByGeneSummary> knockoutByGeneSummaryList = new ArrayList<>(geneIds.size()); try { for (Future<List<KnockoutByGeneSummary>> summaryFuture : geneSummaryFutureList) { knockoutByGeneSummaryList.addAll(summaryFuture.get()); } } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByGeneSummary> result = new OpenCGAResult<>(time, Collections.emptyList(), knockoutByGeneSummaryList.size(), knockoutByGeneSummaryList, -1); if (queryOptions.getBoolean(QueryOptions.COUNT)) { try { assert numTotalResults != null; result.setNumMatches(numTotalResults.get()); } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } } return result; } private List<KnockoutByGeneSummary> calculateGeneSummary(String collection, Query query, List<String> geneIdList) throws RgaException, IOException { List<KnockoutByGeneSummary> knockoutByGeneSummaryList = new ArrayList<>(geneIdList.size()); for (String geneId : geneIdList) { Query auxQuery = new Query(query); auxQuery.put(RgaQueryParams.GENE_ID.key(), geneId); // 1. Get KnockoutByGene information Query individualQuery = new Query(RgaQueryParams.GENE_ID.key(), geneId); QueryOptions options = new QueryOptions() .append(QueryOptions.LIMIT, 1) .append(QueryOptions.EXCLUDE, "individuals"); RgaIterator rgaIterator = rgaEngine.geneQuery(collection, individualQuery, options); if (!rgaIterator.hasNext()) { throw new RgaException("Unexpected error. Gene '" + geneId + "' not found"); } RgaDataModel rgaDataModel = rgaIterator.next(); KnockoutByGeneSummary geneSummary = new KnockoutByGeneSummary(rgaDataModel.getGeneId(), rgaDataModel.getGeneName(), rgaDataModel.getChromosome(), rgaDataModel.getStart(), rgaDataModel.getEnd(), rgaDataModel.getStrand(), rgaDataModel.getGeneBiotype(), null, null); // 2. Get KnockoutType counts QueryOptions knockoutTypeFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.VARIANT_SUMMARY); DataResult<FacetField> facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, knockoutTypeFacet); KnockoutTypeCount knockoutTypeCount = new KnockoutTypeCount(auxQuery); for (FacetField.Bucket variantBucket : facetFieldDataResult.first().getBuckets()) { RgaUtils.CodedFeature codedFeature = RgaUtils.CodedFeature.parseEncodedId(variantBucket.getValue()); knockoutTypeCount.processFeature(codedFeature); } VariantStats variantStats = new VariantStats(knockoutTypeCount.getNumIds(), knockoutTypeCount.getNumHomIds(), knockoutTypeCount.getNumCompHetIds(), knockoutTypeCount.getNumHetIds(), knockoutTypeCount.getNumDelOverlapIds()); geneSummary.setVariantStats(variantStats); // 3. Get individual knockout type counts QueryOptions geneFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.INDIVIDUAL_SUMMARY); facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, geneFacet); KnockoutTypeCount noParentsCount = new KnockoutTypeCount(auxQuery); KnockoutTypeCount singleParentCount = new KnockoutTypeCount(auxQuery); KnockoutTypeCount bothParentsCount = new KnockoutTypeCount(auxQuery); for (FacetField.Bucket bucket : facetFieldDataResult.first().getBuckets()) { RgaUtils.CodedIndividual codedIndividual = RgaUtils.CodedIndividual.parseEncodedId(bucket.getValue()); KnockoutTypeCount auxKnockoutType; switch (codedIndividual.getNumParents()) { case 0: auxKnockoutType = noParentsCount; break; case 1: auxKnockoutType = singleParentCount; break; case 2: auxKnockoutType = bothParentsCount; break; default: throw new IllegalStateException("Unexpected value: " + codedIndividual.getNumParents()); } auxKnockoutType.processFeature(codedIndividual); } VariantStats noParentIndividualStats = new VariantStats(noParentsCount.getNumIds(), noParentsCount.getNumHomIds(), noParentsCount.getNumCompHetIds(), noParentsCount.getNumHetIds(), noParentsCount.getNumDelOverlapIds()); VariantStats singleParentIndividualStats = new VariantStats(singleParentCount.getNumIds(), singleParentCount.getNumHomIds(), singleParentCount.getNumCompHetIds(), singleParentCount.getNumHetIds(), singleParentCount.getNumDelOverlapIds()); VariantStats bothParentIndividualStats = new VariantStats(bothParentsCount.getNumIds(), bothParentsCount.getNumHomIds(), bothParentsCount.getNumCompHetIds(), bothParentsCount.getNumHetIds(), bothParentsCount.getNumDelOverlapIds()); geneSummary.setIndividualStats(new IndividualStats(noParentIndividualStats, singleParentIndividualStats, bothParentIndividualStats)); knockoutByGeneSummaryList.add(geneSummary); } return knockoutByGeneSummaryList; } private List<KnockoutByIndividualSummary> calculateIndividualSummary(String collection, Query query, List<String> sampleIdList) throws RgaException, IOException { List<KnockoutByIndividualSummary> knockoutByIndividualSummaryList = new ArrayList<>(sampleIdList.size()); for (String sampleId : sampleIdList) { Query auxQuery = new Query(query); auxQuery.put(RgaQueryParams.SAMPLE_ID.key(), sampleId); // 1. Get KnockoutByIndividual information Query individualQuery = new Query(RgaQueryParams.SAMPLE_ID.key(), sampleId); QueryOptions options = new QueryOptions() .append(QueryOptions.LIMIT, 1) .append(QueryOptions.EXCLUDE, "genes"); RgaIterator rgaIterator = rgaEngine.individualQuery(collection, individualQuery, options); if (!rgaIterator.hasNext()) { throw new RgaException("Unexpected error. Sample '" + sampleId + "' not found"); } RgaDataModel rgaDataModel = rgaIterator.next(); KnockoutByIndividual knockoutByIndividual = AbstractRgaConverter.fillIndividualInfo(rgaDataModel); KnockoutByIndividualSummary knockoutByIndividualSummary = new KnockoutByIndividualSummary(knockoutByIndividual); // 2. Get KnockoutType counts QueryOptions knockoutTypeFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.VARIANT_SUMMARY); DataResult<FacetField> facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, knockoutTypeFacet); KnockoutTypeCount knockoutTypeCount = new KnockoutTypeCount(auxQuery); for (FacetField.Bucket variantBucket : facetFieldDataResult.first().getBuckets()) { RgaUtils.CodedFeature codedFeature = RgaUtils.CodedFeature.parseEncodedId(variantBucket.getValue()); knockoutTypeCount.processFeature(codedFeature); } VariantStats variantStats = new VariantStats(knockoutTypeCount.getNumIds(), knockoutTypeCount.getNumHomIds(), knockoutTypeCount.getNumCompHetIds(), knockoutTypeCount.getNumHetIds(), knockoutTypeCount.getNumDelOverlapIds()); knockoutByIndividualSummary.setVariantStats(variantStats); // 3. Get gene name list QueryOptions geneFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.GENE_NAME); facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, geneFacet); List<String> geneIds = facetFieldDataResult.first().getBuckets() .stream() .map(FacetField.Bucket::getValue) .collect(Collectors.toList()); knockoutByIndividualSummary.setGenes(geneIds); knockoutByIndividualSummaryList.add(knockoutByIndividualSummary); } return knockoutByIndividualSummaryList; } private static class KnockoutTypeCount { private Set<String> knockoutTypeQuery; private List<Set<String>> popFreqQuery; private Set<String> typeQuery; private Set<String> consequenceTypeQuery; private Set<String> ids; private Set<String> compHetIds; private Set<String> homIds; private Set<String> hetIds; private Set<String> delOverlapIds; public KnockoutTypeCount(Query query) throws RgaException { knockoutTypeQuery = new HashSet<>(); popFreqQuery = new LinkedList<>(); typeQuery = new HashSet<>(); consequenceTypeQuery = new HashSet<>(); ids = new HashSet<>(); compHetIds = new HashSet<>(); homIds = new HashSet<>(); hetIds = new HashSet<>(); delOverlapIds = new HashSet<>(); query = ParamUtils.defaultObject(query, Query::new); knockoutTypeQuery.addAll(query.getAsStringList(RgaQueryParams.KNOCKOUT.key())); typeQuery.addAll(query.getAsStringList(RgaQueryParams.TYPE.key())); consequenceTypeQuery.addAll(query.getAsStringList(RgaQueryParams.CONSEQUENCE_TYPE.key()) .stream() .map(VariantQueryUtils::parseConsequenceType) .map(String::valueOf) .collect(Collectors.toList())); List<String> popFreqs = query.getAsStringList(RgaQueryParams.POPULATION_FREQUENCY.key(), ";"); if (!popFreqs.isEmpty()) { Map<String, List<String>> popFreqList = RgaUtils.parsePopulationFrequencyQuery(popFreqs); for (List<String> values : popFreqList.values()) { popFreqQuery.add(new HashSet<>(values)); } } } public void processFeature(RgaUtils.CodedFeature codedFeature) { if (!knockoutTypeQuery.isEmpty() && !knockoutTypeQuery.contains(codedFeature.getKnockoutType())) { return; } if (!popFreqQuery.isEmpty()) { for (Set<String> popFreq : popFreqQuery) { if (codedFeature.getPopulationFrequencies().stream().noneMatch(popFreq::contains)) { return; } } } if (!typeQuery.isEmpty() && !typeQuery.contains(codedFeature.getType())) { return; } if (!consequenceTypeQuery.isEmpty() && codedFeature.getConsequenceType().stream().noneMatch((ct) -> consequenceTypeQuery.contains(ct))) { return; } ids.add(codedFeature.getId()); KnockoutVariant.KnockoutType knockoutType = KnockoutVariant.KnockoutType.valueOf(codedFeature.getKnockoutType()); switch (knockoutType) { case HOM_ALT: homIds.add(codedFeature.getId()); break; case COMP_HET: compHetIds.add(codedFeature.getId()); break; case HET_ALT: hetIds.add(codedFeature.getId()); break; case DELETION_OVERLAP: delOverlapIds.add(codedFeature.getId()); break; default: throw new IllegalStateException("Unexpected value: " + codedFeature.getKnockoutType()); } } public int getNumIds() { return ids.size(); } public int getNumCompHetIds() { return compHetIds.size(); } public int getNumHomIds() { return homIds.size(); } public int getNumHetIds() { return hetIds.size(); } public int getNumDelOverlapIds() { return delOverlapIds.size(); } } private Preprocess individualQueryPreprocess(Study study, Query query, QueryOptions options, String token) throws RgaException, CatalogException, IOException { String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } Boolean isOwnerOrAdmin = catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); Preprocess preprocessResult = new Preprocess(); preprocessResult.setQuery(query != null ? new Query(query) : new Query()); preprocessResult.setQueryOptions(setDefaultLimit(options)); QueryOptions queryOptions = preprocessResult.getQueryOptions(); int limit = queryOptions.getInt(QueryOptions.LIMIT, AbstractManager.DEFAULT_LIMIT); int skip = queryOptions.getInt(QueryOptions.SKIP); List<String> sampleIds; boolean count = queryOptions.getBoolean(QueryOptions.COUNT); if (preprocessResult.getQuery().isEmpty()) { QueryOptions catalogOptions = new QueryOptions(SampleManager.INCLUDE_SAMPLE_IDS) .append(QueryOptions.LIMIT, limit) .append(QueryOptions.SKIP, skip) .append(QueryOptions.COUNT, queryOptions.getBoolean(QueryOptions.COUNT)); Query catalogQuery = new Query(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED); if (!isOwnerOrAdmin) { catalogQuery.put(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS); } OpenCGAResult<Sample> search = catalogManager.getSampleManager().search(study.getFqn(), catalogQuery, catalogOptions, token); if (search.getNumResults() == 0) { throw RgaException.noResultsMatching(); } sampleIds = search.getResults().stream().map(Sample::getId).collect(Collectors.toList()); preprocessResult.setNumTotalResults(search.getNumMatches()); } else { if (!preprocessResult.getQuery().containsKey("sampleId") && !preprocessResult.getQuery().containsKey("individualId")) { // 1st. we perform a facet to get the different sample ids matching the user query DataResult<FacetField> result = rgaEngine.facetedQuery(collection, preprocessResult.getQuery(), new QueryOptions(QueryOptions.FACET, RgaDataModel.SAMPLE_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { throw RgaException.noResultsMatching(); } List<String> samples = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); preprocessResult.getQuery().put("sampleId", samples); } // From the list of sample ids the user wants to retrieve data from, we filter those for which the user has permissions Query sampleQuery = new Query(); if (!isOwnerOrAdmin) { sampleQuery.put(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS); } List<String> authorisedSamples = new LinkedList<>(); if (!isOwnerOrAdmin || !preprocessResult.getQuery().containsKey("sampleId")) { int maxSkip = 10000; if (skip > maxSkip) { throw new RgaException("Cannot paginate further than " + maxSkip + " individuals. Please, narrow down your query."); } int batchSize = 1000; int currentBatch = 0; boolean queryNextBatch = true; String sampleQueryField; List<String> values; if (preprocessResult.getQuery().containsKey("individualId")) { sampleQueryField = SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(); values = preprocessResult.getQuery().getAsStringList("individualId"); } else { sampleQueryField = SampleDBAdaptor.QueryParams.ID.key(); values = preprocessResult.getQuery().getAsStringList("sampleId"); } if (count && values.size() > maxSkip) { preprocessResult.setEvent(new Event(Event.Type.WARNING, "numMatches value is approximated considering the " + "individuals that are accessible for the user from the first batch of 10000 individuals matching the solr " + "query.")); } while (queryNextBatch) { List<String> tmpValues = values.subList(currentBatch, Math.min(values.size(), batchSize + currentBatch)); sampleQuery.put(sampleQueryField, tmpValues); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); authorisedSamples.addAll((Collection<? extends String>) authorisedSampleIdResult.getResults()); if (values.size() < batchSize + currentBatch) { queryNextBatch = false; preprocessResult.setNumTotalResults(authorisedSamples.size()); } else if (count && currentBatch < maxSkip) { currentBatch += batchSize; } else if (authorisedSamples.size() > skip + limit) { queryNextBatch = false; // We will get an approximate number of total results preprocessResult.setNumTotalResults(Math.round(((float) authorisedSamples.size() * values.size()) / (currentBatch + batchSize))); } else { currentBatch += batchSize; } } } else { authorisedSamples = preprocessResult.getQuery().getAsStringList("sampleId"); preprocessResult.setNumTotalResults(authorisedSamples.size()); } if (skip == 0 && limit > authorisedSamples.size()) { sampleIds = authorisedSamples; } else if (skip > authorisedSamples.size()) { throw RgaException.noResultsMatching(); } else { int to = Math.min(authorisedSamples.size(), skip + limit); sampleIds = authorisedSamples.subList(skip, to); } } preprocessResult.getQuery().put("sampleId", sampleIds); return preprocessResult; } private class Preprocess { private Query query; private QueryOptions queryOptions; private long numTotalResults; private Event event; public Preprocess() { } public Query getQuery() { return query; } public Preprocess setQuery(Query query) { this.query = query; return this; } public QueryOptions getQueryOptions() { return queryOptions; } public Preprocess setQueryOptions(QueryOptions queryOptions) { this.queryOptions = queryOptions; return this; } public long getNumTotalResults() { return numTotalResults; } public Preprocess setNumTotalResults(long numTotalResults) { this.numTotalResults = numTotalResults; return this; } public Event getEvent() { return event; } public Preprocess setEvent(Event event) { this.event = event; return this; } } public OpenCGAResult<FacetField> aggregationStats(String studyStr, Query query, QueryOptions options, String fields, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); catalogManager.getAuthorizationManager().checkCanViewStudy(study.getUid(), userId); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } ParamUtils.checkObj(fields, "Missing mandatory field 'field"); QueryOptions queryOptions = options != null ? new QueryOptions(options) : new QueryOptions(); queryOptions.put(QueryOptions.FACET, fields); return new OpenCGAResult<>(rgaEngine.facetedQuery(collection, query, queryOptions)); } private QueryOptions setDefaultLimit(QueryOptions options) { QueryOptions queryOptions = options != null ? new QueryOptions(options) : new QueryOptions(); if (!queryOptions.containsKey(QueryOptions.LIMIT)) { queryOptions.put(QueryOptions.LIMIT, AbstractManager.DEFAULT_LIMIT); } return queryOptions; } public void index(String studyStr, String fileStr, String token) throws CatalogException, RgaException, IOException { File file = catalogManager.getFileManager().get(studyStr, fileStr, FileManager.INCLUDE_FILE_URI_PATH, token).first(); Path filePath = Paths.get(file.getUri()); index(studyStr, filePath, token); } public void index(String studyStr, Path file, String token) throws CatalogException, IOException, RgaException { String userId = catalogManager.getUserManager().getUserId(token); Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); try { catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); } catch (CatalogException e) { logger.error(e.getMessage(), e); throw new CatalogException("Only owners or admins can index", e.getCause()); } load(study.getFqn(), file, token); } /** * Load a multi KnockoutByIndividual JSON file into the Solr core/collection. * * @param path Path to the JSON file * @param path Path to the JSON file * @param path Path to the JSON file * @param path Path to the JSON file * @throws IOException * @throws SolrException */ private void load(String study, Path path, String token) throws IOException, RgaException { String fileName = path.getFileName().toString(); if (fileName.endsWith("json") || fileName.endsWith("json.gz")) { String collection = getCollectionName(study); try { if (!rgaEngine.exists(collection)) { rgaEngine.create(collection); } } catch (RgaException e) { logger.error("Could not perform RGA index in collection {}", collection, e); throw new RgaException("Could not perform RGA index in collection '" + collection + "'."); } try { IOConnectorProvider ioConnectorProvider = new IOConnectorProvider(storageConfiguration); // This opens json and json.gz files automatically try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( ioConnectorProvider.newInputStream(path.toUri())))) { List<KnockoutByIndividual> knockoutByIndividualList = new ArrayList<>(KNOCKOUT_INSERT_BATCH_SIZE); int count = 0; String line; ObjectReader objectReader = new ObjectMapper().readerFor(KnockoutByIndividual.class); while ((line = bufferedReader.readLine()) != null) { KnockoutByIndividual knockoutByIndividual = objectReader.readValue(line); knockoutByIndividualList.add(knockoutByIndividual); count++; if (count % KNOCKOUT_INSERT_BATCH_SIZE == 0) { List<RgaDataModel> rgaDataModelList = individualRgaConverter.convertToStorageType(knockoutByIndividualList); rgaEngine.insert(collection, rgaDataModelList); logger.debug("Loaded {} knockoutByIndividual entries from '{}'", count, path); // Update RGA Index status try { updateRgaInternalIndexStatus(study, knockoutByIndividualList.stream() .map(KnockoutByIndividual::getSampleId).collect(Collectors.toList()), RgaIndex.Status.INDEXED, token); logger.debug("Updated sample RGA index statuses"); } catch (CatalogException e) { logger.warn("Sample RGA index status could not be updated: {}", e.getMessage(), e); } knockoutByIndividualList.clear(); } } // Insert the remaining entries if (CollectionUtils.isNotEmpty(knockoutByIndividualList)) { List<RgaDataModel> rgaDataModelList = individualRgaConverter.convertToStorageType(knockoutByIndividualList); rgaEngine.insert(collection, rgaDataModelList); logger.debug("Loaded remaining {} knockoutByIndividual entries from '{}'", count, path); // Update RGA Index status try { updateRgaInternalIndexStatus(study, knockoutByIndividualList.stream() .map(KnockoutByIndividual::getSampleId).collect(Collectors.toList()), RgaIndex.Status.INDEXED, token); logger.debug("Updated sample RGA index statuses"); } catch (CatalogException e) { logger.warn("Sample RGA index status could not be updated: {}", e.getMessage(), e); } } } } catch (SolrServerException e) { throw new RgaException("Error loading KnockoutIndividual from JSON file.", e); } } else { throw new RgaException("File format " + path + " not supported. Please, use JSON file format."); } } public void testConnection() throws StorageEngineException { rgaEngine.isAlive("test"); } private String getCollectionName(String study) { return catalogManager.getConfiguration().getDatabasePrefix() + "-rga-" + study.replace("@", "_").replace(":", "_"); } @Override public void close() throws Exception { rgaEngine.close(); } private boolean includeVariants(AbstractRgaConverter converter, QueryOptions queryOptions) { if (queryOptions.containsKey(QueryOptions.INCLUDE)) { for (String include : converter.getIncludeFields(queryOptions.getAsStringList(QueryOptions.INCLUDE))) { if (include.contains("variant")) { return true; } } return false; } else if (queryOptions.containsKey(QueryOptions.EXCLUDE)) { for (String include : converter.getIncludeFromExcludeFields(queryOptions.getAsStringList(QueryOptions.EXCLUDE))) { if (include.contains("variant")) { return true; } } return false; } return true; } }
opencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java
package org.opencb.opencga.analysis.rga; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import org.apache.commons.lang3.time.StopWatch; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrException; import org.opencb.commons.datastore.core.*; import org.opencb.commons.utils.CollectionUtils; import org.opencb.opencga.analysis.rga.exceptions.RgaException; import org.opencb.opencga.analysis.rga.iterators.RgaIterator; import org.opencb.opencga.analysis.variant.manager.VariantStorageManager; import org.opencb.opencga.catalog.db.api.SampleDBAdaptor; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.AbstractManager; import org.opencb.opencga.catalog.managers.CatalogManager; import org.opencb.opencga.catalog.managers.FileManager; import org.opencb.opencga.catalog.managers.SampleManager; import org.opencb.opencga.catalog.utils.ParamUtils; import org.opencb.opencga.core.common.TimeUtils; import org.opencb.opencga.core.config.Configuration; import org.opencb.opencga.core.config.storage.StorageConfiguration; import org.opencb.opencga.core.models.analysis.knockout.*; import org.opencb.opencga.core.models.common.RgaIndex; import org.opencb.opencga.core.models.file.File; import org.opencb.opencga.core.models.sample.Sample; import org.opencb.opencga.core.models.sample.SampleAclEntry; import org.opencb.opencga.core.models.study.Study; import org.opencb.opencga.core.response.OpenCGAResult; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.io.managers.IOConnectorProvider; import org.opencb.opencga.storage.core.variant.adaptors.VariantField; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam; import org.opencb.opencga.storage.core.variant.adaptors.iterators.VariantDBIterator; import org.opencb.opencga.storage.core.variant.query.VariantQueryUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import static org.opencb.opencga.core.api.ParamConstants.ACL_PARAM; public class RgaManager implements AutoCloseable { private CatalogManager catalogManager; private StorageConfiguration storageConfiguration; private final RgaEngine rgaEngine; private final VariantStorageManager variantStorageManager; private IndividualRgaConverter individualRgaConverter; private GeneRgaConverter geneConverter; private VariantRgaConverter variantConverter; private final Logger logger; private static final int KNOCKOUT_INSERT_BATCH_SIZE = 25; private static ExecutorService executor; static { executor = Executors.newCachedThreadPool(); } public RgaManager(CatalogManager catalogManager, VariantStorageManager variantStorageManager, StorageEngineFactory storageEngineFactory) { this.catalogManager = catalogManager; this.storageConfiguration = storageEngineFactory.getStorageConfiguration(); this.rgaEngine = new RgaEngine(storageConfiguration); this.variantStorageManager = variantStorageManager; this.individualRgaConverter = new IndividualRgaConverter(); this.geneConverter = new GeneRgaConverter(); this.variantConverter = new VariantRgaConverter(); this.logger = LoggerFactory.getLogger(getClass()); } public RgaManager(Configuration configuration, StorageConfiguration storageConfiguration) throws CatalogException { this.catalogManager = new CatalogManager(configuration); this.storageConfiguration = storageConfiguration; StorageEngineFactory storageEngineFactory = StorageEngineFactory.get(storageConfiguration); this.variantStorageManager = new VariantStorageManager(catalogManager, storageEngineFactory); this.rgaEngine = new RgaEngine(storageConfiguration); this.individualRgaConverter = new IndividualRgaConverter(); this.geneConverter = new GeneRgaConverter(); this.variantConverter = new VariantRgaConverter(); this.logger = LoggerFactory.getLogger(getClass()); } public RgaManager(Configuration configuration, StorageConfiguration storageConfiguration, VariantStorageManager variantStorageManager, RgaEngine rgaEngine) throws CatalogException { this.catalogManager = new CatalogManager(configuration); this.storageConfiguration = storageConfiguration; this.rgaEngine = rgaEngine; this.variantStorageManager = variantStorageManager; this.individualRgaConverter = new IndividualRgaConverter(); this.geneConverter = new GeneRgaConverter(); this.variantConverter = new VariantRgaConverter(); this.logger = LoggerFactory.getLogger(getClass()); } public OpenCGAResult<KnockoutByIndividual> individualQuery(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); Preprocess preprocess; try { preprocess = individualQueryPreprocess(study, query, options, token); } catch (RgaException e) { if (RgaException.NO_RESULTS_FOUND.equals(e.getMessage())) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByIndividual.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } throw e; } catch (CatalogException | IOException e) { throw e; } RgaIterator rgaIterator = rgaEngine.individualQuery(collection, preprocess.getQuery(), QueryOptions.empty()); List<KnockoutByIndividual> knockoutByIndividuals = individualRgaConverter.convertToDataModelType(rgaIterator); int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByIndividual> result = new OpenCGAResult<>(time, Collections.emptyList(), knockoutByIndividuals.size(), knockoutByIndividuals, -1); if (preprocess.getQueryOptions().getBoolean(QueryOptions.COUNT)) { result.setNumMatches(preprocess.getNumTotalResults()); } if (preprocess.getEvent() != null) { result.setEvents(Collections.singletonList(preprocess.getEvent())); } return result; } public OpenCGAResult<RgaKnockoutByGene> geneQuery(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions queryOptions = setDefaultLimit(options); List<String> includeIndividuals = queryOptions.getAsStringList(RgaQueryParams.INCLUDE_INDIVIDUAL); Boolean isOwnerOrAdmin = catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); Query auxQuery = query != null ? new Query(query) : new Query(); // Get numTotalResults in a future Future<Integer> numTotalResults = null; if (queryOptions.getBoolean(QueryOptions.COUNT)) { numTotalResults = executor.submit(() -> { QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, "unique(" + RgaDataModel.GENE_ID + ")"); try { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); return ((Number) result.first().getAggregationValues().get(0)).intValue(); } catch (Exception e) { e.printStackTrace(); } return -1; }); } // If the user is querying by gene id, we don't need to do a facet first if (!auxQuery.containsKey(RgaDataModel.GENE_ID)) { // 1st. we perform a facet to get the different gene ids matching the user query and using the skip and limit values QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, RgaDataModel.GENE_ID); facetOptions.putIfNotNull(QueryOptions.LIMIT, queryOptions.get(QueryOptions.LIMIT)); facetOptions.putIfNotNull(QueryOptions.SKIP, queryOptions.get(QueryOptions.SKIP)); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(RgaKnockoutByGene.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> geneIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); auxQuery.put(RgaDataModel.GENE_ID, geneIds); } // Fetch all individuals matching the user query if (!auxQuery.containsKey("sampleId") && !auxQuery.containsKey("individualId") && includeIndividuals.isEmpty()) { // We perform a facet to get the different individual ids matching the user query DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, new QueryOptions(QueryOptions.FACET, RgaDataModel.INDIVIDUAL_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(RgaKnockoutByGene.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } includeIndividuals = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); } // Get the set of sample ids the user will be able to see Set<String> includeSampleIds; if (!isOwnerOrAdmin) { if (!includeIndividuals.isEmpty()) { // 3. Get list of indexed sample ids for which the user has permissions from the list of includeIndividuals provided Query sampleQuery = new Query() .append(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED) .append(SampleDBAdaptor.QueryParams.ID.key(), includeIndividuals); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } else { // 2. Check permissions DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, new QueryOptions(QueryOptions.FACET, RgaDataModel.SAMPLE_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(RgaKnockoutByGene.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> sampleIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); // 3. Get list of sample ids for which the user has permissions Query sampleQuery = new Query(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.ID.key(), sampleIds); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); // TODO: The number of samples to include could be really high includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } } else { // TODO: Check if samples or individuals are provided // Obtain samples Query sampleQuery = new Query(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED); if (!includeIndividuals.isEmpty()) { query.put(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), includeIndividuals); } else { // TODO: Include only the samples that will be necessary logger.warn("Include only the samples that are actually necessary"); } OpenCGAResult<?> sampleResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) sampleResult.getResults()); } RgaIterator rgaIterator = rgaEngine.geneQuery(collection, auxQuery, queryOptions); int skipIndividuals = queryOptions.getInt(RgaQueryParams.SKIP_INDIVIDUAL); int limitIndividuals = queryOptions.getInt(RgaQueryParams.LIMIT_INDIVIDUAL, RgaQueryParams.DEFAULT_INDIVIDUAL_LIMIT); // 4. Solr gene query List<RgaKnockoutByGene> knockoutResultList = geneConverter.convertToDataModelType(rgaIterator, includeIndividuals, skipIndividuals, limitIndividuals); int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<RgaKnockoutByGene> knockoutResult = new OpenCGAResult<>(time, Collections.emptyList(), knockoutResultList.size(), knockoutResultList, -1); knockoutResult.setTime((int) stopWatch.getTime(TimeUnit.MILLISECONDS)); try { knockoutResult.setNumMatches(numTotalResults != null ? numTotalResults.get() : -1); } catch (InterruptedException | ExecutionException e) { knockoutResult.setNumMatches(-1); } if (isOwnerOrAdmin && includeSampleIds.isEmpty()) { return knockoutResult; } else { // 5. Filter out individual or samples for which user does not have permissions for (RgaKnockoutByGene knockout : knockoutResult.getResults()) { List<RgaKnockoutByGene.KnockoutIndividual> individualList = new ArrayList<>(knockout.getIndividuals().size()); for (RgaKnockoutByGene.KnockoutIndividual individual : knockout.getIndividuals()) { if (includeSampleIds.contains(individual.getSampleId())) { individualList.add(individual); } } knockout.setIndividuals(individualList); } return knockoutResult; } } public OpenCGAResult<KnockoutByVariant> variantQuery(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions queryOptions = setDefaultLimit(options); List<String> includeIndividuals = queryOptions.getAsStringList(RgaQueryParams.INCLUDE_INDIVIDUAL); Boolean isOwnerOrAdmin = catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); Query auxQuery = query != null ? new Query(query) : new Query(); Future<Integer> numTotalResults = null; if (queryOptions.getBoolean(QueryOptions.COUNT)) { numTotalResults = executor.submit(() -> { QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, "unique(" + RgaDataModel.VARIANTS + ")"); try { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); return ((Number) result.first().getAggregationValues().get(0)).intValue(); } catch (Exception e) { logger.error("Could not obtain the count: {}", e.getMessage(), e); } return -1; }); } // If the user is querying by variant id, we don't need to do a facet first if (!auxQuery.containsKey(RgaDataModel.VARIANTS)) { // 1st. we perform a facet to get the different variant ids matching the user query and using the skip and limit values QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, RgaDataModel.VARIANTS); facetOptions.putIfNotNull(QueryOptions.LIMIT, queryOptions.get(QueryOptions.LIMIT)); facetOptions.putIfNotNull(QueryOptions.SKIP, queryOptions.get(QueryOptions.SKIP)); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByVariant.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> variantIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); auxQuery.put(RgaDataModel.VARIANTS, variantIds); } Set<String> includeSampleIds; if (!isOwnerOrAdmin) { if (!includeIndividuals.isEmpty()) { // 3. Get list of sample ids for which the user has permissions from the list of includeIndividuals provided Query sampleQuery = new Query() .append(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED) .append(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), includeIndividuals); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } else { // 2. Check permissions DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, new QueryOptions(QueryOptions.FACET, RgaDataModel.SAMPLE_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByVariant.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } List<String> sampleIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue) .collect(Collectors.toList()); // 3. Get list of individual ids for which the user has permissions Query sampleQuery = new Query() .append(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS) .append(SampleDBAdaptor.QueryParams.ID.key(), sampleIds); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) authorisedSampleIdResult.getResults()); } } else { // Obtain samples Query sampleQuery = new Query(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED); if (!includeIndividuals.isEmpty()) { query.put(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), includeIndividuals); } else { // TODO: Include only the samples that will be necessary logger.warn("Include only the samples that are actually necessary"); } OpenCGAResult<?> sampleResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); includeSampleIds = new HashSet<>((List<String>) sampleResult.getResults()); } Future<VariantDBIterator> variantFuture = executor.submit( () -> variantStorageQuery(study.getFqn(), new ArrayList<>(includeSampleIds), auxQuery, options, token) ); Future<RgaIterator> rgaIteratorFuture = executor.submit(() -> rgaEngine.variantQuery(collection, auxQuery, queryOptions)); VariantDBIterator variantDBIterator; try { variantDBIterator = variantFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } RgaIterator rgaIterator; try { rgaIterator = rgaIteratorFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } int skipIndividuals = queryOptions.getInt(RgaQueryParams.SKIP_INDIVIDUAL); int limitIndividuals = queryOptions.getInt(RgaQueryParams.LIMIT_INDIVIDUAL, RgaQueryParams.DEFAULT_INDIVIDUAL_LIMIT); // 4. Solr gene query List<KnockoutByVariant> knockoutResultList = variantConverter.convertToDataModelType(rgaIterator, variantDBIterator, query.getAsStringList(RgaQueryParams.VARIANTS.key()), includeIndividuals, skipIndividuals, limitIndividuals); int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByVariant> knockoutResult = new OpenCGAResult<>(time, Collections.emptyList(), knockoutResultList.size(), knockoutResultList, -1); knockoutResult.setTime((int) stopWatch.getTime(TimeUnit.MILLISECONDS)); try { knockoutResult.setNumMatches(numTotalResults != null ? numTotalResults.get() : -1); } catch (InterruptedException | ExecutionException e) { knockoutResult.setNumMatches(-1); } if (isOwnerOrAdmin && includeSampleIds.isEmpty()) { return knockoutResult; } else { // 5. Filter out individual or samples for which user does not have permissions for (KnockoutByVariant knockout : knockoutResult.getResults()) { List<KnockoutByIndividual> individualList = new ArrayList<>(knockout.getIndividuals().size()); for (KnockoutByIndividual individual : knockout.getIndividuals()) { if (includeSampleIds.contains(individual.getSampleId())) { individualList.add(individual); } } knockout.setIndividuals(individualList); } return knockoutResult; } } private VariantDBIterator variantStorageQuery(String study, List<String> sampleIds, Query query, QueryOptions options, String token) throws CatalogException, IOException, StorageEngineException, RgaException { String collection = getCollectionName(study); List<String> variantIds = query.getAsStringList(RgaDataModel.VARIANTS); if (variantIds.isEmpty()) { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, query, new QueryOptions(QueryOptions.FACET, RgaDataModel.VARIANTS).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { return VariantDBIterator.EMPTY_ITERATOR; } variantIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); } if (variantIds.size() > RgaQueryParams.DEFAULT_INDIVIDUAL_LIMIT) { throw new RgaException("Too many variants requested"); } Query variantQuery = new Query(VariantQueryParam.ID.key(), variantIds) .append(VariantQueryParam.STUDY.key(), study) .append(VariantQueryParam.INCLUDE_SAMPLE.key(), sampleIds) .append(VariantQueryParam.INCLUDE_SAMPLE_DATA.key(), "GT,DP"); QueryOptions queryOptions = new QueryOptions() .append(QueryOptions.EXCLUDE, Arrays.asList( // VariantField.ANNOTATION_POPULATION_FREQUENCIES, VariantField.ANNOTATION_CYTOBAND, VariantField.ANNOTATION_CONSERVATION, VariantField.ANNOTATION_DRUGS, VariantField.ANNOTATION_GENE_EXPRESSION )); return variantStorageManager.iterator(variantQuery, queryOptions, token); } public OpenCGAResult<Long> updateRgaInternalIndexStatus(String studyStr, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions facetOptions = new QueryOptions() .append(QueryOptions.FACET, RgaDataModel.SAMPLE_ID) .append(QueryOptions.LIMIT, -1); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, new Query(), facetOptions); int totalSamples = result.first().getBuckets().size(); int updatedSamples = 0; // Before doing anything, we first reset all the sample rga indexes OpenCGAResult<Sample> resetResult = catalogManager.getSampleManager().resetRgaIndexes(studyStr, token); logger.debug("Resetting RGA indexes for " + resetResult.getNumMatches() + " samples took " + resetResult.getTime() + " ms."); // Update samples in batches of 100 List<String> sampleIds = new ArrayList<>(100); RgaIndex rgaIndex = new RgaIndex(RgaIndex.Status.INDEXED, TimeUtils.getTime()); for (FacetField.Bucket bucket : result.first().getBuckets()) { sampleIds.add(bucket.getValue()); if (sampleIds.size() == 100) { OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), sampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); sampleIds = new ArrayList<>(100); } } if (!sampleIds.isEmpty()) { // Update last batch OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), sampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); } stopWatch.stop(); return new OpenCGAResult<>((int) stopWatch.getTime(TimeUnit.MILLISECONDS), null, totalSamples, 0, updatedSamples, 0); } public OpenCGAResult<Long> updateRgaInternalIndexStatus(String studyStr, List<String> sampleIds, RgaIndex.Status status, String token) throws CatalogException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); int updatedSamples = 0; // Update samples in batches of 100 List<String> tmpSampleIds = new ArrayList<>(100); RgaIndex rgaIndex = new RgaIndex(status, TimeUtils.getTime()); for (String sampleId : sampleIds) { tmpSampleIds.add(sampleId); if (tmpSampleIds.size() == 100) { OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), tmpSampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); tmpSampleIds = new ArrayList<>(100); } } if (!tmpSampleIds.isEmpty()) { // Update last batch OpenCGAResult<Sample> update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), tmpSampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); } stopWatch.stop(); return new OpenCGAResult<>((int) stopWatch.getTime(TimeUnit.MILLISECONDS), null, sampleIds.size(), 0, updatedSamples, 0); } public OpenCGAResult<KnockoutByIndividualSummary> individualSummary(String studyStr, Query query, QueryOptions options, String token) throws RgaException, CatalogException, IOException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); Preprocess preprocess; try { preprocess = individualQueryPreprocess(study, query, options, token); } catch (RgaException e) { if (RgaException.NO_RESULTS_FOUND.equals(e.getMessage())) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByIndividualSummary.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } throw e; } catch (CatalogException | IOException e) { throw e; } List<String> sampleIds = preprocess.getQuery().getAsStringList(RgaQueryParams.SAMPLE_ID.key()); preprocess.getQuery().remove(RgaQueryParams.SAMPLE_ID.key()); List<KnockoutByIndividualSummary> knockoutByIndividualSummaryList = new ArrayList<>(sampleIds.size()); // Generate 4 batches to create 4 threads int batchSize = 4; List<List<String>> batchList = new ArrayList<>(batchSize); int size = (int) Math.ceil(sampleIds.size() / (double) batchSize); List<String> batch = null; for (int i = 0; i < sampleIds.size(); i++) { if (i % size == 0) { if (batch != null) { batchList.add(batch); } batch = new ArrayList<>(size); } batch.add(sampleIds.get(i)); } batchList.add(batch); List<Future<List<KnockoutByIndividualSummary>>> futureList = new ArrayList<>(batchSize); for (List<String> sampleIdList : batchList) { futureList.add(executor.submit(() -> calculateIndividualSummary(collection, preprocess.getQuery(), sampleIdList))); } try { for (Future<List<KnockoutByIndividualSummary>> summaryFuture : futureList) { knockoutByIndividualSummaryList.addAll(summaryFuture.get()); } } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByIndividualSummary> result = new OpenCGAResult<>(time, Collections.emptyList(), knockoutByIndividualSummaryList.size(), knockoutByIndividualSummaryList, -1); if (preprocess.getQueryOptions().getBoolean(QueryOptions.COUNT)) { result.setNumMatches(preprocess.getNumTotalResults()); } if (preprocess.getEvent() != null) { result.setEvents(Collections.singletonList(preprocess.getEvent())); } return result; } public OpenCGAResult<KnockoutByGeneSummary> geneSummary(String studyStr, Query query, QueryOptions options, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } catalogManager.getAuthorizationManager().checkCanViewStudy(study.getUid(), userId); StopWatch stopWatch = new StopWatch(); stopWatch.start(); QueryOptions queryOptions = setDefaultLimit(options); Query auxQuery = query != null ? new Query(query) : new Query(); // Get numTotalResults in a future Future<Integer> numTotalResults = null; if (queryOptions.getBoolean(QueryOptions.COUNT)) { numTotalResults = executor.submit(() -> { QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, "unique(" + RgaDataModel.GENE_ID + ")"); try { DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); return ((Number) result.first().getAggregationValues().get(0)).intValue(); } catch (Exception e) { e.printStackTrace(); } return -1; }); } List<String> geneIds = auxQuery.getAsStringList(RgaDataModel.GENE_ID); auxQuery.remove(RgaDataModel.GENE_ID); // If the user is querying by gene id, we don't need to do a facet first if (geneIds.isEmpty()) { // 1st. we perform a facet to get the different gene ids matching the user query and using the skip and limit values QueryOptions facetOptions = new QueryOptions(QueryOptions.FACET, RgaDataModel.GENE_ID); facetOptions.putIfNotNull(QueryOptions.LIMIT, queryOptions.get(QueryOptions.LIMIT)); facetOptions.putIfNotNull(QueryOptions.SKIP, queryOptions.get(QueryOptions.SKIP)); DataResult<FacetField> result = rgaEngine.facetedQuery(collection, auxQuery, facetOptions); if (result.getNumResults() == 0) { stopWatch.stop(); return OpenCGAResult.empty(KnockoutByGeneSummary.class, (int) stopWatch.getTime(TimeUnit.MILLISECONDS)); } geneIds = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); } // Generate 4 batches to create 4 threads int batchSize = 4; List<List<String>> batchList = new ArrayList<>(batchSize); int size = (int) Math.ceil(geneIds.size() / (double) batchSize); List<String> batch = null; for (int i = 0; i < geneIds.size(); i++) { if (i % size == 0) { if (batch != null) { batchList.add(batch); } batch = new ArrayList<>(size); } batch.add(geneIds.get(i)); } batchList.add(batch); List<Future<List<KnockoutByGeneSummary>>> geneSummaryFutureList = new ArrayList<>(batchSize); for (List<String> geneIdList : batchList) { geneSummaryFutureList.add(executor.submit(() -> calculateGeneSummary(collection, auxQuery, geneIdList))); } List<KnockoutByGeneSummary> knockoutByGeneSummaryList = new ArrayList<>(geneIds.size()); try { for (Future<List<KnockoutByGeneSummary>> summaryFuture : geneSummaryFutureList) { knockoutByGeneSummaryList.addAll(summaryFuture.get()); } } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); OpenCGAResult<KnockoutByGeneSummary> result = new OpenCGAResult<>(time, Collections.emptyList(), knockoutByGeneSummaryList.size(), knockoutByGeneSummaryList, -1); if (queryOptions.getBoolean(QueryOptions.COUNT)) { try { assert numTotalResults != null; result.setNumMatches(numTotalResults.get()); } catch (InterruptedException | ExecutionException e) { throw new RgaException(e.getMessage(), e); } } return result; } private List<KnockoutByGeneSummary> calculateGeneSummary(String collection, Query query, List<String> geneIdList) throws RgaException, IOException { List<KnockoutByGeneSummary> knockoutByGeneSummaryList = new ArrayList<>(geneIdList.size()); for (String geneId : geneIdList) { Query auxQuery = new Query(query); auxQuery.put(RgaQueryParams.GENE_ID.key(), geneId); // 1. Get KnockoutByGene information Query individualQuery = new Query(RgaQueryParams.GENE_ID.key(), geneId); QueryOptions options = new QueryOptions() .append(QueryOptions.LIMIT, 1) .append(QueryOptions.EXCLUDE, "individuals"); RgaIterator rgaIterator = rgaEngine.geneQuery(collection, individualQuery, options); if (!rgaIterator.hasNext()) { throw new RgaException("Unexpected error. Gene '" + geneId + "' not found"); } RgaDataModel rgaDataModel = rgaIterator.next(); KnockoutByGeneSummary geneSummary = new KnockoutByGeneSummary(rgaDataModel.getGeneId(), rgaDataModel.getGeneName(), rgaDataModel.getChromosome(), rgaDataModel.getStart(), rgaDataModel.getEnd(), rgaDataModel.getStrand(), rgaDataModel.getGeneBiotype(), null, null); // 2. Get KnockoutType counts QueryOptions knockoutTypeFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.VARIANT_SUMMARY); DataResult<FacetField> facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, knockoutTypeFacet); KnockoutTypeCount knockoutTypeCount = new KnockoutTypeCount(auxQuery); for (FacetField.Bucket variantBucket : facetFieldDataResult.first().getBuckets()) { RgaUtils.CodedFeature codedFeature = RgaUtils.CodedFeature.parseEncodedId(variantBucket.getValue()); knockoutTypeCount.processFeature(codedFeature); } VariantStats variantStats = new VariantStats(knockoutTypeCount.getNumIds(), knockoutTypeCount.getNumHomIds(), knockoutTypeCount.getNumCompHetIds(), knockoutTypeCount.getNumHetIds(), knockoutTypeCount.getNumDelOverlapIds()); geneSummary.setVariantStats(variantStats); // 3. Get individual knockout type counts QueryOptions geneFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.INDIVIDUAL_SUMMARY); facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, geneFacet); KnockoutTypeCount noParentsCount = new KnockoutTypeCount(auxQuery); KnockoutTypeCount singleParentCount = new KnockoutTypeCount(auxQuery); KnockoutTypeCount bothParentsCount = new KnockoutTypeCount(auxQuery); for (FacetField.Bucket bucket : facetFieldDataResult.first().getBuckets()) { RgaUtils.CodedIndividual codedIndividual = RgaUtils.CodedIndividual.parseEncodedId(bucket.getValue()); KnockoutTypeCount auxKnockoutType; switch (codedIndividual.getNumParents()) { case 0: auxKnockoutType = noParentsCount; break; case 1: auxKnockoutType = singleParentCount; break; case 2: auxKnockoutType = bothParentsCount; break; default: throw new IllegalStateException("Unexpected value: " + codedIndividual.getNumParents()); } auxKnockoutType.processFeature(codedIndividual); } VariantStats noParentIndividualStats = new VariantStats(noParentsCount.getNumIds(), noParentsCount.getNumHomIds(), noParentsCount.getNumCompHetIds(), noParentsCount.getNumHetIds(), noParentsCount.getNumDelOverlapIds()); VariantStats singleParentIndividualStats = new VariantStats(singleParentCount.getNumIds(), singleParentCount.getNumHomIds(), singleParentCount.getNumCompHetIds(), singleParentCount.getNumHetIds(), singleParentCount.getNumDelOverlapIds()); VariantStats bothParentIndividualStats = new VariantStats(bothParentsCount.getNumIds(), bothParentsCount.getNumHomIds(), bothParentsCount.getNumCompHetIds(), bothParentsCount.getNumHetIds(), bothParentsCount.getNumDelOverlapIds()); geneSummary.setIndividualStats(new IndividualStats(noParentIndividualStats, singleParentIndividualStats, bothParentIndividualStats)); knockoutByGeneSummaryList.add(geneSummary); } return knockoutByGeneSummaryList; } private List<KnockoutByIndividualSummary> calculateIndividualSummary(String collection, Query query, List<String> sampleIdList) throws RgaException, IOException { List<KnockoutByIndividualSummary> knockoutByIndividualSummaryList = new ArrayList<>(sampleIdList.size()); for (String sampleId : sampleIdList) { Query auxQuery = new Query(query); auxQuery.put(RgaQueryParams.SAMPLE_ID.key(), sampleId); // 1. Get KnockoutByIndividual information Query individualQuery = new Query(RgaQueryParams.SAMPLE_ID.key(), sampleId); QueryOptions options = new QueryOptions() .append(QueryOptions.LIMIT, 1) .append(QueryOptions.EXCLUDE, "genes"); RgaIterator rgaIterator = rgaEngine.individualQuery(collection, individualQuery, options); if (!rgaIterator.hasNext()) { throw new RgaException("Unexpected error. Sample '" + sampleId + "' not found"); } RgaDataModel rgaDataModel = rgaIterator.next(); KnockoutByIndividual knockoutByIndividual = AbstractRgaConverter.fillIndividualInfo(rgaDataModel); KnockoutByIndividualSummary knockoutByIndividualSummary = new KnockoutByIndividualSummary(knockoutByIndividual); // 2. Get KnockoutType counts QueryOptions knockoutTypeFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.VARIANT_SUMMARY); DataResult<FacetField> facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, knockoutTypeFacet); KnockoutTypeCount knockoutTypeCount = new KnockoutTypeCount(auxQuery); for (FacetField.Bucket variantBucket : facetFieldDataResult.first().getBuckets()) { RgaUtils.CodedFeature codedFeature = RgaUtils.CodedFeature.parseEncodedId(variantBucket.getValue()); knockoutTypeCount.processFeature(codedFeature); } VariantStats variantStats = new VariantStats(knockoutTypeCount.getNumIds(), knockoutTypeCount.getNumHomIds(), knockoutTypeCount.getNumCompHetIds(), knockoutTypeCount.getNumHetIds(), knockoutTypeCount.getNumDelOverlapIds()); knockoutByIndividualSummary.setVariantStats(variantStats); // 3. Get gene name list QueryOptions geneFacet = new QueryOptions() .append(QueryOptions.LIMIT, -1) .append(QueryOptions.FACET, RgaDataModel.GENE_NAME); facetFieldDataResult = rgaEngine.facetedQuery(collection, auxQuery, geneFacet); List<String> geneIds = facetFieldDataResult.first().getBuckets() .stream() .map(FacetField.Bucket::getValue) .collect(Collectors.toList()); knockoutByIndividualSummary.setGenes(geneIds); knockoutByIndividualSummaryList.add(knockoutByIndividualSummary); } return knockoutByIndividualSummaryList; } private static class KnockoutTypeCount { private Set<String> knockoutTypeQuery; private List<Set<String>> popFreqQuery; private Set<String> typeQuery; private Set<String> consequenceTypeQuery; private Set<String> ids; private Set<String> compHetIds; private Set<String> homIds; private Set<String> hetIds; private Set<String> delOverlapIds; public KnockoutTypeCount(Query query) throws RgaException { knockoutTypeQuery = new HashSet<>(); popFreqQuery = new LinkedList<>(); typeQuery = new HashSet<>(); consequenceTypeQuery = new HashSet<>(); ids = new HashSet<>(); compHetIds = new HashSet<>(); homIds = new HashSet<>(); hetIds = new HashSet<>(); delOverlapIds = new HashSet<>(); query = ParamUtils.defaultObject(query, Query::new); knockoutTypeQuery.addAll(query.getAsStringList(RgaQueryParams.KNOCKOUT.key())); typeQuery.addAll(query.getAsStringList(RgaQueryParams.TYPE.key())); consequenceTypeQuery.addAll(query.getAsStringList(RgaQueryParams.CONSEQUENCE_TYPE.key()) .stream() .map(VariantQueryUtils::parseConsequenceType) .map(String::valueOf) .collect(Collectors.toList())); List<String> popFreqs = query.getAsStringList(RgaQueryParams.POPULATION_FREQUENCY.key(), ";"); if (!popFreqs.isEmpty()) { Map<String, List<String>> popFreqList = RgaUtils.parsePopulationFrequencyQuery(popFreqs); for (List<String> values : popFreqList.values()) { popFreqQuery.add(new HashSet<>(values)); } } } public void processFeature(RgaUtils.CodedFeature codedFeature) { if (!knockoutTypeQuery.isEmpty() && !knockoutTypeQuery.contains(codedFeature.getKnockoutType())) { return; } if (!popFreqQuery.isEmpty()) { for (Set<String> popFreq : popFreqQuery) { if (codedFeature.getPopulationFrequencies().stream().noneMatch(popFreq::contains)) { return; } } } if (!typeQuery.isEmpty() && !typeQuery.contains(codedFeature.getType())) { return; } if (!consequenceTypeQuery.isEmpty() && codedFeature.getConsequenceType().stream().noneMatch((ct) -> consequenceTypeQuery.contains(ct))) { return; } ids.add(codedFeature.getId()); KnockoutVariant.KnockoutType knockoutType = KnockoutVariant.KnockoutType.valueOf(codedFeature.getKnockoutType()); switch (knockoutType) { case HOM_ALT: homIds.add(codedFeature.getId()); break; case COMP_HET: compHetIds.add(codedFeature.getId()); break; case HET_ALT: hetIds.add(codedFeature.getId()); break; case DELETION_OVERLAP: delOverlapIds.add(codedFeature.getId()); break; default: throw new IllegalStateException("Unexpected value: " + codedFeature.getKnockoutType()); } } public int getNumIds() { return ids.size(); } public int getNumCompHetIds() { return compHetIds.size(); } public int getNumHomIds() { return homIds.size(); } public int getNumHetIds() { return hetIds.size(); } public int getNumDelOverlapIds() { return delOverlapIds.size(); } } private Preprocess individualQueryPreprocess(Study study, Query query, QueryOptions options, String token) throws RgaException, CatalogException, IOException { String userId = catalogManager.getUserManager().getUserId(token); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } Boolean isOwnerOrAdmin = catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); Preprocess preprocessResult = new Preprocess(); preprocessResult.setQuery(query != null ? new Query(query) : new Query()); preprocessResult.setQueryOptions(setDefaultLimit(options)); QueryOptions queryOptions = preprocessResult.getQueryOptions(); int limit = queryOptions.getInt(QueryOptions.LIMIT, AbstractManager.DEFAULT_LIMIT); int skip = queryOptions.getInt(QueryOptions.SKIP); List<String> sampleIds; boolean count = queryOptions.getBoolean(QueryOptions.COUNT); if (preprocessResult.getQuery().isEmpty()) { QueryOptions catalogOptions = new QueryOptions(SampleManager.INCLUDE_SAMPLE_IDS) .append(QueryOptions.LIMIT, limit) .append(QueryOptions.SKIP, skip) .append(QueryOptions.COUNT, queryOptions.getBoolean(QueryOptions.COUNT)); Query catalogQuery = new Query(SampleDBAdaptor.QueryParams.INTERNAL_RGA_STATUS.key(), RgaIndex.Status.INDEXED); if (!isOwnerOrAdmin) { catalogQuery.put(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS); } OpenCGAResult<Sample> search = catalogManager.getSampleManager().search(study.getFqn(), catalogQuery, catalogOptions, token); if (search.getNumResults() == 0) { throw RgaException.noResultsMatching(); } sampleIds = search.getResults().stream().map(Sample::getId).collect(Collectors.toList()); preprocessResult.setNumTotalResults(search.getNumMatches()); } else { if (!preprocessResult.getQuery().containsKey("sampleId") && !preprocessResult.getQuery().containsKey("individualId")) { // 1st. we perform a facet to get the different sample ids matching the user query DataResult<FacetField> result = rgaEngine.facetedQuery(collection, preprocessResult.getQuery(), new QueryOptions(QueryOptions.FACET, RgaDataModel.SAMPLE_ID).append(QueryOptions.LIMIT, -1)); if (result.getNumResults() == 0) { throw RgaException.noResultsMatching(); } List<String> samples = result.first().getBuckets().stream().map(FacetField.Bucket::getValue).collect(Collectors.toList()); preprocessResult.getQuery().put("sampleId", samples); } // From the list of sample ids the user wants to retrieve data from, we filter those for which the user has permissions Query sampleQuery = new Query(); if (!isOwnerOrAdmin) { sampleQuery.put(ACL_PARAM, userId + ":" + SampleAclEntry.SamplePermissions.VIEW + "," + SampleAclEntry.SamplePermissions.VIEW_VARIANTS); } List<String> authorisedSamples = new LinkedList<>(); if (!isOwnerOrAdmin || !preprocessResult.getQuery().containsKey("sampleId")) { int maxSkip = 10000; if (skip > maxSkip) { throw new RgaException("Cannot paginate further than " + maxSkip + " individuals. Please, narrow down your query."); } int batchSize = 1000; int currentBatch = 0; boolean queryNextBatch = true; String sampleQueryField; List<String> values; if (preprocessResult.getQuery().containsKey("individualId")) { sampleQueryField = SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(); values = preprocessResult.getQuery().getAsStringList("individualId"); } else { sampleQueryField = SampleDBAdaptor.QueryParams.ID.key(); values = preprocessResult.getQuery().getAsStringList("sampleId"); } if (count && values.size() > maxSkip) { preprocessResult.setEvent(new Event(Event.Type.WARNING, "numMatches value is approximated considering the " + "individuals that are accessible for the user from the first batch of 10000 individuals matching the solr " + "query.")); } while (queryNextBatch) { List<String> tmpValues = values.subList(currentBatch, Math.min(values.size(), batchSize + currentBatch)); sampleQuery.put(sampleQueryField, tmpValues); OpenCGAResult<?> authorisedSampleIdResult = catalogManager.getSampleManager().distinct(study.getFqn(), SampleDBAdaptor.QueryParams.ID.key(), sampleQuery, token); authorisedSamples.addAll((Collection<? extends String>) authorisedSampleIdResult.getResults()); if (values.size() < batchSize + currentBatch) { queryNextBatch = false; preprocessResult.setNumTotalResults(authorisedSamples.size()); } else if (count && currentBatch < maxSkip) { currentBatch += batchSize; } else if (authorisedSamples.size() > skip + limit) { queryNextBatch = false; // We will get an approximate number of total results preprocessResult.setNumTotalResults(Math.round(((float) authorisedSamples.size() * values.size()) / (currentBatch + batchSize))); } else { currentBatch += batchSize; } } } else { authorisedSamples = preprocessResult.getQuery().getAsStringList("sampleId"); preprocessResult.setNumTotalResults(authorisedSamples.size()); } if (skip == 0 && limit > authorisedSamples.size()) { sampleIds = authorisedSamples; } else if (skip > authorisedSamples.size()) { throw RgaException.noResultsMatching(); } else { int to = Math.min(authorisedSamples.size(), skip + limit); sampleIds = authorisedSamples.subList(skip, to); } } preprocessResult.getQuery().put("sampleId", sampleIds); return preprocessResult; } private class Preprocess { private Query query; private QueryOptions queryOptions; private long numTotalResults; private Event event; public Preprocess() { } public Query getQuery() { return query; } public Preprocess setQuery(Query query) { this.query = query; return this; } public QueryOptions getQueryOptions() { return queryOptions; } public Preprocess setQueryOptions(QueryOptions queryOptions) { this.queryOptions = queryOptions; return this; } public long getNumTotalResults() { return numTotalResults; } public Preprocess setNumTotalResults(long numTotalResults) { this.numTotalResults = numTotalResults; return this; } public Event getEvent() { return event; } public Preprocess setEvent(Event event) { this.event = event; return this; } } public OpenCGAResult<FacetField> aggregationStats(String studyStr, Query query, QueryOptions options, String fields, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); String userId = catalogManager.getUserManager().getUserId(token); catalogManager.getAuthorizationManager().checkCanViewStudy(study.getUid(), userId); String collection = getCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); } ParamUtils.checkObj(fields, "Missing mandatory field 'field"); QueryOptions queryOptions = options != null ? new QueryOptions(options) : new QueryOptions(); queryOptions.put(QueryOptions.FACET, fields); return new OpenCGAResult<>(rgaEngine.facetedQuery(collection, query, queryOptions)); } private QueryOptions setDefaultLimit(QueryOptions options) { QueryOptions queryOptions = options != null ? new QueryOptions(options) : new QueryOptions(); if (!queryOptions.containsKey(QueryOptions.LIMIT)) { queryOptions.put(QueryOptions.LIMIT, AbstractManager.DEFAULT_LIMIT); } return queryOptions; } public void index(String studyStr, String fileStr, String token) throws CatalogException, RgaException, IOException { File file = catalogManager.getFileManager().get(studyStr, fileStr, FileManager.INCLUDE_FILE_URI_PATH, token).first(); Path filePath = Paths.get(file.getUri()); index(studyStr, filePath, token); } public void index(String studyStr, Path file, String token) throws CatalogException, IOException, RgaException { String userId = catalogManager.getUserManager().getUserId(token); Study study = catalogManager.getStudyManager().get(studyStr, QueryOptions.empty(), token).first(); try { catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); } catch (CatalogException e) { logger.error(e.getMessage(), e); throw new CatalogException("Only owners or admins can index", e.getCause()); } load(study.getFqn(), file, token); } /** * Load a multi KnockoutByIndividual JSON file into the Solr core/collection. * * @param path Path to the JSON file * @param path Path to the JSON file * @param path Path to the JSON file * @param path Path to the JSON file * @throws IOException * @throws SolrException */ private void load(String study, Path path, String token) throws IOException, RgaException { String fileName = path.getFileName().toString(); if (fileName.endsWith("json") || fileName.endsWith("json.gz")) { String collection = getCollectionName(study); try { if (!rgaEngine.exists(collection)) { rgaEngine.create(collection); } } catch (RgaException e) { logger.error("Could not perform RGA index in collection {}", collection, e); throw new RgaException("Could not perform RGA index in collection '" + collection + "'."); } try { IOConnectorProvider ioConnectorProvider = new IOConnectorProvider(storageConfiguration); // This opens json and json.gz files automatically try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( ioConnectorProvider.newInputStream(path.toUri())))) { List<KnockoutByIndividual> knockoutByIndividualList = new ArrayList<>(KNOCKOUT_INSERT_BATCH_SIZE); int count = 0; String line; ObjectReader objectReader = new ObjectMapper().readerFor(KnockoutByIndividual.class); while ((line = bufferedReader.readLine()) != null) { KnockoutByIndividual knockoutByIndividual = objectReader.readValue(line); knockoutByIndividualList.add(knockoutByIndividual); count++; if (count % KNOCKOUT_INSERT_BATCH_SIZE == 0) { List<RgaDataModel> rgaDataModelList = individualRgaConverter.convertToStorageType(knockoutByIndividualList); rgaEngine.insert(collection, rgaDataModelList); logger.debug("Loaded {} knockoutByIndividual entries from '{}'", count, path); // Update RGA Index status try { updateRgaInternalIndexStatus(study, knockoutByIndividualList.stream() .map(KnockoutByIndividual::getSampleId).collect(Collectors.toList()), RgaIndex.Status.INDEXED, token); logger.debug("Updated sample RGA index statuses"); } catch (CatalogException e) { logger.warn("Sample RGA index status could not be updated: {}", e.getMessage(), e); } knockoutByIndividualList.clear(); } } // Insert the remaining entries if (CollectionUtils.isNotEmpty(knockoutByIndividualList)) { List<RgaDataModel> rgaDataModelList = individualRgaConverter.convertToStorageType(knockoutByIndividualList); rgaEngine.insert(collection, rgaDataModelList); logger.debug("Loaded remaining {} knockoutByIndividual entries from '{}'", count, path); // Update RGA Index status try { updateRgaInternalIndexStatus(study, knockoutByIndividualList.stream() .map(KnockoutByIndividual::getSampleId).collect(Collectors.toList()), RgaIndex.Status.INDEXED, token); logger.debug("Updated sample RGA index statuses"); } catch (CatalogException e) { logger.warn("Sample RGA index status could not be updated: {}", e.getMessage(), e); } } } } catch (SolrServerException e) { throw new RgaException("Error loading KnockoutIndividual from JSON file.", e); } } else { throw new RgaException("File format " + path + " not supported. Please, use JSON file format."); } } public void testConnection() throws StorageEngineException { rgaEngine.isAlive("test"); } private String getCollectionName(String study) { return catalogManager.getConfiguration().getDatabasePrefix() + "-rga-" + study.replace("@", "_").replace(":", "_"); } @Override public void close() throws Exception { rgaEngine.close(); } private boolean includeVariants(AbstractRgaConverter converter, QueryOptions queryOptions) { if (queryOptions.containsKey(QueryOptions.INCLUDE)) { for (String include : converter.getIncludeFields(queryOptions.getAsStringList(QueryOptions.INCLUDE))) { if (include.contains("variant")) { return true; } } return false; } else if (queryOptions.containsKey(QueryOptions.EXCLUDE)) { for (String include : converter.getIncludeFromExcludeFields(queryOptions.getAsStringList(QueryOptions.EXCLUDE))) { if (include.contains("variant")) { return true; } } return false; } return true; } }
analysis: fix minor variant issue, #1693
opencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java
analysis: fix minor variant issue, #1693
<ide><path>pencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java <ide> <ide> // 4. Solr gene query <ide> List<KnockoutByVariant> knockoutResultList = variantConverter.convertToDataModelType(rgaIterator, variantDBIterator, <del> query.getAsStringList(RgaQueryParams.VARIANTS.key()), includeIndividuals, skipIndividuals, limitIndividuals); <add> auxQuery.getAsStringList(RgaQueryParams.VARIANTS.key()), includeIndividuals, skipIndividuals, limitIndividuals); <ide> <ide> int time = (int) stopWatch.getTime(TimeUnit.MILLISECONDS); <ide> OpenCGAResult<KnockoutByVariant> knockoutResult = new OpenCGAResult<>(time, Collections.emptyList(), knockoutResultList.size(),
Java
apache-2.0
65ba409e4566b24d31ed5e04c5d1524819e3b38b
0
firebase/firebase-admin-java,firebase/firebase-admin-java
/* * Copyright 2018 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.firebase.messaging; import static com.google.common.base.Preconditions.checkArgument; import com.google.api.client.util.Key; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.firebase.internal.NonNull; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Represents the Android-specific notification options that can be included in a {@link Message}. * Instances of this class are thread-safe and immutable. */ public class AndroidNotification { @Key("title") private final String title; @Key("body") private final String body; @Key("icon") private final String icon; @Key("color") private final String color; @Key("sound") private final String sound; @Key("tag") private final String tag; @Key("click_action") private final String clickAction; @Key("body_loc_key") private final String bodyLocKey; @Key("body_loc_args") private final List<String> bodyLocArgs; @Key("title_loc_key") private final String titleLocKey; @Key("title_loc_args") private final List<String> titleLocArgs; @Key("channel_id") private final String channelId; @Key("image") private final String image; @Key("ticker") private final String ticker; @Key("sticky") private final Boolean sticky; @Key("event_time") private final String eventTime; @Key("local_only") private final Boolean localOnly; @Key("notification_priority") private final String priority; @Key("vibrate_timings") private final List<String> vibrateTimings; @Key("default_vibrate_timings") private final Boolean defaultVibrateTimings; @Key("default_sound") private final Boolean defaultSound; @Key("light_settings") private final LightSettings lightSettings; @Key("default_light_settings") private final Boolean defaultLightSettings; @Key("visibility") private final String visibility; @Key("notification_count") private final Integer notificationCount; private static final Map<Priority, String> PRIORITY_MAP = ImmutableMap.<Priority, String>builder() .put(Priority.MIN, "PRIORITY_MIN") .put(Priority.LOW, "PRIORITY_LOW") .put(Priority.DEFAULT, "PRIORITY_DEFAULT") .put(Priority.HIGH, "PRIORITY_HIGH") .put(Priority.MAX, "PRIORITY_MAX") .build(); private AndroidNotification(Builder builder) { this.title = builder.title; this.body = builder.body; this.icon = builder.icon; if (builder.color != null) { checkArgument(builder.color.matches("^#[0-9a-fA-F]{6}$"), "color must be in the form #RRGGBB"); } this.color = builder.color; this.sound = builder.sound; this.tag = builder.tag; this.clickAction = builder.clickAction; this.bodyLocKey = builder.bodyLocKey; if (!builder.bodyLocArgs.isEmpty()) { checkArgument(!Strings.isNullOrEmpty(builder.bodyLocKey), "bodyLocKey is required when specifying bodyLocArgs"); this.bodyLocArgs = ImmutableList.copyOf(builder.bodyLocArgs); } else { this.bodyLocArgs = null; } this.titleLocKey = builder.titleLocKey; if (!builder.titleLocArgs.isEmpty()) { checkArgument(!Strings.isNullOrEmpty(builder.titleLocKey), "titleLocKey is required when specifying titleLocArgs"); this.titleLocArgs = ImmutableList.copyOf(builder.titleLocArgs); } else { this.titleLocArgs = null; } this.channelId = builder.channelId; this.image = builder.image; this.ticker = builder.ticker; this.sticky = builder.sticky; this.eventTime = builder.eventTime; this.localOnly = builder.localOnly; if (builder.priority != null) { this.priority = builder.priority.toString(); } else { this.priority = null; } if (!builder.vibrateTimings.isEmpty()) { this.vibrateTimings = ImmutableList.copyOf(builder.vibrateTimings); } else { this.vibrateTimings = null; } this.defaultVibrateTimings = builder.defaultVibrateTimings; this.defaultSound = builder.defaultSound; this.lightSettings = builder.lightSettings; this.defaultLightSettings = builder.defaultLightSettings; if (builder.visibility != null) { this.visibility = builder.visibility.name().toLowerCase(); } else { this.visibility = null; } this.notificationCount = builder.notificationCount; } public enum Priority { MIN, LOW, DEFAULT, HIGH, MAX; @Override public String toString() { return PRIORITY_MAP.get(this); } } public enum Visibility { PRIVATE, PUBLIC, SECRET, } /** * Creates a new {@link AndroidNotification.Builder}. * * @return A {@link AndroidNotification.Builder} instance. */ public static Builder builder() { return new Builder(); } public static class Builder { private String title; private String body; private String icon; private String color; private String sound; private String tag; private String clickAction; private String bodyLocKey; private List<String> bodyLocArgs = new ArrayList<>(); private String titleLocKey; private List<String> titleLocArgs = new ArrayList<>(); private String channelId; private String image; private String ticker; private Boolean sticky; private String eventTime; private Boolean localOnly; private Priority priority; private List<String> vibrateTimings = new ArrayList<>(); private Boolean defaultVibrateTimings; private Boolean defaultSound; private LightSettings lightSettings; private Boolean defaultLightSettings; private Visibility visibility; private Integer notificationCount; private Builder() {} /** * Sets the title of the Android notification. When provided, overrides the title set * via {@link Notification}. * * @param title Title of the notification. * @return This builder. */ public Builder setTitle(String title) { this.title = title; return this; } /** * Sets the body of the Android notification. When provided, overrides the body set * via {@link Notification}. * * @param body Body of the notification. * @return This builder. */ public Builder setBody(String body) { this.body = body; return this; } /** * Sets the icon of the Android notification. * * @param icon Icon resource for the notification. * @return This builder. */ public Builder setIcon(String icon) { this.icon = icon; return this; } /** * Sets the notification icon color. * * @param color Color specified in the {@code #rrggbb} format. * @return This builder. */ public Builder setColor(String color) { this.color = color; return this; } /** * Sets the sound to be played when the device receives the notification. * * @param sound File name of the sound resource or "default". * @return This builder. */ public Builder setSound(String sound) { this.sound = sound; return this; } /** * Sets the notification tag. This is an identifier used to replace existing notifications in * the notification drawer. If not specified, each request creates a new notification. * * @param tag Notification tag. * @return This builder. */ public Builder setTag(String tag) { this.tag = tag; return this; } /** * Sets the action associated with a user click on the notification. If specified, an activity * with a matching Intent Filter is launched when a user clicks on the notification. * * @param clickAction Click action name. * @return This builder. */ public Builder setClickAction(String clickAction) { this.clickAction = clickAction; return this; } /** * Sets the key of the body string in the app's string resources to use to localize the body * text. * * @param bodyLocKey Resource key string. * @return This builder. */ public Builder setBodyLocalizationKey(String bodyLocKey) { this.bodyLocKey = bodyLocKey; return this; } /** * Adds a resource key string that will be used in place of the format specifiers in * {@code bodyLocKey}. * * @param arg Resource key string. * @return This builder. */ public Builder addBodyLocalizationArg(@NonNull String arg) { this.bodyLocArgs.add(arg); return this; } /** * Adds a list of resource keys that will be used in place of the format specifiers in * {@code bodyLocKey}. * * @param args List of resource key strings. * @return This builder. */ public Builder addAllBodyLocalizationArgs(@NonNull List<String> args) { this.bodyLocArgs.addAll(args); return this; } /** * Sets the key of the title string in the app's string resources to use to localize the title * text. * * @param titleLocKey Resource key string. * @return This builder. */ public Builder setTitleLocalizationKey(String titleLocKey) { this.titleLocKey = titleLocKey; return this; } /** * Adds a resource key string that will be used in place of the format specifiers in * {@code titleLocKey}. * * @param arg Resource key string. * @return This builder. */ public Builder addTitleLocalizationArg(@NonNull String arg) { this.titleLocArgs.add(arg); return this; } /** * Adds a list of resource keys that will be used in place of the format specifiers in * {@code titleLocKey}. * * @param args List of resource key strings. * @return This builder. */ public Builder addAllTitleLocalizationArgs(@NonNull List<String> args) { this.titleLocArgs.addAll(args); return this; } /** * Sets the Android notification channel ID (new in Android O). The app must create a channel * with this channel ID before any notification with this channel ID is received. If you * don't send this channel ID in the request, or if the channel ID provided has not yet been * created by the app, FCM uses the channel ID specified in the app manifest. * * @param channelId The notification's channel ID. * @return This builder. */ public Builder setChannelId(String channelId) { this.channelId = channelId; return this; } /** * Sets the URL of the image that is going to be displayed in the notification. When provided, * overrides the imageUrl set via {@link Notification}. * * @param imageUrl URL of the image that is going to be displayed in the notification. * @return This builder. */ public Builder setImage(String imageUrl) { this.image = imageUrl; return this; } /** * Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21 * (Lollipop), sets the text that is displayed in the status bar when the notification * first arrives. * * @param ticker Ticker name. * @return This builder. */ public Builder setTicker(String ticker) { this.ticker = ticker; return this; } /** * Sets the sticky flag. When set to false or unset, the notification is automatically * dismissed when the user clicks it in the panel. When set to true, the notification * persists even when the user clicks it. * * @param sticky The sticky flag * @return This builder. */ public Builder setSticky(boolean sticky) { this.sticky = sticky; return this; } /** * For notifications that inform users about events with an absolute time reference, sets * the time that the event in the notification occurred in milliseconds. Notifications * in the panel are sorted by this time. The time is formatted in RFC3339 UTC "Zulu" * format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z". Note that * since the time is in milliseconds, the last section of the time representation always * has 6 leading zeros. * * @param eventTimeInMillis The event time in milliseconds * @return This builder. */ public Builder setEventTimeInMillis(long eventTimeInMillis) { this.eventTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'") .format(new Date(eventTimeInMillis)); return this; } /** * Sets whether or not this notification is relevant only to the current device. Some * notifications can be bridged to other devices for remote display, such as a Wear * OS watch. This hint can be set to recommend this notification not be bridged. * * @param localOnly The "local only" flag * @return This builder. */ public Builder setLocalOnly(boolean localOnly) { this.localOnly = localOnly; return this; } /** * Sets the relative priority for this notification. Priority is an indication of how much of * the user's attention should be consumed by this notification. Low-priority notifications * may be hidden from the user in certain situations, while the user might be interrupted * for a higher-priority notification. * * @param priority The priority value, one of the values in {MIN, LOW, DEFAULT, HIGH, MAX} * @return This builder. */ public Builder setPriority(Priority priority) { this.priority = priority; return this; } /** * Sets a list of vibration timings in milliseconds in the array to use. The first value in the * array indicates the duration to wait before turning the vibrator on. The next value * indicates the duration to keep the vibrator on. Subsequent values alternate between * duration to turn the vibrator off and to turn the vibrator on. If {@code vibrate_timings} * is set and {@code default_vibrate_timings} is set to true, the default value is used instead * of the user-specified {@code vibrate_timings}. * A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s". * * @param vibrateTimingsInMillis List of vibration time in milliseconds * @return This builder. */ public Builder setVibrateTimingsInMillis(long[] vibrateTimingsInMillis) { List<String> list = new ArrayList<>(); for (long value : vibrateTimingsInMillis) { checkArgument(value >= 0, "elements in vibrateTimingsInMillis must not be negative"); long seconds = TimeUnit.MILLISECONDS.toSeconds(value); long subsecondNanos = TimeUnit.MILLISECONDS.toNanos(value - seconds * 1000L); if (subsecondNanos > 0) { list.add(String.format("%d.%09ds", seconds, subsecondNanos)); } else { list.add(String.format("%ds", seconds)); } } this.vibrateTimings = ImmutableList.copyOf(list); return this; } /** * Sets the whether to use the default vibration timings. If set to true, use the Android * framework's default vibrate pattern for the notification. Default values are specified * in {@code config.xml}. If {@code default_vibrate_timings} is set to true and * {@code vibrate_timings} is also set, the default value is used instead of the * user-specified {@code vibrate_timings}. * * @param defaultVibrateTimings The flag indicating whether to use the default vibration timings * @return This builder. */ public Builder setDefaultVibrateTimings(boolean defaultVibrateTimings) { this.defaultVibrateTimings = defaultVibrateTimings; return this; } /** * Sets the whether to use the default sound. If set to true, use the Android framework's * default sound for the notification. Default values are specified in config.xml. * * @param defaultSound The flag indicating whether to use the default sound * @return This builder. */ public Builder setDefaultSound(boolean defaultSound) { this.defaultSound = defaultSound; return this; } /** * Sets the settings to control the notification's LED blinking rate and color if LED is * available on the device. The total blinking time is controlled by the OS. * * @param lightSettings The light settings to use * @return This builder. */ public Builder setLightSettings(LightSettings lightSettings) { this.lightSettings = lightSettings; return this; } /** * Sets the whether to use the default light settings. If set to true, use the Android * framework's default LED light settings for the notification. Default values are * specified in config.xml. If {@code default_light_settings} is set to true and * {@code light_settings} is also set, the user-specified {@code light_settings} is used * instead of the default value. * * @param defaultLightSettings The flag indicating whether to use the default light * settings * @return This builder. */ public Builder setDefaultLightSettings(boolean defaultLightSettings) { this.defaultLightSettings = defaultLightSettings; return this; } /** * Sets the visibility of this notification. * * @param visibility The visibility value. one of the values in {PRIVATE, PUBLIC, SECRET} * @return This builder. */ public Builder setVisibility(Visibility visibility) { this.visibility = visibility; return this; } /** * Sets the number of items this notification represents. May be displayed as a badge * count for launchers that support badging. For example, this might be useful if you're * using just one notification to represent multiple new messages but you want the count * here to represent the number of total new messages. If zero or unspecified, systems * that support badging use the default, which is to increment a number displayed on * the long-press menu each time a new notification arrives. * * @param notificationCount The notification count * @return This builder. */ public Builder setNotificationCount(int notificationCount) { this.notificationCount = notificationCount; return this; } /** * Creates a new {@link AndroidNotification} instance from the parameters set on this builder. * * @return A new {@link AndroidNotification} instance. * @throws IllegalArgumentException If any of the parameters set on the builder are invalid. */ public AndroidNotification build() { return new AndroidNotification(this); } } }
src/main/java/com/google/firebase/messaging/AndroidNotification.java
/* * Copyright 2018 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.firebase.messaging; import static com.google.common.base.Preconditions.checkArgument; import com.google.api.client.util.Key; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.firebase.internal.NonNull; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Represents the Android-specific notification options that can be included in a {@link Message}. * Instances of this class are thread-safe and immutable. */ public class AndroidNotification { @Key("title") private final String title; @Key("body") private final String body; @Key("icon") private final String icon; @Key("color") private final String color; @Key("sound") private final String sound; @Key("tag") private final String tag; @Key("click_action") private final String clickAction; @Key("body_loc_key") private final String bodyLocKey; @Key("body_loc_args") private final List<String> bodyLocArgs; @Key("title_loc_key") private final String titleLocKey; @Key("title_loc_args") private final List<String> titleLocArgs; @Key("channel_id") private final String channelId; @Key("image") private final String image; @Key("ticker") private final String ticker; @Key("sticky") private final Boolean sticky; @Key("event_time") private final String eventTime; @Key("local_only") private final Boolean localOnly; @Key("notification_priority") private final String priority; @Key("vibrate_timings") private final List<String> vibrateTimings; @Key("default_vibrate_timings") private final Boolean defaultVibrateTimings; @Key("default_sound") private final Boolean defaultSound; @Key("light_settings") private final LightSettings lightSettings; @Key("default_light_settings") private final Boolean defaultLightSettings; @Key("visibility") private final String visibility; @Key("notification_count") private final Integer notificationCount; private static final Map<Priority, String> PRIORITY_MAP = ImmutableMap.<Priority, String>builder() .put(Priority.MIN, "PRIORITY_MIN") .put(Priority.LOW, "PRIORITY_LOW") .put(Priority.DEFAULT, "PRIORITY_DEFAULT") .put(Priority.HIGH, "PRIORITY_HIGH") .put(Priority.MAX, "PRIORITY_MAX") .build(); private AndroidNotification(Builder builder) { this.title = builder.title; this.body = builder.body; this.icon = builder.icon; if (builder.color != null) { checkArgument(builder.color.matches("^#[0-9a-fA-F]{6}$"), "color must be in the form #RRGGBB"); } this.color = builder.color; this.sound = builder.sound; this.tag = builder.tag; this.clickAction = builder.clickAction; this.bodyLocKey = builder.bodyLocKey; if (!builder.bodyLocArgs.isEmpty()) { checkArgument(!Strings.isNullOrEmpty(builder.bodyLocKey), "bodyLocKey is required when specifying bodyLocArgs"); this.bodyLocArgs = ImmutableList.copyOf(builder.bodyLocArgs); } else { this.bodyLocArgs = null; } this.titleLocKey = builder.titleLocKey; if (!builder.titleLocArgs.isEmpty()) { checkArgument(!Strings.isNullOrEmpty(builder.titleLocKey), "titleLocKey is required when specifying titleLocArgs"); this.titleLocArgs = ImmutableList.copyOf(builder.titleLocArgs); } else { this.titleLocArgs = null; } this.channelId = builder.channelId; this.image = builder.image; this.ticker = builder.ticker; this.sticky = builder.sticky; this.eventTime = builder.eventTime; this.localOnly = builder.localOnly; if (builder.priority != null) { this.priority = builder.priority.toString(); } else { this.priority = null; } if (!builder.vibrateTimings.isEmpty()) { this.vibrateTimings = ImmutableList.copyOf(builder.vibrateTimings); } else { this.vibrateTimings = null; } this.defaultVibrateTimings = builder.defaultVibrateTimings; this.defaultSound = builder.defaultSound; this.lightSettings = builder.lightSettings; this.defaultLightSettings = builder.defaultLightSettings; if (builder.visibility != null) { this.visibility = builder.visibility.name().toLowerCase(); } else { this.visibility = null; } this.notificationCount = builder.notificationCount; } public enum Priority { MIN, LOW, DEFAULT, HIGH, MAX; @Override public String toString() { return PRIORITY_MAP.get(this); } } public enum Visibility { PRIVATE, PUBLIC, SECRET, } /** * Creates a new {@link AndroidNotification.Builder}. * * @return A {@link AndroidNotification.Builder} instance. */ public static Builder builder() { return new Builder(); } public static class Builder { private String title; private String body; private String icon; private String color; private String sound; private String tag; private String clickAction; private String bodyLocKey; private List<String> bodyLocArgs = new ArrayList<>(); private String titleLocKey; private List<String> titleLocArgs = new ArrayList<>(); private String channelId; private String image; private String ticker; private Boolean sticky; private String eventTime; private Boolean localOnly; private Priority priority; private List<String> vibrateTimings = new ArrayList<>(); private Boolean defaultVibrateTimings; private Boolean defaultSound; private LightSettings lightSettings; private Boolean defaultLightSettings; private Visibility visibility; private Integer notificationCount; private Builder() {} /** * Sets the title of the Android notification. When provided, overrides the title set * via {@link Notification}. * * @param title Title of the notification. * @return This builder. */ public Builder setTitle(String title) { this.title = title; return this; } /** * Sets the body of the Android notification. When provided, overrides the body set * via {@link Notification}. * * @param body Body of the notification. * @return This builder. */ public Builder setBody(String body) { this.body = body; return this; } /** * Sets the icon of the Android notification. * * @param icon Icon resource for the notification. * @return This builder. */ public Builder setIcon(String icon) { this.icon = icon; return this; } /** * Sets the notification icon color. * * @param color Color specified in the {@code #rrggbb} format. * @return This builder. */ public Builder setColor(String color) { this.color = color; return this; } /** * Sets the sound to be played when the device receives the notification. * * @param sound File name of the sound resource or "default". * @return This builder. */ public Builder setSound(String sound) { this.sound = sound; return this; } /** * Sets the notification tag. This is an identifier used to replace existing notifications in * the notification drawer. If not specified, each request creates a new notification. * * @param tag Notification tag. * @return This builder. */ public Builder setTag(String tag) { this.tag = tag; return this; } /** * Sets the action associated with a user click on the notification. If specified, an activity * with a matching Intent Filter is launched when a user clicks on the notification. * * @param clickAction Click action name. * @return This builder. */ public Builder setClickAction(String clickAction) { this.clickAction = clickAction; return this; } /** * Sets the key of the body string in the app's string resources to use to localize the body * text. * * @param bodyLocKey Resource key string. * @return This builder. */ public Builder setBodyLocalizationKey(String bodyLocKey) { this.bodyLocKey = bodyLocKey; return this; } /** * Adds a resource key string that will be used in place of the format specifiers in * {@code bodyLocKey}. * * @param arg Resource key string. * @return This builder. */ public Builder addBodyLocalizationArg(@NonNull String arg) { this.bodyLocArgs.add(arg); return this; } /** * Adds a list of resource keys that will be used in place of the format specifiers in * {@code bodyLocKey}. * * @param args List of resource key strings. * @return This builder. */ public Builder addAllBodyLocalizationArgs(@NonNull List<String> args) { this.bodyLocArgs.addAll(args); return this; } /** * Sets the key of the title string in the app's string resources to use to localize the title * text. * * @param titleLocKey Resource key string. * @return This builder. */ public Builder setTitleLocalizationKey(String titleLocKey) { this.titleLocKey = titleLocKey; return this; } /** * Adds a resource key string that will be used in place of the format specifiers in * {@code titleLocKey}. * * @param arg Resource key string. * @return This builder. */ public Builder addTitleLocalizationArg(@NonNull String arg) { this.titleLocArgs.add(arg); return this; } /** * Adds a list of resource keys that will be used in place of the format specifiers in * {@code titleLocKey}. * * @param args List of resource key strings. * @return This builder. */ public Builder addAllTitleLocalizationArgs(@NonNull List<String> args) { this.titleLocArgs.addAll(args); return this; } /** * Sets the Android notification channel ID (new in Android O). The app must create a channel * with this channel ID before any notification with this channel ID is received. If you * don't send this channel ID in the request, or if the channel ID provided has not yet been * created by the app, FCM uses the channel ID specified in the app manifest. * * @param channelId The notification's channel ID. * @return This builder. */ public Builder setChannelId(String channelId) { this.channelId = channelId; return this; } /** * Sets the URL of the image that is going to be displayed in the notification. When provided, * overrides the imageUrl set via {@link Notification}. * * @param imageUrl URL of the image that is going to be displayed in the notification. * @return This builder. */ public Builder setImage(String imageUrl) { this.image = imageUrl; return this; } /** * Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21 * (Lollipop), sets the text that is displayed in the status bar when the notification * first arrives. * * @param ticker Ticker name. * @return This builder. */ public Builder setTicker(String ticker) { this.ticker = ticker; return this; } /** * Sets the sticky flag. When set to false or unset, the notification is automatically * dismissed when the user clicks it in the panel. When set to true, the notification * persists even when the user clicks it. * * @param sticky The sticky flag * @return This builder. */ public Builder setSticky(boolean sticky) { this.sticky = sticky; return this; } /** * For notifications that inform users about events with an absolute time reference, sets * the time that the event in the notification occurred in milliseconds. Notifications * in the panel are sorted by this time. The time is be formated in RFC3339 UTC "Zulu" * format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z". Note that * since the time is in milliseconds, the last section of the time representation always * has 6 leading zeros. * * @param eventTimeInMillis The event time in milliseconds * @return This builder. */ public Builder setEventTimeInMillis(long eventTimeInMillis) { this.eventTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'") .format(new Date(eventTimeInMillis)); return this; } /** * Sets whether or not this notification is relevant only to the current device. Some * notifications can be bridged to other devices for remote display, such as a Wear * OS watch. This hint can be set to recommend this notification not be bridged. * * @param localOnly The "local only" flag * @return This builder. */ public Builder setLocalOnly(boolean localOnly) { this.localOnly = localOnly; return this; } /** * Sets the relative priority for this notification. Priority is an indication of how much of * the user's attention should be consumed by this notification. Low-priority notifications * may be hidden from the user in certain situations, while the user might be interrupted * for a higher-priority notification. * * @param priority The priority value, one of the values in {MIN, LOW, DEFAULT, HIGH, MAX} * @return This builder. */ public Builder setPriority(Priority priority) { this.priority = priority; return this; } /** * Sets a list of vibration timings in milliseconds in the array to use. The first value in the * array indicates the duration to wait before turning the vibrator on. The next value * indicates the duration to keep the vibrator on. Subsequent values alternate between * duration to turn the vibrator off and to turn the vibrator on. If {@code vibrate_timings} * is set and {@code default_vibrate_timings} is set to true, the default value is used instead * of the user-specified {@code vibrate_timings}. * A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s". * * @param vibrateTimingsInMillis List of vibration time in milliseconds * @return This builder. */ public Builder setVibrateTimingsInMillis(long[] vibrateTimingsInMillis) { List<String> list = new ArrayList<>(); for (long value : vibrateTimingsInMillis) { checkArgument(value >= 0, "elements in vibrateTimingsInMillis must not be negative"); long seconds = TimeUnit.MILLISECONDS.toSeconds(value); long subsecondNanos = TimeUnit.MILLISECONDS.toNanos(value - seconds * 1000L); if (subsecondNanos > 0) { list.add(String.format("%d.%09ds", seconds, subsecondNanos)); } else { list.add(String.format("%ds", seconds)); } } this.vibrateTimings = ImmutableList.copyOf(list); return this; } /** * Sets the whether to use the default vibration timings. If set to true, use the Android * framework's default vibrate pattern for the notification. Default values are specified * in {@code config.xml}. If {@code default_vibrate_timings} is set to true and * {@code vibrate_timings} is also set, the default value is used instead of the * user-specified {@code vibrate_timings}. * * @param defaultVibrateTimings The flag indicating whether to use the default vibration timings * @return This builder. */ public Builder setDefaultVibrateTimings(boolean defaultVibrateTimings) { this.defaultVibrateTimings = defaultVibrateTimings; return this; } /** * Sets the whether to use the default sound. If set to true, use the Android framework's * default sound for the notification. Default values are specified in config.xml. * * @param defaultSound The flag indicating whether to use the default sound * @return This builder. */ public Builder setDefaultSound(boolean defaultSound) { this.defaultSound = defaultSound; return this; } /** * Sets the settings to control the notification's LED blinking rate and color if LED is * available on the device. The total blinking time is controlled by the OS. * * @param lightSettings The light settings to use * @return This builder. */ public Builder setLightSettings(LightSettings lightSettings) { this.lightSettings = lightSettings; return this; } /** * Sets the whether to use the default light settings. If set to true, use the Android * framework's default LED light settings for the notification. Default values are * specified in config.xml. If {@code default_light_settings} is set to true and * {@code light_settings} is also set, the user-specified {@code light_settings} is used * instead of the default value. * * @param defaultLightSettings The flag indicating whether to use the default light * settings * @return This builder. */ public Builder setDefaultLightSettings(boolean defaultLightSettings) { this.defaultLightSettings = defaultLightSettings; return this; } /** * Sets the visibility of this notification. * * @param visibility The visibility value. one of the values in {PRIVATE, PUBLIC, SECRET} * @return This builder. */ public Builder setVisibility(Visibility visibility) { this.visibility = visibility; return this; } /** * Sets the number of items this notification represents. May be displayed as a badge * count for launchers that support badging. For example, this might be useful if you're * using just one notification to represent multiple new messages but you want the count * here to represent the number of total new messages. If zero or unspecified, systems * that support badging use the default, which is to increment a number displayed on * the long-press menu each time a new notification arrives. * * @param notificationCount The notification count * @return This builder. */ public Builder setNotificationCount(int notificationCount) { this.notificationCount = notificationCount; return this; } /** * Creates a new {@link AndroidNotification} instance from the parameters set on this builder. * * @return A new {@link AndroidNotification} instance. * @throws IllegalArgumentException If any of the parameters set on the builder are invalid. */ public AndroidNotification build() { return new AndroidNotification(this); } } }
Fix a typo in AndroidNotification (#324) * Fix a common typo in AndroidNotification * Update text
src/main/java/com/google/firebase/messaging/AndroidNotification.java
Fix a typo in AndroidNotification (#324)
<ide><path>rc/main/java/com/google/firebase/messaging/AndroidNotification.java <ide> /** <ide> * For notifications that inform users about events with an absolute time reference, sets <ide> * the time that the event in the notification occurred in milliseconds. Notifications <del> * in the panel are sorted by this time. The time is be formated in RFC3339 UTC "Zulu" <add> * in the panel are sorted by this time. The time is formatted in RFC3339 UTC "Zulu" <ide> * format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z". Note that <ide> * since the time is in milliseconds, the last section of the time representation always <ide> * has 6 leading zeros.
Java
apache-2.0
1012d3ee86f4da14b9a2d8054eebf92dea69a7a6
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2008 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.util.xml; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.w3c.dom.CharacterData; import org.w3c.dom.Comment; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.springframework.util.Assert; /** * Convenience methods for working with the DOM API, * in particular for working with DOM Nodes and DOM Elements. * * @author Juergen Hoeller * @author Rob Harrop * @author Costin Leau * @since 1.2 * @see org.w3c.dom.Node * @see org.w3c.dom.Element */ public abstract class DomUtils { /** * Retrieve all child elements of the given DOM element that match any of * the given element names. Only look at the direct child level of the * given element; do not go into further depth (in contrast to the * DOM API's <code>getElementsByTagName</code> method). * @param ele the DOM element to analyze * @param childEleNames the child element names to look for * @return a List of child <code>org.w3c.dom.Element</code> instances * @see org.w3c.dom.Element * @see org.w3c.dom.Element#getElementsByTagName */ public static List getChildElementsByTagName(Element ele, String[] childEleNames) { Assert.notNull(ele, "Element must not be null"); Assert.notNull(childEleNames, "Element names collection must not be null"); List childEleNameList = Arrays.asList(childEleNames); NodeList nl = ele.getChildNodes(); List childEles = new ArrayList(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element && nodeNameMatch(node, childEleNameList)) { childEles.add(node); } } return childEles; } /** * Retrieve all child elements of the given DOM element that match * the given element name. Only look at the direct child level of the * given element; do not go into further depth (in contrast to the * DOM API's <code>getElementsByTagName</code> method). * @param ele the DOM element to analyze * @param childEleName the child element name to look for * @return a List of child <code>org.w3c.dom.Element</code> instances * @see org.w3c.dom.Element * @see org.w3c.dom.Element#getElementsByTagName */ public static List getChildElementsByTagName(Element ele, String childEleName) { return getChildElementsByTagName(ele, new String[] {childEleName}); } /** * Utility method that returns the first child element * identified by its name. * @param ele the DOM element to analyze * @param childEleName the child element name to look for * @return the <code>org.w3c.dom.Element</code> instance, * or <code>null</code> if none found */ public static Element getChildElementByTagName(Element ele, String childEleName) { Assert.notNull(ele, "Element must not be null"); Assert.notNull(childEleName, "Element name must not be null"); NodeList nl = ele.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element && nodeNameMatch(node, childEleName)) { return (Element) node; } } return null; } /** * Utility method that returns the first child element value * identified by its name. * @param ele the DOM element to analyze * @param childEleName the child element name to look for * @return the extracted text value, * or <code>null</code> if no child element found */ public static String getChildElementValueByTagName(Element ele, String childEleName) { Element child = getChildElementByTagName(ele, childEleName); return (child != null ? getTextValue(child) : null); } /** * Extract the text value from the given DOM element, ignoring XML comments. * <p>Appends all CharacterData nodes and EntityReference nodes * into a single String value, excluding Comment nodes. * @see CharacterData * @see EntityReference * @see Comment */ public static String getTextValue(Element valueEle) { Assert.notNull(valueEle, "Element must not be null"); StringBuffer value = new StringBuffer(); NodeList nl = valueEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) { value.append(item.getNodeValue()); } } return value.toString(); } /** * Namespace-aware equals comparison. Returns <code>true</code> if either * {@link Node#getLocalName} or {@link Node#getNodeName} equals <code>desiredName</code>, * otherwise returns <code>false</code>. */ public static boolean nodeNameEquals(Node node, String desiredName) { Assert.notNull(node, "Node must not be null"); Assert.notNull(desiredName, "Desired name must not be null"); return nodeNameMatch(node, desiredName); } /** * Matches the given node's name and local name against the given desired name. */ private static boolean nodeNameMatch(Node node, String desiredName) { return (desiredName.equals(node.getNodeName()) || desiredName.equals(node.getLocalName())); } /** * Matches the given node's name and local name against the given desired names. */ private static boolean nodeNameMatch(Node node, Collection desiredNames) { return (desiredNames.contains(node.getNodeName()) || desiredNames.contains(node.getLocalName())); } }
src/org/springframework/util/xml/DomUtils.java
/* * Copyright 2002-2008 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.util.xml; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.w3c.dom.CharacterData; import org.w3c.dom.Comment; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.springframework.util.Assert; /** * Convenience methods for working with the DOM API, * in particular for working with DOM Nodes and DOM Elements. * * @author Juergen Hoeller * @author Rob Harrop * @author Costin Leau * @since 1.2 * @see org.w3c.dom.Node * @see org.w3c.dom.Element */ public abstract class DomUtils { /** * Retrieve all child elements of the given DOM element that match any of * the given element names. Only look at the direct child level of the * given element; do not go into further depth (in contrast to the * DOM API's <code>getElementsByTagName</code> method). * @param ele the DOM element to analyze * @param childEleNames the child element names to look for * @return a List of child <code>org.w3c.dom.Element</code> instances * @see org.w3c.dom.Element * @see org.w3c.dom.Element#getElementsByTagName */ public static List getChildElementsByTagNames(Element ele, Collection childEleNames) { Assert.notNull(ele, "Element must not be null"); Assert.notNull(childEleNames, "Element names collection must not be null"); NodeList nl = ele.getChildNodes(); List childEles = new ArrayList(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element && nodeNameMatch(node, childEleNames)) { childEles.add(node); } } return childEles; } /** * Retrieve all child elements of the given DOM element that match * the given element name. Only look at the direct child level of the * given element; do not go into further depth (in contrast to the * DOM API's <code>getElementsByTagName</code> method). * @param ele the DOM element to analyze * @param childEleName the child element name to look for * @return a List of child <code>org.w3c.dom.Element</code> instances * @see org.w3c.dom.Element * @see org.w3c.dom.Element#getElementsByTagName */ public static List getChildElementsByTagName(Element ele, String childEleName) { return getChildElementsByTagNames(ele, Collections.singleton(childEleName)); } /** * Utility method that returns the first child element * identified by its name. * @param ele the DOM element to analyze * @param childEleName the child element name to look for * @return the <code>org.w3c.dom.Element</code> instance, * or <code>null</code> if none found */ public static Element getChildElementByTagName(Element ele, String childEleName) { Assert.notNull(ele, "Element must not be null"); Assert.notNull(childEleName, "Element name must not be null"); NodeList nl = ele.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element && nodeNameMatch(node, childEleName)) { return (Element) node; } } return null; } /** * Utility method that returns the first child element value * identified by its name. * @param ele the DOM element to analyze * @param childEleName the child element name to look for * @return the extracted text value, * or <code>null</code> if no child element found */ public static String getChildElementValueByTagName(Element ele, String childEleName) { Element child = getChildElementByTagName(ele, childEleName); return (child != null ? getTextValue(child) : null); } /** * Extract the text value from the given DOM element, ignoring XML comments. * <p>Appends all CharacterData nodes and EntityReference nodes * into a single String value, excluding Comment nodes. * @see CharacterData * @see EntityReference * @see Comment */ public static String getTextValue(Element valueEle) { Assert.notNull(valueEle, "Element must not be null"); StringBuffer value = new StringBuffer(); NodeList nl = valueEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) { value.append(item.getNodeValue()); } } return value.toString(); } /** * Namespace-aware equals comparison. Returns <code>true</code> if either * {@link Node#getLocalName} or {@link Node#getNodeName} equals <code>desiredName</code>, * otherwise returns <code>false</code>. */ public static boolean nodeNameEquals(Node node, String desiredName) { Assert.notNull(node, "Node must not be null"); Assert.notNull(desiredName, "Desired name must not be null"); return nodeNameMatch(node, desiredName); } /** * Matches the given node's name and local name against the given desired name. */ private static boolean nodeNameMatch(Node node, String desiredName) { return (desiredName.equals(node.getNodeName()) || desiredName.equals(node.getLocalName())); } /** * Matches the given node's name and local name against the given desired names. */ private static boolean nodeNameMatch(Node node, Collection desiredNames) { return (desiredNames.contains(node.getNodeName()) || desiredNames.contains(node.getLocalName())); } }
reworked "getChildElementsByTagNames" into "getChildElementsByTagName" with a String array argument git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@16490 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/util/xml/DomUtils.java
reworked "getChildElementsByTagNames" into "getChildElementsByTagName" with a String array argument
<ide><path>rc/org/springframework/util/xml/DomUtils.java <ide> package org.springframework.util.xml; <ide> <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.Collection; <del>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import org.w3c.dom.CharacterData; <ide> * @see org.w3c.dom.Element <ide> * @see org.w3c.dom.Element#getElementsByTagName <ide> */ <del> public static List getChildElementsByTagNames(Element ele, Collection childEleNames) { <add> public static List getChildElementsByTagName(Element ele, String[] childEleNames) { <ide> Assert.notNull(ele, "Element must not be null"); <ide> Assert.notNull(childEleNames, "Element names collection must not be null"); <add> List childEleNameList = Arrays.asList(childEleNames); <ide> NodeList nl = ele.getChildNodes(); <ide> List childEles = new ArrayList(); <ide> for (int i = 0; i < nl.getLength(); i++) { <ide> Node node = nl.item(i); <del> if (node instanceof Element && nodeNameMatch(node, childEleNames)) { <add> if (node instanceof Element && nodeNameMatch(node, childEleNameList)) { <ide> childEles.add(node); <ide> } <ide> } <ide> * @see org.w3c.dom.Element#getElementsByTagName <ide> */ <ide> public static List getChildElementsByTagName(Element ele, String childEleName) { <del> return getChildElementsByTagNames(ele, Collections.singleton(childEleName)); <add> return getChildElementsByTagName(ele, new String[] {childEleName}); <ide> } <ide> <ide> /**
Java
mit
error: pathspec 'src/main/java/fi/helsinki/cs/tmc/cli/tmcstuff/SettingsIO.java' did not match any file(s) known to git
18206871d198e29f59ba71d2b1876eeb98a4a5ea
1
tmc-cli/tmc-cli,tmc-cli/tmc-cli,testmycode/tmc-cli,testmycode/tmc-cli
package fi.helsinki.cs.tmc.cli.tmcstuff; /** * Reads and writes to config files on the system. */ public class SettingsIO { private String configPath; private String configFileName; public SettingsIO() { String os = System.getProperty("os.name").toLowerCase(); configFileName = "tmc.conf"; if (os.contains("windows")) { //TODO: Use proper Windows config file location this.configPath = System.getProperty("user.home") + configFileName; } else { //Assume we're using Unix (Linux, Mac OS X or *BSD) String configEnv = System.getenv("XDG_CONFIG_HOME"); if (configEnv != null) { this.configPath = configEnv + configFileName; } else { this.configPath = System.getProperty("user.home") + ".config/tmc/" + configFileName; } } } }
src/main/java/fi/helsinki/cs/tmc/cli/tmcstuff/SettingsIO.java
DO NOT MERGE, work in progress
src/main/java/fi/helsinki/cs/tmc/cli/tmcstuff/SettingsIO.java
DO NOT MERGE, work in progress
<ide><path>rc/main/java/fi/helsinki/cs/tmc/cli/tmcstuff/SettingsIO.java <add>package fi.helsinki.cs.tmc.cli.tmcstuff; <add> <add>/** <add> * Reads and writes to config files on the system. <add> */ <add>public class SettingsIO { <add> private String configPath; <add> private String configFileName; <add> <add> public SettingsIO() { <add> String os = System.getProperty("os.name").toLowerCase(); <add> configFileName = "tmc.conf"; <add> <add> if (os.contains("windows")) { <add> //TODO: Use proper Windows config file location <add> this.configPath = System.getProperty("user.home") + configFileName; <add> } else { <add> //Assume we're using Unix (Linux, Mac OS X or *BSD) <add> String configEnv = System.getenv("XDG_CONFIG_HOME"); <add> <add> if (configEnv != null) { <add> this.configPath = configEnv + configFileName; <add> } else { <add> this.configPath = System.getProperty("user.home") + ".config/tmc/" + configFileName; <add> } <add> } <add> } <add>}
JavaScript
mit
61d5679c73df9c6bb444ff61dc6745c361d8336a
0
atmajs/MaskJS,atmajs/MaskJS,atmajs/MaskJS
var Builder = { build: function(node, model, container, cntx) { if (node == null) { return container; } if (container == null) { container = document.createDocumentFragment(); } if (cntx == null) { cntx = { components: null }; } var parent = null, element = container, stack = [node], stackIndex = 0; while (node != null) { element = createNode(node, model, element, cntx); if (node.currentNode) { console.warn('this node is already visited', node); } node.currentNode = node.firstChild; if (node.currentNode != null) { parent = node; node = node.currentNode; parent.currentNode = node.nextNode; stack[++stackIndex] = element } else { while (parent != null) { if (parent.currentNode != null) { node = parent.currentNode; parent.currentNode = parent.currentNode.nextNode; break; } stackIndex--; node.currentNode = null; node = parent = parent.parent; } element = stack[stackIndex]; } } return container; } }; function createNode(node, model, container, cntx) { var j, jmax; if (CustomTags.all[node.tagName] != null) { /* if (!DEBUG) try { */ var Handler = CustomTags.all[node.tagName], custom = typeof Handler === 'function' ? new Handler(model) : Handler; custom.compoName = node.tagName; custom.firstChild = node.firstChild; //creating new attr object for custom handler, preventing collisions due to template caching custom.attr = Helper.extend(custom.attr, node.attr); (cntx.components || (cntx.components = [])).push(custom); custom.parent = cntx; if (listeners != null) { var fns = listeners['customCreated']; if (fns != null) { for (j = 0, jmax = fns.length; j < jmax; j++) { fns[j](custom, model, container); } } } custom.render(model, container, custom); /* if (!DEBUG) }catch(error){ console.error('Custom Tag Handler:', node.tagName, error.toString()); } */ return null; } if (node.content != null) { if (typeof node.content === 'function') { var arr = node.content(model, 'node', cntx, container), str = ''; j = 0; jmax = arr.length; for (; j < jmax; j++) { if (typeof arr[j] === 'object') { /* In this casee arr[j] should be any element */ if (str !== '') { container.appendChild(document.createTextNode(str)); str = ''; } container.appendChild(arr[j]); continue; } str += arr[j]; } if (str !== '') { container.appendChild(document.createTextNode(str)); } } else { container.appendChild(document.createTextNode(node.content)); } return null; } var tag = document.createElement(node.tagName), attr = node.attr, key, value; for (key in attr) { if (hasOwnProp.call(attr, key) === false) { continue; } if (typeof attr[key] === 'function') { value = attr[key](model, 'attr', cntx, tag, key).join(''); } else { value = attr[key]; } if (value) { // null or empty string will not be handled if (hasOwnProp.call(CustomAttributes, key) === true) { CustomAttributes[key](node, model, value, tag, cntx); } else { tag.setAttribute(key, value); } } } container.appendChild(tag); return tag; }
src/7.Builder.dom.iterate.js
var Builder = { build: function(node, model, container, cntx) { if (node == null) { return container; } if (container == null) { container = document.createDocumentFragment(); } if (cntx == null) { cntx = {}; } var parent, element = container, stack = [node], stackIndex = 0; while (node != null) { if (node.currentNode == null) { element = createNode(node, model, element, cntx); node.currentNode = node.firstChild; } if (node.currentNode != null) { parent = node; node = node.currentNode; parent.currentNode = node.nextNode; stack[++stackIndex] = element } else { while (parent != null) { if (parent.currentNode != null) { node = parent.currentNode; parent.currentNode = parent.currentNode.nextNode; break; } stackIndex--; node = parent = parent.parent; } element = stack[stackIndex]; } } return container; } }; function createNode(node, model, container, cntx) { var j, jmax; if (CustomTags.all[node.tagName] != null) { /* if (!DEBUG) try { */ var Handler = CustomTags.all[node.tagName], custom = Handler instanceof Function ? new Handler(model) : Handler; custom.compoName = node.tagName; custom.nodes = node.nodes; /* creating new attr object for custom handler, preventing collisions due to template caching */ custom.attr = Helper.extend(custom.attr, node.attr); (cntx.components || (cntx.components = [])).push(custom); custom.parent = cntx; if (listeners != null) { var fns = listeners['customCreated']; if (fns != null) { for (j = 0, jmax = fns.length; j < jmax; j++) { fns[j](custom, model, container); } } } custom.render(model, container, custom); /* if (!DEBUG) }catch(error){ console.error('Custom Tag Handler:', node.tagName, error.toString()); } */ return null; } if (node.content != null) { if (typeof node.content === 'function') { var arr = node.content(model, 'node', cntx, container), str = ''; j = 0; jmax = arr.length; for (; j < jmax; j++) { if (typeof arr[j] === 'object') { /* In this casee arr[j] should be any element */ if (str !== '') { container.appendChild(document.createTextNode(str)); str = ''; } container.appendChild(arr[j]); continue; } str += arr[j]; } if (str !== '') { container.appendChild(document.createTextNode(str)); } } else { container.appendChild(document.createTextNode(node.content)); } return null; } var tag = document.createElement(node.tagName), attr = node.attr; for (var key in attr) { if (hasOwnProp.call(attr, key) === true) { var value; if (typeof attr[key] === 'function') { value = attr[key](model, 'attr', cntx, tag, key).join(''); } else { value = attr[key]; } if (value) { if (CustomAttributes[key] != null) { CustomAttributes[key](node, model, value, tag, cntx); } else { tag.setAttribute(key, value); } } } } container.appendChild(tag); return tag; }
[refactor]
src/7.Builder.dom.iterate.js
[refactor]
<ide><path>rc/7.Builder.dom.iterate.js <ide> container = document.createDocumentFragment(); <ide> } <ide> if (cntx == null) { <del> cntx = {}; <add> cntx = { <add> components: null <add> }; <ide> } <ide> <ide> <del> var parent, element = container, <add> var parent = null, <add> element = container, <ide> stack = [node], <ide> stackIndex = 0; <ide> <ide> while (node != null) { <add> element = createNode(node, model, element, cntx); <ide> <del> if (node.currentNode == null) { <del> element = createNode(node, model, element, cntx); <del> <del> node.currentNode = node.firstChild; <add> if (node.currentNode) { <add> console.warn('this node is already visited', node); <ide> } <ide> <add> <add> node.currentNode = node.firstChild; <ide> <ide> if (node.currentNode != null) { <ide> parent = node; <ide> node = node.currentNode; <ide> <ide> parent.currentNode = node.nextNode; <del> <ide> stack[++stackIndex] = element <ide> <ide> } else { <ide> break; <ide> } <ide> stackIndex--; <add> node.currentNode = null; <add> <ide> node = parent = parent.parent; <ide> } <ide> <ide> element = stack[stackIndex]; <ide> } <del> <ide> } <ide> <ide> return container; <ide> try { <ide> */ <ide> var Handler = CustomTags.all[node.tagName], <del> custom = Handler instanceof Function ? new Handler(model) : Handler; <add> custom = typeof Handler === 'function' ? new Handler(model) : Handler; <ide> <ide> custom.compoName = node.tagName; <del> custom.nodes = node.nodes; /* creating new attr object for custom handler, preventing collisions due to template caching */ <add> custom.firstChild = node.firstChild; <add> //creating new attr object for custom handler, preventing collisions due to template caching <ide> custom.attr = Helper.extend(custom.attr, node.attr); <ide> <ide> (cntx.components || (cntx.components = [])).push(custom); <ide> <ide> return null; <ide> } <add> <ide> if (node.content != null) { <ide> if (typeof node.content === 'function') { <ide> var arr = node.content(model, 'node', cntx, container), <ide> } <ide> <ide> var tag = document.createElement(node.tagName), <del> attr = node.attr; <del> for (var key in attr) { <del> if (hasOwnProp.call(attr, key) === true) { <del> var value; <del> if (typeof attr[key] === 'function') { <del> value = attr[key](model, 'attr', cntx, tag, key).join(''); <add> attr = node.attr, <add> key, <add> value; <add> <add> for (key in attr) { <add> <add> if (hasOwnProp.call(attr, key) === false) { <add> continue; <add> } <add> <add> if (typeof attr[key] === 'function') { <add> value = attr[key](model, 'attr', cntx, tag, key).join(''); <add> } else { <add> value = attr[key]; <add> } <add> <add> if (value) { <add> // null or empty string will not be handled <add> if (hasOwnProp.call(CustomAttributes, key) === true) { <add> CustomAttributes[key](node, model, value, tag, cntx); <ide> } else { <del> value = attr[key]; <del> } <del> if (value) { <del> <del> if (CustomAttributes[key] != null) { <del> CustomAttributes[key](node, model, value, tag, cntx); <del> } else { <del> tag.setAttribute(key, value); <del> } <add> tag.setAttribute(key, value); <ide> } <ide> } <add> <ide> } <ide> <ide> container.appendChild(tag);
Java
apache-2.0
5fb125b329de1a90d38d4e6a7387c4d9b1d6ac80
0
Doloops/arondor-common-reflection,Doloops/arondor-common-reflection
package com.arondor.common.reflection.gwt.client.nview; import java.util.logging.Logger; import com.arondor.common.reflection.gwt.client.presenter.ClassTreeNodePresenter.ClassDisplay; import com.arondor.common.reflection.gwt.client.presenter.TreeNodePresenter.Display; import com.arondor.common.reflection.gwt.client.presenter.fields.ListTreeNodePresenter.ListRootDisplay; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.FlowPanel; import gwt.material.design.client.ui.MaterialButton; /** * TODO : Implement this ! */ public class NListView extends NNodeView implements ListRootDisplay { private static final Logger LOG = Logger.getLogger(NListView.class.getName()); private final MaterialButton addButton = new MaterialButton(); // private final FlowPanel inputGroupPanel = new FlowPanel(); public NListView() { // LOG.severe(">> asking to create a listView"); // inputGroupPanel.getElement().setAttribute("style", "border:3px solid red"); // add(inputGroupPanel); } @Override public void setNodeDescription(String description) { // TODO Auto-generated method stub LOG.severe("Node description is : " + description); } @Override public HasClickHandlers addElementClickHandler() { return addButton; } @Override public void removeChild(Display childDisplay) { // TODO Auto-generated method stub } @Override public ClassDisplay createChildDisplay() { // TODO Auto-generated method stub return null; } }
arondor-common-reflection-gwt/src/main/java/com/arondor/common/reflection/gwt/client/nview/NListView.java
package com.arondor.common.reflection.gwt.client.nview; import java.util.logging.Logger; import com.arondor.common.reflection.gwt.client.presenter.ClassTreeNodePresenter.ClassDisplay; import com.arondor.common.reflection.gwt.client.presenter.TreeNodePresenter.Display; import com.arondor.common.reflection.gwt.client.presenter.fields.ListTreeNodePresenter.ListRootDisplay; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.FlowPanel; import gwt.material.design.client.ui.MaterialButton; /** * TODO : Implement this ! */ public class NListView extends NNodeView implements ListRootDisplay { private static final Logger LOG = Logger.getLogger(NListView.class.getName()); private final MaterialButton addButton = new MaterialButton(); private final FlowPanel inputGroupPanel = new FlowPanel(); public NListView() { LOG.severe(">> asking to create a listView"); inputGroupPanel.getElement().setAttribute("style", "border:3px solid red"); add(inputGroupPanel); } @Override public void setNodeDescription(String description) { // TODO Auto-generated method stub LOG.severe(">> node description is : " + description); } @Override public HasClickHandlers addElementClickHandler() { return addButton; } @Override public void removeChild(Display childDisplay) { // TODO Auto-generated method stub } @Override public ClassDisplay createChildDisplay() { // TODO Auto-generated method stub return null; } }
#34 WiP for ListView (not prioritary) - last details to disable
arondor-common-reflection-gwt/src/main/java/com/arondor/common/reflection/gwt/client/nview/NListView.java
#34 WiP for ListView (not prioritary) - last details to disable
<ide><path>rondor-common-reflection-gwt/src/main/java/com/arondor/common/reflection/gwt/client/nview/NListView.java <ide> <ide> private final MaterialButton addButton = new MaterialButton(); <ide> <del> private final FlowPanel inputGroupPanel = new FlowPanel(); <add> // private final FlowPanel inputGroupPanel = new FlowPanel(); <ide> <ide> public NListView() <ide> { <del> LOG.severe(">> asking to create a listView"); <del> inputGroupPanel.getElement().setAttribute("style", "border:3px solid red"); <del> add(inputGroupPanel); <add> // LOG.severe(">> asking to create a listView"); <add> // inputGroupPanel.getElement().setAttribute("style", "border:3px solid red"); <add> // add(inputGroupPanel); <ide> } <ide> <ide> @Override <ide> public void setNodeDescription(String description) <ide> { <ide> // TODO Auto-generated method stub <del> LOG.severe(">> node description is : " + description); <add> LOG.severe("Node description is : " + description); <ide> } <ide> <ide> @Override
Java
bsd-3-clause
4745054339a231a8bb5e7049656fae34f94d0b14
0
tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui; import pythagoras.f.Point; import playn.core.Layer; import playn.core.Pointer; /** * The base class for all user interface widgets. Provides helper methods for managing a canvas * into which a widget is rendered when its state changes. */ public abstract class Widget<T extends Widget<T>> extends Element<T> { /** * Widgets that are interactive can call this method to wire up the appropriate listeners. */ protected void enableInteraction () { // an interactive widget absorbs clicks and does not descend (propagate them to sublayers) set(Flag.HIT_DESCEND, false); set(Flag.HIT_ABSORB, true); // add a pointer listener for handling mouse events layer.addListener(new Pointer.Listener() { public void onPointerStart (Pointer.Event event) { Widget.this.onPointerStart(event, event.localX(), event.localY()); } public void onPointerDrag (Pointer.Event event) { Widget.this.onPointerDrag(event, event.localX(), event.localY()); } public void onPointerEnd (Pointer.Event event) { Widget.this.onPointerEnd(event, event.localX(), event.localY()); } public void onPointerCancel (Pointer.Event event) { Widget.this.onPointerCancel(event); } }); } /** * Called when the a touch/drag is started within the bounds of this component. * * @param event the pointer event that triggered this call. * @param x the x-coordinate of the event, translated into this element's coordinates. * @param y the y-coordinate of the event, translated into this element's coordinates. */ protected void onPointerStart (Pointer.Event event, float x, float y) { } /** * Called when a touch that started within the bounds of this component is dragged. The drag * may progress outside the bounds of this component, but the events will still be dispatched * to this component until the touch is released. * * @param event the pointer event that triggered this call. * @param x the x-coordinate of the event, translated into this element's coordinates. * @param y the y-coordinate of the event, translated into this element's coordinates. */ protected void onPointerDrag (Pointer.Event event, float x, float y) { } /** * Called when a touch that started within the bounds of this component is released. The * coordinates may be outside the bounds of this component, but the touch in question started * inside this component's bounds. * * @param event the pointer event that triggered this call. * @param x the x-coordinate of the event, translated into this element's coordinates. * @param y the y-coordinate of the event, translated into this element's coordinates. */ protected void onPointerEnd (Pointer.Event event, float x, float y) { } /** * Called when a touch that started within the bounds of this component is canceled. This * should generally terminate any active interaction without triggering a click, etc. * * @param event the pointer event that triggered this call. */ protected void onPointerCancel (Pointer.Event event) { } /** * Extends base Glyph to automatically wire up to this Widget's {@link #layer}. */ protected class Glyph extends tripleplay.util.Glyph { public Glyph () { super(layer); } } }
core/src/main/java/tripleplay/ui/Widget.java
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui; import pythagoras.f.Point; import playn.core.Layer; import playn.core.Pointer; /** * The base class for all user interface widgets. Provides helper methods for managing a canvas * into which a widget is rendered when its state changes. */ public abstract class Widget<T extends Widget<T>> extends Element<T> { /** * Widgets that are interactive can call this method to wire up the appropriate listeners. */ protected void enableInteraction () { // we receive all pointer events for a root in that root and then dispatch events via our // custom mechanism from there on down set(Flag.HIT_DESCEND, false); set(Flag.HIT_ABSORB, true); // add a pointer listener for handling mouse events layer.addListener(new Pointer.Listener() { public void onPointerStart (Pointer.Event event) { Widget.this.onPointerStart(event, event.localX(), event.localY()); } public void onPointerDrag (Pointer.Event event) { Widget.this.onPointerDrag(event, event.localX(), event.localY()); } public void onPointerEnd (Pointer.Event event) { Widget.this.onPointerEnd(event, event.localX(), event.localY()); } public void onPointerCancel (Pointer.Event event) { Widget.this.onPointerCancel(event); } }); } /** * Called when the a touch/drag is started within the bounds of this component. * * @param event the pointer event that triggered this call. * @param x the x-coordinate of the event, translated into this element's coordinates. * @param y the y-coordinate of the event, translated into this element's coordinates. */ protected void onPointerStart (Pointer.Event event, float x, float y) { } /** * Called when a touch that started within the bounds of this component is dragged. The drag * may progress outside the bounds of this component, but the events will still be dispatched * to this component until the touch is released. * * @param event the pointer event that triggered this call. * @param x the x-coordinate of the event, translated into this element's coordinates. * @param y the y-coordinate of the event, translated into this element's coordinates. */ protected void onPointerDrag (Pointer.Event event, float x, float y) { } /** * Called when a touch that started within the bounds of this component is released. The * coordinates may be outside the bounds of this component, but the touch in question started * inside this component's bounds. * * @param event the pointer event that triggered this call. * @param x the x-coordinate of the event, translated into this element's coordinates. * @param y the y-coordinate of the event, translated into this element's coordinates. */ protected void onPointerEnd (Pointer.Event event, float x, float y) { } /** * Called when a touch that started within the bounds of this component is canceled. This * should generally terminate any active interaction without triggering a click, etc. * * @param event the pointer event that triggered this call. */ protected void onPointerCancel (Pointer.Event event) { } /** * Extends base Glyph to automatically wire up to this Widget's {@link #layer}. */ protected class Glyph extends tripleplay.util.Glyph { public Glyph () { super(layer); } } }
Update old, misleading comment.
core/src/main/java/tripleplay/ui/Widget.java
Update old, misleading comment.
<ide><path>ore/src/main/java/tripleplay/ui/Widget.java <ide> * Widgets that are interactive can call this method to wire up the appropriate listeners. <ide> */ <ide> protected void enableInteraction () { <del> // we receive all pointer events for a root in that root and then dispatch events via our <del> // custom mechanism from there on down <add> // an interactive widget absorbs clicks and does not descend (propagate them to sublayers) <ide> set(Flag.HIT_DESCEND, false); <ide> set(Flag.HIT_ABSORB, true); <ide>
Java
apache-2.0
db8a390af9ef2119a473b93ca1d820ccfda5c4c3
0
Terracotta-OSS/terracotta-platform,chrisdennis/terracotta-platform,albinsuresh/terracotta-platform,albinsuresh/terracotta-platform,Terracotta-OSS/terracotta-platform,chrisdennis/terracotta-platform
/* * Copyright Terracotta, 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.terracotta.dynamic_config.cli.config_tool; import com.beust.jcommander.ParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terracotta.common.struct.TimeUnit; import org.terracotta.diagnostic.client.connection.ConcurrencySizing; import org.terracotta.diagnostic.client.connection.ConcurrentDiagnosticServiceProvider; import org.terracotta.diagnostic.client.connection.DiagnosticServiceProvider; import org.terracotta.diagnostic.client.connection.MultiDiagnosticServiceProvider; import org.terracotta.dynamic_config.api.model.NodeContext; import org.terracotta.dynamic_config.cli.command.CommandRepository; import org.terracotta.dynamic_config.cli.command.CustomJCommander; import org.terracotta.dynamic_config.cli.command.RemoteMainCommand; import org.terracotta.dynamic_config.cli.config_tool.command.ActivateCommand; import org.terracotta.dynamic_config.cli.config_tool.command.AttachCommand; import org.terracotta.dynamic_config.cli.config_tool.command.DetachCommand; import org.terracotta.dynamic_config.cli.config_tool.command.DiagnosticCommand; import org.terracotta.dynamic_config.cli.config_tool.command.ExportCommand; import org.terracotta.dynamic_config.cli.config_tool.command.GetCommand; import org.terracotta.dynamic_config.cli.config_tool.command.ImportCommand; import org.terracotta.dynamic_config.cli.config_tool.command.LogCommand; import org.terracotta.dynamic_config.cli.config_tool.command.RepairCommand; import org.terracotta.dynamic_config.cli.config_tool.command.SetCommand; import org.terracotta.dynamic_config.cli.config_tool.command.UnsetCommand; import org.terracotta.dynamic_config.cli.config_tool.nomad.NomadManager; import org.terracotta.dynamic_config.cli.config_tool.restart.RestartService; import org.terracotta.dynamic_config.cli.config_tool.stop.StopService; import org.terracotta.nomad.NomadEnvironment; import org.terracotta.nomad.entity.client.NomadEntity; import org.terracotta.nomad.entity.client.NomadEntityProvider; import java.time.Duration; import java.util.Arrays; import java.util.HashSet; import static java.lang.System.lineSeparator; public class ConfigTool { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigTool.class); public static void main(String... args) { try { ConfigTool.start(args); } catch (Exception e) { String message = e.getMessage(); if (message != null && !message.isEmpty()) { if (LOGGER.isDebugEnabled()) { LOGGER.error("{}Error:", lineSeparator(), e); // do not output e.getMassage() because it duplicates the output } else { LOGGER.error("{}Error:{}{}{}", lineSeparator(), lineSeparator(), message, lineSeparator()); } } else { LOGGER.error("{}Internal error:", lineSeparator(), e); } System.exit(1); } } public static void start(String... args) { final RemoteMainCommand mainCommand = new RemoteMainCommand(); LOGGER.debug("Registering commands with CommandRepository"); CommandRepository commandRepository = new CommandRepository(); commandRepository.addAll( new HashSet<>( Arrays.asList( mainCommand, new ActivateCommand(), new AttachCommand(), new DetachCommand(), new ImportCommand(), new ExportCommand(), new GetCommand(), new SetCommand(), new UnsetCommand(), new DiagnosticCommand(), new RepairCommand(), new LogCommand() ) ) ); LOGGER.debug("Parsing command-line arguments"); CustomJCommander jCommander = parseArguments(commandRepository, mainCommand, args); // Process arguments like '-v' mainCommand.validate(); mainCommand.run(); ConcurrencySizing concurrencySizing = new ConcurrencySizing(); Duration connectionTimeout = Duration.ofMillis(mainCommand.getConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); Duration requestTimeout = Duration.ofMillis(mainCommand.getRequestTimeout().getQuantity(TimeUnit.MILLISECONDS)); Duration entityOperationTimeout = Duration.ofMillis(mainCommand.getEntityOperationTimeout().getQuantity(TimeUnit.MILLISECONDS)); Duration entityConnectionTimeout = Duration.ofMillis(mainCommand.getEntityConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); // create services DiagnosticServiceProvider diagnosticServiceProvider = new DiagnosticServiceProvider("CONFIG-TOOL", connectionTimeout, requestTimeout, mainCommand.getSecurityRootDirectory()); MultiDiagnosticServiceProvider multiDiagnosticServiceProvider = new ConcurrentDiagnosticServiceProvider(diagnosticServiceProvider, connectionTimeout, concurrencySizing); NomadEntityProvider nomadEntityProvider = new NomadEntityProvider( "CONFIG-TOOL", entityConnectionTimeout, // A long timeout is important here. // We need to block the call and wait for any return. // We cannot timeout shortly otherwise we won't know the outcome of the 2PC Nomad transaction in case of a failover. new NomadEntity.Settings().setRequestTimeout(entityOperationTimeout), mainCommand.getSecurityRootDirectory()); NomadManager<NodeContext> nomadManager = new NomadManager<>(new NomadEnvironment(), multiDiagnosticServiceProvider, nomadEntityProvider); RestartService restartService = new RestartService(diagnosticServiceProvider, concurrencySizing); StopService stopService = new StopService(diagnosticServiceProvider, concurrencySizing); LOGGER.debug("Injecting services in CommandRepository"); commandRepository.inject(diagnosticServiceProvider, multiDiagnosticServiceProvider, nomadManager, restartService, stopService); jCommander.getAskedCommand().map(command -> { // check for help if (command.isHelp()) { jCommander.printUsage(); return true; } // validate the real command command.validate(); // run the real command command.run(); return true; }).orElseGet(() -> { // If no command is provided, process help command jCommander.usage(); return false; }); } private static CustomJCommander parseArguments(CommandRepository commandRepository, RemoteMainCommand mainCommand, String[] args) { CustomJCommander jCommander = new CustomJCommander("config-tool", commandRepository, mainCommand); try { jCommander.parse(args); } catch (ParameterException e) { jCommander.printUsage(); throw e; } return jCommander; } }
dynamic-config/cli/config-tool/src/main/java/org/terracotta/dynamic_config/cli/config_tool/ConfigTool.java
/* * Copyright Terracotta, 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.terracotta.dynamic_config.cli.config_tool; import com.beust.jcommander.ParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terracotta.common.struct.TimeUnit; import org.terracotta.diagnostic.client.connection.ConcurrencySizing; import org.terracotta.diagnostic.client.connection.ConcurrentDiagnosticServiceProvider; import org.terracotta.diagnostic.client.connection.DiagnosticServiceProvider; import org.terracotta.diagnostic.client.connection.MultiDiagnosticServiceProvider; import org.terracotta.dynamic_config.api.model.NodeContext; import org.terracotta.dynamic_config.cli.command.CommandRepository; import org.terracotta.dynamic_config.cli.command.CustomJCommander; import org.terracotta.dynamic_config.cli.command.RemoteMainCommand; import org.terracotta.dynamic_config.cli.config_tool.command.ActivateCommand; import org.terracotta.dynamic_config.cli.config_tool.command.AttachCommand; import org.terracotta.dynamic_config.cli.config_tool.command.DetachCommand; import org.terracotta.dynamic_config.cli.config_tool.command.DiagnosticCommand; import org.terracotta.dynamic_config.cli.config_tool.command.ExportCommand; import org.terracotta.dynamic_config.cli.config_tool.command.GetCommand; import org.terracotta.dynamic_config.cli.config_tool.command.ImportCommand; import org.terracotta.dynamic_config.cli.config_tool.command.LogCommand; import org.terracotta.dynamic_config.cli.config_tool.command.RepairCommand; import org.terracotta.dynamic_config.cli.config_tool.command.SetCommand; import org.terracotta.dynamic_config.cli.config_tool.command.UnsetCommand; import org.terracotta.dynamic_config.cli.config_tool.nomad.NomadManager; import org.terracotta.dynamic_config.cli.config_tool.restart.RestartService; import org.terracotta.dynamic_config.cli.config_tool.stop.StopService; import org.terracotta.nomad.NomadEnvironment; import org.terracotta.nomad.entity.client.NomadEntity; import org.terracotta.nomad.entity.client.NomadEntityProvider; import java.time.Duration; import java.util.Arrays; import java.util.HashSet; import static java.lang.System.lineSeparator; public class ConfigTool { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigTool.class); private static final RemoteMainCommand MAIN = new RemoteMainCommand(); public static void main(String... args) { try { ConfigTool.start(args); } catch (Exception e) { String message = e.getMessage(); if (message != null && !message.isEmpty()) { if (LOGGER.isDebugEnabled()) { LOGGER.error("{}Error:", lineSeparator(), e); // do not output e.getMassage() because it duplicates the output } else { LOGGER.error("{}Error:{}{}{}", lineSeparator(), lineSeparator(), message, lineSeparator()); } } else { LOGGER.error("{}Internal error:", lineSeparator(), e); } System.exit(1); } } public static void start(String... args) { LOGGER.debug("Registering commands with CommandRepository"); CommandRepository commandRepository = new CommandRepository(); commandRepository.addAll( new HashSet<>( Arrays.asList( MAIN, new ActivateCommand(), new AttachCommand(), new DetachCommand(), new ImportCommand(), new ExportCommand(), new GetCommand(), new SetCommand(), new UnsetCommand(), new DiagnosticCommand(), new RepairCommand(), new LogCommand() ) ) ); LOGGER.debug("Parsing command-line arguments"); CustomJCommander jCommander = parseArguments(commandRepository, args); // Process arguments like '-v' MAIN.validate(); MAIN.run(); ConcurrencySizing concurrencySizing = new ConcurrencySizing(); Duration connectionTimeout = Duration.ofMillis(MAIN.getConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); Duration requestTimeout = Duration.ofMillis(MAIN.getRequestTimeout().getQuantity(TimeUnit.MILLISECONDS)); Duration entityOperationTimeout = Duration.ofMillis(MAIN.getEntityOperationTimeout().getQuantity(TimeUnit.MILLISECONDS)); Duration entityConnectionTimeout = Duration.ofMillis(MAIN.getEntityConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); // create services DiagnosticServiceProvider diagnosticServiceProvider = new DiagnosticServiceProvider("CONFIG-TOOL", connectionTimeout, requestTimeout, MAIN.getSecurityRootDirectory()); MultiDiagnosticServiceProvider multiDiagnosticServiceProvider = new ConcurrentDiagnosticServiceProvider(diagnosticServiceProvider, connectionTimeout, concurrencySizing); NomadEntityProvider nomadEntityProvider = new NomadEntityProvider( "CONFIG-TOOL", entityConnectionTimeout, // A long timeout is important here. // We need to block the call and wait for any return. // We cannot timeout shortly otherwise we won't know the outcome of the 2PC Nomad transaction in case of a failover. new NomadEntity.Settings().setRequestTimeout(entityOperationTimeout), MAIN.getSecurityRootDirectory()); NomadManager<NodeContext> nomadManager = new NomadManager<>(new NomadEnvironment(), multiDiagnosticServiceProvider, nomadEntityProvider); RestartService restartService = new RestartService(diagnosticServiceProvider, concurrencySizing); StopService stopService = new StopService(diagnosticServiceProvider, concurrencySizing); LOGGER.debug("Injecting services in CommandRepository"); commandRepository.inject(diagnosticServiceProvider, multiDiagnosticServiceProvider, nomadManager, restartService, stopService); jCommander.getAskedCommand().map(command -> { // check for help if (command.isHelp()) { jCommander.printUsage(); return true; } // validate the real command command.validate(); // run the real command command.run(); return true; }).orElseGet(() -> { // If no command is provided, process help command jCommander.usage(); return false; }); } private static CustomJCommander parseArguments(CommandRepository commandRepository, String[] args) { CustomJCommander jCommander = new CustomJCommander("config-tool", commandRepository, MAIN); try { jCommander.parse(args); } catch (ParameterException e) { jCommander.printUsage(); throw e; } return jCommander; } }
Made RemoteMainCommand reference non-static so that multiple tests can successfully call ConfigTool.main with unrelated CLI arguments
dynamic-config/cli/config-tool/src/main/java/org/terracotta/dynamic_config/cli/config_tool/ConfigTool.java
Made RemoteMainCommand reference non-static so that multiple tests can successfully call ConfigTool.main with unrelated CLI arguments
<ide><path>ynamic-config/cli/config-tool/src/main/java/org/terracotta/dynamic_config/cli/config_tool/ConfigTool.java <ide> <ide> public class ConfigTool { <ide> private static final Logger LOGGER = LoggerFactory.getLogger(ConfigTool.class); <del> private static final RemoteMainCommand MAIN = new RemoteMainCommand(); <ide> <ide> public static void main(String... args) { <ide> try { <ide> } <ide> <ide> public static void start(String... args) { <add> final RemoteMainCommand mainCommand = new RemoteMainCommand(); <ide> LOGGER.debug("Registering commands with CommandRepository"); <ide> CommandRepository commandRepository = new CommandRepository(); <ide> commandRepository.addAll( <ide> new HashSet<>( <ide> Arrays.asList( <del> MAIN, <add> mainCommand, <ide> new ActivateCommand(), <ide> new AttachCommand(), <ide> new DetachCommand(), <ide> ); <ide> <ide> LOGGER.debug("Parsing command-line arguments"); <del> CustomJCommander jCommander = parseArguments(commandRepository, args); <add> CustomJCommander jCommander = parseArguments(commandRepository, mainCommand, args); <ide> <ide> // Process arguments like '-v' <del> MAIN.validate(); <del> MAIN.run(); <add> mainCommand.validate(); <add> mainCommand.run(); <ide> <ide> ConcurrencySizing concurrencySizing = new ConcurrencySizing(); <del> Duration connectionTimeout = Duration.ofMillis(MAIN.getConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); <del> Duration requestTimeout = Duration.ofMillis(MAIN.getRequestTimeout().getQuantity(TimeUnit.MILLISECONDS)); <del> Duration entityOperationTimeout = Duration.ofMillis(MAIN.getEntityOperationTimeout().getQuantity(TimeUnit.MILLISECONDS)); <del> Duration entityConnectionTimeout = Duration.ofMillis(MAIN.getEntityConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); <add> Duration connectionTimeout = Duration.ofMillis(mainCommand.getConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); <add> Duration requestTimeout = Duration.ofMillis(mainCommand.getRequestTimeout().getQuantity(TimeUnit.MILLISECONDS)); <add> Duration entityOperationTimeout = Duration.ofMillis(mainCommand.getEntityOperationTimeout().getQuantity(TimeUnit.MILLISECONDS)); <add> Duration entityConnectionTimeout = Duration.ofMillis(mainCommand.getEntityConnectionTimeout().getQuantity(TimeUnit.MILLISECONDS)); <ide> <ide> // create services <del> DiagnosticServiceProvider diagnosticServiceProvider = new DiagnosticServiceProvider("CONFIG-TOOL", connectionTimeout, requestTimeout, MAIN.getSecurityRootDirectory()); <add> DiagnosticServiceProvider diagnosticServiceProvider = new DiagnosticServiceProvider("CONFIG-TOOL", connectionTimeout, requestTimeout, mainCommand.getSecurityRootDirectory()); <ide> MultiDiagnosticServiceProvider multiDiagnosticServiceProvider = new ConcurrentDiagnosticServiceProvider(diagnosticServiceProvider, connectionTimeout, concurrencySizing); <ide> NomadEntityProvider nomadEntityProvider = new NomadEntityProvider( <ide> "CONFIG-TOOL", <ide> // We need to block the call and wait for any return. <ide> // We cannot timeout shortly otherwise we won't know the outcome of the 2PC Nomad transaction in case of a failover. <ide> new NomadEntity.Settings().setRequestTimeout(entityOperationTimeout), <del> MAIN.getSecurityRootDirectory()); <add> mainCommand.getSecurityRootDirectory()); <ide> NomadManager<NodeContext> nomadManager = new NomadManager<>(new NomadEnvironment(), multiDiagnosticServiceProvider, nomadEntityProvider); <ide> RestartService restartService = new RestartService(diagnosticServiceProvider, concurrencySizing); <ide> StopService stopService = new StopService(diagnosticServiceProvider, concurrencySizing); <ide> }); <ide> } <ide> <del> private static CustomJCommander parseArguments(CommandRepository commandRepository, String[] args) { <del> CustomJCommander jCommander = new CustomJCommander("config-tool", commandRepository, MAIN); <add> private static CustomJCommander parseArguments(CommandRepository commandRepository, RemoteMainCommand mainCommand, String[] args) { <add> CustomJCommander jCommander = new CustomJCommander("config-tool", commandRepository, mainCommand); <ide> try { <ide> jCommander.parse(args); <ide> } catch (ParameterException e) {
Java
apache-2.0
e2ae773a344bc5ee844d4c486b217b92ef2d3574
0
arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint
/* * Copyright (c) 2010-2018 Evolveum * * 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.evolveum.midpoint.repo.sql.helpers.modify; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.NameItemPathSegment; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.sql.data.RepositoryContext; import com.evolveum.midpoint.repo.sql.data.common.ObjectReference; import com.evolveum.midpoint.repo.sql.data.common.RObject; import com.evolveum.midpoint.repo.sql.data.common.RObjectReference; import com.evolveum.midpoint.repo.sql.data.common.container.RAssignment; import com.evolveum.midpoint.repo.sql.data.common.container.RExclusion; import com.evolveum.midpoint.repo.sql.data.common.container.ROperationExecution; import com.evolveum.midpoint.repo.sql.data.common.container.RTrigger; import com.evolveum.midpoint.repo.sql.data.common.embedded.*; import com.evolveum.midpoint.repo.sql.data.common.enums.SchemaEnum; import com.evolveum.midpoint.repo.sql.data.common.other.RReferenceOwner; import com.evolveum.midpoint.repo.sql.util.DtoTranslationException; import com.evolveum.midpoint.repo.sql.util.RUtil; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.xml.namespace.QName; import java.util.HashMap; import java.util.Map; /** * @Author Viliam Repan (lazyman). */ @Component public class PrismEntityMapper { private static final Map<Key, Mapper> mappers = new HashMap<>(); static { mappers.put(new Key(Enum.class, SchemaEnum.class), new EnumMapper()); mappers.put(new Key(PolyString.class, RPolyString.class), new PolyStringMapper()); mappers.put(new Key(ActivationType.class, RActivation.class), new ActivationMapper()); mappers.put(new Key(Referencable.class, REmbeddedReference.class), new EmbeddedObjectReferenceMapper()); mappers.put(new Key(OperationalStateType.class, ROperationalState.class), new OperationalStateMapper()); mappers.put(new Key(AutoassignSpecificationType.class, RAutoassignSpecification.class), new AutoassignSpecificationMapper()); mappers.put(new Key(QName.class, String.class), new QNameMapper()); mappers.put(new Key(Referencable.class, RObjectReference.class), new ObjectReferenceMapper()); mappers.put(new Key(AssignmentType.class, RAssignment.class), new AssignmentMapper()); mappers.put(new Key(TriggerType.class, RTrigger.class), new TriggerMapper()); mappers.put(new Key(OperationExecutionType.class, ROperationExecution.class), new OperationExecutionMapper()); } @Autowired private RepositoryService repositoryService; @Autowired private PrismContext prismContext; public boolean supports(Class inputType, Class outputType) { Key key = buildKey(inputType, outputType); return mappers.containsKey(key); } public <I, O> O map(I input, Class<O> outputType) { return map(input, outputType, null); } public <I, O> O map(I input, Class<O> outputType, MapperContext context) { if (input == null) { return null; } if (!supports(input.getClass(), outputType)) { return (O) input; } if (context == null) { context = new MapperContext(); } context.setPrismContext(prismContext); context.setRepositoryService(repositoryService); Key key = buildKey(input.getClass(), outputType); Mapper<I, O> mapper = mappers.get(key); if (mapper == null) { throw new SystemException("Can't map '" + input.getClass() + "' to '" + outputType + "'"); } return mapper.map(input, context); } //RObjectTextInfo //RLookupTableRow //RAccessCertificationWorkItem //RAssignmentReference //RFocusPhoto //RObjectReference //RObjectDeltaOperation //ROperationExecution //RAccessCertificationCase //RAssignment //RCertWorkItemReference //RTrigger public <O> O mapPrismValue(PrismValue input, Class<O> outputType, MapperContext context) { if (input instanceof PrismPropertyValue) { return map(input.getRealValue(), outputType, context); } else if (input instanceof PrismReferenceValue) { ObjectReferenceType ref = new ObjectReferenceType(); ref.setupReferenceValue((PrismReferenceValue) input); return map(ref, outputType, context); } else if (input instanceof PrismContainerValue) { Class<Containerable> inputType = (Class) input.getRealClass(); try { Containerable container = inputType.newInstance(); container.setupContainerValue((PrismContainerValue) input); return map(container, outputType, context); } catch (Exception ex) { throw new RuntimeException(ex); //todo error handling } } // todo implement transformation from prism to entity return (O) input; } private Key buildKey(Class inputType, Class outputType) { if (isSchemaEnum(inputType, outputType)) { return new Key(Enum.class, SchemaEnum.class); } if (Referencable.class.isAssignableFrom(inputType)) { return new Key(Referencable.class, outputType); } return new Key(inputType, outputType); } private boolean isSchemaEnum(Class inputType, Class outputType) { return Enum.class.isAssignableFrom(inputType) && SchemaEnum.class.isAssignableFrom(outputType); } private static class OperationExecutionMapper implements Mapper<OperationExecutionType, ROperationExecution> { @Override public ROperationExecution map(OperationExecutionType input, MapperContext context) { ROperationExecution execution = new ROperationExecution(); RObject owner = (RObject) context.getOwner(); RepositoryContext repositoryContext = new RepositoryContext(context.getRepositoryService(), context.getPrismContext()); try { ROperationExecution.copyFromJAXB(input, execution, owner, repositoryContext); } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate trigger to entity", ex); } return execution; } } private static class TriggerMapper implements Mapper<TriggerType, RTrigger> { @Override public RTrigger map(TriggerType input, MapperContext context) { RTrigger trigger = new RTrigger(); RObject owner = (RObject) context.getOwner(); RepositoryContext repositoryContext = new RepositoryContext(context.getRepositoryService(), context.getPrismContext()); try { RTrigger.copyFromJAXB(input, trigger, owner, repositoryContext); } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate trigger to entity", ex); } return trigger; } } private static class AssignmentMapper implements Mapper<AssignmentType, RAssignment> { @Override public RAssignment map(AssignmentType input, MapperContext context) { RAssignment ass = new RAssignment(); RObject owner = (RObject) context.getOwner(); RepositoryContext repositoryContext = new RepositoryContext(context.getRepositoryService(), context.getPrismContext()); try { RAssignment.copyFromJAXB(input, ass, owner, repositoryContext); } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate assignment to entity", ex); } return ass; } } private static class ObjectReferenceMapper implements Mapper<Referencable, RObjectReference> { @Override public RObjectReference map(Referencable input, MapperContext context) { ObjectReferenceType objectRef; if (input instanceof ObjectReferenceType) { objectRef = (ObjectReferenceType) input; } else { objectRef = new ObjectReferenceType(); objectRef.setupReferenceValue(input.asReferenceValue()); } RObject owner = (RObject) context.getOwner(); ItemPath named = context.getDelta().getPath().namedSegmentsOnly(); NameItemPathSegment last = named.lastNamed(); RReferenceOwner refType = RReferenceOwner.getOwnerByQName(last.getName()); return RUtil.jaxbRefToRepo(objectRef, context.getPrismContext(), owner, refType); } } private static class QNameMapper implements Mapper<QName, String> { @Override public String map(QName input, MapperContext context) { return RUtil.qnameToString(input); } } private static class AutoassignSpecificationMapper implements Mapper<AutoassignSpecificationType, RAutoassignSpecification> { @Override public RAutoassignSpecification map(AutoassignSpecificationType input, MapperContext context) { RAutoassignSpecification rspec = new RAutoassignSpecification(); RAutoassignSpecification.copyFromJAXB(input, rspec); return rspec; } } private static class OperationalStateMapper implements Mapper<OperationalStateType, ROperationalState> { @Override public ROperationalState map(OperationalStateType input, MapperContext context) { try { ROperationalState rstate = new ROperationalState(); ROperationalState.copyFromJAXB(input, rstate); return rstate; } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate operational state to entity", ex); } } } private static class EmbeddedObjectReferenceMapper implements Mapper<Referencable, REmbeddedReference> { @Override public REmbeddedReference map(Referencable input, MapperContext context) { ObjectReferenceType objectRef; if (input instanceof ObjectReferenceType) { objectRef = (ObjectReferenceType) input; } else { objectRef = new ObjectReferenceType(); objectRef.setupReferenceValue(input.asReferenceValue()); } REmbeddedReference rref = new REmbeddedReference(); REmbeddedReference.copyFromJAXB(objectRef, rref); return rref; } } private static class ActivationMapper implements Mapper<ActivationType, RActivation> { @Override public RActivation map(ActivationType input, MapperContext context) { try { RActivation ractivation = new RActivation(); RActivation.copyFromJAXB(input, ractivation, null); return ractivation; } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate activation to entity", ex); } } } private static class PolyStringMapper implements Mapper<PolyString, RPolyString> { @Override public RPolyString map(PolyString input, MapperContext context) { return new RPolyString(input.getOrig(), input.getNorm()); } } private static class EnumMapper implements Mapper<Enum, SchemaEnum> { @Override public SchemaEnum map(Enum input, MapperContext context) { String repoEnumClass = null; try { String className = input.getClass().getSimpleName(); className = StringUtils.left(className, className.length() - 4); repoEnumClass = "com.evolveum.midpoint.repo.sql.data.common.enums.R" + className; Class clazz = Class.forName(repoEnumClass); if (!SchemaEnum.class.isAssignableFrom(clazz)) { throw new SystemException("Can't translate enum value " + input); } return RUtil.getRepoEnumValue(input, clazz); } catch (ClassNotFoundException ex) { throw new SystemException("Couldn't find class '" + repoEnumClass + "' for enum '" + input + "'", ex); } } } private interface Mapper<I, O> { O map(I input, MapperContext context); } private static class Key { private Class from; private Class to; public Key(Class from, Class to) { this.from = from; this.to = to; } public Class getFrom() { return from; } public Class getTo() { return to; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Key key = (Key) o; if (from != null ? !from.equals(key.from) : key.from != null) return false; return to != null ? to.equals(key.to) : key.to == null; } @Override public int hashCode() { int result = from != null ? from.hashCode() : 0; result = 31 * result + (to != null ? to.hashCode() : 0); return result; } } }
repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/modify/PrismEntityMapper.java
/* * Copyright (c) 2010-2018 Evolveum * * 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.evolveum.midpoint.repo.sql.helpers.modify; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.NameItemPathSegment; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.sql.data.RepositoryContext; import com.evolveum.midpoint.repo.sql.data.common.ObjectReference; import com.evolveum.midpoint.repo.sql.data.common.RObject; import com.evolveum.midpoint.repo.sql.data.common.RObjectReference; import com.evolveum.midpoint.repo.sql.data.common.container.RAssignment; import com.evolveum.midpoint.repo.sql.data.common.container.RExclusion; import com.evolveum.midpoint.repo.sql.data.common.container.ROperationExecution; import com.evolveum.midpoint.repo.sql.data.common.container.RTrigger; import com.evolveum.midpoint.repo.sql.data.common.embedded.*; import com.evolveum.midpoint.repo.sql.data.common.enums.SchemaEnum; import com.evolveum.midpoint.repo.sql.data.common.other.RReferenceOwner; import com.evolveum.midpoint.repo.sql.util.DtoTranslationException; import com.evolveum.midpoint.repo.sql.util.RUtil; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.xml.namespace.QName; import java.util.HashMap; import java.util.Map; /** * @Author Viliam Repan (lazyman). */ @Component public class PrismEntityMapper { private static final Map<Key, Mapper> mappers = new HashMap<>(); static { mappers.put(new Key(Enum.class, SchemaEnum.class), new EnumMapper()); mappers.put(new Key(PolyString.class, RPolyString.class), new PolyStringMapper()); mappers.put(new Key(ActivationType.class, RActivation.class), new ActivationMapper()); mappers.put(new Key(ObjectReferenceType.class, REmbeddedReference.class), new EmbeddedObjectReferenceMapper()); mappers.put(new Key(OperationalStateType.class, ROperationalState.class), new OperationalStateMapper()); mappers.put(new Key(AutoassignSpecificationType.class, RAutoassignSpecification.class), new AutoassignSpecificationMapper()); mappers.put(new Key(QName.class, String.class), new QNameMapper()); mappers.put(new Key(ObjectReferenceType.class, RObjectReference.class), new ObjectReferenceMapper()); mappers.put(new Key(AssignmentType.class, RAssignment.class), new AssignmentMapper()); mappers.put(new Key(TriggerType.class, RTrigger.class), new TriggerMapper()); mappers.put(new Key(OperationExecutionType.class, ROperationExecution.class), new OperationExecutionMapper()); } @Autowired private RepositoryService repositoryService; @Autowired private PrismContext prismContext; public boolean supports(Class inputType, Class outputType) { Key key = buildKey(inputType, outputType); return mappers.containsKey(key); } public <I, O> O map(I input, Class<O> outputType) { return map(input, outputType, null); } public <I, O> O map(I input, Class<O> outputType, MapperContext context) { if (input == null) { return null; } if (!supports(input.getClass(), outputType)) { return (O) input; } if (context == null) { context = new MapperContext(); } context.setPrismContext(prismContext); context.setRepositoryService(repositoryService); Key key = buildKey(input.getClass(), outputType); Mapper<I, O> mapper = mappers.get(key); if (mapper == null) { throw new SystemException("Can't map '" + input.getClass() + "' to '" + outputType + "'"); } return mapper.map(input, context); } //RObjectTextInfo //RLookupTableRow //RAccessCertificationWorkItem //RAssignmentReference //RFocusPhoto //RObjectReference //RObjectDeltaOperation //ROperationExecution //RAccessCertificationCase //RAssignment //RCertWorkItemReference //RTrigger public <O> O mapPrismValue(PrismValue input, Class<O> outputType, MapperContext context) { if (input instanceof PrismPropertyValue) { return map(input.getRealValue(), outputType, context); } else if (input instanceof PrismReferenceValue) { ObjectReferenceType ref = new ObjectReferenceType(); ref.setupReferenceValue((PrismReferenceValue) input); return map(ref, outputType, context); } else if (input instanceof PrismContainerValue) { Class<Containerable> inputType = (Class) input.getRealClass(); try { Containerable container = inputType.newInstance(); container.setupContainerValue((PrismContainerValue) input); return map(container, outputType, context); } catch (Exception ex) { throw new RuntimeException(ex); //todo error handling } } // todo implement transformation from prism to entity return (O) input; } private Key buildKey(Class inputType, Class outputType) { if (isSchemaEnum(inputType, outputType)) { return new Key(Enum.class, SchemaEnum.class); } return new Key(inputType, outputType); } private boolean isSchemaEnum(Class inputType, Class outputType) { return Enum.class.isAssignableFrom(inputType) && SchemaEnum.class.isAssignableFrom(outputType); } private static class OperationExecutionMapper implements Mapper<OperationExecutionType, ROperationExecution> { @Override public ROperationExecution map(OperationExecutionType input, MapperContext context) { ROperationExecution execution = new ROperationExecution(); RObject owner = (RObject) context.getOwner(); RepositoryContext repositoryContext = new RepositoryContext(context.getRepositoryService(), context.getPrismContext()); try { ROperationExecution.copyFromJAXB(input, execution, owner, repositoryContext); } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate trigger to entity", ex); } return execution; } } private static class TriggerMapper implements Mapper<TriggerType, RTrigger> { @Override public RTrigger map(TriggerType input, MapperContext context) { RTrigger trigger = new RTrigger(); RObject owner = (RObject) context.getOwner(); RepositoryContext repositoryContext = new RepositoryContext(context.getRepositoryService(), context.getPrismContext()); try { RTrigger.copyFromJAXB(input, trigger, owner, repositoryContext); } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate trigger to entity", ex); } return trigger; } } private static class AssignmentMapper implements Mapper<AssignmentType, RAssignment> { @Override public RAssignment map(AssignmentType input, MapperContext context) { RAssignment ass = new RAssignment(); RObject owner = (RObject) context.getOwner(); RepositoryContext repositoryContext = new RepositoryContext(context.getRepositoryService(), context.getPrismContext()); try { RAssignment.copyFromJAXB(input, ass, owner, repositoryContext); } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate assignment to entity", ex); } return ass; } } private static class ObjectReferenceMapper implements Mapper<ObjectReferenceType, RObjectReference> { @Override public RObjectReference map(ObjectReferenceType input, MapperContext context) { RObject owner = (RObject) context.getOwner(); ItemPath named = context.getDelta().getPath().namedSegmentsOnly(); NameItemPathSegment last = named.lastNamed(); RReferenceOwner refType = RReferenceOwner.getOwnerByQName(last.getName()); return RUtil.jaxbRefToRepo(input, context.getPrismContext(), owner, refType); } } private static class QNameMapper implements Mapper<QName, String> { @Override public String map(QName input, MapperContext context) { return RUtil.qnameToString(input); } } private static class AutoassignSpecificationMapper implements Mapper<AutoassignSpecificationType, RAutoassignSpecification> { @Override public RAutoassignSpecification map(AutoassignSpecificationType input, MapperContext context) { RAutoassignSpecification rspec = new RAutoassignSpecification(); RAutoassignSpecification.copyFromJAXB(input, rspec); return rspec; } } private static class OperationalStateMapper implements Mapper<OperationalStateType, ROperationalState> { @Override public ROperationalState map(OperationalStateType input, MapperContext context) { try { ROperationalState rstate = new ROperationalState(); ROperationalState.copyFromJAXB(input, rstate); return rstate; } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate operational state to entity", ex); } } } private static class EmbeddedObjectReferenceMapper implements Mapper<ObjectReferenceType, REmbeddedReference> { @Override public REmbeddedReference map(ObjectReferenceType input, MapperContext context) { REmbeddedReference rref = new REmbeddedReference(); REmbeddedReference.copyFromJAXB(input, rref); return rref; } } private static class ActivationMapper implements Mapper<ActivationType, RActivation> { @Override public RActivation map(ActivationType input, MapperContext context) { try { RActivation ractivation = new RActivation(); RActivation.copyFromJAXB(input, ractivation, null); return ractivation; } catch (DtoTranslationException ex) { throw new SystemException("Couldn't translate activation to entity", ex); } } } private static class PolyStringMapper implements Mapper<PolyString, RPolyString> { @Override public RPolyString map(PolyString input, MapperContext context) { return new RPolyString(input.getOrig(), input.getNorm()); } } private static class EnumMapper implements Mapper<Enum, SchemaEnum> { @Override public SchemaEnum map(Enum input, MapperContext context) { String repoEnumClass = null; try { String className = input.getClass().getSimpleName(); className = StringUtils.left(className, className.length() - 4); repoEnumClass = "com.evolveum.midpoint.repo.sql.data.common.enums.R" + className; Class clazz = Class.forName(repoEnumClass); if (!SchemaEnum.class.isAssignableFrom(clazz)) { throw new SystemException("Can't translate enum value " + input); } return RUtil.getRepoEnumValue(input, clazz); } catch (ClassNotFoundException ex) { throw new SystemException("Couldn't find class '" + repoEnumClass + "' for enum '" + input + "'", ex); } } } private interface Mapper<I, O> { O map(I input, MapperContext context); } private static class Key { private Class from; private Class to; public Key(Class from, Class to) { this.from = from; this.to = to; } public Class getFrom() { return from; } public Class getTo() { return to; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Key key = (Key) o; if (from != null ? !from.equals(key.from) : key.from != null) return false; return to != null ? to.equals(key.to) : key.to == null; } @Override public int hashCode() { int result = from != null ? from.hashCode() : 0; result = 31 * result + (to != null ? to.hashCode() : 0); return result; } } }
references mapping improved
repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/modify/PrismEntityMapper.java
references mapping improved
<ide><path>epo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/modify/PrismEntityMapper.java <ide> mappers.put(new Key(Enum.class, SchemaEnum.class), new EnumMapper()); <ide> mappers.put(new Key(PolyString.class, RPolyString.class), new PolyStringMapper()); <ide> mappers.put(new Key(ActivationType.class, RActivation.class), new ActivationMapper()); <del> mappers.put(new Key(ObjectReferenceType.class, REmbeddedReference.class), new EmbeddedObjectReferenceMapper()); <add> mappers.put(new Key(Referencable.class, REmbeddedReference.class), new EmbeddedObjectReferenceMapper()); <ide> mappers.put(new Key(OperationalStateType.class, ROperationalState.class), new OperationalStateMapper()); <ide> mappers.put(new Key(AutoassignSpecificationType.class, RAutoassignSpecification.class), new AutoassignSpecificationMapper()); <ide> mappers.put(new Key(QName.class, String.class), new QNameMapper()); <ide> <del> mappers.put(new Key(ObjectReferenceType.class, RObjectReference.class), new ObjectReferenceMapper()); <add> mappers.put(new Key(Referencable.class, RObjectReference.class), new ObjectReferenceMapper()); <ide> mappers.put(new Key(AssignmentType.class, RAssignment.class), new AssignmentMapper()); <ide> mappers.put(new Key(TriggerType.class, RTrigger.class), new TriggerMapper()); <ide> mappers.put(new Key(OperationExecutionType.class, ROperationExecution.class), new OperationExecutionMapper()); <ide> return new Key(Enum.class, SchemaEnum.class); <ide> } <ide> <add> if (Referencable.class.isAssignableFrom(inputType)) { <add> return new Key(Referencable.class, outputType); <add> } <add> <ide> return new Key(inputType, outputType); <ide> } <ide> <ide> } <ide> } <ide> <del> private static class ObjectReferenceMapper implements Mapper<ObjectReferenceType, RObjectReference> { <del> <del> @Override <del> public RObjectReference map(ObjectReferenceType input, MapperContext context) { <add> private static class ObjectReferenceMapper implements Mapper<Referencable, RObjectReference> { <add> <add> @Override <add> public RObjectReference map(Referencable input, MapperContext context) { <add> ObjectReferenceType objectRef; <add> if (input instanceof ObjectReferenceType) { <add> objectRef = (ObjectReferenceType) input; <add> } else { <add> objectRef = new ObjectReferenceType(); <add> objectRef.setupReferenceValue(input.asReferenceValue()); <add> } <add> <ide> RObject owner = (RObject) context.getOwner(); <ide> <ide> ItemPath named = context.getDelta().getPath().namedSegmentsOnly(); <ide> NameItemPathSegment last = named.lastNamed(); <ide> RReferenceOwner refType = RReferenceOwner.getOwnerByQName(last.getName()); <ide> <del> return RUtil.jaxbRefToRepo(input, context.getPrismContext(), owner, refType); <add> return RUtil.jaxbRefToRepo(objectRef, context.getPrismContext(), owner, refType); <ide> } <ide> } <ide> <ide> } <ide> } <ide> <del> private static class EmbeddedObjectReferenceMapper implements Mapper<ObjectReferenceType, REmbeddedReference> { <del> <del> @Override <del> public REmbeddedReference map(ObjectReferenceType input, MapperContext context) { <add> private static class EmbeddedObjectReferenceMapper implements Mapper<Referencable, REmbeddedReference> { <add> <add> @Override <add> public REmbeddedReference map(Referencable input, MapperContext context) { <add> ObjectReferenceType objectRef; <add> if (input instanceof ObjectReferenceType) { <add> objectRef = (ObjectReferenceType) input; <add> } else { <add> objectRef = new ObjectReferenceType(); <add> objectRef.setupReferenceValue(input.asReferenceValue()); <add> } <add> <ide> REmbeddedReference rref = new REmbeddedReference(); <del> REmbeddedReference.copyFromJAXB(input, rref); <add> REmbeddedReference.copyFromJAXB(objectRef, rref); <ide> return rref; <ide> } <ide> }
Java
apache-2.0
ea0d290fdb2861caeebac1dbfcbaefde86f9a9b3
0
simanett/AHA
/* * 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 com.aha.businesslogic.model; import java.util.Date; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; /** * * @author simonicsanett */ @XmlRootElement public class Booking { private String bookingReference; private Passenger passenger; private boolean approved; private Date bookingDate; private Flight flight; private int row; private String letter; private int price; public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Flight getFlight() { return flight; } @XmlIDREF public void setFlight(Flight flight) { this.flight = flight; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public String getLetter() { return letter; } public void setLetter(String letter) { this.letter = letter; } public Date getBookingDate() { return bookingDate; } public void setBookingDate(Date bookingDate) { this.bookingDate = bookingDate; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } @XmlID public void setBookingReference(String bookingReference) { this.bookingReference = bookingReference; } public String getBookingReference() { return bookingReference; } public Passenger getPassenger() { return passenger; } @XmlIDREF public void setPassenger(Passenger passenger) { this.passenger = passenger; } }
src/com/aha/businesslogic/model/Booking.java
/* * 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 com.aha.businesslogic.model; import java.util.Date; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; /** * * @author simonicsanett */ @XmlRootElement public class Booking { private String bookingNumber; private Passenger passenger; private boolean approved; private Date bookingDate; private Flight flight; private int row; private String letter; private int price; public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Flight getFlight() { return flight; } @XmlIDREF public void setFlight(Flight flight) { this.flight = flight; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public String getLetter() { return letter; } public void setLetter(String letter) { this.letter = letter; } public Date getBookingDate() { return bookingDate; } public void setBookingDate(Date bookingDate) { this.bookingDate = bookingDate; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } @XmlID public void setBookingNumber(String bookingNumber) { this.bookingNumber = bookingNumber; } public String getBookingNumber() { return bookingNumber; } public Passenger getPassenger() { return passenger; } @XmlIDREF public void setPassenger(Passenger passenger) { this.passenger = passenger; } }
@param bookingNumber replaced with bookingReference as is in db.
src/com/aha/businesslogic/model/Booking.java
@param bookingNumber replaced with bookingReference as is in db.
<ide><path>rc/com/aha/businesslogic/model/Booking.java <ide> @XmlRootElement <ide> public class Booking { <ide> <del> private String bookingNumber; <add> private String bookingReference; <ide> private Passenger passenger; <ide> private boolean approved; <ide> private Date bookingDate; <ide> } <ide> <ide> @XmlID <del> public void setBookingNumber(String bookingNumber) { <del> this.bookingNumber = bookingNumber; <add> public void setBookingReference(String bookingReference) { <add> this.bookingReference = bookingReference; <ide> } <ide> <del> public String getBookingNumber() { <del> return bookingNumber; <add> public String getBookingReference() { <add> return bookingReference; <ide> } <ide> <ide> public Passenger getPassenger() {
Java
apache-2.0
255d9f506608107fbff2e6531cd01fa5d2b8fabf
0
gspandy/Alibaba_RocketMQ,NDPMediaCorp/RocketMQ,gspandy/Alibaba_RocketMQ,lizhanhui/Alibaba_RocketMQ,NDPMediaCorp/RocketMQ,masterasia/Alibaba_RocketMQ,masterasia/Alibaba_RocketMQ,gspandy/Alibaba_RocketMQ,masterasia/Alibaba_RocketMQ,masterasia/Alibaba_RocketMQ,lizhanhui/Alibaba_RocketMQ,gspandy/Alibaba_RocketMQ,lizhanhui/Alibaba_RocketMQ
package com.alibaba.rocketmq.action; import com.alibaba.rocketmq.remoting.netty.SslHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * console auto login. * must login in cockpit . */ @Controller @RequestMapping("/authority") public class AutoLoginAction { private static final String COOKIE_ENCRYPTION_KEY = "C0ckp1t"; @Autowired private AuthenticationManager myAuthenticationManager; @RequestMapping(value = "/login.do", method = {RequestMethod.GET, RequestMethod.POST}) public void login(HttpServletRequest request, HttpServletResponse response) throws IOException { boolean hasLoggedIn = false; try { UsernamePasswordAuthenticationToken token = getToken(request); token.setDetails(new WebAuthenticationDetails(request)); Authentication authenticatedUser = myAuthenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); request.getRequestDispatcher("../cluster/list.do").forward(request, response); hasLoggedIn = true; } catch (Exception e) { e.printStackTrace(); } finally { if (!hasLoggedIn) { response.sendRedirect(request.getProtocol() + "://" + request.getServerName() + ":" + request.getServerPort() + "/"); } } } private Collection<GrantedAuthority> getAuthority(String role) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); if (role.contains(";")) { String[] roles = role.split(";"); for (String ro : roles) authList.add(new SimpleGrantedAuthority(ro)); } else { authList.add(new SimpleGrantedAuthority(role)); } return authList; } private UsernamePasswordAuthenticationToken getToken(HttpServletRequest request) throws Exception { String uid = null; String password = null; Collection<? extends GrantedAuthority> authorities = null; Cookie[] cookies = request.getCookies(); for (Cookie c : cookies) { if ("JSESSIONID".equals(c.getName())) { continue; } String value = new String(SslHelper.decrypt(COOKIE_ENCRYPTION_KEY, c.getValue())); System.out.println(c.getName() + " [request.getRemoteHost()] " + value); if (c.getName().contains("username")) { uid = value; } if (c.getName().contains("password")) { password = value; } if (c.getName().contains("authority")) { authorities = getAuthority(value); } } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(uid, password, authorities); return token; } public AuthenticationManager getMyAuthenticationManager() { return myAuthenticationManager; } public void setMyAuthenticationManager(AuthenticationManager myAuthenticationManager) { this.myAuthenticationManager = myAuthenticationManager; } }
rocketmq-console/src/main/java/com/alibaba/rocketmq/action/AutoLoginAction.java
package com.alibaba.rocketmq.action; import com.alibaba.rocketmq.remoting.netty.SslHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * console auto login. * must login in cockpit . */ @Controller @RequestMapping("/authority") public class AutoLoginAction { private static final String COOKIE_ENCRYPTION_KEY = "C0ckp1t"; @Autowired private AuthenticationManager myAuthenticationManager; @RequestMapping(value = "/login.do", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView login(HttpServletRequest request, HttpServletResponse response) { try { UsernamePasswordAuthenticationToken token = getToken(request); token.setDetails(new WebAuthenticationDetails(request)); Authentication authenticatedUser = myAuthenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); request.getRequestDispatcher("../cluster/list.do").forward(request, response); } catch (Exception e) { e.printStackTrace(); } return new ModelAndView("forward:/"); } private Collection<GrantedAuthority> getAuthority(String role) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); if (role.contains(";")) { String[] roles = role.split(";"); for (String ro : roles) authList.add(new SimpleGrantedAuthority(ro)); } else { authList.add(new SimpleGrantedAuthority(role)); } return authList; } private UsernamePasswordAuthenticationToken getToken(HttpServletRequest request) throws Exception { String uid = null; String password = null; Collection<? extends GrantedAuthority> authorities = null; Cookie[] cookies = request.getCookies(); for (Cookie c : cookies) { if ("JSESSIONID".equals(c.getName())) { continue; } String value = new String(SslHelper.decrypt(COOKIE_ENCRYPTION_KEY, c.getValue())); System.out.println(c.getName() + " [request.getRemoteHost()] " + value); if (c.getName().contains("username")) { uid = value; } if (c.getName().contains("password")) { password = value; } if (c.getName().contains("authority")) { authorities = getAuthority(value); } } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(uid, password, authorities); return token; } public AuthenticationManager getMyAuthenticationManager() { return myAuthenticationManager; } public void setMyAuthenticationManager(AuthenticationManager myAuthenticationManager) { this.myAuthenticationManager = myAuthenticationManager; } }
Fix dead loop of console if auto-login fails.
rocketmq-console/src/main/java/com/alibaba/rocketmq/action/AutoLoginAction.java
Fix dead loop of console if auto-login fails.
<ide><path>ocketmq-console/src/main/java/com/alibaba/rocketmq/action/AutoLoginAction.java <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestMethod; <del>import org.springframework.web.servlet.ModelAndView; <ide> <ide> import javax.servlet.http.Cookie; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <add>import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.List; <ide> private AuthenticationManager myAuthenticationManager; <ide> <ide> @RequestMapping(value = "/login.do", method = {RequestMethod.GET, RequestMethod.POST}) <del> public ModelAndView login(HttpServletRequest request, HttpServletResponse response) { <add> public void login(HttpServletRequest request, HttpServletResponse response) throws IOException { <add> <add> boolean hasLoggedIn = false; <ide> try { <ide> UsernamePasswordAuthenticationToken token = getToken(request); <ide> <ide> SecurityContextHolder.getContext().setAuthentication(authenticatedUser); <ide> <ide> request.getRequestDispatcher("../cluster/list.do").forward(request, response); <add> hasLoggedIn = true; <ide> } catch (Exception e) { <ide> e.printStackTrace(); <add> } finally { <add> if (!hasLoggedIn) { <add> response.sendRedirect(request.getProtocol() + "://" + request.getServerName() + ":" <add> + request.getServerPort() + "/"); <add> } <ide> } <del> <del> return new ModelAndView("forward:/"); <ide> } <ide> <ide>
Java
apache-2.0
5f8d99b7031f51e8ae3c40bc357b173014aadbd7
0
shils/incubator-groovy,jwagenleitner/incubator-groovy,shils/incubator-groovy,apache/incubator-groovy,shils/incubator-groovy,russel/incubator-groovy,apache/groovy,paulk-asert/groovy,jwagenleitner/groovy,paulk-asert/groovy,apache/incubator-groovy,avafanasiev/groovy,avafanasiev/groovy,russel/groovy,paulk-asert/incubator-groovy,russel/incubator-groovy,armsargis/groovy,jwagenleitner/incubator-groovy,apache/groovy,armsargis/groovy,shils/groovy,jwagenleitner/groovy,traneHead/groovy-core,armsargis/groovy,paulk-asert/incubator-groovy,russel/groovy,paulk-asert/incubator-groovy,apache/groovy,shils/groovy,russel/incubator-groovy,apache/groovy,jwagenleitner/groovy,armsargis/groovy,paulk-asert/groovy,jwagenleitner/incubator-groovy,paulk-asert/incubator-groovy,russel/groovy,jwagenleitner/groovy,shils/incubator-groovy,avafanasiev/groovy,paulk-asert/incubator-groovy,apache/incubator-groovy,shils/groovy,avafanasiev/groovy,traneHead/groovy-core,apache/incubator-groovy,paulk-asert/groovy,jwagenleitner/incubator-groovy,russel/groovy,traneHead/groovy-core,traneHead/groovy-core,shils/groovy,russel/incubator-groovy
/* * 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.control; import org.apache.groovy.util.Maps; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.control.io.NullWriter; import org.codehaus.groovy.control.messages.WarningMessage; import org.objectweb.asm.Opcodes; import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; /** * Compilation control flags and coordination stuff. * * @author <a href="mailto:[email protected]">Chris Poirier</a> * @author <a href="mailto:[email protected]">Jochen Theodorou</a> * @author <a href="mailto:[email protected]">Jim White</a> * @author <a href="mailto:[email protected]">Cedric Champeau</a> */ public class CompilerConfiguration { /** This (<code>"indy"</code>) is the Optimization Option value for enabling <code>invokedynamic</code> complilation. */ public static final String INVOKEDYNAMIC = "indy"; /** This (<code>"1.4"</code>) is the value for targetBytecode to compile for a JDK 1.4. **/ public static final String JDK4 = "1.4"; /** This (<code>"1.5"</code>) is the value for targetBytecode to compile for a JDK 1.5. **/ public static final String JDK5 = "1.5"; /** This (<code>"1.6"</code>) is the value for targetBytecode to compile for a JDK 1.6. **/ public static final String JDK6 = "1.6"; /** This (<code>"1.7"</code>) is the value for targetBytecode to compile for a JDK 1.7. **/ public static final String JDK7 = "1.7"; /** This (<code>"1.8"</code>) is the value for targetBytecode to compile for a JDK 1.8. **/ public static final String JDK8 = "1.8"; /** This (<code>"1.5"</code>) is the value for targetBytecode to compile for a JDK 1.5 or later JVM. **/ public static final String POST_JDK5 = JDK5; // for backwards compatibility /** This (<code>"1.4"</code>) is the value for targetBytecode to compile for a JDK 1.4 JVM. **/ public static final String PRE_JDK5 = JDK4; /** * JDK version to bytecode version mapping */ public static final Map<String, Integer> JDK_TO_BYTECODE_VERSION_MAP = Maps.of( JDK4, Opcodes.V1_4, JDK5, Opcodes.V1_5, JDK6, Opcodes.V1_6, JDK7, Opcodes.V1_7, JDK8, Opcodes.V1_8 ); /** An array of the valid targetBytecode values **/ public static final String[] ALLOWED_JDKS = JDK_TO_BYTECODE_VERSION_MAP.keySet().toArray(new String[0]); // Just call getVMVersion() once. public static final String currentJVMVersion = getVMVersion(); // Static initializers are executed in text order, // therefore we must do this one last! /** * A convenience for getting a default configuration. Do not modify it! * See {@link #CompilerConfiguration(Properties)} for an example on how to * make a suitable copy to modify. But if you're really starting from a * default context, then you probably just want <code>new CompilerConfiguration()</code>. */ public static final CompilerConfiguration DEFAULT = new CompilerConfiguration(); /** * See {@link WarningMessage} for levels. */ private int warningLevel; /** * Encoding for source files */ private String sourceEncoding; /** * The <code>PrintWriter</code> does nothing. */ private PrintWriter output; /** * Directory into which to write classes */ private File targetDirectory; /** * Classpath for use during compilation */ private LinkedList<String> classpath; /** * If true, the compiler should produce action information */ private boolean verbose; /** * If true, debugging code should be activated */ private boolean debug; /** * If true, generates metadata for reflection on method parameters */ private boolean parameters = false; /** * The number of non-fatal errors to allow before bailing */ private int tolerance; /** * Base class name for scripts (must derive from Script) */ private String scriptBaseClass; private ParserPluginFactory pluginFactory; /** * extension used to find a groovy file */ private String defaultScriptExtension; /** * extensions used to find a groovy files */ private Set<String> scriptExtensions = new LinkedHashSet<String>(); /** * if set to true recompilation is enabled */ private boolean recompileGroovySource; /** * sets the minimum of time after a script can be recompiled. */ private int minimumRecompilationInterval; /** * sets the bytecode version target */ private String targetBytecode; /** * options for joint compilation (null by default == no joint compilation) */ private Map<String, Object> jointCompilationOptions; /** * options for optimizations (empty map by default) */ private Map<String, Boolean> optimizationOptions; private final List<CompilationCustomizer> compilationCustomizers = new LinkedList<CompilationCustomizer>(); /** * Sets a list of global AST transformations which should not be loaded even if they are * defined in META-INF/org.codehaus.groovy.transform.ASTTransformation files. By default, * none is disabled. */ private Set<String> disabledGlobalASTTransformations; private BytecodeProcessor bytecodePostprocessor; /** * defines if antlr2 parser should be used or the antlr4 one if * no factory is set yet */ private ParserVersion parserVersion = ParserVersion.V_2; /** * Sets the Flags to defaults. */ public CompilerConfiguration() { // // Set in safe defaults setWarningLevel(WarningMessage.LIKELY_ERRORS); setOutput(null); setTargetDirectory((File) null); setClasspath(""); setVerbose(false); setDebug(false); setParameters(safeGetSystemProperty("groovy.parameters") != null); setTolerance(10); setScriptBaseClass(null); setRecompileGroovySource(false); setMinimumRecompilationInterval(100); setTargetBytecode(safeGetSystemProperty("groovy.target.bytecode", getVMVersion())); setDefaultScriptExtension(safeGetSystemProperty("groovy.default.scriptExtension", ".groovy")); // Source file encoding String encoding = safeGetSystemProperty("file.encoding", "US-ASCII"); encoding = safeGetSystemProperty("groovy.source.encoding", encoding); setSourceEncoding(encoding); try { setOutput(new PrintWriter(System.err)); } catch (Exception e) { // IGNORE } String target = safeGetSystemProperty("groovy.target.directory"); if (target != null) { setTargetDirectory(target); } boolean indy = false; try { indy = Boolean.getBoolean("groovy.target.indy"); } catch (Exception e) { // IGNORE } if (DEFAULT!=null && Boolean.TRUE.equals(DEFAULT.getOptimizationOptions().get(INVOKEDYNAMIC))) { indy = true; } Map options = new HashMap<String,Boolean>(3); if (indy) { options.put(INVOKEDYNAMIC, Boolean.TRUE); } setOptimizationOptions(options); try { if ("true".equals(System.getProperty("groovy.antlr4"))) { this.parserVersion = ParserVersion.V_4; } } catch (Exception e) { // IGNORE } } /** * Retrieves a System property, or null if any of the following exceptions occur. * <ul> * <li>SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property.</li> * <li>NullPointerException - if key is null.</li> * <li>IllegalArgumentException - if key is empty.</li> * </ul> * @param key the name of the system property. * @return value of the system property or null */ private static String safeGetSystemProperty(String key){ return safeGetSystemProperty(key, null); } /** * Retrieves a System property, or null if any of the following exceptions occur (Warning: Exception messages are * suppressed). * <ul> * <li>SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property.</li> * <li>NullPointerException - if key is null.</li> * <li>IllegalArgumentException - if key is empty.</li> * </ul> * @param key the name of the system property. * @param def a default value. * @return value of the system property or null */ private static String safeGetSystemProperty(String key, String def){ try { return System.getProperty(key, def); } catch (SecurityException t){ // suppress exception } catch (NullPointerException t){ // suppress exception } catch (IllegalArgumentException t){ // suppress exception } return def; } /** * Copy constructor. Use this if you have a mostly correct configuration * for your compilation but you want to make a some changes programatically. * An important reason to prefer this approach is that your code will most * likely be forward compatible with future changes to this configuration API. * <p> * An example of this copy constructor at work: * <pre> * // In all likelihood there is already a configuration in your code's context * // for you to copy, but for the sake of this example we'll use the global default. * CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT); * myConfiguration.setDebug(true); *</pre> * * @param configuration The configuration to copy. */ public CompilerConfiguration(CompilerConfiguration configuration) { setWarningLevel(configuration.getWarningLevel()); setOutput(configuration.getOutput()); setTargetDirectory(configuration.getTargetDirectory()); setClasspathList(new LinkedList<String>(configuration.getClasspath())); setVerbose(configuration.getVerbose()); setDebug(configuration.getDebug()); setParameters(configuration.getParameters()); setTolerance(configuration.getTolerance()); setScriptBaseClass(configuration.getScriptBaseClass()); setRecompileGroovySource(configuration.getRecompileGroovySource()); setMinimumRecompilationInterval(configuration.getMinimumRecompilationInterval()); setTargetBytecode(configuration.getTargetBytecode()); setDefaultScriptExtension(configuration.getDefaultScriptExtension()); setSourceEncoding(configuration.getSourceEncoding()); setTargetDirectory(configuration.getTargetDirectory()); Map<String, Object> jointCompilationOptions = configuration.getJointCompilationOptions(); if (jointCompilationOptions != null) { jointCompilationOptions = new HashMap<String, Object>(jointCompilationOptions); } setJointCompilationOptions(jointCompilationOptions); setPluginFactory(configuration.getPluginFactory()); setScriptExtensions(configuration.getScriptExtensions()); setOptimizationOptions(new HashMap<String, Boolean>(configuration.getOptimizationOptions())); } /** * Sets the Flags to the specified configuration, with defaults * for those not supplied. * Note that those "defaults" here do <em>not</em> include checking the * settings in {@link System#getProperties()} in general, only file.encoding, * groovy.target.directory and groovy.source.encoding are. * <p> * If you want to set a few flags but keep Groovy's default * configuration behavior then be sure to make your settings in * a Properties that is backed by <code>System.getProperties()</code> (which * is done using this constructor). That might be done like this: * <pre> * Properties myProperties = new Properties(System.getProperties()); * myProperties.setProperty("groovy.output.debug", "true"); * myConfiguration = new CompilerConfiguration(myProperties); * </pre> * And you also have to contend with a possible SecurityException when * getting the system properties (See {@link java.lang.System#getProperties()}). * A safer approach would be to copy a default * CompilerConfiguration and make your changes there using the setter: * <pre> * // In all likelihood there is already a configuration for you to copy, * // but for the sake of this example we'll use the global default. * CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT); * myConfiguration.setDebug(true); * </pre> * <p> * <table summary="Groovy Compiler Configuration Properties"> * <tr> * <th>Property Key</th><th>Get/Set Property Name</th> * </tr> * <tr> * <td><code>"groovy.warnings"</code></td><td>{@link #getWarningLevel}</td></tr> * <tr><td><code>"groovy.source.encoding"</code></td><td>{@link #getSourceEncoding}</td></tr> * <tr><td><code>"groovy.target.directory"</code></td><td>{@link #getTargetDirectory}</td></tr> * <tr><td><code>"groovy.target.bytecode"</code></td><td>{@link #getTargetBytecode}</td></tr> * <tr><td><code>"groovy.classpath"</code></td><td>{@link #getClasspath}</td></tr> * <tr><td><code>"groovy.output.verbose"</code></td><td>{@link #getVerbose}</td></tr> * <tr><td><code>"groovy.output.debug"</code></td><td>{@link #getDebug}</td></tr> * <tr><td><code>"groovy.errors.tolerance"</code></td><td>{@link #getTolerance}</td></tr> * <tr><td><code>"groovy.script.extension"</code></td><td>{@link #getDefaultScriptExtension}</td></tr> * <tr><td><code>"groovy.script.base"</code></td><td>{@link #getScriptBaseClass}</td></tr> * <tr><td><code>"groovy.recompile"</code></td><td>{@link #getRecompileGroovySource}</td></tr> * <tr><td><code>"groovy.recompile.minimumInterval"</code></td><td>{@link #getMinimumRecompilationInterval}</td></tr> * <tr><td> * </tr> * </table> * * @param configuration The properties to get flag values from. */ public CompilerConfiguration(Properties configuration) throws ConfigurationException { this(); configure(configuration); } /** * Checks if the specified bytecode version string represents a JDK 1.5+ compatible * bytecode version. * @param bytecodeVersion the bytecode version string (1.4, 1.5, 1.6, 1.7 or 1.8) * @return true if the bytecode version is JDK 1.5+ */ public static boolean isPostJDK5(String bytecodeVersion) { return JDK5.equals(bytecodeVersion) || JDK6.equals(bytecodeVersion) || JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); } /** * Checks if the specified bytecode version string represents a JDK 1.7+ compatible * bytecode version. * @param bytecodeVersion the bytecode version string (1.4, 1.5, 1.6, 1.7 or 1.8) * @return true if the bytecode version is JDK 1.7+ */ public static boolean isPostJDK7(String bytecodeVersion) { return JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); } /** * Method to configure a CompilerConfiguration by using Properties. * For a list of available properties look at {@link #CompilerConfiguration(Properties)}. * @param configuration The properties to get flag values from. */ public void configure(Properties configuration) throws ConfigurationException { String text = null; int numeric = 0; // // Warning level numeric = getWarningLevel(); try { text = configuration.getProperty("groovy.warnings", "likely errors"); numeric = Integer.parseInt(text); } catch (NumberFormatException e) { text = text.toLowerCase(); if (text.equals("none")) { numeric = WarningMessage.NONE; } else if (text.startsWith("likely")) { numeric = WarningMessage.LIKELY_ERRORS; } else if (text.startsWith("possible")) { numeric = WarningMessage.POSSIBLE_ERRORS; } else if (text.startsWith("paranoia")) { numeric = WarningMessage.PARANOIA; } else { throw new ConfigurationException("unrecognized groovy.warnings: " + text); } } setWarningLevel(numeric); // // Source file encoding // text = configuration.getProperty("groovy.source.encoding"); if (text == null) { text = configuration.getProperty("file.encoding", "US-ASCII"); } setSourceEncoding(text); // // Target directory for classes // text = configuration.getProperty("groovy.target.directory"); if (text != null) setTargetDirectory(text); text = configuration.getProperty("groovy.target.bytecode"); if (text != null) setTargetBytecode(text); // // Classpath // text = configuration.getProperty("groovy.classpath"); if (text != null) setClasspath(text); // // Verbosity // text = configuration.getProperty("groovy.output.verbose"); if (text != null && text.equalsIgnoreCase("true")) setVerbose(true); // // Debugging // text = configuration.getProperty("groovy.output.debug"); if (text != null && text.equalsIgnoreCase("true")) setDebug(true); // // Parameters // setParameters(configuration.getProperty("groovy.parameters") != null); // // Tolerance // numeric = 10; try { text = configuration.getProperty("groovy.errors.tolerance", "10"); numeric = Integer.parseInt(text); } catch (NumberFormatException e) { throw new ConfigurationException(e); } setTolerance(numeric); // // Script Base Class // text = configuration.getProperty("groovy.script.base"); if (text!=null) setScriptBaseClass(text); // // recompilation options // text = configuration.getProperty("groovy.recompile"); if (text != null) { setRecompileGroovySource(text.equalsIgnoreCase("true")); } numeric = 100; try { text = configuration.getProperty("groovy.recompile.minimumIntervall"); if (text==null) text = configuration.getProperty("groovy.recompile.minimumInterval"); if (text!=null) { numeric = Integer.parseInt(text); } else { numeric = 100; } } catch (NumberFormatException e) { throw new ConfigurationException(e); } setMinimumRecompilationInterval(numeric); // disabled global AST transformations text = configuration.getProperty("groovy.disabled.global.ast.transformations"); if (text!=null) { String[] classNames = text.split(",\\s*}"); Set<String> blacklist = new HashSet<String>(Arrays.asList(classNames)); setDisabledGlobalASTTransformations(blacklist); } } /** * Gets the currently configured warning level. See {@link WarningMessage} * for level details. */ public int getWarningLevel() { return this.warningLevel; } /** * Sets the warning level. See {@link WarningMessage} for level details. */ public void setWarningLevel(int level) { if (level < WarningMessage.NONE || level > WarningMessage.PARANOIA) { this.warningLevel = WarningMessage.LIKELY_ERRORS; } else { this.warningLevel = level; } } /** * Gets the currently configured source file encoding. */ public String getSourceEncoding() { return this.sourceEncoding; } /** * Sets the encoding to be used when reading source files. */ public void setSourceEncoding(String encoding) { if (encoding == null) encoding = "US-ASCII"; this.sourceEncoding = encoding; } /** * Gets the currently configured output writer. * @deprecated not used anymore */ @Deprecated public PrintWriter getOutput() { return this.output; } /** * Sets the output writer. * @deprecated not used anymore, has no effect */ @Deprecated public void setOutput(PrintWriter output) { if (output == null) { this.output = new PrintWriter(NullWriter.DEFAULT); } else { this.output = output; } } /** * Gets the target directory for writing classes. */ public File getTargetDirectory() { return this.targetDirectory; } /** * Sets the target directory. */ public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } } /** * Sets the target directory. */ public void setTargetDirectory(File directory) { this.targetDirectory = directory; } /** * @return the classpath */ public List<String> getClasspath() { return this.classpath; } /** * Sets the classpath. */ public void setClasspath(String classpath) { this.classpath = new LinkedList<String>(); StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { this.classpath.add(tokenizer.nextToken()); } } /** * sets the classpath using a list of Strings * @param parts list of strings containing the classpath parts */ public void setClasspathList(List<String> parts) { this.classpath = new LinkedList<String>(parts); } /** * Returns true if verbose operation has been requested. */ public boolean getVerbose() { return this.verbose; } /** * Turns verbose operation on or off. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Returns true if debugging operation has been requested. */ public boolean getDebug() { return this.debug; } /** * Returns true if parameter metadata generation has been enabled. */ public boolean getParameters() { return this.parameters; } /** * Turns debugging operation on or off. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Turns parameter metadata generation on or off. */ public void setParameters(boolean parameters) { this.parameters = parameters; } /** * Returns the requested error tolerance. */ public int getTolerance() { return this.tolerance; } /** * Sets the error tolerance, which is the number of * non-fatal errors (per unit) that should be tolerated before * compilation is aborted. */ public void setTolerance(int tolerance) { this.tolerance = tolerance; } /** * Gets the name of the base class for scripts. It must be a subclass * of Script. */ public String getScriptBaseClass() { return this.scriptBaseClass; } /** * Sets the name of the base class for scripts. It must be a subclass * of Script. */ public void setScriptBaseClass(String scriptBaseClass) { this.scriptBaseClass = scriptBaseClass; } public ParserPluginFactory getPluginFactory() { if (pluginFactory == null) { pluginFactory = ParserVersion.V_2 == parserVersion ? ParserPluginFactory.antlr2() : ParserPluginFactory.antlr4(); } return pluginFactory; } public void setPluginFactory(ParserPluginFactory pluginFactory) { this.pluginFactory = pluginFactory; } public void setScriptExtensions(Set<String> scriptExtensions) { if(scriptExtensions == null) scriptExtensions = new LinkedHashSet<String>(); this.scriptExtensions = scriptExtensions; } public Set<String> getScriptExtensions() { if(scriptExtensions == null || scriptExtensions.isEmpty()) { /* * this happens * * when groovyc calls FileSystemCompiler in forked mode, or * * when FileSystemCompiler is run from the command line directly, or * * when groovy was not started using groovyc or FileSystemCompiler either */ scriptExtensions = SourceExtensionHandler.getRegisteredExtensions( this.getClass().getClassLoader()); } return scriptExtensions; } public String getDefaultScriptExtension() { return defaultScriptExtension; } public void setDefaultScriptExtension(String defaultScriptExtension) { this.defaultScriptExtension = defaultScriptExtension; } public void setRecompileGroovySource(boolean recompile) { recompileGroovySource = recompile; } public boolean getRecompileGroovySource(){ return recompileGroovySource; } public void setMinimumRecompilationInterval(int time) { minimumRecompilationInterval = Math.max(0,time); } public int getMinimumRecompilationInterval() { return minimumRecompilationInterval; } /** * Allow setting the bytecode compatibility. The parameter can take * one of the values <tt>1.7</tt>, <tt>1.6</tt>, <tt>1.5</tt> or <tt>1.4</tt>. * If wrong parameter then the value will default to VM determined version. * * @param version the bytecode compatibility mode */ public void setTargetBytecode(String version) { for (String allowedJdk : ALLOWED_JDKS) { if (allowedJdk.equals(version)) { this.targetBytecode = version; } } } /** * Retrieves the compiler bytecode compatibility mode. * * @return bytecode compatibility mode. Can be either <tt>1.5</tt> or <tt>1.4</tt>. */ public String getTargetBytecode() { return this.targetBytecode; } private static String getVMVersion() { return POST_JDK5; } /** * Gets the joint compilation options for this configuration. * @return the options */ public Map<String, Object> getJointCompilationOptions() { return jointCompilationOptions; } /** * Sets the joint compilation options for this configuration. * Using null will disable joint compilation. * @param options the options */ public void setJointCompilationOptions(Map<String, Object> options) { jointCompilationOptions = options; } /** * Gets the optimization options for this configuration. * @return the options (always not null) */ public Map<String, Boolean> getOptimizationOptions() { return optimizationOptions; } /** * Sets the optimization options for this configuration. * No entry or a true for that entry means to enable that optimization, * a false means the optimization is disabled. * Valid keys are "all" and "int". * @param options the options. * @throws IllegalArgumentException if the options are null */ public void setOptimizationOptions(Map<String, Boolean> options) { if (options==null) throw new IllegalArgumentException("provided option map must not be null"); optimizationOptions = options; } /** * Adds compilation customizers to the compilation process. A compilation customizer is a class node * operation which performs various operations going from adding imports to access control. * @param customizers the list of customizers to be added * @return this configuration instance */ public CompilerConfiguration addCompilationCustomizers(CompilationCustomizer... customizers) { if (customizers==null) throw new IllegalArgumentException("provided customizers list must not be null"); compilationCustomizers.addAll(Arrays.asList(customizers)); return this; } /** * Returns the list of compilation customizers. * @return the customizers (always not null) */ public List<CompilationCustomizer> getCompilationCustomizers() { return compilationCustomizers; } /** * Returns the list of disabled global AST transformation class names. * @return a list of global AST transformation fully qualified class names */ public Set<String> getDisabledGlobalASTTransformations() { return disabledGlobalASTTransformations; } /** * Disables global AST transformations. In order to avoid class loading side effects, it is not recommended * to use MyASTTransformation.class.getName() by directly use the class name as a string. Disabled AST transformations * only apply to automatically loaded global AST transformations, that is to say transformations defined in a * META-INF/org.codehaus.groovy.transform.ASTTransformation file. If you explicitly add a global AST transformation * in your compilation process, for example using the {@link org.codehaus.groovy.control.customizers.ASTTransformationCustomizer} or * using a {@link org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation}, then nothing will prevent * the transformation from being loaded. * @param disabledGlobalASTTransformations a set of fully qualified class names of global AST transformations * which should not be loaded. */ public void setDisabledGlobalASTTransformations(final Set<String> disabledGlobalASTTransformations) { this.disabledGlobalASTTransformations = disabledGlobalASTTransformations; } public BytecodeProcessor getBytecodePostprocessor() { return bytecodePostprocessor; } public void setBytecodePostprocessor(final BytecodeProcessor bytecodePostprocessor) { this.bytecodePostprocessor = bytecodePostprocessor; } public ParserVersion getParserVersion() { return this.parserVersion; } public void setParserVersion(ParserVersion parserVersion) { this.parserVersion = parserVersion; } }
src/main/org/codehaus/groovy/control/CompilerConfiguration.java
/* * 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.control; import org.apache.groovy.util.Maps; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.codehaus.groovy.control.io.NullWriter; import org.codehaus.groovy.control.messages.WarningMessage; import org.objectweb.asm.Opcodes; import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; /** * Compilation control flags and coordination stuff. * * @author <a href="mailto:[email protected]">Chris Poirier</a> * @author <a href="mailto:[email protected]">Jochen Theodorou</a> * @author <a href="mailto:[email protected]">Jim White</a> * @author <a href="mailto:[email protected]">Cedric Champeau</a> */ public class CompilerConfiguration { /** This (<code>"indy"</code>) is the Optimization Option value for enabling <code>invokedynamic</code> complilation. */ public static final String INVOKEDYNAMIC = "indy"; /** This (<code>"1.4"</code>) is the value for targetBytecode to compile for a JDK 1.4. **/ public static final String JDK4 = "1.4"; /** This (<code>"1.5"</code>) is the value for targetBytecode to compile for a JDK 1.5. **/ public static final String JDK5 = "1.5"; /** This (<code>"1.6"</code>) is the value for targetBytecode to compile for a JDK 1.6. **/ public static final String JDK6 = "1.6"; /** This (<code>"1.7"</code>) is the value for targetBytecode to compile for a JDK 1.7. **/ public static final String JDK7 = "1.7"; /** This (<code>"1.8"</code>) is the value for targetBytecode to compile for a JDK 1.8. **/ public static final String JDK8 = "1.8"; /** This (<code>"1.5"</code>) is the value for targetBytecode to compile for a JDK 1.5 or later JVM. **/ public static final String POST_JDK5 = JDK5; // for backwards compatibility /** This (<code>"1.4"</code>) is the value for targetBytecode to compile for a JDK 1.4 JVM. **/ public static final String PRE_JDK5 = JDK4; /** * JDK version to bytecode version mapping */ public static final Map<String, Integer> JDK_TO_BYTECODE_VERSION_MAP = Maps.of( JDK4, Opcodes.V1_4, JDK5, Opcodes.V1_5, JDK6, Opcodes.V1_6, JDK7, Opcodes.V1_7, JDK8, Opcodes.V1_8 ); /** An array of the valid targetBytecode values **/ public static final String[] ALLOWED_JDKS = JDK_TO_BYTECODE_VERSION_MAP.keySet().toArray(new String[0]); // Just call getVMVersion() once. public static final String currentJVMVersion = getVMVersion(); // Static initializers are executed in text order, // therefore we must do this one last! /** * A convenience for getting a default configuration. Do not modify it! * See {@link #CompilerConfiguration(Properties)} for an example on how to * make a suitable copy to modify. But if you're really starting from a * default context, then you probably just want <code>new CompilerConfiguration()</code>. */ public static final CompilerConfiguration DEFAULT = new CompilerConfiguration(); /** * See {@link WarningMessage} for levels. */ private int warningLevel; /** * Encoding for source files */ private String sourceEncoding; /** * The <code>PrintWriter</code> does nothing. */ private PrintWriter output; /** * Directory into which to write classes */ private File targetDirectory; /** * Classpath for use during compilation */ private LinkedList<String> classpath; /** * If true, the compiler should produce action information */ private boolean verbose; /** * If true, debugging code should be activated */ private boolean debug; /** * If true, generates metadata for reflection on method parameters */ private boolean parameters = false; /** * The number of non-fatal errors to allow before bailing */ private int tolerance; /** * Base class name for scripts (must derive from Script) */ private String scriptBaseClass; private ParserPluginFactory pluginFactory; /** * extension used to find a groovy file */ private String defaultScriptExtension; /** * extensions used to find a groovy files */ private Set<String> scriptExtensions = new LinkedHashSet<String>(); /** * if set to true recompilation is enabled */ private boolean recompileGroovySource; /** * sets the minimum of time after a script can be recompiled. */ private int minimumRecompilationInterval; /** * sets the bytecode version target */ private String targetBytecode; /** * options for joint compilation (null by default == no joint compilation) */ private Map<String, Object> jointCompilationOptions; /** * options for optimizations (empty map by default) */ private Map<String, Boolean> optimizationOptions; private final List<CompilationCustomizer> compilationCustomizers = new LinkedList<CompilationCustomizer>(); /** * Sets a list of global AST transformations which should not be loaded even if they are * defined in META-INF/org.codehaus.groovy.transform.ASTTransformation files. By default, * none is disabled. */ private Set<String> disabledGlobalASTTransformations; private BytecodeProcessor bytecodePostprocessor; /** * defines if antlr2 parser should be used or the antlr4 one if * no factory is set yet */ private boolean antlr2Parser = true; // TODO replace it with ParserVersion /** * Sets the Flags to defaults. */ public CompilerConfiguration() { // // Set in safe defaults setWarningLevel(WarningMessage.LIKELY_ERRORS); setOutput(null); setTargetDirectory((File) null); setClasspath(""); setVerbose(false); setDebug(false); setParameters(safeGetSystemProperty("groovy.parameters") != null); setTolerance(10); setScriptBaseClass(null); setRecompileGroovySource(false); setMinimumRecompilationInterval(100); setTargetBytecode(safeGetSystemProperty("groovy.target.bytecode", getVMVersion())); setDefaultScriptExtension(safeGetSystemProperty("groovy.default.scriptExtension", ".groovy")); // Source file encoding String encoding = safeGetSystemProperty("file.encoding", "US-ASCII"); encoding = safeGetSystemProperty("groovy.source.encoding", encoding); setSourceEncoding(encoding); try { setOutput(new PrintWriter(System.err)); } catch (Exception e) { // IGNORE } String target = safeGetSystemProperty("groovy.target.directory"); if (target != null) { setTargetDirectory(target); } boolean indy = false; try { indy = Boolean.getBoolean("groovy.target.indy"); } catch (Exception e) { // IGNORE } if (DEFAULT!=null && Boolean.TRUE.equals(DEFAULT.getOptimizationOptions().get(INVOKEDYNAMIC))) { indy = true; } Map options = new HashMap<String,Boolean>(3); if (indy) { options.put(INVOKEDYNAMIC, Boolean.TRUE); } setOptimizationOptions(options); try { antlr2Parser = !"true".equals(System.getProperty("groovy.antlr4")); } catch (Exception e) { // IGNORE } } /** * Retrieves a System property, or null if any of the following exceptions occur. * <ul> * <li>SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property.</li> * <li>NullPointerException - if key is null.</li> * <li>IllegalArgumentException - if key is empty.</li> * </ul> * @param key the name of the system property. * @return value of the system property or null */ private static String safeGetSystemProperty(String key){ return safeGetSystemProperty(key, null); } /** * Retrieves a System property, or null if any of the following exceptions occur (Warning: Exception messages are * suppressed). * <ul> * <li>SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property.</li> * <li>NullPointerException - if key is null.</li> * <li>IllegalArgumentException - if key is empty.</li> * </ul> * @param key the name of the system property. * @param def a default value. * @return value of the system property or null */ private static String safeGetSystemProperty(String key, String def){ try { return System.getProperty(key, def); } catch (SecurityException t){ // suppress exception } catch (NullPointerException t){ // suppress exception } catch (IllegalArgumentException t){ // suppress exception } return def; } /** * Copy constructor. Use this if you have a mostly correct configuration * for your compilation but you want to make a some changes programatically. * An important reason to prefer this approach is that your code will most * likely be forward compatible with future changes to this configuration API. * <p> * An example of this copy constructor at work: * <pre> * // In all likelihood there is already a configuration in your code's context * // for you to copy, but for the sake of this example we'll use the global default. * CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT); * myConfiguration.setDebug(true); *</pre> * * @param configuration The configuration to copy. */ public CompilerConfiguration(CompilerConfiguration configuration) { setWarningLevel(configuration.getWarningLevel()); setOutput(configuration.getOutput()); setTargetDirectory(configuration.getTargetDirectory()); setClasspathList(new LinkedList<String>(configuration.getClasspath())); setVerbose(configuration.getVerbose()); setDebug(configuration.getDebug()); setParameters(configuration.getParameters()); setTolerance(configuration.getTolerance()); setScriptBaseClass(configuration.getScriptBaseClass()); setRecompileGroovySource(configuration.getRecompileGroovySource()); setMinimumRecompilationInterval(configuration.getMinimumRecompilationInterval()); setTargetBytecode(configuration.getTargetBytecode()); setDefaultScriptExtension(configuration.getDefaultScriptExtension()); setSourceEncoding(configuration.getSourceEncoding()); setTargetDirectory(configuration.getTargetDirectory()); Map<String, Object> jointCompilationOptions = configuration.getJointCompilationOptions(); if (jointCompilationOptions != null) { jointCompilationOptions = new HashMap<String, Object>(jointCompilationOptions); } setJointCompilationOptions(jointCompilationOptions); setPluginFactory(configuration.getPluginFactory()); setScriptExtensions(configuration.getScriptExtensions()); setOptimizationOptions(new HashMap<String, Boolean>(configuration.getOptimizationOptions())); } /** * Sets the Flags to the specified configuration, with defaults * for those not supplied. * Note that those "defaults" here do <em>not</em> include checking the * settings in {@link System#getProperties()} in general, only file.encoding, * groovy.target.directory and groovy.source.encoding are. * <p> * If you want to set a few flags but keep Groovy's default * configuration behavior then be sure to make your settings in * a Properties that is backed by <code>System.getProperties()</code> (which * is done using this constructor). That might be done like this: * <pre> * Properties myProperties = new Properties(System.getProperties()); * myProperties.setProperty("groovy.output.debug", "true"); * myConfiguration = new CompilerConfiguration(myProperties); * </pre> * And you also have to contend with a possible SecurityException when * getting the system properties (See {@link java.lang.System#getProperties()}). * A safer approach would be to copy a default * CompilerConfiguration and make your changes there using the setter: * <pre> * // In all likelihood there is already a configuration for you to copy, * // but for the sake of this example we'll use the global default. * CompilerConfiguration myConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT); * myConfiguration.setDebug(true); * </pre> * <p> * <table summary="Groovy Compiler Configuration Properties"> * <tr> * <th>Property Key</th><th>Get/Set Property Name</th> * </tr> * <tr> * <td><code>"groovy.warnings"</code></td><td>{@link #getWarningLevel}</td></tr> * <tr><td><code>"groovy.source.encoding"</code></td><td>{@link #getSourceEncoding}</td></tr> * <tr><td><code>"groovy.target.directory"</code></td><td>{@link #getTargetDirectory}</td></tr> * <tr><td><code>"groovy.target.bytecode"</code></td><td>{@link #getTargetBytecode}</td></tr> * <tr><td><code>"groovy.classpath"</code></td><td>{@link #getClasspath}</td></tr> * <tr><td><code>"groovy.output.verbose"</code></td><td>{@link #getVerbose}</td></tr> * <tr><td><code>"groovy.output.debug"</code></td><td>{@link #getDebug}</td></tr> * <tr><td><code>"groovy.errors.tolerance"</code></td><td>{@link #getTolerance}</td></tr> * <tr><td><code>"groovy.script.extension"</code></td><td>{@link #getDefaultScriptExtension}</td></tr> * <tr><td><code>"groovy.script.base"</code></td><td>{@link #getScriptBaseClass}</td></tr> * <tr><td><code>"groovy.recompile"</code></td><td>{@link #getRecompileGroovySource}</td></tr> * <tr><td><code>"groovy.recompile.minimumInterval"</code></td><td>{@link #getMinimumRecompilationInterval}</td></tr> * <tr><td> * </tr> * </table> * * @param configuration The properties to get flag values from. */ public CompilerConfiguration(Properties configuration) throws ConfigurationException { this(); configure(configuration); } /** * Checks if the specified bytecode version string represents a JDK 1.5+ compatible * bytecode version. * @param bytecodeVersion the bytecode version string (1.4, 1.5, 1.6, 1.7 or 1.8) * @return true if the bytecode version is JDK 1.5+ */ public static boolean isPostJDK5(String bytecodeVersion) { return JDK5.equals(bytecodeVersion) || JDK6.equals(bytecodeVersion) || JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); } /** * Checks if the specified bytecode version string represents a JDK 1.7+ compatible * bytecode version. * @param bytecodeVersion the bytecode version string (1.4, 1.5, 1.6, 1.7 or 1.8) * @return true if the bytecode version is JDK 1.7+ */ public static boolean isPostJDK7(String bytecodeVersion) { return JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); } /** * Method to configure a CompilerConfiguration by using Properties. * For a list of available properties look at {@link #CompilerConfiguration(Properties)}. * @param configuration The properties to get flag values from. */ public void configure(Properties configuration) throws ConfigurationException { String text = null; int numeric = 0; // // Warning level numeric = getWarningLevel(); try { text = configuration.getProperty("groovy.warnings", "likely errors"); numeric = Integer.parseInt(text); } catch (NumberFormatException e) { text = text.toLowerCase(); if (text.equals("none")) { numeric = WarningMessage.NONE; } else if (text.startsWith("likely")) { numeric = WarningMessage.LIKELY_ERRORS; } else if (text.startsWith("possible")) { numeric = WarningMessage.POSSIBLE_ERRORS; } else if (text.startsWith("paranoia")) { numeric = WarningMessage.PARANOIA; } else { throw new ConfigurationException("unrecognized groovy.warnings: " + text); } } setWarningLevel(numeric); // // Source file encoding // text = configuration.getProperty("groovy.source.encoding"); if (text == null) { text = configuration.getProperty("file.encoding", "US-ASCII"); } setSourceEncoding(text); // // Target directory for classes // text = configuration.getProperty("groovy.target.directory"); if (text != null) setTargetDirectory(text); text = configuration.getProperty("groovy.target.bytecode"); if (text != null) setTargetBytecode(text); // // Classpath // text = configuration.getProperty("groovy.classpath"); if (text != null) setClasspath(text); // // Verbosity // text = configuration.getProperty("groovy.output.verbose"); if (text != null && text.equalsIgnoreCase("true")) setVerbose(true); // // Debugging // text = configuration.getProperty("groovy.output.debug"); if (text != null && text.equalsIgnoreCase("true")) setDebug(true); // // Parameters // setParameters(configuration.getProperty("groovy.parameters") != null); // // Tolerance // numeric = 10; try { text = configuration.getProperty("groovy.errors.tolerance", "10"); numeric = Integer.parseInt(text); } catch (NumberFormatException e) { throw new ConfigurationException(e); } setTolerance(numeric); // // Script Base Class // text = configuration.getProperty("groovy.script.base"); if (text!=null) setScriptBaseClass(text); // // recompilation options // text = configuration.getProperty("groovy.recompile"); if (text != null) { setRecompileGroovySource(text.equalsIgnoreCase("true")); } numeric = 100; try { text = configuration.getProperty("groovy.recompile.minimumIntervall"); if (text==null) text = configuration.getProperty("groovy.recompile.minimumInterval"); if (text!=null) { numeric = Integer.parseInt(text); } else { numeric = 100; } } catch (NumberFormatException e) { throw new ConfigurationException(e); } setMinimumRecompilationInterval(numeric); // disabled global AST transformations text = configuration.getProperty("groovy.disabled.global.ast.transformations"); if (text!=null) { String[] classNames = text.split(",\\s*}"); Set<String> blacklist = new HashSet<String>(Arrays.asList(classNames)); setDisabledGlobalASTTransformations(blacklist); } } /** * Gets the currently configured warning level. See {@link WarningMessage} * for level details. */ public int getWarningLevel() { return this.warningLevel; } /** * Sets the warning level. See {@link WarningMessage} for level details. */ public void setWarningLevel(int level) { if (level < WarningMessage.NONE || level > WarningMessage.PARANOIA) { this.warningLevel = WarningMessage.LIKELY_ERRORS; } else { this.warningLevel = level; } } /** * Gets the currently configured source file encoding. */ public String getSourceEncoding() { return this.sourceEncoding; } /** * Sets the encoding to be used when reading source files. */ public void setSourceEncoding(String encoding) { if (encoding == null) encoding = "US-ASCII"; this.sourceEncoding = encoding; } /** * Gets the currently configured output writer. * @deprecated not used anymore */ @Deprecated public PrintWriter getOutput() { return this.output; } /** * Sets the output writer. * @deprecated not used anymore, has no effect */ @Deprecated public void setOutput(PrintWriter output) { if (output == null) { this.output = new PrintWriter(NullWriter.DEFAULT); } else { this.output = output; } } /** * Gets the target directory for writing classes. */ public File getTargetDirectory() { return this.targetDirectory; } /** * Sets the target directory. */ public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } } /** * Sets the target directory. */ public void setTargetDirectory(File directory) { this.targetDirectory = directory; } /** * @return the classpath */ public List<String> getClasspath() { return this.classpath; } /** * Sets the classpath. */ public void setClasspath(String classpath) { this.classpath = new LinkedList<String>(); StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { this.classpath.add(tokenizer.nextToken()); } } /** * sets the classpath using a list of Strings * @param parts list of strings containing the classpath parts */ public void setClasspathList(List<String> parts) { this.classpath = new LinkedList<String>(parts); } /** * Returns true if verbose operation has been requested. */ public boolean getVerbose() { return this.verbose; } /** * Turns verbose operation on or off. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Returns true if debugging operation has been requested. */ public boolean getDebug() { return this.debug; } /** * Returns true if parameter metadata generation has been enabled. */ public boolean getParameters() { return this.parameters; } /** * Turns debugging operation on or off. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Turns parameter metadata generation on or off. */ public void setParameters(boolean parameters) { this.parameters = parameters; } /** * Returns the requested error tolerance. */ public int getTolerance() { return this.tolerance; } /** * Sets the error tolerance, which is the number of * non-fatal errors (per unit) that should be tolerated before * compilation is aborted. */ public void setTolerance(int tolerance) { this.tolerance = tolerance; } /** * Gets the name of the base class for scripts. It must be a subclass * of Script. */ public String getScriptBaseClass() { return this.scriptBaseClass; } /** * Sets the name of the base class for scripts. It must be a subclass * of Script. */ public void setScriptBaseClass(String scriptBaseClass) { this.scriptBaseClass = scriptBaseClass; } public ParserPluginFactory getPluginFactory() { if (pluginFactory == null) { if (antlr2Parser) { pluginFactory = ParserPluginFactory.antlr2(); } else { pluginFactory = ParserPluginFactory.antlr4(); } } return pluginFactory; } public void setPluginFactory(ParserPluginFactory pluginFactory) { this.pluginFactory = pluginFactory; } public void setScriptExtensions(Set<String> scriptExtensions) { if(scriptExtensions == null) scriptExtensions = new LinkedHashSet<String>(); this.scriptExtensions = scriptExtensions; } public Set<String> getScriptExtensions() { if(scriptExtensions == null || scriptExtensions.isEmpty()) { /* * this happens * * when groovyc calls FileSystemCompiler in forked mode, or * * when FileSystemCompiler is run from the command line directly, or * * when groovy was not started using groovyc or FileSystemCompiler either */ scriptExtensions = SourceExtensionHandler.getRegisteredExtensions( this.getClass().getClassLoader()); } return scriptExtensions; } public String getDefaultScriptExtension() { return defaultScriptExtension; } public void setDefaultScriptExtension(String defaultScriptExtension) { this.defaultScriptExtension = defaultScriptExtension; } public void setRecompileGroovySource(boolean recompile) { recompileGroovySource = recompile; } public boolean getRecompileGroovySource(){ return recompileGroovySource; } public void setMinimumRecompilationInterval(int time) { minimumRecompilationInterval = Math.max(0,time); } public int getMinimumRecompilationInterval() { return minimumRecompilationInterval; } /** * Allow setting the bytecode compatibility. The parameter can take * one of the values <tt>1.7</tt>, <tt>1.6</tt>, <tt>1.5</tt> or <tt>1.4</tt>. * If wrong parameter then the value will default to VM determined version. * * @param version the bytecode compatibility mode */ public void setTargetBytecode(String version) { for (String allowedJdk : ALLOWED_JDKS) { if (allowedJdk.equals(version)) { this.targetBytecode = version; } } } /** * Retrieves the compiler bytecode compatibility mode. * * @return bytecode compatibility mode. Can be either <tt>1.5</tt> or <tt>1.4</tt>. */ public String getTargetBytecode() { return this.targetBytecode; } private static String getVMVersion() { return POST_JDK5; } /** * Gets the joint compilation options for this configuration. * @return the options */ public Map<String, Object> getJointCompilationOptions() { return jointCompilationOptions; } /** * Sets the joint compilation options for this configuration. * Using null will disable joint compilation. * @param options the options */ public void setJointCompilationOptions(Map<String, Object> options) { jointCompilationOptions = options; } /** * Gets the optimization options for this configuration. * @return the options (always not null) */ public Map<String, Boolean> getOptimizationOptions() { return optimizationOptions; } /** * Sets the optimization options for this configuration. * No entry or a true for that entry means to enable that optimization, * a false means the optimization is disabled. * Valid keys are "all" and "int". * @param options the options. * @throws IllegalArgumentException if the options are null */ public void setOptimizationOptions(Map<String, Boolean> options) { if (options==null) throw new IllegalArgumentException("provided option map must not be null"); optimizationOptions = options; } /** * Adds compilation customizers to the compilation process. A compilation customizer is a class node * operation which performs various operations going from adding imports to access control. * @param customizers the list of customizers to be added * @return this configuration instance */ public CompilerConfiguration addCompilationCustomizers(CompilationCustomizer... customizers) { if (customizers==null) throw new IllegalArgumentException("provided customizers list must not be null"); compilationCustomizers.addAll(Arrays.asList(customizers)); return this; } /** * Returns the list of compilation customizers. * @return the customizers (always not null) */ public List<CompilationCustomizer> getCompilationCustomizers() { return compilationCustomizers; } /** * Returns the list of disabled global AST transformation class names. * @return a list of global AST transformation fully qualified class names */ public Set<String> getDisabledGlobalASTTransformations() { return disabledGlobalASTTransformations; } /** * Disables global AST transformations. In order to avoid class loading side effects, it is not recommended * to use MyASTTransformation.class.getName() by directly use the class name as a string. Disabled AST transformations * only apply to automatically loaded global AST transformations, that is to say transformations defined in a * META-INF/org.codehaus.groovy.transform.ASTTransformation file. If you explicitly add a global AST transformation * in your compilation process, for example using the {@link org.codehaus.groovy.control.customizers.ASTTransformationCustomizer} or * using a {@link org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation}, then nothing will prevent * the transformation from being loaded. * @param disabledGlobalASTTransformations a set of fully qualified class names of global AST transformations * which should not be loaded. */ public void setDisabledGlobalASTTransformations(final Set<String> disabledGlobalASTTransformations) { this.disabledGlobalASTTransformations = disabledGlobalASTTransformations; } public BytecodeProcessor getBytecodePostprocessor() { return bytecodePostprocessor; } public void setBytecodePostprocessor(final BytecodeProcessor bytecodePostprocessor) { this.bytecodePostprocessor = bytecodePostprocessor; } public ParserVersion getParserVersion() { if (this.antlr2Parser) { return ParserVersion.V_2; } return ParserVersion.V_4; } public void setParserVersion(ParserVersion parserVersion) { if (ParserVersion.V_2 == parserVersion) { this.antlr2Parser = true; } else { this.antlr2Parser = false; } } }
Minor refactoring
src/main/org/codehaus/groovy/control/CompilerConfiguration.java
Minor refactoring
<ide><path>rc/main/org/codehaus/groovy/control/CompilerConfiguration.java <ide> * defines if antlr2 parser should be used or the antlr4 one if <ide> * no factory is set yet <ide> */ <del> private boolean antlr2Parser = true; // TODO replace it with ParserVersion <add> private ParserVersion parserVersion = ParserVersion.V_2; <ide> <ide> /** <ide> * Sets the Flags to defaults. <ide> setOptimizationOptions(options); <ide> <ide> try { <del> antlr2Parser = !"true".equals(System.getProperty("groovy.antlr4")); <add> if ("true".equals(System.getProperty("groovy.antlr4"))) { <add> this.parserVersion = ParserVersion.V_4; <add> } <ide> } catch (Exception e) { <ide> // IGNORE <ide> } <ide> <ide> public ParserPluginFactory getPluginFactory() { <ide> if (pluginFactory == null) { <del> if (antlr2Parser) { <del> pluginFactory = ParserPluginFactory.antlr2(); <del> } else { <del> pluginFactory = ParserPluginFactory.antlr4(); <del> } <add> pluginFactory = ParserVersion.V_2 == parserVersion <add> ? ParserPluginFactory.antlr2() <add> : ParserPluginFactory.antlr4(); <ide> } <ide> return pluginFactory; <ide> } <ide> } <ide> <ide> public ParserVersion getParserVersion() { <del> if (this.antlr2Parser) { <del> return ParserVersion.V_2; <del> } <del> <del> return ParserVersion.V_4; <add> return this.parserVersion; <ide> } <ide> <ide> public void setParserVersion(ParserVersion parserVersion) { <del> if (ParserVersion.V_2 == parserVersion) { <del> this.antlr2Parser = true; <del> } else { <del> this.antlr2Parser = false; <del> } <add> this.parserVersion = parserVersion; <ide> } <ide> }
JavaScript
apache-2.0
2836e897e89e703a82d0d1fead351b6ee03c162d
0
xebia/mock-rest-request
var http = require('http'); var request = require('supertest'); var mockRequests = require('..'); describe('mockRequests()', function () { var server; beforeEach(function () { server = createServer({}, function (req, res) { res.end('not mocked'); }); }); it('should not mock when no mocks are configured', function (done) { request(server) .get('/') .expect(200) .expect('not mocked', done); }); describe('that mocks a GET request', function () { beforeEach(function () { request(server) .post('/mock/api') .send({mock: 'data'}) .end(function () {}); }); it('should return the mocked content when the mocked path is requested', function (done) { request(server) .get('/api') .expect(200) .expect('{"mock":"data"}', done); }); it('should return the normal content when another path is requested', function (done) { request(server) .get('/something') .expect(200) .expect('not mocked', done); }); it('should not mock non GET requests', function (done) { request(server) .put('/api') .expect(200) .expect('not mocked', done); }) }); it('should allow a different status code', function (done) { request(server) .post('/mock/api') .set('mock-response', '500') .send({mock: 'data'}) .end(function () {}); request(server) .get('/api') .expect(500) .expect('{"mock":"data"}', done); }); it('should allow a different method', function (done) { request(server) .post('/mock/api') .set('mock-method', 'POST') .send({mock: 'data'}) .end(function () {}); request(server) .get('/api') .expect(200) .expect('not mocked'); request(server) .post('/api') .expect(200) .expect('{"mock":"data"}', done); }) }); function createServer(opts, fn) { var _mockRequests = mockRequests(opts) return http.createServer(function (req, res) { _mockRequests(req, res, function (err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return; } fn(req, res) }) }) }
test/test.js
var http = require('http'); var request = require('supertest'); var mockRequests = require('..'); describe('mockRequests()', function () { var server; beforeEach(function () { server = createServer({}, function (req, res) { res.end('not mocked') }); }) it('should not mock when no mocks are configured', function (done) { request(server) .get('/') .expect(200) .expect('not mocked', done); }); describe('that mocks a GET request', function () { beforeEach(function () { request(server) .post('/mock/api') .send({mock: 'data'}) .end(function () {}); }); it('should return the mocked content when the mocked path is requested', function (done) { request(server) .get('/api') .expect(200) .expect('{"mock":"data"}', done); }); it('should return the normal content when another path is requested', function (done) { request(server) .get('/something') .expect(200) .expect('not mocked', done); }); it('should not mock non GET requests', function (done) { request(server) .put('/api') .expect(200) .expect('not mocked', done); }) }) }); function createServer(opts, fn) { var _mockRequests = mockRequests(opts) return http.createServer(function (req, res) { _mockRequests(req, res, function (err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return; } fn(req, res) }) }) }
Test different status code and method
test/test.js
Test different status code and method
<ide><path>est/test.js <ide> <ide> beforeEach(function () { <ide> server = createServer({}, function (req, res) { <del> res.end('not mocked') <add> res.end('not mocked'); <ide> }); <del> }) <add> }); <add> <ide> it('should not mock when no mocks are configured', function (done) { <ide> <ide> request(server) <ide> .expect(200) <ide> .expect('not mocked', done); <ide> }) <add> }); <add> <add> it('should allow a different status code', function (done) { <add> request(server) <add> .post('/mock/api') <add> .set('mock-response', '500') <add> .send({mock: 'data'}) <add> .end(function () {}); <add> <add> request(server) <add> .get('/api') <add> .expect(500) <add> .expect('{"mock":"data"}', done); <add> }); <add> <add> it('should allow a different method', function (done) { <add> request(server) <add> .post('/mock/api') <add> .set('mock-method', 'POST') <add> .send({mock: 'data'}) <add> .end(function () {}); <add> <add> request(server) <add> .get('/api') <add> .expect(200) <add> .expect('not mocked'); <add> <add> request(server) <add> .post('/api') <add> .expect(200) <add> .expect('{"mock":"data"}', done); <ide> }) <ide> <ide> });
Java
apache-2.0
d9cd029f8783792b31dd48bf1e32f80628f2c4a3
0
garpinc/pac4j,garpinc/pac4j
package org.pac4j.oidc.authorization.generator; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import org.pac4j.core.authorization.generator.AuthorizationGenerator; import org.pac4j.core.context.WebContext; import org.pac4j.core.profile.UserProfile; import org.pac4j.oidc.profile.keycloak.KeycloakOidcProfile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; /** * Specific {@link AuthorizationGenerator} to Keycloak. * * @author Jerome Leleu * @since 3.4.0 */ public class KeycloakRolesAuthorizationGenerator implements AuthorizationGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(KeycloakRolesAuthorizationGenerator.class); private String clientId; public KeycloakRolesAuthorizationGenerator() {} public KeycloakRolesAuthorizationGenerator(final String clientId) { this.clientId = clientId; } @Override public Optional<UserProfile> generate(final WebContext context, final UserProfile profile) { if (profile instanceof KeycloakOidcProfile) { try { final JWT jwt = SignedJWT.parse(((KeycloakOidcProfile) profile).getAccessToken().getValue()); final JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet(); final JSONObject realmRolesJsonObject = jwtClaimsSet.getJSONObjectClaim("realm_access"); if (realmRolesJsonObject != null) { final JSONArray realmRolesJsonArray = (JSONArray) realmRolesJsonObject.get("roles"); if (realmRolesJsonArray != null) { realmRolesJsonArray.forEach(role -> profile.addRole((String) role)); } } if (clientId != null) { JSONObject resourceAccess = jwtClaimsSet.getJSONObjectClaim("resource_access"); if (resourceAccess != null) { final JSONObject clientRolesJsonObject = (JSONObject) resourceAccess.get(clientId); if (clientRolesJsonObject != null) { final JSONArray clientRolesJsonArray = (JSONArray) clientRolesJsonObject.get("roles"); if (clientRolesJsonArray != null) { clientRolesJsonArray.forEach(role -> profile.addRole((String) role)); } } } } } catch (final Exception e) { LOGGER.warn("Cannot parse Keycloak roles", e); } } return Optional.of(profile); } public String getClientId() { return clientId; } public void setClientId(final String clientId) { this.clientId = clientId; } }
pac4j-oidc/src/main/java/org/pac4j/oidc/authorization/generator/KeycloakRolesAuthorizationGenerator.java
package org.pac4j.oidc.authorization.generator; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import org.pac4j.core.authorization.generator.AuthorizationGenerator; import org.pac4j.core.context.WebContext; import org.pac4j.core.profile.UserProfile; import org.pac4j.oidc.profile.keycloak.KeycloakOidcProfile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; /** * Specific {@link AuthorizationGenerator} to Keycloak. * * @author Jerome Leleu * @since 3.4.0 */ public class KeycloakRolesAuthorizationGenerator implements AuthorizationGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(KeycloakRolesAuthorizationGenerator.class); private final String clientId; public KeycloakRolesAuthorizationGenerator(final String clientId) { this.clientId = clientId; } @Override public Optional<UserProfile> generate(final WebContext context, final UserProfile profile) { if (profile instanceof KeycloakOidcProfile) { try { final JWT jwt = SignedJWT.parse(((KeycloakOidcProfile) profile).getAccessToken().getValue()); final JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet(); final JSONObject realmRolesJsonObject = jwtClaimsSet.getJSONObjectClaim("realm_access"); if (realmRolesJsonObject != null) { final JSONArray realmRolesJsonArray = (JSONArray) realmRolesJsonObject.get("roles"); if (realmRolesJsonArray != null) { realmRolesJsonArray.forEach(role -> profile.addRole((String) role)); } } if (clientId != null) { JSONObject resourceAccess = jwtClaimsSet.getJSONObjectClaim("resource_access"); if (resourceAccess != null) { final JSONObject clientRolesJsonObject = (JSONObject) resourceAccess.get(clientId); if (clientRolesJsonObject != null) { final JSONArray clientRolesJsonArray = (JSONArray) clientRolesJsonObject.get("roles"); if (clientRolesJsonArray != null) { clientRolesJsonArray.forEach(role -> profile.addRole((String) role)); } } } } } catch (final Exception e) { LOGGER.warn("Cannot parse Keycloak roles", e); } } return Optional.of(profile); } }
Default constructor for KeycloakRolesAuthorizationGenerator
pac4j-oidc/src/main/java/org/pac4j/oidc/authorization/generator/KeycloakRolesAuthorizationGenerator.java
Default constructor for KeycloakRolesAuthorizationGenerator
<ide><path>ac4j-oidc/src/main/java/org/pac4j/oidc/authorization/generator/KeycloakRolesAuthorizationGenerator.java <ide> <ide> private static final Logger LOGGER = LoggerFactory.getLogger(KeycloakRolesAuthorizationGenerator.class); <ide> <del> private final String clientId; <add> private String clientId; <add> <add> public KeycloakRolesAuthorizationGenerator() {} <ide> <ide> public KeycloakRolesAuthorizationGenerator(final String clientId) { <ide> this.clientId = clientId; <ide> <ide> return Optional.of(profile); <ide> } <add> <add> public String getClientId() { <add> return clientId; <add> } <add> <add> public void setClientId(final String clientId) { <add> this.clientId = clientId; <add> } <ide> }
Java
apache-2.0
376f40a61ae2dee8827539ff4f78f9932f9db500
0
NLeSC/Xenon,benvanwerkhoven/Xenon,NLeSC/Xenon,benvanwerkhoven/Xenon
/* * Copyright 2013 Netherlands eScience Center * * 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 nl.esciencecenter.octopus.adaptors; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import nl.esciencecenter.octopus.Octopus; import nl.esciencecenter.octopus.OctopusFactory; import nl.esciencecenter.octopus.adaptors.ssh.SshAdaptor; import nl.esciencecenter.octopus.credentials.Credential; import nl.esciencecenter.octopus.credentials.Credentials; import nl.esciencecenter.octopus.exceptions.InvalidCredentialsException; import nl.esciencecenter.octopus.exceptions.InvalidJobDescriptionException; import nl.esciencecenter.octopus.exceptions.InvalidPropertyException; import nl.esciencecenter.octopus.exceptions.JobCanceledException; import nl.esciencecenter.octopus.exceptions.NoSuchQueueException; import nl.esciencecenter.octopus.exceptions.NoSuchSchedulerException; import nl.esciencecenter.octopus.exceptions.OctopusException; import nl.esciencecenter.octopus.exceptions.UnknownPropertyException; import nl.esciencecenter.octopus.exceptions.UnsupportedJobDescriptionException; import nl.esciencecenter.octopus.files.AbsolutePath; import nl.esciencecenter.octopus.files.FileSystem; import nl.esciencecenter.octopus.files.Files; import nl.esciencecenter.octopus.files.OpenOption; import nl.esciencecenter.octopus.files.RelativePath; import nl.esciencecenter.octopus.jobs.Job; import nl.esciencecenter.octopus.jobs.JobDescription; import nl.esciencecenter.octopus.jobs.JobStatus; import nl.esciencecenter.octopus.jobs.Jobs; import nl.esciencecenter.octopus.jobs.QueueStatus; import nl.esciencecenter.octopus.jobs.Scheduler; import nl.esciencecenter.octopus.jobs.Streams; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jason Maassen <[email protected]> * */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class GenericJobAdaptorTestParent { private static final Logger logger = LoggerFactory.getLogger(GenericJobAdaptorTestParent.class); private static String TEST_ROOT; protected static JobTestConfig config; protected Octopus octopus; protected Files files; protected Jobs jobs; protected Credentials credentials; protected AbsolutePath testDir; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void starting(Description description) { logger.info("Running test {}", description.getMethodName()); } @Override public void failed(Throwable reason, Description description) { logger.info("Test {} failed due to exception", description.getMethodName(), reason); } @Override public void succeeded(Description description) { logger.info("Test {} succeeded", description.getMethodName()); } @Override public void skipped(AssumptionViolatedException reason, Description description) { logger.info("Test {} skipped due to failed assumption", description.getMethodName(), reason); } }; // MUST be invoked by a @BeforeClass method of the subclass! public static void prepareClass(JobTestConfig testConfig) { config = testConfig; TEST_ROOT = "octopus_test_" + config.getAdaptorName() + "_" + System.currentTimeMillis(); } // MUST be invoked by a @AfterClass method of the subclass! public static void cleanupClass() throws Exception { System.err.println("GenericJobAdaptorTest.cleanupClass() attempting to remove: " + TEST_ROOT); Octopus octopus = OctopusFactory.newOctopus(null); Files files = octopus.files(); Credentials credentials = octopus.credentials(); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(TEST_ROOT)); if (files.exists(root)) { files.delete(root); } OctopusFactory.endOctopus(octopus); } @Before public void prepare() throws OctopusException { // This is not an adaptor option, so it will throw an exception! //Map<String, String> properties = new HashMap<>(); //properties.put(SshAdaptor.POLLING_DELAY, "100"); octopus = OctopusFactory.newOctopus(null); files = octopus.files(); jobs = octopus.jobs(); credentials = octopus.credentials(); } @After public void cleanup() throws OctopusException { // OctopusFactory.endOctopus(octopus); OctopusFactory.endAll(); } protected String getWorkingDir(String testName) { return TEST_ROOT + "/" + testName; } // TEST: newScheduler // // location: null / valid URI / invalid URI // credential: null / default / set / wrong // properties: null / empty / set / wrong @Test(expected = NullPointerException.class) public void test00_newScheduler() throws Exception { jobs.newScheduler(null, null, null); } @Test public void test01_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), null, null); jobs.close(s); } @Test(expected = OctopusException.class) public void test02a_newScheduler() throws Exception { jobs.newScheduler(config.getURIWrongLocation(), null, null); } @Test(expected = OctopusException.class) public void test02b_newScheduler() throws Exception { jobs.newScheduler(config.getURIWrongPath(), null, null); } @Test public void test03_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), null); jobs.close(s); } @Test public void test04a_newScheduler() throws Exception { if (config.supportsCredentials()) { try { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getInvalidCredential(credentials), null); jobs.close(s); throw new Exception("newScheduler did NOT throw InvalidCredentialsException"); } catch (InvalidCredentialsException e) { // expected } catch (OctopusException e) { // allowed } } } @Test public void test04b_newScheduler() throws Exception { if (!config.supportsCredentials()) { try { Credential c = new Credential() { @Override public Map<String, String> getProperties() { return null; } @Override public String getAdaptorName() { return "local"; } }; Scheduler s = jobs.newScheduler(config.getCorrectURI(), c, null); jobs.close(s); throw new Exception("newScheduler did NOT throw OctopusException"); } catch (OctopusException e) { // expected } } } @Test public void test04c_newScheduler() throws Exception { if (config.supportsCredentials()) { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getPasswordCredential(credentials), config.getDefaultProperties()); jobs.close(s); } } @Test public void test05_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), new HashMap<String, String>()); jobs.close(s); } @Test public void test06_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), config.getDefaultProperties()); jobs.close(s); } @Test public void test07_newScheduler() throws Exception { if (config.supportsProperties()) { Map<String, String>[] tmp = config.getInvalidProperties(); for (Map<String, String> p : tmp) { try { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), p); jobs.close(s); throw new Exception("newScheduler did NOT throw InvalidPropertyException"); } catch (InvalidPropertyException e) { // expected } } } } @Test public void test08_newScheduler() throws Exception { if (config.supportsProperties()) { try { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), config.getUnknownProperties()); jobs.close(s); throw new Exception("newScheduler did NOT throw UnknownPropertyException"); } catch (UnknownPropertyException e) { // expected } } } @Test public void test09_newScheduler() throws Exception { if (!config.supportsProperties()) { try { Map<String, String> p = new HashMap<>(); p.put("aap", "noot"); Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), p); jobs.close(s); throw new Exception("newScheduler did NOT throw OctopusException"); } catch (OctopusException e) { // expected } } } @Test public void test10_getLocalScheduler() throws Exception { Scheduler s = null; try { s = jobs.getLocalScheduler(); assertTrue(s != null); assertTrue(s.getAdaptorName().equals("local")); } finally { if (s != null) { jobs.close(s); } } } @Test public void test11_open_close() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); assertTrue(jobs.isOpen(s)); jobs.close(s); assertFalse(jobs.isOpen(s)); } } @Test public void test12_open_close() throws Exception { if (!config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); assertTrue(jobs.isOpen(s)); jobs.close(s); assertTrue(jobs.isOpen(s)); } } @Test public void test13_open_close() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.close(s); throw new Exception("close did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test14a_getJobs() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getJobs(s, s.getQueueNames()); jobs.close(s); } @Test public void test14b_getJobs() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getJobs(s); jobs.close(s); } @Test public void test15_getJobs() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); try { jobs.getJobs(s, config.getInvalidQueueName()); throw new Exception("getJobs did NOT throw NoSuchQueueException"); } catch (NoSuchQueueException e) { // expected } finally { jobs.close(s); } } @Test public void test16_getJobs() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.getJobs(s, s.getQueueNames()); throw new Exception("close did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test17_getQueueStatus() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getQueueStatus(s, s.getQueueNames()[0]); jobs.close(s); } @Test(expected = NoSuchQueueException.class) public void test18a_getQueueStatus() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); try { jobs.getQueueStatus(s, config.getInvalidQueueName()); } finally { jobs.close(s); } } @Test public void test18b_getQueueStatus() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); String queueName = config.getDefaultQueueName(); try { jobs.getQueueStatus(s, queueName); } finally { jobs.close(s); } } @Test(expected = NullPointerException.class) public void test19_getQueueStatus() throws Exception { jobs.getQueueStatus(null, null); } @Test public void test20_getQueueStatus() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.getQueueStatus(s, s.getQueueNames()[0]); throw new Exception("getQueueStatus did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test21a_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); QueueStatus[] tmp = jobs.getQueueStatuses(s, s.getQueueNames()); jobs.close(s); String[] names = s.getQueueNames(); assertTrue(tmp != null); assertTrue(tmp.length == names.length); for (int i = 0; i < tmp.length; i++) { assertTrue(tmp[i].getQueueName().equals(names[i])); } } @Test public void test21b_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); QueueStatus[] tmp = jobs.getQueueStatuses(s); jobs.close(s); String[] names = s.getQueueNames(); assertTrue(tmp != null); assertTrue(tmp.length == names.length); for (int i = 0; i < tmp.length; i++) { assertTrue(tmp[i].getQueueName().equals(names[i])); } } @Test public void test22a_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); try { QueueStatus[] tmp = jobs.getQueueStatuses(s, config.getInvalidQueueName()); assertTrue(tmp != null); assertTrue(tmp.length == 1); assertTrue(tmp[0].hasException()); assertTrue(tmp[0].getException() instanceof NoSuchQueueException); } finally { jobs.close(s); } } @Test(expected = NullPointerException.class) public void test22b_getQueueStatuses() throws Exception { jobs.getQueueStatuses(null, config.getDefaultQueueName()); } @Test(expected = IllegalArgumentException.class) public void test22c_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getQueueStatuses(s, (String[]) null); } @Test(expected = NullPointerException.class) public void test23_getQueueStatuses() throws Exception { jobs.getQueueStatuses(null); } @Test public void test24_getQueueStatuses() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.getQueueStatuses(s, s.getQueueNames()); throw new Exception("getQueueStatuses did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test25a_getJobStatuses() throws Exception { JobStatus[] tmp = jobs.getJobStatuses(new Job[0]); assertTrue(tmp != null); assertTrue(tmp.length == 0); } @Test public void test25b_getJobStatuses() throws Exception { JobStatus[] tmp = jobs.getJobStatuses((Job[]) null); assertTrue(tmp != null); assertTrue(tmp.length == 0); } @Test public void test25c_getJobStatuses() throws Exception { JobStatus[] tmp = jobs.getJobStatuses(new Job[1]); assertTrue(tmp != null); assertTrue(tmp.length == 1); assertTrue(tmp[0] == null); } protected String readFully(InputStream in) throws IOException { byte[] buffer = new byte[1024]; int offset = 0; int tmp = in.read(buffer, 0, buffer.length - offset); while (tmp != -1) { offset += tmp; if (offset == buffer.length) { buffer = Arrays.copyOf(buffer, buffer.length * 2); } tmp = in.read(buffer, offset, buffer.length - offset); } in.close(); return new String(buffer, 0, offset); } protected void writeFully(OutputStream out, String message) throws IOException { out.write(message.getBytes()); out.close(); } @org.junit.Test public void test30_interactiveJobSubmit() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); if (scheduler.isOnline()) { String message = "Hello World! test30"; JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setArguments("-n", message); description.setInteractive(true); System.err.println("Submitting interactive job to " + scheduler.getUri()); Job job = jobs.submitJob(scheduler, description); System.err.println("Interactive job submitted to " + scheduler.getUri()); Streams streams = jobs.getStreams(job); streams.getStdin().close(); String out = readFully(streams.getStdout()); String err = readFully(streams.getStderr()); // NOTE: Job should already be done here! JobStatus status = jobs.waitUntilDone(job, 5000); if (!status.isDone()) { throw new Exception("Job exceeded dealine!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } assertTrue(out.equals(message)); assertTrue(err.length() == 0); } jobs.close(scheduler); } @org.junit.Test public void test31_batchJobSubmitWithPolling() throws Exception { String message = "Hello World! test31"; String workingDir = getWorkingDir("test31"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setArguments("-n", message); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); long deadline = System.currentTimeMillis() + config.getQueueWaitTime() + config.getUpdateTime(); long pollDelay = (config.getQueueWaitTime() + config.getUpdateTime()) / 10; JobStatus status = jobs.getJobStatus(job); while (!status.isDone()) { Thread.sleep(pollDelay); long now = System.currentTimeMillis(); if (now > deadline) { throw new Exception("Job exceeded deadline!"); } status = jobs.getJobStatus(job); } jobs.close(scheduler); if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } AbsolutePath out = root.resolve(new RelativePath("stdout.txt")); AbsolutePath err = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(out)); String tmperr = readFully(files.newInputStream(err)); files.delete(out); files.delete(err); files.delete(root); files.close(filesystem); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } @org.junit.Test public void test32_batchJobSubmitWithWait() throws Exception { String message = "Hello World! test32"; String workingDir = getWorkingDir("test32"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setArguments("-n", message); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilRunning(job, config.getQueueWaitTime()); if (status.isRunning()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); AbsolutePath out = root.resolve(new RelativePath("stdout.txt")); AbsolutePath err = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(out)); String tmperr = readFully(files.newInputStream(err)); files.delete(out); files.delete(err); files.delete(root); files.close(filesystem); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } private void submitToQueueWithPolling(String testName, String queueName, int jobCount) throws Exception { System.err.println("STARTING TEST submitToQueueWithPolling(" + testName + ", " + queueName + ", " + jobCount); String workingDir = getWorkingDir(testName); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath[] out = new AbsolutePath[jobCount]; AbsolutePath[] err = new AbsolutePath[jobCount]; Jobs jobs = octopus.jobs(); Job[] j = new Job[jobCount]; for (int i = 0; i < j.length; i++) { out[i] = root.resolve(new RelativePath("stdout" + i + ".txt")); err[i] = root.resolve(new RelativePath("stderr" + i + ".txt")); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setWorkingDirectory(workingDir); description.setQueueName(queueName); description.setInteractive(false); description.setStdin(null); description.setStdout("stdout" + i + ".txt"); description.setStderr("stderr" + i + ".txt"); j[i] = jobs.submitJob(scheduler, description); } // Bit hard to determine realistic deadline here ? long deadline = System.currentTimeMillis() + config.getQueueWaitTime() + (jobCount * config.getUpdateTime()); boolean done = false; while (!done) { JobStatus[] status = jobs.getJobStatuses(j); int count = 0; for (int i = 0; i < j.length; i++) { if (j[i] != null) { if (status[i].isDone()) { if (status[i].hasException()) { System.err.println("Job " + i + " failed!"); throw new Exception("Job " + i + " failed", status[i].getException()); } System.err.println("Job " + i + " done."); j[i] = null; } else { count++; } } } if (count == 0) { done = true; } else { Thread.sleep(1000); long now = System.currentTimeMillis(); if (now > deadline) { throw new Exception("Job exceeded deadline!"); } } } for (int i = 0; i < j.length; i++) { String tmpout = readFully(files.newInputStream(out[i])); String tmperr = readFully(files.newInputStream(err[i])); assertTrue(tmpout != null); assertTrue(tmpout.length() == 0); assertTrue(tmperr != null); assertTrue(tmperr.length() == 0); files.delete(out[i]); files.delete(err[i]); } jobs.close(scheduler); files.delete(root); files.close(filesystem); } @org.junit.Test public void test33a_testMultiBatchJobSubmitWithPolling() throws Exception { for (String queue : config.getQueueNames()) { submitToQueueWithPolling("test33a_" + queue, queue, 1); } } @org.junit.Test public void test33b_testMultiBatchJobSubmitWithPolling() throws Exception { System.err.println("STARTING TEST test33b"); for (String queue : config.getQueueNames()) { submitToQueueWithPolling("test33b_" + queue, queue, 10); } } @org.junit.Test public void test34_batchJobSubmitWithKill() throws Exception { String workingDir = getWorkingDir("test34"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("60"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); // We immediately kill the job. Hopefully it isn't running yet! Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.cancelJob(job); // Wait until the job is killed. We assume it takes less than a minute! if (!status.isDone()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Failed to kill job! Expected status done, but job status is " + status); } jobs.close(scheduler); AbsolutePath out = root.resolve(new RelativePath(description.getStdout())); AbsolutePath err = root.resolve(new RelativePath(description.getStderr())); if (files.exists(out)) { files.delete(out); } if (files.exists(err)) { files.delete(err); } files.delete(root); files.close(filesystem); assertTrue(status.hasException()); Exception e = status.getException(); if (!(e instanceof JobCanceledException)) { throw new Exception("test34 expected JobCanceledException, not " + e.getMessage(), e); } } @org.junit.Test public void test35_batchJobSubmitWithKill2() throws Exception { String workingDir = getWorkingDir("test35"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("60"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); // Wait for job to run before killing it! JobStatus status = jobs.waitUntilRunning(job, config.getQueueWaitTime()); if (!status.isRunning()) { throw new Exception("Job failed to start! Expected status running, but job status is " + status); } status = jobs.cancelJob(job); // Wait until the job is killed. We assume it takes less than a minute! if (!status.isDone()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Failed to kill job! Expected status done, but job status is " + status); } jobs.close(scheduler); AbsolutePath out = root.resolve(new RelativePath(description.getStdout())); AbsolutePath err = root.resolve(new RelativePath(description.getStderr())); if (files.exists(out)) { files.delete(out); } if (files.exists(err)) { files.delete(err); } files.delete(root); files.close(filesystem); assertTrue(status.hasException()); Exception e = status.getException(); assertTrue(e instanceof JobCanceledException); } @org.junit.Test public void test36a_batchJobSubmitWithInput() throws Exception { String message = "Hello World! test36a"; String workingDir = getWorkingDir("test36a"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath stdin = root.resolve(new RelativePath("stdin.txt")); OutputStream out = files.newOutputStream(stdin, OpenOption.CREATE, OpenOption.APPEND, OpenOption.WRITE); writeFully(out, message); JobDescription description = new JobDescription(); description.setExecutable("/bin/cat"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin("stdin.txt"); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, config.getQueueWaitTime() + config.getUpdateTime()); if (!status.isDone()) { throw new Exception("Job exceeded deadline! status = " + status); } if (status.hasException()) { throw new Exception("Job failed! exception is = ", status.getException()); } jobs.close(scheduler); AbsolutePath stdout = root.resolve(new RelativePath("stdout.txt")); AbsolutePath stderr = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(stdout)); String tmperr = readFully(files.newInputStream(stderr)); files.delete(stdin); files.delete(stdout); files.delete(stderr); files.delete(root); files.close(filesystem); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } @org.junit.Test public void test36b_batchJobSubmitWithInput() throws Exception { String message = "Hello World! test36b"; String workingDir = getWorkingDir("test36b"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath stdin = root.resolve(new RelativePath("stdin.txt")); OutputStream out = files.newOutputStream(stdin, OpenOption.CREATE, OpenOption.APPEND, OpenOption.WRITE); writeFully(out, message); JobDescription description = new JobDescription(); description.setExecutable("/bin/cat"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin("stdin.txt"); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilRunning(job, config.getQueueWaitTime()); if (status.isRunning()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); AbsolutePath stdout = root.resolve(new RelativePath("stdout.txt")); AbsolutePath stderr = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(stdout)); String tmperr = readFully(files.newInputStream(stderr)); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); files.delete(stdin); files.delete(stdout); files.delete(stderr); files.delete(root); files.close(filesystem); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } @org.junit.Test public void test37a_batchJobSubmitWithoutWorkDir() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setWorkingDirectory(null); description.setStdout(null); description.setStderr(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); } @org.junit.Test public void test37b_batchJobSubmitWithRelativeWorkDir() throws Exception { String workingDir = getWorkingDir("test37b"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setStdout(null); description.setStderr(null); //relative working dir name used description.setWorkingDirectory(workingDir); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } files.delete(root); jobs.close(scheduler); files.close(filesystem); } @org.junit.Test public void test37c_batchJobSubmitWithAbsoluteWorkDir() throws Exception { String workingDir = getWorkingDir("test37c"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setStdout(null); description.setStderr(null); //absolute working dir name used description.setWorkingDirectory(root.getPath()); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } files.delete(root); jobs.close(scheduler); files.close(filesystem); } @org.junit.Test public void test37d_batchJobSubmitWithIncorrectWorkingDir() throws Exception { //note that we are _not_ creating this directory, making it invalid String workingDir = getWorkingDir("test37d"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setStdout(null); description.setStderr(null); //incorrect working dir used description.setWorkingDirectory(workingDir); //submitting this job will either: // 1) throw an InvalidJobDescription when we submit the job // 2) produce an error when the job is run. Job job = null; try { job = jobs.submitJob(scheduler, description); } catch (InvalidJobDescriptionException e) { //Submit failed, as expected (1) jobs.close(scheduler); return; } JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { fail("Job exceeded deadline! Expected status done, got " + status); } //option (2) assertTrue(status.hasException()); jobs.close(scheduler); } //@org.junit.Test public void test38_multipleBatchJobSubmitWithInput() throws Exception { String message = "Hello World! test38"; String workingDir = getWorkingDir("test38"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath stdin = root.resolve(new RelativePath("stdin.txt")); OutputStream out = files.newOutputStream(stdin, OpenOption.CREATE, OpenOption.APPEND, OpenOption.WRITE); writeFully(out, message); JobDescription description = new JobDescription(); description.setExecutable("/bin/cat"); description.setInteractive(false); description.setProcessesPerNode(2); description.setWorkingDirectory(workingDir); description.setStdin("stdin.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } for (int i = 0; i < 2; i++) { AbsolutePath stdoutTmp = root.resolve(new RelativePath("stdout.txt." + i)); AbsolutePath stderrTmp = root.resolve(new RelativePath("stderr.txt." + i)); String tmpout = readFully(files.newInputStream(stdoutTmp)); String tmperr = readFully(files.newInputStream(stderrTmp)); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); files.delete(stdoutTmp); files.delete(stderrTmp); } files.delete(stdin); files.delete(root); jobs.close(scheduler); files.close(filesystem); } @org.junit.Test public void test39_multipleBatchJobSubmitWithExceptions() throws Exception { // NOTE: This test assumes that an exception is thrown when the status of a job is requested twice after the job is done! // This may not be true for all schedulers. if (config.supportsStatusAfterDone()) { return; } Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setWorkingDirectory(null); Job[] j = new Job[2]; j[0] = jobs.submitJob(scheduler, description); description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("2"); description.setInteractive(false); description.setWorkingDirectory(null); j[1] = jobs.submitJob(scheduler, description); long now = System.currentTimeMillis(); long deadline = now + 10000; JobStatus[] s = null; while (now < deadline) { s = jobs.getJobStatuses(j); if (s[0].hasException() && s[1].hasException()) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { // ignored } now = System.currentTimeMillis(); } if (s == null || !(s[0].hasException() && s[1].hasException())) { throw new Exception("Job exceeded deadline!"); } jobs.close(scheduler); } @org.junit.Test public void test40_batchJobSubmitWithExitcode() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setWorkingDirectory(null); description.setStderr(null); description.setStdout(null); description.setStdin(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); assertTrue(status.getExitCode() == 0); } @org.junit.Test public void test40_batchJobSubmitWithNoneZeroExitcode() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); //run an ls with a non existing file. This should make ls return exitcode 2 JobDescription description = new JobDescription(); description.setExecutable("/bin/ls"); description.setArguments("non.existing.file"); description.setInteractive(false); description.setWorkingDirectory(null); description.setStderr(null); description.setStdout(null); description.setStdin(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); assertTrue(status.getExitCode() == 2); } @org.junit.Test public void test41_batchJobSubmitWithEnvironmentVariable() throws Exception { if (!config.supportsEnvironmentVariables()) { return; } String workingDir = getWorkingDir("test41"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); //echo the given variable, to see if the va JobDescription description = new JobDescription(); description.setExecutable("/usr/bin/printenv"); description.setArguments("SOME_VARIABLE"); description.setInteractive(false); description.addEnvironment("SOME_VARIABLE", "some_value"); description.setWorkingDirectory(workingDir); description.setStderr(null); description.setStdout("stdout.txt"); description.setStdin(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } AbsolutePath stdout = root.resolve(new RelativePath("stdout.txt")); String stdoutContent = readFully(files.newInputStream(stdout)); assertTrue(stdoutContent.equals("some_value\n")); files.delete(stdout); files.delete(root); files.close(filesystem); } @org.junit.Test public void test41b_batchJobSubmitWithEnvironmentVariable() throws Exception { if (config.supportsEnvironmentVariables()) { return; } Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); // echo the given variable, to see if the va JobDescription description = new JobDescription(); description.setExecutable("/usr/bin/printenv"); description.setArguments("SOME_VARIABLE"); description.setInteractive(false); description.addEnvironment("SOME_VARIABLE", "some_value"); description.setWorkingDirectory(null); description.setStderr(null); description.setStdin(null); boolean gotException = false; try { Job job = jobs.submitJob(scheduler, description); jobs.waitUntilDone(job, config.getUpdateTime()); } catch (UnsupportedJobDescriptionException e) { gotException = true; } jobs.close(scheduler); if (!gotException) { throw new Exception("Submit did not throw exception, which was expected!"); } } @Test public void test42a_batchJob_parallel_Exception() throws Exception { if (config.supportsParallelJobs()) { return; } Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setNodeCount(2); description.setProcessesPerNode(2); boolean gotException = false; try { jobs.submitJob(scheduler, description); } catch (InvalidJobDescriptionException e) { gotException = true; } finally { jobs.close(scheduler); } if (!gotException) { throw new Exception("Submit did not throw exception, which was expected!"); } } @org.junit.Test public void test43_submit_JobDescriptionShouldBeCopied_Success() throws Exception { String workingDir = getWorkingDir("test43"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("non-existing-executable"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdout("stdout.txt"); Job job = jobs.submitJob(scheduler, description); description.setStdout("aap.txt"); JobDescription original = job.getJobDescription(); assertEquals("Job description should have been copied!", "stdout.txt", original.getStdout()); JobStatus status = jobs.cancelJob(job); if (!status.isDone()) { jobs.waitUntilDone(job, 60000); } AbsolutePath out = root.resolve(new RelativePath("stdout.txt")); if (files.exists(out)) { files.delete(out); } files.delete(root); files.close(filesystem); } }
test/src/nl/esciencecenter/octopus/adaptors/GenericJobAdaptorTestParent.java
/* * Copyright 2013 Netherlands eScience Center * * 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 nl.esciencecenter.octopus.adaptors; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import nl.esciencecenter.octopus.Octopus; import nl.esciencecenter.octopus.OctopusFactory; import nl.esciencecenter.octopus.adaptors.ssh.SshAdaptor; import nl.esciencecenter.octopus.credentials.Credential; import nl.esciencecenter.octopus.credentials.Credentials; import nl.esciencecenter.octopus.exceptions.InvalidCredentialsException; import nl.esciencecenter.octopus.exceptions.InvalidJobDescriptionException; import nl.esciencecenter.octopus.exceptions.InvalidPropertyException; import nl.esciencecenter.octopus.exceptions.JobCanceledException; import nl.esciencecenter.octopus.exceptions.NoSuchQueueException; import nl.esciencecenter.octopus.exceptions.NoSuchSchedulerException; import nl.esciencecenter.octopus.exceptions.OctopusException; import nl.esciencecenter.octopus.exceptions.UnknownPropertyException; import nl.esciencecenter.octopus.exceptions.UnsupportedJobDescriptionException; import nl.esciencecenter.octopus.files.AbsolutePath; import nl.esciencecenter.octopus.files.FileSystem; import nl.esciencecenter.octopus.files.Files; import nl.esciencecenter.octopus.files.OpenOption; import nl.esciencecenter.octopus.files.RelativePath; import nl.esciencecenter.octopus.jobs.Job; import nl.esciencecenter.octopus.jobs.JobDescription; import nl.esciencecenter.octopus.jobs.JobStatus; import nl.esciencecenter.octopus.jobs.Jobs; import nl.esciencecenter.octopus.jobs.QueueStatus; import nl.esciencecenter.octopus.jobs.Scheduler; import nl.esciencecenter.octopus.jobs.Streams; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jason Maassen <[email protected]> * */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class GenericJobAdaptorTestParent { private static final Logger logger = LoggerFactory.getLogger(GenericJobAdaptorTestParent.class); private static String TEST_ROOT; protected static JobTestConfig config; protected Octopus octopus; protected Files files; protected Jobs jobs; protected Credentials credentials; protected AbsolutePath testDir; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void starting(Description description) { logger.info("Running test {}", description.getMethodName()); } @Override public void failed(Throwable reason, Description description) { logger.info("Test {} failed due to exception", description.getMethodName(), reason); } @Override public void succeeded(Description description) { logger.info("Test {} succeeded", description.getMethodName()); } @Override public void skipped(AssumptionViolatedException reason, Description description) { logger.info("Test {} skipped due to failed assumption", description.getMethodName(), reason); } }; // MUST be invoked by a @BeforeClass method of the subclass! public static void prepareClass(JobTestConfig testConfig) { config = testConfig; TEST_ROOT = "octopus_test_" + config.getAdaptorName() + "_" + System.currentTimeMillis(); } // MUST be invoked by a @AfterClass method of the subclass! public static void cleanupClass() throws Exception { System.err.println("GenericJobAdaptorTest.cleanupClass() attempting to remove: " + TEST_ROOT); Octopus octopus = OctopusFactory.newOctopus(null); Files files = octopus.files(); Credentials credentials = octopus.credentials(); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(TEST_ROOT)); if (files.exists(root)) { files.delete(root); } OctopusFactory.endOctopus(octopus); } @Before public void prepare() throws OctopusException { // This is not an adaptor option, so it will throw an exception! //Map<String, String> properties = new HashMap<>(); //properties.put(SshAdaptor.POLLING_DELAY, "100"); octopus = OctopusFactory.newOctopus(null); files = octopus.files(); jobs = octopus.jobs(); credentials = octopus.credentials(); } @After public void cleanup() throws OctopusException { // OctopusFactory.endOctopus(octopus); OctopusFactory.endAll(); } protected String getWorkingDir(String testName) { return TEST_ROOT + "/" + testName; } // TEST: newScheduler // // location: null / valid URI / invalid URI // credential: null / default / set / wrong // properties: null / empty / set / wrong @Test(expected = NullPointerException.class) public void test00_newScheduler() throws Exception { jobs.newScheduler(null, null, null); } @Test public void test01_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), null, null); jobs.close(s); } @Test(expected = OctopusException.class) public void test02a_newScheduler() throws Exception { jobs.newScheduler(config.getURIWrongLocation(), null, null); } @Test(expected = OctopusException.class) public void test02b_newScheduler() throws Exception { jobs.newScheduler(config.getURIWrongPath(), null, null); } @Test public void test03_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), null); jobs.close(s); } @Test public void test04a_newScheduler() throws Exception { if (config.supportsCredentials()) { try { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getInvalidCredential(credentials), null); jobs.close(s); throw new Exception("newScheduler did NOT throw InvalidCredentialsException"); } catch (InvalidCredentialsException e) { // expected } catch (OctopusException e) { // allowed } } } @Test public void test04b_newScheduler() throws Exception { if (!config.supportsCredentials()) { try { Credential c = new Credential() { @Override public Map<String, String> getProperties() { return null; } @Override public String getAdaptorName() { return "local"; } }; Scheduler s = jobs.newScheduler(config.getCorrectURI(), c, null); jobs.close(s); throw new Exception("newScheduler did NOT throw OctopusException"); } catch (OctopusException e) { // expected } } } @Test public void test04c_newScheduler() throws Exception { if (config.supportsCredentials()) { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getPasswordCredential(credentials), config.getDefaultProperties()); jobs.close(s); } } @Test public void test05_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), new HashMap<String, String>()); jobs.close(s); } @Test public void test06_newScheduler() throws Exception { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), config.getDefaultProperties()); jobs.close(s); } @Test public void test07_newScheduler() throws Exception { if (config.supportsProperties()) { Map<String, String>[] tmp = config.getInvalidProperties(); for (Map<String, String> p : tmp) { try { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), p); jobs.close(s); throw new Exception("newScheduler did NOT throw InvalidPropertyException"); } catch (InvalidPropertyException e) { // expected } } } } @Test public void test08_newScheduler() throws Exception { if (config.supportsProperties()) { try { Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), config.getUnknownProperties()); jobs.close(s); throw new Exception("newScheduler did NOT throw UnknownPropertyException"); } catch (UnknownPropertyException e) { // expected } } } @Test public void test09_newScheduler() throws Exception { if (!config.supportsProperties()) { try { Map<String, String> p = new HashMap<>(); p.put("aap", "noot"); Scheduler s = jobs.newScheduler(config.getCorrectURI(), config.getDefaultCredential(credentials), p); jobs.close(s); throw new Exception("newScheduler did NOT throw OctopusException"); } catch (OctopusException e) { // expected } } } @Test public void test10_getLocalScheduler() throws Exception { Scheduler s = null; try { s = jobs.getLocalScheduler(); assertTrue(s != null); assertTrue(s.getAdaptorName().equals("local")); } finally { if (s != null) { jobs.close(s); } } } @Test public void test11_open_close() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); assertTrue(jobs.isOpen(s)); jobs.close(s); assertFalse(jobs.isOpen(s)); } } @Test public void test12_open_close() throws Exception { if (!config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); assertTrue(jobs.isOpen(s)); jobs.close(s); assertTrue(jobs.isOpen(s)); } } @Test public void test13_open_close() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.close(s); throw new Exception("close did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test14a_getJobs() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getJobs(s, s.getQueueNames()); jobs.close(s); } @Test public void test14b_getJobs() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getJobs(s); jobs.close(s); } @Test public void test15_getJobs() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); try { jobs.getJobs(s, config.getInvalidQueueName()); throw new Exception("getJobs did NOT throw NoSuchQueueException"); } catch (NoSuchQueueException e) { // expected } finally { jobs.close(s); } } @Test public void test16_getJobs() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.getJobs(s, s.getQueueNames()); throw new Exception("close did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test17_getQueueStatus() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getQueueStatus(s, s.getQueueNames()[0]); jobs.close(s); } @Test(expected = NoSuchQueueException.class) public void test18a_getQueueStatus() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); try { jobs.getQueueStatus(s, config.getInvalidQueueName()); } finally { jobs.close(s); } } @Test public void test18b_getQueueStatus() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); String queueName = config.getDefaultQueueName(); try { jobs.getQueueStatus(s, queueName); } finally { jobs.close(s); } } @Test(expected = NullPointerException.class) public void test19_getQueueStatus() throws Exception { jobs.getQueueStatus(null, null); } @Test public void test20_getQueueStatus() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.getQueueStatus(s, s.getQueueNames()[0]); throw new Exception("getQueueStatus did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test21a_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); QueueStatus[] tmp = jobs.getQueueStatuses(s, s.getQueueNames()); jobs.close(s); String[] names = s.getQueueNames(); assertTrue(tmp != null); assertTrue(tmp.length == names.length); for (int i = 0; i < tmp.length; i++) { assertTrue(tmp[i].getQueueName().equals(names[i])); } } @Test public void test21b_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); QueueStatus[] tmp = jobs.getQueueStatuses(s); jobs.close(s); String[] names = s.getQueueNames(); assertTrue(tmp != null); assertTrue(tmp.length == names.length); for (int i = 0; i < tmp.length; i++) { assertTrue(tmp[i].getQueueName().equals(names[i])); } } @Test public void test22a_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); try { QueueStatus[] tmp = jobs.getQueueStatuses(s, config.getInvalidQueueName()); assertTrue(tmp != null); assertTrue(tmp.length == 1); assertTrue(tmp[0].hasException()); assertTrue(tmp[0].getException() instanceof NoSuchQueueException); } finally { jobs.close(s); } } @Test(expected = NullPointerException.class) public void test22b_getQueueStatuses() throws Exception { jobs.getQueueStatuses(null, config.getDefaultQueueName()); } @Test(expected = IllegalArgumentException.class) public void test22c_getQueueStatuses() throws Exception { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.getQueueStatuses(s, (String[]) null); } @Test(expected = NullPointerException.class) public void test23_getQueueStatuses() throws Exception { jobs.getQueueStatuses(null); } @Test public void test24_getQueueStatuses() throws Exception { if (config.supportsClose()) { Scheduler s = config.getDefaultScheduler(jobs, credentials); jobs.close(s); try { jobs.getQueueStatuses(s, s.getQueueNames()); throw new Exception("getQueueStatuses did NOT throw NoSuchSchedulerException"); } catch (NoSuchSchedulerException e) { // expected } } } @Test public void test25a_getJobStatuses() throws Exception { JobStatus[] tmp = jobs.getJobStatuses(new Job[0]); assertTrue(tmp != null); assertTrue(tmp.length == 0); } @Test public void test25b_getJobStatuses() throws Exception { JobStatus[] tmp = jobs.getJobStatuses((Job[]) null); assertTrue(tmp != null); assertTrue(tmp.length == 0); } @Test public void test25c_getJobStatuses() throws Exception { JobStatus[] tmp = jobs.getJobStatuses(new Job[1]); assertTrue(tmp != null); assertTrue(tmp.length == 1); assertTrue(tmp[0] == null); } protected String readFully(InputStream in) throws IOException { byte[] buffer = new byte[1024]; int offset = 0; int tmp = in.read(buffer, 0, buffer.length - offset); while (tmp != -1) { offset += tmp; if (offset == buffer.length) { buffer = Arrays.copyOf(buffer, buffer.length * 2); } tmp = in.read(buffer, offset, buffer.length - offset); } in.close(); return new String(buffer, 0, offset); } protected void writeFully(OutputStream out, String message) throws IOException { out.write(message.getBytes()); out.close(); } @org.junit.Test public void test30_interactiveJobSubmit() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); if (scheduler.isOnline()) { String message = "Hello World! test30"; JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setArguments("-n", message); description.setInteractive(true); System.err.println("Submitting interactive job to " + scheduler.getUri()); Job job = jobs.submitJob(scheduler, description); System.err.println("Interactive job submitted to " + scheduler.getUri()); Streams streams = jobs.getStreams(job); streams.getStdin().close(); String out = readFully(streams.getStdout()); String err = readFully(streams.getStderr()); // NOTE: Job should already be done here! JobStatus status = jobs.waitUntilDone(job, 5000); if (!status.isDone()) { throw new Exception("Job exceeded dealine!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } assertTrue(out.equals(message)); assertTrue(err.length() == 0); } jobs.close(scheduler); } @org.junit.Test public void test31_batchJobSubmitWithPolling() throws Exception { String message = "Hello World! test31"; String workingDir = getWorkingDir("test31"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setArguments("-n", message); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); long deadline = System.currentTimeMillis() + config.getQueueWaitTime() + config.getUpdateTime(); long pollDelay = (config.getQueueWaitTime() + config.getUpdateTime()) / 10; JobStatus status = jobs.getJobStatus(job); while (!status.isDone()) { Thread.sleep(pollDelay); long now = System.currentTimeMillis(); if (now > deadline) { throw new Exception("Job exceeded deadline!"); } status = jobs.getJobStatus(job); } jobs.close(scheduler); if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } AbsolutePath out = root.resolve(new RelativePath("stdout.txt")); AbsolutePath err = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(out)); String tmperr = readFully(files.newInputStream(err)); files.delete(out); files.delete(err); files.delete(root); files.close(filesystem); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } @org.junit.Test public void test32_batchJobSubmitWithWait() throws Exception { String message = "Hello World! test32"; String workingDir = getWorkingDir("test32"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setArguments("-n", message); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilRunning(job, config.getQueueWaitTime()); if (status.isRunning()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); AbsolutePath out = root.resolve(new RelativePath("stdout.txt")); AbsolutePath err = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(out)); String tmperr = readFully(files.newInputStream(err)); files.delete(out); files.delete(err); files.delete(root); files.close(filesystem); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } private void submitToQueueWithPolling(String testName, String queueName, int jobCount) throws Exception { System.err.println("STARTING TEST submitToQueueWithPolling(" + testName + ", " + queueName + ", " + jobCount); String workingDir = getWorkingDir(testName); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath[] out = new AbsolutePath[jobCount]; AbsolutePath[] err = new AbsolutePath[jobCount]; Jobs jobs = octopus.jobs(); Job[] j = new Job[jobCount]; for (int i = 0; i < j.length; i++) { out[i] = root.resolve(new RelativePath("stdout" + i + ".txt")); err[i] = root.resolve(new RelativePath("stderr" + i + ".txt")); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setWorkingDirectory(workingDir); description.setQueueName(queueName); description.setInteractive(false); description.setStdin(null); description.setStdout("stdout" + i + ".txt"); description.setStderr("stderr" + i + ".txt"); j[i] = jobs.submitJob(scheduler, description); } // Bit hard to determine realistic deadline here ? long deadline = System.currentTimeMillis() + config.getQueueWaitTime() + (jobCount * config.getUpdateTime()); boolean done = false; while (!done) { JobStatus[] status = jobs.getJobStatuses(j); int count = 0; for (int i = 0; i < j.length; i++) { if (j[i] != null) { if (status[i].isDone()) { if (status[i].hasException()) { System.err.println("Job " + i + " failed!"); throw new Exception("Job " + i + " failed", status[i].getException()); } System.err.println("Job " + i + " done."); j[i] = null; } else { count++; } } } if (count == 0) { done = true; } else { Thread.sleep(1000); long now = System.currentTimeMillis(); if (now > deadline) { throw new Exception("Job exceeded deadline!"); } } } for (int i = 0; i < j.length; i++) { String tmpout = readFully(files.newInputStream(out[i])); String tmperr = readFully(files.newInputStream(err[i])); assertTrue(tmpout != null); assertTrue(tmpout.length() == 0); assertTrue(tmperr != null); assertTrue(tmperr.length() == 0); files.delete(out[i]); files.delete(err[i]); } jobs.close(scheduler); files.delete(root); files.close(filesystem); } @org.junit.Test public void test33a_testMultiBatchJobSubmitWithPolling() throws Exception { for (String queue : config.getQueueNames()) { submitToQueueWithPolling("test33a_" + queue, queue, 1); } } @org.junit.Test public void test33b_testMultiBatchJobSubmitWithPolling() throws Exception { System.err.println("STARTING TEST test33b"); for (String queue : config.getQueueNames()) { submitToQueueWithPolling("test33b_" + queue, queue, 10); } } @org.junit.Test public void test34_batchJobSubmitWithKill() throws Exception { String workingDir = getWorkingDir("test34"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("60"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); // We immediately kill the job. Hopefully it isn't running yet! Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.cancelJob(job); // Wait until the job is killed. We assume it takes less than a minute! if (!status.isDone()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Failed to kill job! Expected status done, but job status is " + status); } jobs.close(scheduler); AbsolutePath out = root.resolve(new RelativePath(description.getStdout())); AbsolutePath err = root.resolve(new RelativePath(description.getStderr())); if (files.exists(out)) { files.delete(out); } if (files.exists(err)) { files.delete(err); } files.delete(root); files.close(filesystem); assertTrue(status.hasException()); Exception e = status.getException(); if (!(e instanceof JobCanceledException)) { throw new Exception("test34 expected JobCanceledException, not " + e.getMessage(), e); } } @org.junit.Test public void test35_batchJobSubmitWithKill2() throws Exception { String workingDir = getWorkingDir("test35"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("60"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin(null); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); // Wait for job to run before killing it! JobStatus status = jobs.waitUntilRunning(job, config.getQueueWaitTime()); if (!status.isRunning()) { throw new Exception("Job failed to start! Expected status running, but job status is " + status); } status = jobs.cancelJob(job); // Wait until the job is killed. We assume it takes less than a minute! if (!status.isDone()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Failed to kill job! Expected status done, but job status is " + status); } jobs.close(scheduler); AbsolutePath out = root.resolve(new RelativePath(description.getStdout())); AbsolutePath err = root.resolve(new RelativePath(description.getStderr())); if (files.exists(out)) { files.delete(out); } if (files.exists(err)) { files.delete(err); } files.delete(root); files.close(filesystem); assertTrue(status.hasException()); Exception e = status.getException(); assertTrue(e instanceof JobCanceledException); } @org.junit.Test public void test36a_batchJobSubmitWithInput() throws Exception { String message = "Hello World! test36a"; String workingDir = getWorkingDir("test36a"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath stdin = root.resolve(new RelativePath("stdin.txt")); OutputStream out = files.newOutputStream(stdin, OpenOption.CREATE, OpenOption.APPEND, OpenOption.WRITE); writeFully(out, message); JobDescription description = new JobDescription(); description.setExecutable("/bin/cat"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin("stdin.txt"); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, config.getQueueWaitTime() + config.getUpdateTime()); if (!status.isDone()) { throw new Exception("Job exceeded deadline! status = " + status); } if (status.hasException()) { throw new Exception("Job failed! exception is = ", status.getException()); } jobs.close(scheduler); AbsolutePath stdout = root.resolve(new RelativePath("stdout.txt")); AbsolutePath stderr = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(stdout)); String tmperr = readFully(files.newInputStream(stderr)); files.delete(stdin); files.delete(stdout); files.delete(stderr); files.delete(root); files.close(filesystem); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } @org.junit.Test public void test36b_batchJobSubmitWithInput() throws Exception { String message = "Hello World! test36b"; String workingDir = getWorkingDir("test36b"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath stdin = root.resolve(new RelativePath("stdin.txt")); OutputStream out = files.newOutputStream(stdin, OpenOption.CREATE, OpenOption.APPEND, OpenOption.WRITE); writeFully(out, message); JobDescription description = new JobDescription(); description.setExecutable("/bin/cat"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdin("stdin.txt"); description.setStdout("stdout.txt"); description.setStderr("stderr.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilRunning(job, config.getQueueWaitTime()); if (status.isRunning()) { status = jobs.waitUntilDone(job, config.getUpdateTime()); } if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); AbsolutePath stdout = root.resolve(new RelativePath("stdout.txt")); AbsolutePath stderr = root.resolve(new RelativePath("stderr.txt")); String tmpout = readFully(files.newInputStream(stdout)); String tmperr = readFully(files.newInputStream(stderr)); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); files.delete(stdin); files.delete(stdout); files.delete(stderr); files.delete(root); files.close(filesystem); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); } @org.junit.Test public void test37a_batchJobSubmitWithoutWorkDir() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setWorkingDirectory(null); description.setStdout(null); description.setStderr(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); } @org.junit.Test public void test37b_batchJobSubmitWithRelativeWorkDir() throws Exception { String workingDir = getWorkingDir("test37b"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setStdout(null); description.setStderr(null); //relative working dir name used description.setWorkingDirectory(workingDir); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } files.delete(root); jobs.close(scheduler); files.close(filesystem); } @org.junit.Test public void test37c_batchJobSubmitWithAbsoluteWorkDir() throws Exception { String workingDir = getWorkingDir("test37c"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setStdout(null); description.setStderr(null); //absolute working dir name used description.setWorkingDirectory(root.getPath()); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } files.delete(root); jobs.close(scheduler); files.close(filesystem); } @org.junit.Test public void test37d_batchJobSubmitWithIncorrectWorkingDir() throws Exception { //note that we are _not_ creating this directory, making it invalid String workingDir = getWorkingDir("test37d"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setStdout(null); description.setStderr(null); //incorrect working dir used description.setWorkingDirectory(workingDir); //submitting this job will either: // 1) throw an InvalidJobDescription when we submit the job // 2) produce an error when the job is run. Job job = null; try { job = jobs.submitJob(scheduler, description); } catch (InvalidJobDescriptionException e) { //Submit failed, as expected (1) jobs.close(scheduler); return; } JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { fail("Job exceeded deadline! Expected status done, got " + status); } //option (2) assertTrue(status.hasException()); jobs.close(scheduler); } //@org.junit.Test public void test38_multipleBatchJobSubmitWithInput() throws Exception { String message = "Hello World! test38"; String workingDir = getWorkingDir("test38"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); AbsolutePath stdin = root.resolve(new RelativePath("stdin.txt")); OutputStream out = files.newOutputStream(stdin, OpenOption.CREATE, OpenOption.APPEND, OpenOption.WRITE); writeFully(out, message); JobDescription description = new JobDescription(); description.setExecutable("/bin/cat"); description.setInteractive(false); description.setProcessesPerNode(2); description.setWorkingDirectory(workingDir); description.setStdin("stdin.txt"); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } for (int i = 0; i < 2; i++) { AbsolutePath stdoutTmp = root.resolve(new RelativePath("stdout.txt." + i)); AbsolutePath stderrTmp = root.resolve(new RelativePath("stderr.txt." + i)); String tmpout = readFully(files.newInputStream(stdoutTmp)); String tmperr = readFully(files.newInputStream(stderrTmp)); System.err.println("STDOUT: " + tmpout); System.err.println("STDERR: " + tmperr); assertTrue(tmpout != null); assertTrue(tmpout.length() > 0); assertTrue(tmpout.equals(message)); assertTrue(tmperr.length() == 0); files.delete(stdoutTmp); files.delete(stderrTmp); } files.delete(stdin); files.delete(root); jobs.close(scheduler); files.close(filesystem); } @org.junit.Test public void test39_multipleBatchJobSubmitWithExceptions() throws Exception { // NOTE: This test assumes that an exception is thrown when the status of a job is requested twice after the job is done! // This may not be true for all schedulers. if (config.supportsStatusAfterDone()) { return; } Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setWorkingDirectory(null); Job[] j = new Job[2]; j[0] = jobs.submitJob(scheduler, description); description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("2"); description.setInteractive(false); description.setWorkingDirectory(null); j[1] = jobs.submitJob(scheduler, description); long now = System.currentTimeMillis(); long deadline = now + 10000; JobStatus[] s = null; while (now < deadline) { s = jobs.getJobStatuses(j); if (s[0].hasException() && s[1].hasException()) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { // ignored } now = System.currentTimeMillis(); } if (s == null || !(s[0].hasException() && s[1].hasException())) { throw new Exception("Job exceeded deadline!"); } jobs.close(scheduler); } @org.junit.Test public void test40_batchJobSubmitWithExitcode() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/sleep"); description.setArguments("1"); description.setInteractive(false); description.setWorkingDirectory(null); description.setStderr(null); description.setStdout(null); description.setStdin(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); assertTrue(status.getExitCode() == 0); } @org.junit.Test public void test40_batchJobSubmitWithNoneZeroExitcode() throws Exception { Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); //run an ls with a non existing file. This should make ls return exitcode 2 JobDescription description = new JobDescription(); description.setExecutable("/bin/ls"); description.setArguments("non.existing.file"); description.setInteractive(false); description.setWorkingDirectory(null); description.setStderr(null); description.setStdout(null); description.setStdin(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } jobs.close(scheduler); assertTrue(status.getExitCode() == 2); } @org.junit.Test public void test41_batchJobSubmitWithEnvironmentVariable() throws Exception { if (!config.supportsEnvironmentVariables()) { return; } String workingDir = getWorkingDir("test41"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); //echo the given variable, to see if the va JobDescription description = new JobDescription(); description.setExecutable("/usr/bin/printenv"); description.setArguments("SOME_VARIABLE"); description.setInteractive(false); description.addEnvironment("SOME_VARIABLE", "some_value"); description.setWorkingDirectory(workingDir); description.setStderr(null); description.setStdout("stdout.txt"); description.setStdin(null); Job job = jobs.submitJob(scheduler, description); JobStatus status = jobs.waitUntilDone(job, 60000); if (!status.isDone()) { throw new Exception("Job exceeded deadline!"); } if (status.hasException()) { throw new Exception("Job failed!", status.getException()); } AbsolutePath stdout = root.resolve(new RelativePath("stdout.txt")); String stdoutContent = readFully(files.newInputStream(stdout)); assertTrue(stdoutContent.equals("some_value\n")); files.delete(stdout); files.delete(root); files.close(filesystem); } @org.junit.Test public void test41b_batchJobSubmitWithEnvironmentVariable() throws Exception { if (config.supportsEnvironmentVariables()) { return; } Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); // echo the given variable, to see if the va JobDescription description = new JobDescription(); description.setExecutable("/usr/bin/printenv"); description.setArguments("SOME_VARIABLE"); description.setInteractive(false); description.getEnvironment().put("SOME_VARIABLE", "some_value"); description.setWorkingDirectory(null); description.setStderr(null); description.setStdin(null); boolean gotException = false; try { Job job = jobs.submitJob(scheduler, description); jobs.waitUntilDone(job, config.getUpdateTime()); } catch (UnsupportedJobDescriptionException e) { gotException = true; } jobs.close(scheduler); if (!gotException) { throw new Exception("Submit did not throw exception, which was expected!"); } } @Test public void test42a_batchJob_parallel_Exception() throws Exception { if (config.supportsParallelJobs()) { return; } Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); JobDescription description = new JobDescription(); description.setExecutable("/bin/echo"); description.setNodeCount(2); description.setProcessesPerNode(2); boolean gotException = false; try { jobs.submitJob(scheduler, description); } catch (InvalidJobDescriptionException e) { gotException = true; } finally { jobs.close(scheduler); } if (!gotException) { throw new Exception("Submit did not throw exception, which was expected!"); } } @org.junit.Test public void test43_submit_JobDescriptionShouldBeCopied_Success() throws Exception { String workingDir = getWorkingDir("test43"); Scheduler scheduler = config.getDefaultScheduler(jobs, credentials); FileSystem filesystem = config.getDefaultFileSystem(files, credentials); AbsolutePath root = filesystem.getEntryPath().resolve(new RelativePath(workingDir)); files.createDirectories(root); JobDescription description = new JobDescription(); description.setExecutable("non-existing-executable"); description.setInteractive(false); description.setWorkingDirectory(workingDir); description.setStdout("stdout.txt"); Job job = jobs.submitJob(scheduler, description); description.setStdout("aap.txt"); JobDescription original = job.getJobDescription(); assertEquals("Job description should have been copied!", "stdout.txt", original.getStdout()); JobStatus status = jobs.cancelJob(job); if (!status.isDone()) { jobs.waitUntilDone(job, 60000); } AbsolutePath out = root.resolve(new RelativePath("stdout.txt")); if (files.exists(out)) { files.delete(out); } files.delete(root); files.close(filesystem); } }
Fixed bug in test
test/src/nl/esciencecenter/octopus/adaptors/GenericJobAdaptorTestParent.java
Fixed bug in test
<ide><path>est/src/nl/esciencecenter/octopus/adaptors/GenericJobAdaptorTestParent.java <ide> description.setExecutable("/usr/bin/printenv"); <ide> description.setArguments("SOME_VARIABLE"); <ide> description.setInteractive(false); <del> <del> description.getEnvironment().put("SOME_VARIABLE", "some_value"); <add> description.addEnvironment("SOME_VARIABLE", "some_value"); <ide> <ide> description.setWorkingDirectory(null); <ide> description.setStderr(null);
Java
apache-2.0
b4ae3fdc704cb8ee2e6477602bee808b862d0067
0
lburgazzoli/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,lburgazzoli/logging-log4j2,GFriedrich/logging-log4j2,lburgazzoli/apache-logging-log4j2,lqbweb/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,codescale/logging-log4j2,lburgazzoli/logging-log4j2,xnslong/logging-log4j2,lqbweb/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2
/* * 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.logging.log4j.spi; import java.io.Serializable; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.MessageFactory; import org.apache.logging.log4j.message.ParameterizedMessageFactory; import org.apache.logging.log4j.message.StringFormattedMessage; import org.apache.logging.log4j.status.StatusLogger; import org.apache.logging.log4j.util.LambdaUtil; import org.apache.logging.log4j.util.MessageSupplier; import org.apache.logging.log4j.util.Strings; import org.apache.logging.log4j.util.Supplier; /** * Base implementation of a Logger. It is highly recommended that any Logger implementation extend this class. */ public abstract class AbstractLogger implements ExtendedLogger, Serializable { /** * Marker for flow tracing. */ public static final Marker FLOW_MARKER = MarkerManager.getMarker("FLOW"); /** * Marker for method entry tracing. */ public static final Marker ENTRY_MARKER = MarkerManager.getMarker("ENTRY").setParents(FLOW_MARKER); /** * Marker for method exit tracing. */ public static final Marker EXIT_MARKER = MarkerManager.getMarker("EXIT").setParents(FLOW_MARKER); /** * Marker for exception tracing. */ public static final Marker EXCEPTION_MARKER = MarkerManager.getMarker("EXCEPTION"); /** * Marker for throwing exceptions. */ public static final Marker THROWING_MARKER = MarkerManager.getMarker("THROWING").setParents(EXCEPTION_MARKER); /** * Marker for catching exceptions. */ public static final Marker CATCHING_MARKER = MarkerManager.getMarker("CATCHING").setParents(EXCEPTION_MARKER); /** * The default MessageFactory class. */ public static final Class<? extends MessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class; private static final long serialVersionUID = 2L; private static final String FQCN = AbstractLogger.class.getName(); private static final String THROWING = "throwing"; private static final String CATCHING = "catching"; private final String name; private final MessageFactory messageFactory; /** * Creates a new logger named after this class (or subclass). */ public AbstractLogger() { this.name = getClass().getName(); this.messageFactory = createDefaultMessageFactory(); } /** * Creates a new named logger. * * @param name the logger name */ public AbstractLogger(final String name) { this.name = name; this.messageFactory = createDefaultMessageFactory(); } /** * Creates a new named logger with a particular {@link MessageFactory}. * * @param name the logger name * @param messageFactory the message factory, if null then use the default message factory. */ public AbstractLogger(final String name, final MessageFactory messageFactory) { this.name = name; this.messageFactory = messageFactory == null ? createDefaultMessageFactory() : messageFactory; } /** * Checks that the message factory a logger was created with is the same as the given messageFactory. If they are * different log a warning to the {@linkplain StatusLogger}. A null MessageFactory translates to the default * MessageFactory {@link #DEFAULT_MESSAGE_FACTORY_CLASS}. * * @param logger The logger to check * @param messageFactory The message factory to check. */ public static void checkMessageFactory(final ExtendedLogger logger, final MessageFactory messageFactory) { final String name = logger.getName(); final MessageFactory loggerMessageFactory = logger.getMessageFactory(); if (messageFactory != null && !loggerMessageFactory.equals(messageFactory)) { StatusLogger.getLogger().warn( "The Logger {} was created with the message factory {} and is now requested with the " + "message factory {}, which may create log events with unexpected formatting.", name, loggerMessageFactory, messageFactory); } else if (messageFactory == null && !loggerMessageFactory.getClass().equals(DEFAULT_MESSAGE_FACTORY_CLASS)) { StatusLogger .getLogger() .warn("The Logger {} was created with the message factory {} and is now requested with a null " + "message factory (defaults to {}), which may create log events with unexpected " + "formatting.", name, loggerMessageFactory, DEFAULT_MESSAGE_FACTORY_CLASS.getName()); } } @Override public void catching(final Level level, final Throwable t) { catching(FQCN, level, t); } /** * Logs a Throwable that has been caught with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param level The logging level. * @param t The Throwable. */ protected void catching(final String fqcn, final Level level, final Throwable t) { if (isEnabled(level, CATCHING_MARKER, (Object) null, null)) { logMessage(fqcn, level, CATCHING_MARKER, catchingMsg(t), t); } } @Override public void catching(final Throwable t) { if (isEnabled(Level.ERROR, CATCHING_MARKER, (Object) null, null)) { logMessage(FQCN, Level.ERROR, CATCHING_MARKER, catchingMsg(t), t); } } protected Message catchingMsg(final Throwable t) { return messageFactory.newMessage(CATCHING); } private MessageFactory createDefaultMessageFactory() { try { return DEFAULT_MESSAGE_FACTORY_CLASS.newInstance(); } catch (final InstantiationException e) { throw new IllegalStateException(e); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public void debug(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.DEBUG, marker, msg, null); } @Override public void debug(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, msg, t); } @Override public void debug(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.DEBUG, marker, message, null); } @Override public void debug(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, message, t); } @Override public void debug(final Marker marker, final String message) { logIfEnabled(FQCN, Level.DEBUG, marker, message, (Throwable) null); } @Override public void debug(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.DEBUG, marker, message, params); } @Override public void debug(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, message, t); } @Override public void debug(final Message msg) { logIfEnabled(FQCN, Level.DEBUG, null, msg, null); } @Override public void debug(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, msg, t); } @Override public void debug(final Object message) { logIfEnabled(FQCN, Level.DEBUG, null, message, null); } @Override public void debug(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, message, t); } @Override public void debug(final String message) { logIfEnabled(FQCN, Level.DEBUG, null, message, (Throwable) null); } @Override public void debug(final String message, final Object... params) { logIfEnabled(FQCN, Level.DEBUG, null, message, params); } @Override public void debug(final String message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, message, t); } @Override public void debug(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, (Throwable) null); } @Override public void debug(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, t); } @Override public void debug(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, (Throwable) null); } @Override public void debug(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.DEBUG, marker, message, paramSuppliers); } @Override public void debug(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, t); } @Override public void debug(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.DEBUG, null, message, paramSuppliers); } @Override public void debug(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, (Throwable) null); } @Override public void debug(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, t); } @Override public void debug(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, (Throwable) null); } @Override public void debug(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, t); } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param format Format String for the parameters. * @param paramSuppliers The Suppliers of the parameters. */ protected void enter(final String fqcn, final String format, final Supplier<?>... paramSuppliers) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(format, paramSuppliers.length, paramSuppliers), null); } } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param format The format String for the parameters. * @param params The parameters to the method. */ protected void enter(final String fqcn, final String format, final Object... params) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(format, params.length, params), null); } } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param msgSupplier The Supplier of the Message. */ protected void enter(final String fqcn, final MessageSupplier msgSupplier) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, new EntryMessage(msgSupplier.get()), null); } } @Override public void entry() { entry(FQCN, (Object[]) null); } @Override public void entry(final Object... params) { entry(FQCN, params); } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param params The parameters to the method. */ protected void entry(final String fqcn, final Object... params) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { if (params == null) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(null, 0, null), null); } else { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(null, params.length, params), null); } } } protected Message entryMsg(final String format, final int count, final Object... params) { if (count == 0) { if (Strings.isEmpty(format)) { return messageFactory.newMessage("entry"); } return messageFactory.newMessage("entry: " + format); } final StringBuilder sb = new StringBuilder("entry"); if (format != null) { sb.append(": ").append(format); return messageFactory.newMessage(sb.toString(), params); } sb.append(" params("); for (int i = 0; i < params.length; i++) { Object parm = params[i]; sb.append(parm != null ? parm.toString() : "null"); if (i + 1 < params.length) { sb.append(", "); } } sb.append(')'); return messageFactory.newMessage(sb.toString()); } protected Message entryMsg(final String format, final int count, final Supplier<?>... paramSuppliers) { Object[] params = new Object[count]; for (int i = 0; i < count; i++) { params[i] = paramSuppliers[i].get(); } return entryMsg(format, count, params); } @Override public void error(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.ERROR, marker, msg, null); } @Override public void error(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, msg, t); } @Override public void error(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.ERROR, marker, message, null); } @Override public void error(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, message, t); } @Override public void error(final Marker marker, final String message) { logIfEnabled(FQCN, Level.ERROR, marker, message, (Throwable) null); } @Override public void error(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.ERROR, marker, message, params); } @Override public void error(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, message, t); } @Override public void error(final Message msg) { logIfEnabled(FQCN, Level.ERROR, null, msg, null); } @Override public void error(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, msg, t); } @Override public void error(final Object message) { logIfEnabled(FQCN, Level.ERROR, null, message, null); } @Override public void error(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, message, t); } @Override public void error(final String message) { logIfEnabled(FQCN, Level.ERROR, null, message, (Throwable) null); } @Override public void error(final String message, final Object... params) { logIfEnabled(FQCN, Level.ERROR, null, message, params); } @Override public void error(final String message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, message, t); } @Override public void error(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, (Throwable) null); } @Override public void error(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, t); } @Override public void error(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, (Throwable) null); } @Override public void error(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.ERROR, marker, message, paramSuppliers); } @Override public void error(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, t); } @Override public void error(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.ERROR, null, message, paramSuppliers); } @Override public void error(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, (Throwable) null); } @Override public void error(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, t); } @Override public void error(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, (Throwable) null); } @Override public void error(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, t); } @Override public void exit() { exit(FQCN, (Object) null); } @Override public <R> R exit(final R result) { return exit(FQCN, result); } /** * Logs exiting from a method with the result and location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param <R> The type of the parameter and object being returned. * @param result The result being returned from the method call. * @return the return value passed to this method. */ protected <R> R exit(final String fqcn, final R result) { logIfEnabled(fqcn, Level.TRACE, EXIT_MARKER, exitMsg(null, result), null); return result; } /** * Logs exiting from a method with the result and location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param <R> The type of the parameter and object being returned. * @param result The result being returned from the method call. * @return the return value passed to this method. */ protected <R> R exit(final String fqcn, final String format, final R result) { logIfEnabled(fqcn, Level.TRACE, EXIT_MARKER, exitMsg(format, result), null); return result; } protected Message exitMsg(final String format, final Object result) { if (result == null) { if (format == null) { return messageFactory.newMessage("exit"); } return messageFactory.newMessage("exit: " + format); } else { if (format == null) { return messageFactory.newMessage("exit with(" + result + ')'); } return messageFactory.newMessage("exit: " + format, result); } } @Override public void fatal(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.FATAL, marker, msg, null); } @Override public void fatal(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, msg, t); } @Override public void fatal(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.FATAL, marker, message, null); } @Override public void fatal(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, message, t); } @Override public void fatal(final Marker marker, final String message) { logIfEnabled(FQCN, Level.FATAL, marker, message, (Throwable) null); } @Override public void fatal(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.FATAL, marker, message, params); } @Override public void fatal(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, message, t); } @Override public void fatal(final Message msg) { logIfEnabled(FQCN, Level.FATAL, null, msg, null); } @Override public void fatal(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, msg, t); } @Override public void fatal(final Object message) { logIfEnabled(FQCN, Level.FATAL, null, message, null); } @Override public void fatal(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, message, t); } @Override public void fatal(final String message) { logIfEnabled(FQCN, Level.FATAL, null, message, (Throwable) null); } @Override public void fatal(final String message, final Object... params) { logIfEnabled(FQCN, Level.FATAL, null, message, params); } @Override public void fatal(final String message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, message, t); } @Override public void fatal(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, (Throwable) null); } @Override public void fatal(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, t); } @Override public void fatal(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, (Throwable) null); } @Override public void fatal(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.FATAL, marker, message, paramSuppliers); } @Override public void fatal(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, t); } @Override public void fatal(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.FATAL, null, message, paramSuppliers); } @Override public void fatal(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, (Throwable) null); } @Override public void fatal(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, t); } @Override public void fatal(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, (Throwable) null); } @Override public void fatal(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, t); } @Override public MessageFactory getMessageFactory() { return messageFactory; } @Override public String getName() { return name; } @Override public void info(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.INFO, marker, msg, null); } @Override public void info(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, msg, t); } @Override public void info(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.INFO, marker, message, null); } @Override public void info(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, message, t); } @Override public void info(final Marker marker, final String message) { logIfEnabled(FQCN, Level.INFO, marker, message, (Throwable) null); } @Override public void info(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.INFO, marker, message, params); } @Override public void info(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, message, t); } @Override public void info(final Message msg) { logIfEnabled(FQCN, Level.INFO, null, msg, null); } @Override public void info(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, msg, t); } @Override public void info(final Object message) { logIfEnabled(FQCN, Level.INFO, null, message, null); } @Override public void info(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, message, t); } @Override public void info(final String message) { logIfEnabled(FQCN, Level.INFO, null, message, (Throwable) null); } @Override public void info(final String message, final Object... params) { logIfEnabled(FQCN, Level.INFO, null, message, params); } @Override public void info(final String message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, message, t); } @Override public void info(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, (Throwable) null); } @Override public void info(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, t); } @Override public void info(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, (Throwable) null); } @Override public void info(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.INFO, marker, message, paramSuppliers); } @Override public void info(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, t); } @Override public void info(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.INFO, null, message, paramSuppliers); } @Override public void info(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, (Throwable) null); } @Override public void info(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, t); } @Override public void info(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, (Throwable) null); } @Override public void info(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, t); } @Override public boolean isDebugEnabled() { return isEnabled(Level.DEBUG, null, null); } @Override public boolean isDebugEnabled(final Marker marker) { return isEnabled(Level.DEBUG, marker, (Object) null, null); } @Override public boolean isEnabled(final Level level) { return isEnabled(level, null, (Object) null, null); } @Override public boolean isEnabled(final Level level, final Marker marker) { return isEnabled(level, marker, (Object) null, null); } @Override public boolean isErrorEnabled() { return isEnabled(Level.ERROR, null, (Object) null, null); } @Override public boolean isErrorEnabled(final Marker marker) { return isEnabled(Level.ERROR, marker, (Object) null, null); } @Override public boolean isFatalEnabled() { return isEnabled(Level.FATAL, null, (Object) null, null); } @Override public boolean isFatalEnabled(final Marker marker) { return isEnabled(Level.FATAL, marker, (Object) null, null); } @Override public boolean isInfoEnabled() { return isEnabled(Level.INFO, null, (Object) null, null); } @Override public boolean isInfoEnabled(final Marker marker) { return isEnabled(Level.INFO, marker, (Object) null, null); } @Override public boolean isTraceEnabled() { return isEnabled(Level.TRACE, null, (Object) null, null); } @Override public boolean isTraceEnabled(final Marker marker) { return isEnabled(Level.TRACE, marker, (Object) null, null); } @Override public boolean isWarnEnabled() { return isEnabled(Level.WARN, null, (Object) null, null); } @Override public boolean isWarnEnabled(final Marker marker) { return isEnabled(Level.WARN, marker, (Object) null, null); } @Override public void log(final Level level, final Marker marker, final Message msg) { logIfEnabled(FQCN, level, marker, msg, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, level, marker, msg, t); } @Override public void log(final Level level, final Marker marker, final Object message) { logIfEnabled(FQCN, level, marker, message, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final Object message, final Throwable t) { if (isEnabled(level, marker, message, t)) { logMessage(FQCN, level, marker, message, t); } } @Override public void log(final Level level, final Marker marker, final String message) { logIfEnabled(FQCN, level, marker, message, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, level, marker, message, params); } @Override public void log(final Level level, final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, level, marker, message, t); } @Override public void log(final Level level, final Message msg) { logIfEnabled(FQCN, level, null, msg, null); } @Override public void log(final Level level, final Message msg, final Throwable t) { logIfEnabled(FQCN, level, null, msg, t); } @Override public void log(final Level level, final Object message) { logIfEnabled(FQCN, level, null, message, null); } @Override public void log(final Level level, final Object message, final Throwable t) { logIfEnabled(FQCN, level, null, message, t); } @Override public void log(final Level level, final String message) { logIfEnabled(FQCN, level, null, message, (Throwable) null); } @Override public void log(final Level level, final String message, final Object... params) { logIfEnabled(FQCN, level, null, message, params); } @Override public void log(final Level level, final String message, final Throwable t) { logIfEnabled(FQCN, level, null, message, t); } @Override public void log(final Level level, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, level, null, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, null, msgSupplier, t); } @Override public void log(final Level level, final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, level, marker, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, level, marker, message, paramSuppliers); } @Override public void log(final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, marker, msgSupplier, t); } @Override public void log(final Level level, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, level, null, message, paramSuppliers); } @Override public void log(final Level level, final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, level, marker, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, marker, msgSupplier, t); } @Override public void log(final Level level, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, level, null, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, null, msgSupplier, t); } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Message msg, final Throwable t) { if (isEnabled(level, marker, msg, t)) { logMessage(fqcn, level, marker, msg, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { if (isEnabled(level, marker, msgSupplier, t)) { logMessage(fqcn, level, marker, msgSupplier, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Object message, final Throwable t) { if (isEnabled(level, marker, message, t)) { logMessage(fqcn, level, marker, message, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { if (isEnabled(level, marker, msgSupplier, t)) { logMessage(fqcn, level, marker, msgSupplier, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message) { if (isEnabled(level, marker, message)) { logMessage(fqcn, level, marker, message); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) { if (isEnabled(level, marker, message)) { logMessage(fqcn, level, marker, message, paramSuppliers); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message, final Object... params) { if (isEnabled(level, marker, message, params)) { logMessage(fqcn, level, marker, message, params); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message, final Throwable t) { if (isEnabled(level, marker, message, t)) { logMessage(fqcn, level, marker, message, t); } } protected void logMessage(final String fqcn, final Level level, final Marker marker, final Object message, final Throwable t) { logMessage(fqcn, level, marker, messageFactory.newMessage(message), t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { final Message message = LambdaUtil.get(msgSupplier); logMessage(fqcn, level, marker, message, t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { final Object message = LambdaUtil.get(msgSupplier); logMessage(fqcn, level, marker, messageFactory.newMessage(message), t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message, final Throwable t) { logMessage(fqcn, level, marker, messageFactory.newMessage(message), t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message) { final Message msg = messageFactory.newMessage(message); logMessage(fqcn, level, marker, msg, msg.getThrowable()); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message, final Object... params) { final Message msg = messageFactory.newMessage(message, params); logMessage(fqcn, level, marker, msg, msg.getThrowable()); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) { final Message msg = messageFactory.newMessage(message, LambdaUtil.getAll(paramSuppliers)); logMessage(fqcn, level, marker, msg, msg.getThrowable()); } @Override public void printf(final Level level, final Marker marker, final String format, final Object... params) { if (isEnabled(level, marker, format, params)) { final Message msg = new StringFormattedMessage(format, params); logMessage(FQCN, level, marker, msg, msg.getThrowable()); } } @Override public void printf(final Level level, final String format, final Object... params) { if (isEnabled(level, null, format, params)) { final Message msg = new StringFormattedMessage(format, params); logMessage(FQCN, level, null, msg, msg.getThrowable()); } } @Override public <T extends Throwable> T throwing(final T t) { return throwing(FQCN, Level.ERROR, t); } @Override public <T extends Throwable> T throwing(final Level level, final T t) { return throwing(FQCN, level, t); } /** * Logs a Throwable to be thrown. * * @param <T> the type of the Throwable. * @param fqcn the fully qualified class name of this Logger implementation. * @param level The logging Level. * @param t The Throwable. * @return the Throwable. */ protected <T extends Throwable> T throwing(final String fqcn, final Level level, final T t) { if (isEnabled(level, THROWING_MARKER, (Object) null, null)) { logMessage(fqcn, level, THROWING_MARKER, throwingMsg(t), t); } return t; } protected Message throwingMsg(final Throwable t) { return messageFactory.newMessage(THROWING); } @Override public void trace(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.TRACE, marker, msg, null); } @Override public void trace(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, msg, t); } @Override public void trace(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.TRACE, marker, message, null); } @Override public void trace(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, message, t); } @Override public void trace(final Marker marker, final String message) { logIfEnabled(FQCN, Level.TRACE, marker, message, (Throwable) null); } @Override public void trace(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.TRACE, marker, message, params); } @Override public void trace(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, message, t); } @Override public void trace(final Message msg) { logIfEnabled(FQCN, Level.TRACE, null, msg, null); } @Override public void trace(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, msg, t); } @Override public void trace(final Object message) { logIfEnabled(FQCN, Level.TRACE, null, message, null); } @Override public void trace(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, message, t); } @Override public void trace(final String message) { logIfEnabled(FQCN, Level.TRACE, null, message, (Throwable) null); } @Override public void trace(final String message, final Object... params) { logIfEnabled(FQCN, Level.TRACE, null, message, params); } @Override public void trace(final String message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, message, t); } @Override public void trace(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, (Throwable) null); } @Override public void trace(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, t); } @Override public void trace(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, (Throwable) null); } @Override public void trace(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.TRACE, marker, message, paramSuppliers); } @Override public void trace(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, t); } @Override public void trace(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.TRACE, null, message, paramSuppliers); } @Override public void trace(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, (Throwable) null); } @Override public void trace(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, t); } @Override public void trace(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, (Throwable) null); } @Override public void trace(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, t); } @Override public void traceEntry() { enter(FQCN, null, (Object[]) null); } @Override public void traceEntry(final String format, final Object... params) { enter(FQCN, format, params); } @Override public void traceEntry(final Supplier<?>... paramSuppliers) { enter(FQCN, null, paramSuppliers); } @Override public void traceEntry(final String format, final Supplier<?>... paramSuppliers) { enter(FQCN, format, paramSuppliers); } @Override public void traceEntry(final Message message) { enter(FQCN, new MessageSupplier() { @Override public Message get() { return message; }}); } @Override public void traceEntry(final MessageSupplier msgSupplier) { enter(FQCN, msgSupplier); } @Override public void traceExit() { exit(FQCN, null, null); } @Override public <R> R traceExit(final R result) { return exit(FQCN, null, result); } @Override public <R> R traceExit(final String format, final R result) { return exit(FQCN, format, result); } @Override public <R> R traceExit(final R result, final MessageSupplier messageSupplier) { if (isEnabled(Level.TRACE, EXIT_MARKER, messageSupplier, null)) { logMessage(FQCN, Level.TRACE, EXIT_MARKER, new MessageSupplier() { public Message get() { return new ExitMessage(messageSupplier.get()); }; }, null); } return result; } @Override public <R> R traceExit(final R result, final Message message) { if (isEnabled(Level.TRACE, EXIT_MARKER, message, null)) { logMessage(FQCN, Level.TRACE, EXIT_MARKER, new MessageSupplier() { public Message get() { return new ExitMessage(message); }; }, null); } return result; } @Override public void warn(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.WARN, marker, msg, null); } @Override public void warn(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, msg, t); } @Override public void warn(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.WARN, marker, message, null); } @Override public void warn(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, message, t); } @Override public void warn(final Marker marker, final String message) { logIfEnabled(FQCN, Level.WARN, marker, message, (Throwable) null); } @Override public void warn(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.WARN, marker, message, params); } @Override public void warn(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, message, t); } @Override public void warn(final Message msg) { logIfEnabled(FQCN, Level.WARN, null, msg, null); } @Override public void warn(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, msg, t); } @Override public void warn(final Object message) { logIfEnabled(FQCN, Level.WARN, null, message, null); } @Override public void warn(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, message, t); } @Override public void warn(final String message) { logIfEnabled(FQCN, Level.WARN, null, message, (Throwable) null); } @Override public void warn(final String message, final Object... params) { logIfEnabled(FQCN, Level.WARN, null, message, params); } @Override public void warn(final String message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, message, t); } @Override public void warn(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, (Throwable) null); } @Override public void warn(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, t); } @Override public void warn(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, (Throwable) null); } @Override public void warn(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.WARN, marker, message, paramSuppliers); } @Override public void warn(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, t); } @Override public void warn(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.WARN, null, message, paramSuppliers); } @Override public void warn(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, (Throwable) null); } @Override public void warn(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, t); } @Override public void warn(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, (Throwable) null); } @Override public void warn(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, t); } private static class FlowMessage implements Message { private static final long serialVersionUID = 7580175170272152912L; private Message message; private final String text; FlowMessage(String text, Message message) { this.message = message; this.text = text; } @Override public String getFormattedMessage() { if (message != null) { return text + ": " + message.getFormattedMessage(); } return text; } @Override public String getFormat() { if (message != null) { return text + ": " + message.getFormat(); } return text; } @Override public Object[] getParameters() { if (message != null) { return message.getParameters(); } return null; } @Override public Throwable getThrowable() { if (message != null) { return message.getThrowable(); } return null; } } private static class EntryMessage extends FlowMessage { EntryMessage(Message message) { super("entry", message); } } private static class ExitMessage extends FlowMessage { ExitMessage(Message message) { super("exit", message); } } }
log4j-api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java
/* * 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.logging.log4j.spi; import java.io.Serializable; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.MessageFactory; import org.apache.logging.log4j.message.ParameterizedMessageFactory; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.message.StringFormattedMessage; import org.apache.logging.log4j.status.StatusLogger; import org.apache.logging.log4j.util.LambdaUtil; import org.apache.logging.log4j.util.MessageSupplier; import org.apache.logging.log4j.util.Strings; import org.apache.logging.log4j.util.Supplier; /** * Base implementation of a Logger. It is highly recommended that any Logger implementation extend this class. */ public abstract class AbstractLogger implements ExtendedLogger, Serializable { /** * Marker for flow tracing. */ public static final Marker FLOW_MARKER = MarkerManager.getMarker("FLOW"); /** * Marker for method entry tracing. */ public static final Marker ENTRY_MARKER = MarkerManager.getMarker("ENTRY").setParents(FLOW_MARKER); /** * Marker for method exit tracing. */ public static final Marker EXIT_MARKER = MarkerManager.getMarker("EXIT").setParents(FLOW_MARKER); /** * Marker for exception tracing. */ public static final Marker EXCEPTION_MARKER = MarkerManager.getMarker("EXCEPTION"); /** * Marker for throwing exceptions. */ public static final Marker THROWING_MARKER = MarkerManager.getMarker("THROWING").setParents(EXCEPTION_MARKER); /** * Marker for catching exceptions. */ public static final Marker CATCHING_MARKER = MarkerManager.getMarker("CATCHING").setParents(EXCEPTION_MARKER); /** * The default MessageFactory class. */ public static final Class<? extends MessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class; private static final long serialVersionUID = 2L; private static final String FQCN = AbstractLogger.class.getName(); private static final String THROWING = "throwing"; private static final String CATCHING = "catching"; private final String name; private final MessageFactory messageFactory; /** * Creates a new logger named after this class (or subclass). */ public AbstractLogger() { this.name = getClass().getName(); this.messageFactory = createDefaultMessageFactory(); } /** * Creates a new named logger. * * @param name the logger name */ public AbstractLogger(final String name) { this.name = name; this.messageFactory = createDefaultMessageFactory(); } /** * Creates a new named logger with a particular {@link MessageFactory}. * * @param name the logger name * @param messageFactory the message factory, if null then use the default message factory. */ public AbstractLogger(final String name, final MessageFactory messageFactory) { this.name = name; this.messageFactory = messageFactory == null ? createDefaultMessageFactory() : messageFactory; } /** * Checks that the message factory a logger was created with is the same as the given messageFactory. If they are * different log a warning to the {@linkplain StatusLogger}. A null MessageFactory translates to the default * MessageFactory {@link #DEFAULT_MESSAGE_FACTORY_CLASS}. * * @param logger The logger to check * @param messageFactory The message factory to check. */ public static void checkMessageFactory(final ExtendedLogger logger, final MessageFactory messageFactory) { final String name = logger.getName(); final MessageFactory loggerMessageFactory = logger.getMessageFactory(); if (messageFactory != null && !loggerMessageFactory.equals(messageFactory)) { StatusLogger.getLogger().warn( "The Logger {} was created with the message factory {} and is now requested with the " + "message factory {}, which may create log events with unexpected formatting.", name, loggerMessageFactory, messageFactory); } else if (messageFactory == null && !loggerMessageFactory.getClass().equals(DEFAULT_MESSAGE_FACTORY_CLASS)) { StatusLogger .getLogger() .warn("The Logger {} was created with the message factory {} and is now requested with a null " + "message factory (defaults to {}), which may create log events with unexpected " + "formatting.", name, loggerMessageFactory, DEFAULT_MESSAGE_FACTORY_CLASS.getName()); } } @Override public void catching(final Level level, final Throwable t) { catching(FQCN, level, t); } /** * Logs a Throwable that has been caught with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param level The logging level. * @param t The Throwable. */ protected void catching(final String fqcn, final Level level, final Throwable t) { if (isEnabled(level, CATCHING_MARKER, (Object) null, null)) { logMessage(fqcn, level, CATCHING_MARKER, catchingMsg(t), t); } } @Override public void catching(final Throwable t) { if (isEnabled(Level.ERROR, CATCHING_MARKER, (Object) null, null)) { logMessage(FQCN, Level.ERROR, CATCHING_MARKER, catchingMsg(t), t); } } protected Message catchingMsg(final Throwable t) { return messageFactory.newMessage(CATCHING); } private MessageFactory createDefaultMessageFactory() { try { return DEFAULT_MESSAGE_FACTORY_CLASS.newInstance(); } catch (final InstantiationException e) { throw new IllegalStateException(e); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } } @Override public void debug(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.DEBUG, marker, msg, null); } @Override public void debug(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, msg, t); } @Override public void debug(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.DEBUG, marker, message, null); } @Override public void debug(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, message, t); } @Override public void debug(final Marker marker, final String message) { logIfEnabled(FQCN, Level.DEBUG, marker, message, (Throwable) null); } @Override public void debug(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.DEBUG, marker, message, params); } @Override public void debug(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, message, t); } @Override public void debug(final Message msg) { logIfEnabled(FQCN, Level.DEBUG, null, msg, null); } @Override public void debug(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, msg, t); } @Override public void debug(final Object message) { logIfEnabled(FQCN, Level.DEBUG, null, message, null); } @Override public void debug(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, message, t); } @Override public void debug(final String message) { logIfEnabled(FQCN, Level.DEBUG, null, message, (Throwable) null); } @Override public void debug(final String message, final Object... params) { logIfEnabled(FQCN, Level.DEBUG, null, message, params); } @Override public void debug(final String message, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, message, t); } @Override public void debug(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, (Throwable) null); } @Override public void debug(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, t); } @Override public void debug(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, (Throwable) null); } @Override public void debug(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.DEBUG, marker, message, paramSuppliers); } @Override public void debug(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, t); } @Override public void debug(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.DEBUG, null, message, paramSuppliers); } @Override public void debug(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, (Throwable) null); } @Override public void debug(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, t); } @Override public void debug(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, (Throwable) null); } @Override public void debug(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, t); } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param format Format String for the parameters. * @param paramSuppliers The Suppliers of the parameters. */ protected void enter(final String fqcn, final String format, final Supplier<?>... paramSuppliers) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(format, paramSuppliers.length, paramSuppliers), null); } } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param format The format String for the parameters. * @param params The parameters to the method. */ protected void enter(final String fqcn, final String format, final Object... params) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(format, params.length, params), null); } } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param msgSupplier The Supplier of the Message. */ protected void enter(final String fqcn, final MessageSupplier msgSupplier) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, new EntryMessage(msgSupplier.get()), null); } } @Override public void entry() { entry(FQCN, (Object[]) null); } @Override public void entry(final Object... params) { entry(FQCN, params); } /** * Logs entry to a method with location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param params The parameters to the method. */ protected void entry(final String fqcn, final Object... params) { if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) { if (params == null) { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(null, 0, null), null); } else { logMessage(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(null, params.length, params), null); } } } protected Message entryMsg(final String format, final int count, final Object... params) { if (count == 0) { if (Strings.isEmpty(format)) { return messageFactory.newMessage("entry"); } return messageFactory.newMessage("entry: " + format); } final StringBuilder sb = new StringBuilder("entry"); if (format != null) { sb.append(": ").append(format); return messageFactory.newMessage(sb.toString(), params); } sb.append(" params("); for (int i = 0; i < params.length; i++) { Object parm = params[i]; sb.append(parm != null ? parm.toString() : "null"); if (i + 1 < params.length) { sb.append(", "); } } sb.append(')'); return messageFactory.newMessage(sb.toString()); } protected Message entryMsg(final String format, final int count, final Supplier<?>... paramSuppliers) { Object[] params = new Object[count]; for (int i = 0; i < count; i++) { params[i] = paramSuppliers[i].get(); } return entryMsg(format, count, params); } @Override public void error(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.ERROR, marker, msg, null); } @Override public void error(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, msg, t); } @Override public void error(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.ERROR, marker, message, null); } @Override public void error(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, message, t); } @Override public void error(final Marker marker, final String message) { logIfEnabled(FQCN, Level.ERROR, marker, message, (Throwable) null); } @Override public void error(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.ERROR, marker, message, params); } @Override public void error(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, message, t); } @Override public void error(final Message msg) { logIfEnabled(FQCN, Level.ERROR, null, msg, null); } @Override public void error(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, msg, t); } @Override public void error(final Object message) { logIfEnabled(FQCN, Level.ERROR, null, message, null); } @Override public void error(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, message, t); } @Override public void error(final String message) { logIfEnabled(FQCN, Level.ERROR, null, message, (Throwable) null); } @Override public void error(final String message, final Object... params) { logIfEnabled(FQCN, Level.ERROR, null, message, params); } @Override public void error(final String message, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, message, t); } @Override public void error(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, (Throwable) null); } @Override public void error(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, t); } @Override public void error(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, (Throwable) null); } @Override public void error(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.ERROR, marker, message, paramSuppliers); } @Override public void error(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, t); } @Override public void error(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.ERROR, null, message, paramSuppliers); } @Override public void error(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, (Throwable) null); } @Override public void error(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, t); } @Override public void error(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, (Throwable) null); } @Override public void error(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, t); } @Override public void exit() { exit(FQCN, (Object) null); } @Override public <R> R exit(final R result) { return exit(FQCN, result); } /** * Logs exiting from a method with the result and location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param <R> The type of the parameter and object being returned. * @param result The result being returned from the method call. * @return the return value passed to this method. */ protected <R> R exit(final String fqcn, final R result) { logIfEnabled(fqcn, Level.TRACE, EXIT_MARKER, exitMsg(null, result), null); return result; } /** * Logs exiting from a method with the result and location information. * * @param fqcn The fully qualified class name of the <b>caller</b>. * @param <R> The type of the parameter and object being returned. * @param result The result being returned from the method call. * @return the return value passed to this method. */ protected <R> R exit(final String fqcn, final String format, final R result) { logIfEnabled(fqcn, Level.TRACE, EXIT_MARKER, exitMsg(format, result), null); return result; } protected Message exitMsg(final String format, final Object result) { if (result == null) { if (format == null) { return messageFactory.newMessage("exit"); } return messageFactory.newMessage("exit: " + format); } else { if (format == null) { return messageFactory.newMessage("exit with(" + result + ')'); } return messageFactory.newMessage("exit: " + format, result); } } @Override public void fatal(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.FATAL, marker, msg, null); } @Override public void fatal(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, msg, t); } @Override public void fatal(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.FATAL, marker, message, null); } @Override public void fatal(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, message, t); } @Override public void fatal(final Marker marker, final String message) { logIfEnabled(FQCN, Level.FATAL, marker, message, (Throwable) null); } @Override public void fatal(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.FATAL, marker, message, params); } @Override public void fatal(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, message, t); } @Override public void fatal(final Message msg) { logIfEnabled(FQCN, Level.FATAL, null, msg, null); } @Override public void fatal(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, msg, t); } @Override public void fatal(final Object message) { logIfEnabled(FQCN, Level.FATAL, null, message, null); } @Override public void fatal(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, message, t); } @Override public void fatal(final String message) { logIfEnabled(FQCN, Level.FATAL, null, message, (Throwable) null); } @Override public void fatal(final String message, final Object... params) { logIfEnabled(FQCN, Level.FATAL, null, message, params); } @Override public void fatal(final String message, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, message, t); } @Override public void fatal(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, (Throwable) null); } @Override public void fatal(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, t); } @Override public void fatal(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, (Throwable) null); } @Override public void fatal(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.FATAL, marker, message, paramSuppliers); } @Override public void fatal(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, t); } @Override public void fatal(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.FATAL, null, message, paramSuppliers); } @Override public void fatal(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, (Throwable) null); } @Override public void fatal(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, t); } @Override public void fatal(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, (Throwable) null); } @Override public void fatal(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, t); } @Override public MessageFactory getMessageFactory() { return messageFactory; } @Override public String getName() { return name; } @Override public void info(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.INFO, marker, msg, null); } @Override public void info(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, msg, t); } @Override public void info(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.INFO, marker, message, null); } @Override public void info(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, message, t); } @Override public void info(final Marker marker, final String message) { logIfEnabled(FQCN, Level.INFO, marker, message, (Throwable) null); } @Override public void info(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.INFO, marker, message, params); } @Override public void info(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, message, t); } @Override public void info(final Message msg) { logIfEnabled(FQCN, Level.INFO, null, msg, null); } @Override public void info(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, msg, t); } @Override public void info(final Object message) { logIfEnabled(FQCN, Level.INFO, null, message, null); } @Override public void info(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, message, t); } @Override public void info(final String message) { logIfEnabled(FQCN, Level.INFO, null, message, (Throwable) null); } @Override public void info(final String message, final Object... params) { logIfEnabled(FQCN, Level.INFO, null, message, params); } @Override public void info(final String message, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, message, t); } @Override public void info(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, (Throwable) null); } @Override public void info(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, t); } @Override public void info(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, (Throwable) null); } @Override public void info(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.INFO, marker, message, paramSuppliers); } @Override public void info(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, t); } @Override public void info(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.INFO, null, message, paramSuppliers); } @Override public void info(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, (Throwable) null); } @Override public void info(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, t); } @Override public void info(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, (Throwable) null); } @Override public void info(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.INFO, null, msgSupplier, t); } @Override public boolean isDebugEnabled() { return isEnabled(Level.DEBUG, null, null); } @Override public boolean isDebugEnabled(final Marker marker) { return isEnabled(Level.DEBUG, marker, (Object) null, null); } @Override public boolean isEnabled(final Level level) { return isEnabled(level, null, (Object) null, null); } @Override public boolean isEnabled(final Level level, final Marker marker) { return isEnabled(level, marker, (Object) null, null); } @Override public boolean isErrorEnabled() { return isEnabled(Level.ERROR, null, (Object) null, null); } @Override public boolean isErrorEnabled(final Marker marker) { return isEnabled(Level.ERROR, marker, (Object) null, null); } @Override public boolean isFatalEnabled() { return isEnabled(Level.FATAL, null, (Object) null, null); } @Override public boolean isFatalEnabled(final Marker marker) { return isEnabled(Level.FATAL, marker, (Object) null, null); } @Override public boolean isInfoEnabled() { return isEnabled(Level.INFO, null, (Object) null, null); } @Override public boolean isInfoEnabled(final Marker marker) { return isEnabled(Level.INFO, marker, (Object) null, null); } @Override public boolean isTraceEnabled() { return isEnabled(Level.TRACE, null, (Object) null, null); } @Override public boolean isTraceEnabled(final Marker marker) { return isEnabled(Level.TRACE, marker, (Object) null, null); } @Override public boolean isWarnEnabled() { return isEnabled(Level.WARN, null, (Object) null, null); } @Override public boolean isWarnEnabled(final Marker marker) { return isEnabled(Level.WARN, marker, (Object) null, null); } @Override public void log(final Level level, final Marker marker, final Message msg) { logIfEnabled(FQCN, level, marker, msg, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, level, marker, msg, t); } @Override public void log(final Level level, final Marker marker, final Object message) { logIfEnabled(FQCN, level, marker, message, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final Object message, final Throwable t) { if (isEnabled(level, marker, message, t)) { logMessage(FQCN, level, marker, message, t); } } @Override public void log(final Level level, final Marker marker, final String message) { logIfEnabled(FQCN, level, marker, message, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, level, marker, message, params); } @Override public void log(final Level level, final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, level, marker, message, t); } @Override public void log(final Level level, final Message msg) { logIfEnabled(FQCN, level, null, msg, null); } @Override public void log(final Level level, final Message msg, final Throwable t) { logIfEnabled(FQCN, level, null, msg, t); } @Override public void log(final Level level, final Object message) { logIfEnabled(FQCN, level, null, message, null); } @Override public void log(final Level level, final Object message, final Throwable t) { logIfEnabled(FQCN, level, null, message, t); } @Override public void log(final Level level, final String message) { logIfEnabled(FQCN, level, null, message, (Throwable) null); } @Override public void log(final Level level, final String message, final Object... params) { logIfEnabled(FQCN, level, null, message, params); } @Override public void log(final Level level, final String message, final Throwable t) { logIfEnabled(FQCN, level, null, message, t); } @Override public void log(final Level level, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, level, null, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, null, msgSupplier, t); } @Override public void log(final Level level, final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, level, marker, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, level, marker, message, paramSuppliers); } @Override public void log(final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, marker, msgSupplier, t); } @Override public void log(final Level level, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, level, null, message, paramSuppliers); } @Override public void log(final Level level, final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, level, marker, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, marker, msgSupplier, t); } @Override public void log(final Level level, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, level, null, msgSupplier, (Throwable) null); } @Override public void log(final Level level, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, level, null, msgSupplier, t); } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Message msg, final Throwable t) { if (isEnabled(level, marker, msg, t)) { logMessage(fqcn, level, marker, msg, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { if (isEnabled(level, marker, msgSupplier, t)) { logMessage(fqcn, level, marker, msgSupplier, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Object message, final Throwable t) { if (isEnabled(level, marker, message, t)) { logMessage(fqcn, level, marker, message, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { if (isEnabled(level, marker, msgSupplier, t)) { logMessage(fqcn, level, marker, msgSupplier, t); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message) { if (isEnabled(level, marker, message)) { logMessage(fqcn, level, marker, message); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) { if (isEnabled(level, marker, message)) { logMessage(fqcn, level, marker, message, paramSuppliers); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message, final Object... params) { if (isEnabled(level, marker, message, params)) { logMessage(fqcn, level, marker, message, params); } } @Override public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message, final Throwable t) { if (isEnabled(level, marker, message, t)) { logMessage(fqcn, level, marker, message, t); } } protected void logMessage(final String fqcn, final Level level, final Marker marker, final Object message, final Throwable t) { logMessage(fqcn, level, marker, messageFactory.newMessage(message), t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { final Message message = LambdaUtil.get(msgSupplier); logMessage(fqcn, level, marker, message, t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { final Object message = LambdaUtil.get(msgSupplier); logMessage(fqcn, level, marker, messageFactory.newMessage(message), t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message, final Throwable t) { logMessage(fqcn, level, marker, messageFactory.newMessage(message), t); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message) { final Message msg = messageFactory.newMessage(message); logMessage(fqcn, level, marker, msg, msg.getThrowable()); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message, final Object... params) { final Message msg = messageFactory.newMessage(message, params); logMessage(fqcn, level, marker, msg, msg.getThrowable()); } protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) { final Message msg = messageFactory.newMessage(message, LambdaUtil.getAll(paramSuppliers)); logMessage(fqcn, level, marker, msg, msg.getThrowable()); } @Override public void printf(final Level level, final Marker marker, final String format, final Object... params) { if (isEnabled(level, marker, format, params)) { final Message msg = new StringFormattedMessage(format, params); logMessage(FQCN, level, marker, msg, msg.getThrowable()); } } @Override public void printf(final Level level, final String format, final Object... params) { if (isEnabled(level, null, format, params)) { final Message msg = new StringFormattedMessage(format, params); logMessage(FQCN, level, null, msg, msg.getThrowable()); } } @Override public <T extends Throwable> T throwing(final T t) { return throwing(FQCN, Level.ERROR, t); } @Override public <T extends Throwable> T throwing(final Level level, final T t) { return throwing(FQCN, level, t); } /** * Logs a Throwable to be thrown. * * @param <T> the type of the Throwable. * @param fqcn the fully qualified class name of this Logger implementation. * @param level The logging Level. * @param t The Throwable. * @return the Throwable. */ protected <T extends Throwable> T throwing(final String fqcn, final Level level, final T t) { if (isEnabled(level, THROWING_MARKER, (Object) null, null)) { logMessage(fqcn, level, THROWING_MARKER, throwingMsg(t), t); } return t; } protected Message throwingMsg(final Throwable t) { return messageFactory.newMessage(THROWING); } @Override public void trace(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.TRACE, marker, msg, null); } @Override public void trace(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, msg, t); } @Override public void trace(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.TRACE, marker, message, null); } @Override public void trace(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, message, t); } @Override public void trace(final Marker marker, final String message) { logIfEnabled(FQCN, Level.TRACE, marker, message, (Throwable) null); } @Override public void trace(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.TRACE, marker, message, params); } @Override public void trace(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, message, t); } @Override public void trace(final Message msg) { logIfEnabled(FQCN, Level.TRACE, null, msg, null); } @Override public void trace(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, msg, t); } @Override public void trace(final Object message) { logIfEnabled(FQCN, Level.TRACE, null, message, null); } @Override public void trace(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, message, t); } @Override public void trace(final String message) { logIfEnabled(FQCN, Level.TRACE, null, message, (Throwable) null); } @Override public void trace(final String message, final Object... params) { logIfEnabled(FQCN, Level.TRACE, null, message, params); } @Override public void trace(final String message, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, message, t); } @Override public void trace(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, (Throwable) null); } @Override public void trace(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, t); } @Override public void trace(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, (Throwable) null); } @Override public void trace(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.TRACE, marker, message, paramSuppliers); } @Override public void trace(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, t); } @Override public void trace(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.TRACE, null, message, paramSuppliers); } @Override public void trace(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, (Throwable) null); } @Override public void trace(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, t); } @Override public void trace(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, (Throwable) null); } @Override public void trace(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, t); } @Override public void traceEntry() { enter(FQCN, null, (Object[]) null); } @Override public void traceEntry(final String format, final Object... params) { enter(FQCN, format, params); } @Override public void traceEntry(final Supplier<?>... paramSuppliers) { enter(FQCN, null, paramSuppliers); } @Override public void traceEntry(final String format, final Supplier<?>... paramSuppliers) { enter(FQCN, format, paramSuppliers); } @Override public void traceEntry(final Message message) { enter(FQCN, new MessageSupplier() { @Override public Message get() { return message; }}); } @Override public void traceEntry(final MessageSupplier msgSupplier) { enter(FQCN, msgSupplier); } @Override public void traceExit() { exit(FQCN, null, null); } @Override public <R> R traceExit(final R result) { return exit(FQCN, null, result); } @Override public <R> R traceExit(final String format, final R result) { return exit(FQCN, format, result); } @Override public <R> R traceExit(final R result, final MessageSupplier messageSupplier) { if (isEnabled(Level.TRACE, EXIT_MARKER, messageSupplier, null)) { logMessage(FQCN, Level.TRACE, EXIT_MARKER, new MessageSupplier() { public Message get() { return new ExitMessage(messageSupplier.get()); }; }, null); } return result; } @Override public <R> R traceExit(final R result, final Message message) { if (isEnabled(Level.TRACE, EXIT_MARKER, message, null)) { logMessage(FQCN, Level.TRACE, EXIT_MARKER, new MessageSupplier() { public Message get() { return new ExitMessage(message); }; }, null); } return result; } @Override public void warn(final Marker marker, final Message msg) { logIfEnabled(FQCN, Level.WARN, marker, msg, null); } @Override public void warn(final Marker marker, final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, msg, t); } @Override public void warn(final Marker marker, final Object message) { logIfEnabled(FQCN, Level.WARN, marker, message, null); } @Override public void warn(final Marker marker, final Object message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, message, t); } @Override public void warn(final Marker marker, final String message) { logIfEnabled(FQCN, Level.WARN, marker, message, (Throwable) null); } @Override public void warn(final Marker marker, final String message, final Object... params) { logIfEnabled(FQCN, Level.WARN, marker, message, params); } @Override public void warn(final Marker marker, final String message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, message, t); } @Override public void warn(final Message msg) { logIfEnabled(FQCN, Level.WARN, null, msg, null); } @Override public void warn(final Message msg, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, msg, t); } @Override public void warn(final Object message) { logIfEnabled(FQCN, Level.WARN, null, message, null); } @Override public void warn(final Object message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, message, t); } @Override public void warn(final String message) { logIfEnabled(FQCN, Level.WARN, null, message, (Throwable) null); } @Override public void warn(final String message, final Object... params) { logIfEnabled(FQCN, Level.WARN, null, message, params); } @Override public void warn(final String message, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, message, t); } @Override public void warn(final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, (Throwable) null); } @Override public void warn(final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, t); } @Override public void warn(final Marker marker, final Supplier<?> msgSupplier) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, (Throwable) null); } @Override public void warn(final Marker marker, final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.WARN, marker, message, paramSuppliers); } @Override public void warn(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, t); } @Override public void warn(final String message, final Supplier<?>... paramSuppliers) { logIfEnabled(FQCN, Level.WARN, null, message, paramSuppliers); } @Override public void warn(final Marker marker, final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, (Throwable) null); } @Override public void warn(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, t); } @Override public void warn(final MessageSupplier msgSupplier) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, (Throwable) null); } @Override public void warn(final MessageSupplier msgSupplier, final Throwable t) { logIfEnabled(FQCN, Level.WARN, null, msgSupplier, t); } private static class FlowMessage implements Message { private static final long serialVersionUID = 7580175170272152912L; private Message message; private final String text; FlowMessage(String text, Message message) { this.message = message; this.text = text; } @Override public String getFormattedMessage() { if (message != null) { return text + ": " + message.getFormattedMessage(); } return text; } @Override public String getFormat() { if (message != null) { return text + ": " + message.getFormat(); } return text; } @Override public Object[] getParameters() { if (message != null) { return message.getParameters(); } return null; } @Override public Throwable getThrowable() { if (message != null) { return message.getThrowable(); } return null; } } private static class EntryMessage extends FlowMessage { EntryMessage(Message message) { super("entry", message); } } private static class ExitMessage extends FlowMessage { ExitMessage(Message message) { super("exit", message); } } }
Remove unused import.
log4j-api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java
Remove unused import.
<ide><path>og4j-api/src/main/java/org/apache/logging/log4j/spi/AbstractLogger.java <ide> import org.apache.logging.log4j.message.Message; <ide> import org.apache.logging.log4j.message.MessageFactory; <ide> import org.apache.logging.log4j.message.ParameterizedMessageFactory; <del>import org.apache.logging.log4j.message.SimpleMessage; <ide> import org.apache.logging.log4j.message.StringFormattedMessage; <ide> import org.apache.logging.log4j.status.StatusLogger; <ide> import org.apache.logging.log4j.util.LambdaUtil;
Java
apache-2.0
0df965e97089d39d123907a27f2cb7d39df74732
0
rbieniek/flow-ninja,rbieniek/flow-ninja,rbieniek/flow-ninja
/** * */ package org.flowninja.persistence.mongodb.services; import static org.fest.assertions.api.Assertions.assertThat; import java.util.Set; import org.flowninja.persistence.generic.types.AccountingGroupRecord; import org.flowninja.persistence.generic.types.RecordAlreadyExistsException; import org.flowninja.persistence.generic.types.RecordNotFoundException; import org.flowninja.persistence.mongodb.data.MongoAccountingGroupRecord; import org.flowninja.persistence.mongodb.repositories.IMongoAccountingGroupRepository; import org.flowninja.types.generic.AccountingGroupKey; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.AssertThrows; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author rainer * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={MongoTestConfig.class}) public class MongoAccountingGroupPersistenceServiceTest { @Autowired private MongoAccountingGroupPersistenceService service; @Autowired private IMongoAccountingGroupRepository repository; private AccountingGroupKey keyOne; private MongoAccountingGroupRecord recordOne; private AccountingGroupKey keyTwo; private MongoAccountingGroupRecord recordTwo; @Before public void prepareDatabase() { repository.findAll().forEach((n) -> repository.delete(n)); keyOne = new AccountingGroupKey(); recordOne = repository.save(new MongoAccountingGroupRecord(keyOne, "dummyOne", "this is a dummy group")); keyTwo = new AccountingGroupKey(); recordTwo = repository.save(new MongoAccountingGroupRecord(keyTwo, "dummyTwo", "this is a dummy group")); assertThat(recordOne.getCreatedWhen()).isNotNull(); assertThat(recordOne.getLastModifiedAt()).isNotNull(); assertThat(recordTwo.getCreatedWhen()).isNotNull(); assertThat(recordTwo.getLastModifiedAt()).isNotNull(); } @Test public void listAccoutingGroups() { Set<AccountingGroupRecord> records = service.listAccountingGroups(); assertThat(records).containsOnly(new AccountingGroupRecord(recordOne.getKey(), recordOne.getName(), recordOne.getComment(), recordOne.getCreatedWhen(), recordOne.getLastModifiedAt()), new AccountingGroupRecord(recordTwo.getKey(), recordTwo.getName(), recordTwo.getComment(), recordTwo.getCreatedWhen(),recordTwo.getLastModifiedAt())); } @Test public void findAccountingGroupByKeyKnownKey() { assertThat(service.findByKey(keyOne)).isEqualTo(new AccountingGroupRecord(recordOne.getKey(), recordOne.getName(), recordOne.getComment(), recordOne.getCreatedWhen(), recordOne.getLastModifiedAt())); } @Test public void findAccountingGroupByKeyUnknownKey() { assertThat(service.findByKey(new AccountingGroupKey())).isNull(); } @Test public void findAccountingGroupByNameKnownName() { assertThat(service.findByName("dummyOne")).isEqualTo(new AccountingGroupRecord(recordOne.getKey(), recordOne.getName(), recordOne.getComment(), recordOne.getCreatedWhen(), recordOne.getLastModifiedAt())); } @Test public void findAccountingGroupByNameUnknownName() { assertThat(service.findByName("foo")).isNull(); } @Test public void createAccountingGroupNewName() { AccountingGroupRecord record = service.createAccountingGroup("dummyThree", "yo ho ho"); assertThat(record).isNotNull(); assertThat(record.getKey()).isNotNull(); assertThat(record.getName()).isEqualTo("dummyThree"); assertThat(record.getComment()).isEqualTo("yo ho ho"); assertThat(service.findByKey(record.getKey())).isEqualTo(record); } @Test(expected=RecordAlreadyExistsException.class) public void createAccountingGroupExistingName() { service.createAccountingGroup("dummyOne", "foo"); } @Test public void updateAccountingGroupNewComment() { AccountingGroupRecord record = service.findByKey(keyOne); assertThat(record).isNotNull(); record.setComment("yo ho ho"); AccountingGroupRecord newRecord = service.updateAccoutingGroup(record); assertThat(newRecord).isNotNull(); assertThat(newRecord.getKey()).isEqualTo(record.getKey()); assertThat(newRecord.getName()).isEqualTo(record.getName()); assertThat(newRecord.getComment()).isEqualTo("yo ho ho"); assertThat(newRecord.getCreatedWhen()).isEqualTo(record.getCreatedWhen()); assertThat(newRecord.getLastModifiedAt()).isNotEqualTo(record.getLastModifiedAt()); assertThat(service.findByKey(record.getKey())).isEqualTo(newRecord); } @Test public void updateAccountingGroupNewName() { AccountingGroupRecord record = service.findByKey(keyOne); assertThat(record).isNotNull(); record.setComment("yo ho ho"); record.setName("dummyFour"); AccountingGroupRecord newRecord = service.updateAccoutingGroup(record); assertThat(newRecord).isNotNull(); assertThat(newRecord.getKey()).isEqualTo(record.getKey()); assertThat(newRecord.getName()).isEqualTo("dummyFour"); assertThat(newRecord.getComment()).isEqualTo("yo ho ho"); assertThat(newRecord.getCreatedWhen()).isEqualTo(record.getCreatedWhen()); assertThat(newRecord.getLastModifiedAt()).isNotEqualTo(record.getLastModifiedAt()); assertThat(service.findByKey(record.getKey())).isEqualTo(newRecord); } @Test(expected=RecordAlreadyExistsException.class) public void updateAccountingGroupExistingName() { AccountingGroupRecord record = service.findByKey(keyOne); assertThat(record).isNotNull(); record.setComment("yo ho ho"); record.setName("dummyTwo"); service.updateAccoutingGroup(record); } @Test(expected=RecordNotFoundException.class) public void updateAccountingGroupUnknownKey() { service.updateAccoutingGroup(new AccountingGroupRecord(new AccountingGroupKey(), null, null, null, null)); } @Test public void deleteAccountingGroupExistingGroup() { service.deleteAccountingGroup(keyOne); assertThat(service.findByKey(keyOne)).isNull(); } @Test(expected=RecordNotFoundException.class) public void deleteAccountingGroupNonExistingGroup() { service.deleteAccountingGroup(new AccountingGroupKey()); } }
ninja-persistence-mongodb/src/test/java/org/flowninja/persistence/mongodb/services/MongoAccountingGroupPersistenceServiceTest.java
/** * */ package org.flowninja.persistence.mongodb.services; import static org.fest.assertions.api.Assertions.assertThat; import java.util.Set; import org.flowninja.persistence.generic.types.AccountingGroupRecord; import org.flowninja.persistence.mongodb.data.MongoAccountingGroupRecord; import org.flowninja.persistence.mongodb.repositories.IMongoAccountingGroupRepository; import org.flowninja.types.generic.AccountingGroupKey; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author rainer * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={MongoTestConfig.class}) public class MongoAccountingGroupPersistenceServiceTest { @Autowired private MongoAccountingGroupPersistenceService service; @Autowired private IMongoAccountingGroupRepository repository; private AccountingGroupKey keyOne; private MongoAccountingGroupRecord recordOne; private AccountingGroupKey keyTwo; private MongoAccountingGroupRecord recordTwo; @Before public void prepareDatabase() { repository.findAll().forEach((n) -> repository.delete(n)); keyOne = new AccountingGroupKey(); recordOne = repository.save(new MongoAccountingGroupRecord(keyOne, "dummyOne", "this is a dummy group")); keyTwo = new AccountingGroupKey(); recordTwo = repository.save(new MongoAccountingGroupRecord(keyTwo, "dummyTwo", "this is a dummy group")); assertThat(recordOne.getCreatedWhen()).isNotNull(); assertThat(recordOne.getLastModifiedAt()).isNotNull(); assertThat(recordTwo.getCreatedWhen()).isNotNull(); assertThat(recordTwo.getLastModifiedAt()).isNotNull(); } @Test public void listAccoutingGroups() { Set<AccountingGroupRecord> records = service.listAccountingGroups(); assertThat(records).containsOnly(new AccountingGroupRecord(recordOne.getKey(), recordOne.getName(), recordOne.getComment(), recordOne.getCreatedWhen(), recordOne.getLastModifiedAt()), new AccountingGroupRecord(recordTwo.getKey(), recordTwo.getName(), recordTwo.getComment(), recordTwo.getCreatedWhen(),recordTwo.getLastModifiedAt())); } }
added unit tests for MongoDB-based accounting group persistence
ninja-persistence-mongodb/src/test/java/org/flowninja/persistence/mongodb/services/MongoAccountingGroupPersistenceServiceTest.java
added unit tests for MongoDB-based accounting group persistence
<ide><path>inja-persistence-mongodb/src/test/java/org/flowninja/persistence/mongodb/services/MongoAccountingGroupPersistenceServiceTest.java <ide> import java.util.Set; <ide> <ide> import org.flowninja.persistence.generic.types.AccountingGroupRecord; <add>import org.flowninja.persistence.generic.types.RecordAlreadyExistsException; <add>import org.flowninja.persistence.generic.types.RecordNotFoundException; <ide> import org.flowninja.persistence.mongodb.data.MongoAccountingGroupRecord; <ide> import org.flowninja.persistence.mongodb.repositories.IMongoAccountingGroupRepository; <ide> import org.flowninja.types.generic.AccountingGroupKey; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.test.AssertThrows; <ide> import org.springframework.test.context.ContextConfiguration; <ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <ide> <ide> recordTwo.getCreatedWhen(),recordTwo.getLastModifiedAt())); <ide> } <ide> <add> @Test <add> public void findAccountingGroupByKeyKnownKey() { <add> assertThat(service.findByKey(keyOne)).isEqualTo(new AccountingGroupRecord(recordOne.getKey(), recordOne.getName(), recordOne.getComment(), <add> recordOne.getCreatedWhen(), recordOne.getLastModifiedAt())); <add> } <add> <add> @Test <add> public void findAccountingGroupByKeyUnknownKey() { <add> assertThat(service.findByKey(new AccountingGroupKey())).isNull(); <add> } <add> <add> <add> @Test <add> public void findAccountingGroupByNameKnownName() { <add> assertThat(service.findByName("dummyOne")).isEqualTo(new AccountingGroupRecord(recordOne.getKey(), recordOne.getName(), recordOne.getComment(), <add> recordOne.getCreatedWhen(), recordOne.getLastModifiedAt())); <add> } <add> <add> @Test <add> public void findAccountingGroupByNameUnknownName() { <add> assertThat(service.findByName("foo")).isNull(); <add> } <add> <add> @Test <add> public void createAccountingGroupNewName() { <add> AccountingGroupRecord record = service.createAccountingGroup("dummyThree", "yo ho ho"); <add> <add> assertThat(record).isNotNull(); <add> assertThat(record.getKey()).isNotNull(); <add> assertThat(record.getName()).isEqualTo("dummyThree"); <add> assertThat(record.getComment()).isEqualTo("yo ho ho"); <add> <add> assertThat(service.findByKey(record.getKey())).isEqualTo(record); <add> } <add> <add> @Test(expected=RecordAlreadyExistsException.class) <add> public void createAccountingGroupExistingName() { <add> service.createAccountingGroup("dummyOne", "foo"); <add> } <add> <add> @Test <add> public void updateAccountingGroupNewComment() { <add> AccountingGroupRecord record = service.findByKey(keyOne); <add> <add> assertThat(record).isNotNull(); <add> <add> record.setComment("yo ho ho"); <add> <add> AccountingGroupRecord newRecord = service.updateAccoutingGroup(record); <add> <add> assertThat(newRecord).isNotNull(); <add> assertThat(newRecord.getKey()).isEqualTo(record.getKey()); <add> assertThat(newRecord.getName()).isEqualTo(record.getName()); <add> assertThat(newRecord.getComment()).isEqualTo("yo ho ho"); <add> assertThat(newRecord.getCreatedWhen()).isEqualTo(record.getCreatedWhen()); <add> assertThat(newRecord.getLastModifiedAt()).isNotEqualTo(record.getLastModifiedAt()); <add> <add> assertThat(service.findByKey(record.getKey())).isEqualTo(newRecord); <add> } <add> <add> @Test <add> public void updateAccountingGroupNewName() { <add> AccountingGroupRecord record = service.findByKey(keyOne); <add> <add> assertThat(record).isNotNull(); <add> <add> record.setComment("yo ho ho"); <add> record.setName("dummyFour"); <add> <add> AccountingGroupRecord newRecord = service.updateAccoutingGroup(record); <add> <add> assertThat(newRecord).isNotNull(); <add> assertThat(newRecord.getKey()).isEqualTo(record.getKey()); <add> assertThat(newRecord.getName()).isEqualTo("dummyFour"); <add> assertThat(newRecord.getComment()).isEqualTo("yo ho ho"); <add> assertThat(newRecord.getCreatedWhen()).isEqualTo(record.getCreatedWhen()); <add> assertThat(newRecord.getLastModifiedAt()).isNotEqualTo(record.getLastModifiedAt()); <add> <add> assertThat(service.findByKey(record.getKey())).isEqualTo(newRecord); <add> } <add> <add> @Test(expected=RecordAlreadyExistsException.class) <add> public void updateAccountingGroupExistingName() { <add> AccountingGroupRecord record = service.findByKey(keyOne); <add> <add> assertThat(record).isNotNull(); <add> <add> record.setComment("yo ho ho"); <add> record.setName("dummyTwo"); <add> <add> service.updateAccoutingGroup(record); <add> } <add> <add> @Test(expected=RecordNotFoundException.class) <add> public void updateAccountingGroupUnknownKey() { <add> service.updateAccoutingGroup(new AccountingGroupRecord(new AccountingGroupKey(), null, null, null, null)); <add> } <add> <add> @Test <add> public void deleteAccountingGroupExistingGroup() { <add> service.deleteAccountingGroup(keyOne); <add> <add> assertThat(service.findByKey(keyOne)).isNull(); <add> } <add> <add> @Test(expected=RecordNotFoundException.class) <add> public void deleteAccountingGroupNonExistingGroup() { <add> service.deleteAccountingGroup(new AccountingGroupKey()); <add> } <ide> }
Java
mit
3a657fd37ec643f8603106de208da6b53a02b505
0
aemreunal/iBeaconServer,aemreunal/iBeaconServer
package com.aemreunal.config; /* ************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * ************************** */ public class GlobalSettings { /** * Used to set the global logging levels, like whether to log SQL queries or prints * inside methods. */ public static final boolean DEBUGGING = true; /** * The BCrypt-hashed password field length (in User.class) is assumed to be 60 with a * 2-digit log factor. For example, in '$2a$10$...', the '10' is the log factor. If it * ever gets a 3-digit log factor (highly unlikely), the length of that field must * become 61. */ public static final int BCRYPT_LOG_FACTOR = 10; /** * This context path is defined inside the gradle build script, named 'build.gradle'. * This value only reflects that one and if that context path is changed, this must be * changed as well, since tests rely on the correctness of this value. */ public static final String BASE_CONTEXT_PATH = "iBeacon"; /** * This regex matches if the given string contains a non-ASCII character. It, however, * does not match punctuation, so while "Hellö" matches this regex, "Hello!" won't. */ public static final String NON_ASCII_REGEX = ".*[^\\p{ASCII}].*"; // User public static final String USER_PATH_MAPPING = ""; public static final String USER_CREATE_MAPPING = "/register"; public static final String USER_USERNAME_MAPPING = "/{username}"; public static final String USER_SPECIFIC_MAPPING = USER_PATH_MAPPING + USER_USERNAME_MAPPING; // Project public static final String PROJECT_PATH_MAPPING = USER_SPECIFIC_MAPPING + "/projects"; public static final String PROJECT_ID_MAPPING = "/{projectId}"; public static final String PROJECT_SPECIFIC_MAPPING = PROJECT_PATH_MAPPING + PROJECT_ID_MAPPING; // Beacon public static final String BEACON_PATH_MAPPING = PROJECT_SPECIFIC_MAPPING + "/beacons"; public static final String BEACON_ID_MAPPING = "/{beaconId}"; public static final String BEACON_SPECIFIC_MAPPING = BEACON_PATH_MAPPING + BEACON_ID_MAPPING; // Beacon group public static final String BEACONGROUP_PATH_MAPPING = PROJECT_SPECIFIC_MAPPING + "/beacongroup"; public static final String BEACONGROUP_ID_MAPPING = "/{beaconGroupId}"; public static final String BEACONGROUP_SPECIFIC_MAPPING = BEACONGROUP_PATH_MAPPING + BEACONGROUP_ID_MAPPING; public static final String BEACONGROUP_MEMBERS_MAPPING = "/members"; public static final String BEACONGROUP_ADD_MEMBER_MAPPING = BEACONGROUP_ID_MAPPING + "/addmember"; public static final String BEACONGROUP_REMOVE_MEMBER_MAPPING = BEACONGROUP_ID_MAPPING + "/removemember"; // Beacon public static final String SCENARIO_PATH_MAPPING = PROJECT_SPECIFIC_MAPPING + "/scenarios"; public static final String SCENARIO_ID_MAPPING = "/{scenarioId}"; public static final String SCENARIO_SPECIFIC_MAPPING = SCENARIO_PATH_MAPPING + SCENARIO_ID_MAPPING; //------------------------------------------------------------------------------------------- // Property name: "hibernate.hbm2ddl.auto" // // hibernate.hbm2ddl.auto: Automatically validates or exports schema DDL to the // database when the SessionFactory is created. With create-drop, the database // schema will be dropped when the SessionFactory is closed explicitly. // // Values: "validate" | "update" | "create" | "create-drop" // // validate: validate the schema, makes no changes to the database. // update: update the schema. // create: creates the schema, destroying previous data. // create-drop: drop the schema at the end of the session. //---------------------------------------- public static final String HBM2DDL_PROPERTY = "update"; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Property name: "hibernate.show_sql" //---------------------------------------- public static final String SHOW_SQL_PROPERTY = String.valueOf(DEBUGGING); // Used for the JDBC adapter public static final boolean SHOW_SQL = DEBUGGING; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Property name: "hibernate.format_sql" //---------------------------------------- public static final Object FORMAT_SQL_PROPERTY = "true"; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Property name: "hibernate.dialect" //---------------------------------------- public static final String DB_DIALECT_PROPERTY = "org.hibernate.dialect.MySQL5InnoDBDialect"; //------------------------------------------------------------------------------------------- }
src/main/java/com/aemreunal/config/GlobalSettings.java
package com.aemreunal.config; /* ************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * ************************** */ public class GlobalSettings { /** * Used to set the global logging levels, like whether to log SQL queries or prints * inside methods. */ public static final boolean DEBUGGING = true; /** * The BCrypt-hashed password field length (in User.class) is assumed to be 60 with a * 2-digit log factor. For example, in '$2a$10$...', the '10' is the log factor. If it * ever gets a 3-digit log factor (highly unlikely), the length of that field must * become 61. */ public static final int BCRYPT_LOG_FACTOR = 10; /** * This context path is defined inside the gradle build script, named 'build.gradle'. * This value only reflects that one and if that context path is changed, this must be * changed as well, since tests rely on the correctness of this value. */ public static final String BASE_CONTEXT_PATH = "iBeacon"; /** * This regex matches if the given string contains a non-ASCII character. It, however, * does not match punctuation, so while "Hellö" matches this regex, "Hello!" won't. */ public static final String NON_ASCII_REGEX = ".*[^\\p{ASCII}].*"; // User public static final String USER_PATH_MAPPING = ""; public static final String USER_CREATE_MAPPING = "/register"; public static final String USER_USERNAME_MAPPING = "/{username}"; public static final String USER_SPECIFIC_MAPPING = USER_PATH_MAPPING + USER_USERNAME_MAPPING; // Project public static final String PROJECT_PATH_MAPPING = USER_SPECIFIC_MAPPING + "/projects"; public static final String PROJECT_ID_MAPPING = "/{projectId}"; public static final String PROJECT_SPECIFIC_MAPPING = PROJECT_PATH_MAPPING + PROJECT_ID_MAPPING; // Beacon public static final String BEACON_PATH_MAPPING = PROJECT_SPECIFIC_MAPPING + "/beacons"; public static final String BEACON_ID_MAPPING = "/{beaconId}"; public static final String BEACON_SPECIFIC_MAPPING = BEACON_PATH_MAPPING + BEACON_ID_MAPPING; // Beacon group public static final String BEACONGROUP_PATH_MAPPING = PROJECT_SPECIFIC_MAPPING + "/beacongroup"; public static final String BEACONGROUP_ID_MAPPING = "/{beaconGroupId}"; public static final String BEACONGROUP_SPECIFIC_MAPPING = BEACONGROUP_PATH_MAPPING + BEACONGROUP_ID_MAPPING; public static final String BEACONGROUP_MEMBERS_MAPPING = "/members"; public static final String BEACONGROUP_ADD_MEMBER_MAPPING = BEACONGROUP_ID_MAPPING + "/addmember"; public static final String BEACONGROUP_REMOVE_MEMBER_MAPPING = BEACONGROUP_ID_MAPPING + "/removemember"; //------------------------------------------------------------------------------------------- // Property name: "hibernate.hbm2ddl.auto" // // hibernate.hbm2ddl.auto: Automatically validates or exports schema DDL to the // database when the SessionFactory is created. With create-drop, the database // schema will be dropped when the SessionFactory is closed explicitly. // // Values: "validate" | "update" | "create" | "create-drop" // // validate: validate the schema, makes no changes to the database. // update: update the schema. // create: creates the schema, destroying previous data. // create-drop: drop the schema at the end of the session. //---------------------------------------- public static final String HBM2DDL_PROPERTY = "update"; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Property name: "hibernate.show_sql" //---------------------------------------- public static final String SHOW_SQL_PROPERTY = String.valueOf(DEBUGGING); // Used for the JDBC adapter public static final boolean SHOW_SQL = DEBUGGING; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Property name: "hibernate.format_sql" //---------------------------------------- public static final Object FORMAT_SQL_PROPERTY = "true"; //------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Property name: "hibernate.dialect" //---------------------------------------- public static final String DB_DIALECT_PROPERTY = "org.hibernate.dialect.MySQL5InnoDBDialect"; //------------------------------------------------------------------------------------------- }
Add Scenario mapping constants
src/main/java/com/aemreunal/config/GlobalSettings.java
Add Scenario mapping constants
<ide><path>rc/main/java/com/aemreunal/config/GlobalSettings.java <ide> public static final String BEACONGROUP_MEMBERS_MAPPING = "/members"; <ide> public static final String BEACONGROUP_ADD_MEMBER_MAPPING = BEACONGROUP_ID_MAPPING + "/addmember"; <ide> public static final String BEACONGROUP_REMOVE_MEMBER_MAPPING = BEACONGROUP_ID_MAPPING + "/removemember"; <add> // Beacon <add> public static final String SCENARIO_PATH_MAPPING = PROJECT_SPECIFIC_MAPPING + "/scenarios"; <add> public static final String SCENARIO_ID_MAPPING = "/{scenarioId}"; <add> public static final String SCENARIO_SPECIFIC_MAPPING = SCENARIO_PATH_MAPPING + SCENARIO_ID_MAPPING; <ide> <ide> <ide> //-------------------------------------------------------------------------------------------
Java
lgpl-2.1
4445163582192ae494e3099a3bea760742562dd7
0
opax/exist,kohsah/exist,ljo/exist,MjAbuz/exist,eXist-db/exist,opax/exist,jensopetersen/exist,wolfgangmm/exist,zwobit/exist,adamretter/exist,patczar/exist,wshager/exist,olvidalo/exist,adamretter/exist,adamretter/exist,jessealama/exist,wolfgangmm/exist,windauer/exist,olvidalo/exist,kohsah/exist,jessealama/exist,jensopetersen/exist,jensopetersen/exist,adamretter/exist,patczar/exist,lcahlander/exist,patczar/exist,patczar/exist,ambs/exist,shabanovd/exist,dizzzz/exist,jensopetersen/exist,ljo/exist,dizzzz/exist,MjAbuz/exist,kohsah/exist,ljo/exist,shabanovd/exist,joewiz/exist,wshager/exist,MjAbuz/exist,jessealama/exist,kohsah/exist,RemiKoutcherawy/exist,ljo/exist,MjAbuz/exist,wshager/exist,eXist-db/exist,joewiz/exist,eXist-db/exist,ambs/exist,lcahlander/exist,opax/exist,zwobit/exist,hungerburg/exist,wolfgangmm/exist,MjAbuz/exist,adamretter/exist,windauer/exist,shabanovd/exist,shabanovd/exist,lcahlander/exist,windauer/exist,RemiKoutcherawy/exist,jessealama/exist,MjAbuz/exist,shabanovd/exist,RemiKoutcherawy/exist,kohsah/exist,hungerburg/exist,eXist-db/exist,hungerburg/exist,dizzzz/exist,ambs/exist,wshager/exist,ljo/exist,RemiKoutcherawy/exist,joewiz/exist,adamretter/exist,wshager/exist,dizzzz/exist,windauer/exist,ambs/exist,windauer/exist,zwobit/exist,dizzzz/exist,lcahlander/exist,jessealama/exist,wolfgangmm/exist,windauer/exist,lcahlander/exist,wolfgangmm/exist,opax/exist,jessealama/exist,olvidalo/exist,olvidalo/exist,patczar/exist,kohsah/exist,zwobit/exist,dizzzz/exist,jensopetersen/exist,RemiKoutcherawy/exist,hungerburg/exist,eXist-db/exist,ljo/exist,lcahlander/exist,ambs/exist,shabanovd/exist,joewiz/exist,ambs/exist,wolfgangmm/exist,olvidalo/exist,jensopetersen/exist,hungerburg/exist,zwobit/exist,wshager/exist,zwobit/exist,eXist-db/exist,opax/exist,joewiz/exist,joewiz/exist,RemiKoutcherawy/exist,patczar/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-04 Wolfgang M. Meier * [email protected] * http://exist-db.org * * This program 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 * of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.storage; import java.util.Map; import org.apache.log4j.Logger; import org.exist.dom.QName; import org.exist.util.FastStringBuffer; /** * @author wolf */ public class NodePath implements Comparable<NodePath>{ private final static Logger LOG = Logger.getLogger(NodePath.class); /** * (Illegal) QNames used as a marker for arbitrary path steps. */ public final static QName SKIP = new QName("//", ""); public final static QName WILDCARD = new QName("*", ""); private QName[] components = new QName[5]; private int pos = 0; private boolean includeDescendants = true; public NodePath() { } public NodePath(NodePath other) { components = new QName[other.components.length]; System.arraycopy(other.components, 0, components, 0, other.components.length); pos = other.pos; includeDescendants = other.includeDescendants; } /** * */ public NodePath(Map<String, String> namespaces, String path) { init(namespaces, path); } public NodePath(Map<String, String> namespaces, String path, boolean includeDescendants) { this.includeDescendants = includeDescendants; init(namespaces, path); } public NodePath(QName qname) { addComponent(qname); } public void addComponent(QName component) { if(pos == components.length) { QName[] t = new QName[pos + 1]; System.arraycopy(components, 0, t, 0, pos); components = t; } components[pos++] = component; } public void addComponentAtStart(QName component) { if(pos == components.length) { QName[] t = new QName[pos + 1]; System.arraycopy(components, 0, t, 1, pos); components = t; components[0] = component; } else { System.arraycopy(components, 0, components, 1, pos); components[0] = component; } pos++; } public void removeLastComponent() { if (pos > 0) components[--pos] = null; } public int length() { return pos; } public QName getComponent(int at) { if (at < 0 || at >= pos) throw new ArrayIndexOutOfBoundsException(at); return components[at]; } public QName getLastComponent() { if (pos > 0) { return components[pos - 1]; } return null; } public boolean hasWildcard() { for (int i = 0; i < pos; i++) { if (components[i] == WILDCARD) return true; } return false; } public boolean match(QName qname) { if (pos > 0) { return components[pos - 1].equals(qname); } return false; } public final boolean match(NodePath other) { boolean skip = false; int i = 0, j = 0; for( ; j < other.pos; j++) { if(i == pos) { if(includeDescendants) return true; return j == other.pos ? true : false; } if(components[i] == SKIP) { ++i; skip = true; } if((components[i] == WILDCARD || other.components[j].compareTo(components[i]) == 0) && (j + 1 == other.pos || other.components[j + 1].compareTo(components[i]) != 0)) { ++i; skip = false; } else if(skip) { continue; } else return false; } if(i == pos) { if(includeDescendants) return true; return j == other.pos ? true : false; } return false; } public void reset() { for(int i = 0; i < pos; i++) components[i] = null; pos = 0; } public String toString() { StringBuilder buf = new StringBuilder(); for(int i = 0; i < pos; i++) { buf.append("/"); if (components[i].getNameType() == ElementValue.ATTRIBUTE) buf.append("@"); buf.append(components[i]); } return buf.toString(); } private void addComponent(Map<String, String> namespaces, String component) { boolean isAttribute = false; if (component.startsWith("@")) { isAttribute = true; component = component.substring(1); } String prefix = QName.extractPrefix(component); String localName = QName.extractLocalName(component); String namespaceURI = ""; if (prefix != null) { namespaceURI = namespaces.get(prefix); if(namespaceURI == null) { LOG.error("No namespace URI defined for prefix: " + prefix); prefix = null; namespaceURI = ""; } } QName qn = new QName(localName, namespaceURI, prefix); if (isAttribute) qn.setNameType(ElementValue.ATTRIBUTE); addComponent(qn); } private void init( Map<String, String> namespaces, String path ) { //TODO : compute better length FastStringBuffer token = new FastStringBuffer(path.length()); int pos = 0; while (pos < path.length()) { char ch = path.charAt(pos); switch (ch) { case '*': addComponent(WILDCARD); token.setLength(0); pos++; break; case '/': String next = token.toString(); token.setLength(0); if (next.length() > 0) addComponent(namespaces, next); if (path.charAt(++pos ) == '/') addComponent(SKIP); break; default: token.append(ch); pos++; } } if (token.length() > 0) addComponent(namespaces, token.toString()); } public boolean equals(Object obj) { if (obj == null) return false; if (obj instanceof NodePath) { NodePath nodePath = (NodePath) obj; if (nodePath.pos == pos) { for(int i = 0; i < pos; i++) { if (!nodePath.components[i].equals(components[i])) { return false; } } return true; } } return false; } public int hashCode() { int h = 0; for(int i = 0; i < pos; i++) { h = 31*h + components[i].hashCode(); } return h; } @Override public int compareTo(NodePath o) { return toString().compareTo(o.toString()); //TODO: optimize } }
src/org/exist/storage/NodePath.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-04 Wolfgang M. Meier * [email protected] * http://exist-db.org * * This program 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 * of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.storage; import java.util.Map; import org.apache.log4j.Logger; import org.exist.dom.QName; import org.exist.util.FastStringBuffer; /** * @author wolf */ public class NodePath { private final static Logger LOG = Logger.getLogger(NodePath.class); /** * (Illegal) QNames used as a marker for arbitrary path steps. */ public final static QName SKIP = new QName("//", ""); public final static QName WILDCARD = new QName("*", ""); private QName[] components = new QName[5]; private int pos = 0; private boolean includeDescendants = true; public NodePath() { } public NodePath(NodePath other) { components = new QName[other.components.length]; System.arraycopy(other.components, 0, components, 0, other.components.length); pos = other.pos; includeDescendants = other.includeDescendants; } /** * */ public NodePath(Map<String, String> namespaces, String path) { init(namespaces, path); } public NodePath(Map<String, String> namespaces, String path, boolean includeDescendants) { this.includeDescendants = includeDescendants; init(namespaces, path); } public NodePath(QName qname) { addComponent(qname); } public void addComponent(QName component) { if(pos == components.length) { QName[] t = new QName[pos + 1]; System.arraycopy(components, 0, t, 0, pos); components = t; } components[pos++] = component; } public void addComponentAtStart(QName component) { if(pos == components.length) { QName[] t = new QName[pos + 1]; System.arraycopy(components, 0, t, 1, pos); components = t; components[0] = component; } else { System.arraycopy(components, 0, components, 1, pos); components[0] = component; } pos++; } public void removeLastComponent() { if (pos > 0) components[--pos] = null; } public int length() { return pos; } public QName getComponent(int at) { if (at < 0 || at >= pos) throw new ArrayIndexOutOfBoundsException(at); return components[at]; } public QName getLastComponent() { if (pos > 0) { return components[pos - 1]; } return null; } public boolean hasWildcard() { for (int i = 0; i < pos; i++) { if (components[i] == WILDCARD) return true; } return false; } public boolean match(QName qname) { if (pos > 0) { return components[pos - 1].equals(qname); } return false; } public final boolean match(NodePath other) { boolean skip = false; int i = 0, j = 0; for( ; j < other.pos; j++) { if(i == pos) { if(includeDescendants) return true; return j == other.pos ? true : false; } if(components[i] == SKIP) { ++i; skip = true; } if((components[i] == WILDCARD || other.components[j].compareTo(components[i]) == 0) && (j + 1 == other.pos || other.components[j + 1].compareTo(components[i]) != 0)) { ++i; skip = false; } else if(skip) { continue; } else return false; } if(i == pos) { if(includeDescendants) return true; return j == other.pos ? true : false; } return false; } public void reset() { for(int i = 0; i < pos; i++) components[i] = null; pos = 0; } public String toString() { StringBuilder buf = new StringBuilder(); for(int i = 0; i < pos; i++) { buf.append("/"); if (components[i].getNameType() == ElementValue.ATTRIBUTE) buf.append("@"); buf.append(components[i]); } return buf.toString(); } private void addComponent(Map<String, String> namespaces, String component) { boolean isAttribute = false; if (component.startsWith("@")) { isAttribute = true; component = component.substring(1); } String prefix = QName.extractPrefix(component); String localName = QName.extractLocalName(component); String namespaceURI = ""; if (prefix != null) { namespaceURI = namespaces.get(prefix); if(namespaceURI == null) { LOG.error("No namespace URI defined for prefix: " + prefix); prefix = null; namespaceURI = ""; } } QName qn = new QName(localName, namespaceURI, prefix); if (isAttribute) qn.setNameType(ElementValue.ATTRIBUTE); addComponent(qn); } private void init( Map<String, String> namespaces, String path ) { //TODO : compute better length FastStringBuffer token = new FastStringBuffer(path.length()); int pos = 0; while (pos < path.length()) { char ch = path.charAt(pos); switch (ch) { case '*': addComponent(WILDCARD); token.setLength(0); pos++; break; case '/': String next = token.toString(); token.setLength(0); if (next.length() > 0) addComponent(namespaces, next); if (path.charAt(++pos ) == '/') addComponent(SKIP); break; default: token.append(ch); pos++; } } if (token.length() > 0) addComponent(namespaces, token.toString()); } }
[API] add NodePath methods: equals, hashCode, compareTo(NodePath) svn path=/trunk/eXist/; revision=12948
src/org/exist/storage/NodePath.java
[API] add NodePath methods: equals, hashCode, compareTo(NodePath)
<ide><path>rc/org/exist/storage/NodePath.java <ide> /** <ide> * @author wolf <ide> */ <del>public class NodePath { <add>public class NodePath implements Comparable<NodePath>{ <ide> <ide> private final static Logger LOG = Logger.getLogger(NodePath.class); <ide> <ide> if (token.length() > 0) <ide> addComponent(namespaces, token.toString()); <ide> } <add> <add> public boolean equals(Object obj) { <add> if (obj == null) return false; <add> <add> if (obj instanceof NodePath) { <add> NodePath nodePath = (NodePath) obj; <add> if (nodePath.pos == pos) { <add> for(int i = 0; i < pos; i++) { <add> if (!nodePath.components[i].equals(components[i])) { <add> return false; <add> } <add> } <add> return true; <add> } <add> } <add> <add> return false; <add> } <add> <add> public int hashCode() { <add> int h = 0; <add> for(int i = 0; i < pos; i++) { <add> h = 31*h + components[i].hashCode(); <add> } <add> return h; <add> } <add> <add> @Override <add> public int compareTo(NodePath o) { <add> return toString().compareTo(o.toString()); //TODO: optimize <add> } <ide> }
Java
apache-2.0
a93838e204e7a008c26cc1dfa2667862cad1ae39
0
walteryang47/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.job.ExecutionContext; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.bll.memory.MemoryImageRemover; import org.ovirt.engine.core.bll.network.MacPoolManager; import org.ovirt.engine.core.bll.network.VmInterfaceManager; import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageDependent; import org.ovirt.engine.core.bll.snapshots.SnapshotsManager; import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.DiskImagesValidator; import org.ovirt.engine.core.bll.validator.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.ImportVmParameters; import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo; import org.ovirt.engine.core.common.asynctasks.EntityInfo; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.CopyVolumeType; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.DiskImageDynamic; import org.ovirt.engine.core.common.businessentities.DiskInterface; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmStatistics; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmTemplateStatus; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.validation.group.ImportClonedEntity; import org.ovirt.engine.core.common.validation.group.ImportEntity; import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NotImplementedException; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.utils.GuidUtils; import org.ovirt.engine.core.utils.linq.Function; import org.ovirt.engine.core.utils.linq.LinqUtils; import org.ovirt.engine.core.utils.linq.Predicate; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.ovf.OvfLogEventHandler; import org.ovirt.engine.core.utils.ovf.VMStaticOvfLogHandler; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @DisableInPrepareMode @NonTransactiveCommandAttribute(forceCompensation = true) @LockIdNameAttribute public class ImportVmCommand extends MoveOrCopyTemplateCommand<ImportVmParameters> implements QuotaStorageDependent, TaskHandlerCommand<ImportVmParameters> { private static final Log log = LogFactory.getLog(ImportVmCommand.class); private static VmStatic vmStaticForDefaultValues = new VmStatic(); private List<DiskImage> imageList; private final List<Guid> diskGuidList = new ArrayList<Guid>(); private final List<Guid> imageGuidList = new ArrayList<Guid>(); private final List<String> macsAdded = new ArrayList<String>(); public ImportVmCommand(ImportVmParameters parameters) { super(parameters); setVmId(parameters.getContainerId()); setVm(parameters.getVm()); setVdsGroupId(parameters.getVdsGroupId()); if (parameters.getVm() != null && getVm().getDiskMap() != null) { imageList = new ArrayList<DiskImage>(); for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { imageList.add((DiskImage) disk); } } } ensureDomainMap(imageList, getParameters().getDestDomainId()); } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { if (!StringUtils.isBlank(getParameters().getVm().getName())) { return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } return null; } protected ImportVmCommand(Guid commandId) { super(commandId); } @Override public Guid getVmId() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm().getId(); } return super.getVmId(); } @Override public VM getVm() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm(); } return super.getVm(); } @Override protected boolean canDoAction() { Map<Guid, StorageDomain> domainsMap = new HashMap<Guid, StorageDomain>(); if (!canDoActionBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); } return canDoActionAfterCloneVm(domainsMap); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); } private void initImportClonedVm() { Guid guid = Guid.newGuid(); getVm().setId(guid); setVmId(guid); getVm().setName(getParameters().getVm().getName()); getVm().setStoragePoolId(getParameters().getStoragePoolId()); getParameters().setVm(getVm()); for (VmNetworkInterface iface : getVm().getInterfaces()) { iface.setId(Guid.newGuid()); } } private boolean canDoActionBeforeCloneVm(Map<Guid, StorageDomain> domainsMap) { List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); if (getVm() != null) { setDescription(getVmName()); } if (!checkStoragePool()) { return false; } Set<Guid> destGuids = new HashSet<Guid>(imageToDestinationDomainMap.values()); for (Guid destGuid : destGuids) { StorageDomain storageDomain = getStorageDomain(destGuid); StorageDomainValidator validator = new StorageDomainValidator(storageDomain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } domainsMap.put(destGuid, storageDomain); } if (getParameters().isImportAsNewEntity() && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORT_CLONE_NOT_COLLAPSED); } setSourceDomainId(getParameters().getSourceDomainId()); StorageDomainValidator validator = new StorageDomainValidator(getSourceDomain()); if (validator.isDomainExistAndActive().isValid() && getSourceDomain().getStorageDomainType() != StorageDomainType.ImportExport) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); } List<VM> vms = getVmsFromExportDomain(); if (vms == null) { return false; } VM vm = LinqUtils.firstOrNull(vms, new Predicate<VM>() { @Override public boolean eval(VM evalVm) { return evalVm.getId().equals(getParameters().getVm().getId()); } }); if (vm != null) { // At this point we should work with the VM that was read from // the OVF setVm(vm); // Iterate over all the VM images (active image and snapshots) for (DiskImage image : getVm().getImages()) { if (Guid.Empty.equals(image.getVmSnapshotId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CORRUPTED_VM_SNAPSHOT_ID); } if (getParameters().getCopyCollapse()) { // If copy collapse sent then iterate over the images got from the parameters, until we got // a match with the image from the VM. for (DiskImage p : imageList) { // copy the new disk volume format/type if provided, // only if requested by the user if (p.getImageId().equals(image.getImageId())) { if (p.getVolumeFormat() != null) { image.setvolumeFormat(p.getVolumeFormat()); } if (p.getVolumeType() != null) { image.setVolumeType(p.getVolumeType()); } // Validate the configuration of the image got from the parameters. if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } break; } } } else { // If no copy collapse sent, validate each image configuration (snapshot or active image). if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } } image.setStoragePoolId(getParameters().getStoragePoolId()); // we put the source domain id in order that copy will // work properly. // we fix it to DestDomainId in // MoveOrCopyAllImageGroups(); image.setStorageIds(new ArrayList<Guid>(Arrays.asList(getParameters().getSourceDomainId()))); } Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getVm().getImages()); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { Guid id = entry.getKey(); List<DiskImage> diskList = entry.getValue(); getVm().getDiskMap().put(id, diskList.get(diskList.size() - 1)); } } return true; } /** * Load images from Import/Export domain. * @return A {@link List} of {@link VM}s, or <code>null</code> if the query to the export domain failed. */ protected List<VM> getVmsFromExportDomain() { GetAllFromExportDomainQueryParameters p = new GetAllFromExportDomainQueryParameters (getParameters().getStoragePoolId(), getParameters().getSourceDomainId()); VdcQueryReturnValue qRetVal = getBackend().runInternalQuery(VdcQueryType.GetVmsFromExportDomain, p); return qRetVal.getSucceeded() ? (List<VM>) qRetVal.getReturnValue() : null; } private boolean validateImageConfig(List<String> canDoActionMessages, Map<Guid, StorageDomain> domainsMap, DiskImage image) { return ImagesHandler.CheckImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(image.getId())) .getStorageStaticData(), image, canDoActionMessages); } private boolean canDoActionAfterCloneVm(Map<Guid, StorageDomain> domainsMap) { VM vm = getParameters().getVm(); // check that the imported vm guid is not in engine if (!validateNoDuplicateVm()) { return false; } if (!validateNoDuplicateDiskImages(imageList)) { return false; } if (!validateDiskInterface(imageList)) { return false; } setVmTemplateId(getVm().getVmtGuid()); if (!templateExists() || !checkTemplateInStorageDomain() || !checkImagesGUIDsLegal() || !canAddVm()) { return false; } if (!VmTemplateHandler.BlankVmTemplateId.equals(getVm().getVmtGuid()) && getVmTemplate() != null && getVmTemplate().getStatus() == VmTemplateStatus.Locked) { return failCanDoAction(VdcBllMessages.VM_TEMPLATE_IMAGE_IS_LOCKED); } if (getParameters().getCopyCollapse() && vm.getDiskMap() != null) { for (Disk disk : vm.getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage key = (DiskImage) getVm().getDiskMap().get(disk.getId()); if (key != null) { if (!ImagesHandler.CheckImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(key.getId())) .getStorageStaticData(), (DiskImageBase) disk, getReturnValue().getCanDoActionMessages())) { return false; } } } } } // if collapse true we check that we have the template on source // (backup) domain if (getParameters().getCopyCollapse() && !isTemplateExistsOnExportDomain()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_IMPORTED_TEMPLATE_IS_MISSING); addCanDoActionMessage(String.format("$DomainName %1$s", getStorageDomainStaticDAO().get(getParameters().getSourceDomainId()).getStorageName())); return false; } if (!validateVdsCluster()) { return false; } Map<StorageDomain, Integer> domainMap = getSpaceRequirementsForStorageDomains(imageList); if (!setDomainsForMemoryImages(domainMap)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } for (Map.Entry<StorageDomain, Integer> entry : domainMap.entrySet()) { if (!doesStorageDomainhaveSpaceForRequest(entry.getKey(), entry.getValue())) { return false; } } if (!validateUsbPolicy()) { return false; } if (!validateMacAddress(getVm().getInterfaces())) { return false; } return true; } private Set<String> getMemoryVolumesToBeImported() { Set<String> memories = new HashSet<String>(); for (Snapshot snapshot : getVm().getSnapshots()) { memories.add(snapshot.getMemoryVolume()); } memories.remove(StringUtils.EMPTY); return memories; } /** * This method fills the given map of domain to the required size for storing memory images * within it, and also update the memory volume in each snapshot that has memory volume with * the right storage pool and storage domain where it is going to be imported. * * @param domain2requiredSize * Maps domain to size required for storing memory volumes in it * @return true if we managed to assign storage domain for every memory volume, false otherwise */ private boolean setDomainsForMemoryImages(Map<StorageDomain, Integer> domain2requiredSize) { Map<String, String> handledMemoryVolumes = new HashMap<String, String>(); for (Snapshot snapshot : getVm().getSnapshots()) { String memoryVolume = snapshot.getMemoryVolume(); if (memoryVolume.isEmpty()) { continue; } if (handledMemoryVolumes.containsKey(memoryVolume)) { // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(handledMemoryVolumes.get(memoryVolume)); continue; } VM vm = getVmFromSnapshot(snapshot); int requiredSizeForMemory = (int) Math.ceil((vm.getTotalMemorySizeInBytes() + HibernateVmCommand.META_DATA_SIZE_IN_BYTES) * 1.0 / BYTES_IN_GB); StorageDomain storageDomain = VmHandler.findStorageDomainForMemory( getParameters().getStoragePoolId(),requiredSizeForMemory, domain2requiredSize); if (storageDomain == null) { return false; } domain2requiredSize.put(storageDomain, domain2requiredSize.get(storageDomain) + requiredSizeForMemory); String modifiedMemoryVolume = createMemoryVolumeStringWithGivenDomainAndPool( memoryVolume, storageDomain, getParameters().getStoragePoolId()); // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(modifiedMemoryVolume); // save it in case we'll find other snapshots with the same memory volume handledMemoryVolumes.put(memoryVolume, modifiedMemoryVolume); } return true; } /** * Modified the given memory volume String representation to have the given storage * pool and storage domain */ private String createMemoryVolumeStringWithGivenDomainAndPool(String originalMemoryVolume, StorageDomain storageDomain, Guid storagePoolId) { List<Guid> guids = GuidUtils.getGuidListFromString(originalMemoryVolume); return String.format("%1$s,%2$s,%3$s,%4$s,%5$s,%6$s", storageDomain.getId().toString(), storagePoolId.toString(), guids.get(2), guids.get(3), guids.get(4), guids.get(5)); } /** * Validates that there is no duplicate VM. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateNoDuplicateVm() { VmStatic duplicateVm = getVmStaticDAO().get(getVm().getId()); if (duplicateVm != null) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_IMPORT_VM_EXISTS); addCanDoActionMessage(String.format("$VmName %1$s", duplicateVm.getName())); return false; } return true; } protected boolean isDiskExists(Guid id) { return getBaseDiskDao().exists(id); } protected boolean validateDiskInterface(Iterable<DiskImage> images) { for (DiskImage diskImage : images) { if (diskImage.getDiskInterface() == DiskInterface.VirtIO_SCSI && !FeatureSupported.virtIoScsi(getVdsGroup().getcompatibility_version())) { return failCanDoAction(VdcBllMessages.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); } } return true; } protected boolean validateNoDuplicateDiskImages(Iterable<DiskImage> images) { if (!getParameters().isImportAsNewEntity()) { DiskImagesValidator diskImagesValidator = new DiskImagesValidator(images); return validate(diskImagesValidator.diskImagesAlreadyExist()); } return true; } /** * Validates that that the required cluster exists. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateVdsCluster() { List<VDSGroup> groups = getVdsGroupDAO().getAllForStoragePool(getParameters().getStoragePoolId()); for (VDSGroup group : groups) { if (group.getId().equals(getParameters().getVdsGroupId())) { return true; } } return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } /** * Validates the USB policy. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateUsbPolicy() { VM vm = getParameters().getVm(); VmHandler.updateImportedVmUsbPolicy(vm.getStaticData()); return VmHandler.isUsbPolicyLegal(vm.getUsbPolicy(), vm.getOs(), getVdsGroup(), getReturnValue().getCanDoActionMessages()); } private boolean isTemplateExistsOnExportDomain() { if (VmTemplateHandler.BlankVmTemplateId.equals(getParameters().getVm().getVmtGuid())) { return true; } VdcQueryReturnValue qRetVal = Backend.getInstance().runInternalQuery( VdcQueryType.GetTemplatesFromExportDomain, new GetAllFromExportDomainQueryParameters(getParameters().getStoragePoolId(), getParameters().getSourceDomainId())); if (qRetVal.getSucceeded()) { Map<VmTemplate, ?> templates = (Map<VmTemplate, ?>) qRetVal.getReturnValue(); for (VmTemplate template : templates.keySet()) { if (getParameters().getVm().getVmtGuid().equals(template.getId())) { return true; } } } return false; } protected boolean checkTemplateInStorageDomain() { boolean retValue = getParameters().isImportAsNewEntity() || checkIfDisksExist(imageList); if (retValue && !VmTemplateHandler.BlankVmTemplateId.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { List<StorageDomain> domains = (List<StorageDomain>) Backend .getInstance() .runInternalQuery(VdcQueryType.GetStorageDomainsByVmTemplateId, new IdQueryParameters(getVm().getVmtGuid())).getReturnValue(); List<Guid> domainsId = LinqUtils.foreach(domains, new Function<StorageDomain, Guid>() { @Override public Guid eval(StorageDomain storageDomainStatic) { return storageDomainStatic.getId(); } }); if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } return retValue; } private boolean templateExists() { if (getVmTemplate() == null && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } return true; } protected boolean checkImagesGUIDsLegal() { for (DiskImage image : getVm().getImages()) { Guid imageGUID = image.getImageId(); Guid storagePoolId = image.getStoragePoolId() != null ? image.getStoragePoolId() : Guid.Empty; Guid storageDomainId = getParameters().getSourceDomainId(); Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; VDSReturnValue retValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DoesImageExist, new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId, imageGUID)); if (Boolean.FALSE.equals(retValue.getReturnValue())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); } } return true; } protected boolean canAddVm() { // Checking if a desktop with same name already exists if (VmHandler.isVmWithSameNameExistStatic(getVm().getName())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_IMPORT_VM_NAME_EXISTS); } return true; } @Override protected void executeCommand() { try { addVmToDb(); processImages(); // if there aren't tasks - we can just perform the end // vm related ops if (getReturnValue().getVdsmTaskIdList().isEmpty()) { endVmRelatedOps(); } } catch (RuntimeException e) { MacPoolManager.getInstance().freeMacs(macsAdded); throw e; } setSucceeded(true); } private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmInterfaces(); addVmStatistics(); getCompensationContext().stateChanged(); return null; } }); freeLock(); } private void processImages() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmImagesAndSnapshots(); updateSnapshotsFromExport(); moveOrCopyAllImageGroups(); VmDeviceUtils.addImportedDevices(getVm().getStaticData(), getParameters().isImportAsNewEntity()); VmHandler.LockVm(getVm().getId()); if (getParameters().isImportAsNewEntity()) { getParameters().setVm(getVm()); setVmId(getVm().getId()); } return null; } }); } @Override protected void moveOrCopyAllImageGroups() { moveOrCopyAllImageGroups(getVm().getId(), ImagesHandler.filterImageDisks(getVm().getDiskMap().values(), false, false)); copyAllMemoryImages(getVm().getId()); } private void copyAllMemoryImages(Guid containerId) { for (String memoryVolumes : getMemoryVolumesToBeImported()) { List<Guid> guids = GuidUtils.getGuidListFromString(memoryVolumes); // copy the memory dump image VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryDumpImage( containerId, guids.get(0), guids.get(2), guids.get(3)), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); // copy the memory configuration (of the VM) image vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryConfImage( containerId, guids.get(0), guids.get(4), guids.get(5)), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setParentParameters(getParameters()); if (getStoragePool().getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Preallocated); params.setVolumeFormat(VolumeFormat.RAW); } return params; } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryConfImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); // This volume is always of type 'sparse' and format 'cow' so no need to convert, // and there're no snapshots for it so no reason to use copy collapse params.setUseCopyCollapse(false); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setParentParameters(getParameters()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); return params; } @Override protected void moveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { int i = 0; for (DiskImage disk : disks) { VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForDisk(disk, containerID, i++), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "ImportVmCommand::MoveOrCopyAllImageGroups: Failed to copy disk!"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForDisk(DiskImage disk, Guid containerID, int i) { Guid destinationDomain = imageToDestinationDomainMap.get(diskGuidList.get(i)); MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, diskGuidList.get(i), imageGuidList.get(i), disk.getId(), disk.getImageId(), destinationDomain, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setUseCopyCollapse(getParameters().getCopyCollapse()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setQuotaId(disk.getQuotaId() != null ? disk.getQuotaId() : getParameters().getQuotaId()); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(diskGuidList.get(i))) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(diskGuidList.get(i)); params.setVolumeType(diskImageBase.getVolumeType()); params.setVolumeFormat(diskImageBase.getVolumeFormat()); } params.setParentParameters(getParameters()); return params; } protected void addVmImagesAndSnapshots() { Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getVm().getImages()); if (getParameters().getCopyCollapse()) { Guid snapshotId = Guid.newGuid(); int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = diskList.get(diskList.size() - 1); disk.setParentId(VmTemplateHandler.BlankVmTemplateId); disk.setImageTemplateId(VmTemplateHandler.BlankVmTemplateId); disk.setVmSnapshotId(snapshotId); disk.setActive(true); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(disk.getId())) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(disk.getId()); disk.setvolumeFormat(diskImageBase.getVolumeFormat()); disk.setVolumeType(diskImageBase.getVolumeType()); } setDiskStorageDomainInfo(disk); diskGuidList.add(disk.getId()); imageGuidList.add(disk.getImageId()); if (getParameters().isImportAsNewEntity()) { disk.setId(Guid.newGuid()); disk.setImageId(Guid.newGuid()); for (int i = 0; i < diskList.size() - 1; i++) { diskList.get(i).setId(disk.getId()); } } disk.setCreationDate(new Date()); saveImage(disk); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); saveBaseDisk(disk); saveDiskImageDynamic(disk); } Snapshot snapshot = addActiveSnapshot(snapshotId); getVm().setSnapshots(Arrays.asList(snapshot)); } else { Guid snapshotId = null; for (DiskImage disk : getVm().getImages()) { disk.setActive(false); setDiskStorageDomainInfo(disk); saveImage(disk); snapshotId = disk.getVmSnapshotId(); saveSnapshotIfNotExists(snapshotId, disk); saveDiskImageDynamic(disk); } int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = diskList.get(diskList.size() - 1); diskGuidList.add(disk.getId()); imageGuidList.add(disk.getImageId()); snapshotId = disk.getVmSnapshotId(); disk.setActive(true); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); updateImage(disk); saveBaseDisk(disk); } // Update active snapshot's data, since it was inserted as a regular snapshot. updateActiveSnapshot(snapshotId); } } private void setDiskStorageDomainInfo(DiskImage disk) { ArrayList<Guid> storageDomain = new ArrayList<Guid>(); storageDomain.add(imageToDestinationDomainMap.get(disk.getId())); disk.setStorageIds(storageDomain); } /** Saves the base disk object */ protected void saveBaseDisk(DiskImage disk) { getBaseDiskDao().save(disk); } /** Save the entire image, including it's storage mapping */ protected void saveImage(DiskImage disk) { BaseImagesCommand.saveImage(disk); } /** Updates an image of a disk */ protected void updateImage(DiskImage disk) { getImageDao().update(disk.getImage()); } /** * Generates and saves a {@link DiskImageDynamic} for the given {@link #disk}. * @param disk The imported disk **/ protected void saveDiskImageDynamic(DiskImage disk) { DiskImageDynamic diskDynamic = new DiskImageDynamic(); diskDynamic.setId(disk.getImageId()); diskDynamic.setactual_size(disk.getActualSizeInBytes()); getDiskImageDynamicDAO().save(diskDynamic); } /** * Saves a new active snapshot for the VM * @param snapshotId The ID to assign to the snapshot * @return The generated snapshot */ protected Snapshot addActiveSnapshot(Guid snapshotId) { return new SnapshotsManager(). addActiveSnapshot(snapshotId, getVm(), getMemoryVolumeForNewActiveSnapshot(), getCompensationContext()); } private String getMemoryVolumeForNewActiveSnapshot() { return getParameters().isImportAsNewEntity() ? // We currently don't support using memory that was // saved when a snapshot was taken for VM with different id StringUtils.EMPTY : getMemoryVolumeFromActiveSnapshotInExportDomain(); } private String getMemoryVolumeFromActiveSnapshotInExportDomain() { for (Snapshot snapshot : getVm().getSnapshots()) { if (snapshot.getType() == SnapshotType.ACTIVE) return snapshot.getMemoryVolume(); } log.warnFormat("VM {0} doesn't have active snapshot in export domain", getVmId()); return StringUtils.EMPTY; } /** * Go over the snapshots that were read from the export data. If the snapshot exists (since it was added for the * images), it will be updated. If it doesn't exist, it will be saved. */ private void updateSnapshotsFromExport() { if (getVm().getSnapshots() == null) { return; } for (Snapshot snapshot : getVm().getSnapshots()) { if (getSnapshotDao().exists(getVm().getId(), snapshot.getId())) { getSnapshotDao().update(snapshot); } else { getSnapshotDao().save(snapshot); } } } /** * Save a snapshot if it does not exist in the database. * @param snapshotId The snapshot to save. * @param disk The disk containing the snapshot's information. */ protected void saveSnapshotIfNotExists(Guid snapshotId, DiskImage disk) { if (!getSnapshotDao().exists(getVm().getId(), snapshotId)) { getSnapshotDao().save( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.REGULAR, disk.getDescription(), disk.getLastModifiedDate(), disk.getAppList())); } } /** * Update a snapshot and make it the active snapshot. * @param snapshotId The snapshot to update. */ protected void updateActiveSnapshot(Guid snapshotId) { getSnapshotDao().update( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.ACTIVE, "Active VM snapshot", new Date(), null)); } protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); } private int computeMinAllocatedMem() { int vmMem = getVm().getMemSizeMb(); int minAllocatedMem = vmMem; if (getVm().getMinAllocatedMem() > 0) { minAllocatedMem = getVm().getMinAllocatedMem(); } else { // first get cluster memory over commit value VDSGroup vdsGroup = getVdsGroupDAO().get(getVm().getVdsGroupId()); if (vdsGroup != null && vdsGroup.getmax_vds_memory_over_commit() > 0) { minAllocatedMem = (vmMem * 100) / vdsGroup.getmax_vds_memory_over_commit(); } } return minAllocatedMem; } private void logImportEvents() { // Some values at the OVF file are used for creating events at the GUI // for the sake of providing information on the content of the VM that // was exported, // but not setting it in the imported VM VmStatic vmStaticFromOvf = getVm().getStaticData(); OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(vmStaticFromOvf); Map<String, String> aliasesValuesMap = handler.getAliasesValuesMap(); for (Map.Entry<String, String> entry : aliasesValuesMap.entrySet()) { String fieldName = entry.getKey(); String fieldValue = entry.getValue(); logField(vmStaticFromOvf, fieldName, fieldValue); } handler.resetDefaults(vmStaticForDefaultValues); } private static void logField(VmStatic vmStaticFromOvf, String fieldName, String fieldValue) { String vmName = vmStaticFromOvf.getName(); AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("FieldName", fieldName); logable.addCustomValue("VmName", vmName); logable.addCustomValue("FieldValue", fieldValue); AuditLogDirector.log(logable, AuditLogType.VM_IMPORT_INFO); } protected void addVmInterfaces() { VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); List<String> invalidNetworkNames = new ArrayList<String>(); List<String> invalidIfaceNames = new ArrayList<String>(); Map<String, Network> networksInClusterByName = Entities.entitiesByName(getNetworkDAO().getAllForCluster(getVm().getVdsGroupId())); for (VmNetworkInterface iface : getVm().getInterfaces()) { initInterface(iface); if (!vmInterfaceManager.isValidVmNetwork(iface, networksInClusterByName)) { invalidNetworkNames.add(iface.getNetworkName()); invalidIfaceNames.add(iface.getName()); iface.setNetworkName(null); } vmInterfaceManager.add(iface, getCompensationContext(), getParameters().isImportAsNewEntity(), getVdsGroup().getcompatibility_version()); macsAdded.add(iface.getMacAddress()); } auditInvalidInterfaces(invalidNetworkNames, invalidIfaceNames); } private void initInterface(VmNetworkInterface iface) { if (iface.getId() == null) { iface.setId(Guid.newGuid()); } fillMacAddressIfMissing(iface); iface.setVmTemplateId(null); iface.setVmId(getVmId()); iface.setVmName(getVm().getName()); } private void addVmDynamic() { VmDynamic tempVar = new VmDynamic(); tempVar.setId(getVmId()); tempVar.setStatus(VMStatus.ImageLocked); tempVar.setVmHost(""); tempVar.setVmIp(""); tempVar.setAppList(getParameters().getVm().getDynamicData().getAppList()); getVmDynamicDAO().save(tempVar); getCompensationContext().snapshotNewEntity(tempVar); } private void addVmStatistics() { VmStatistics stats = new VmStatistics(); stats.setId(getVmId()); getVmStatisticsDAO().save(stats); getCompensationContext().snapshotNewEntity(stats); getCompensationContext().stateChanged(); } @Override protected void endSuccessfully() { endImportCommand(); } @Override protected void endActionOnAllImageGroups() { for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(getParameters().getTaskGroupSuccess()); getBackend().EndAction(getImagesActionType(), p); } } @Override protected void endWithFailure() { // Going to try and refresh the VM by re-loading it form DB setVm(null); if (getVm() != null) { endActionOnAllImageGroups(); removeVmNetworkInterfaces(); removeVmSnapshots(getVm()); getVmDynamicDAO().remove(getVmId()); getVmStatisticsDAO().remove(getVmId()); getVmStaticDAO().remove(getVmId()); setSucceeded(true); } else { setVm(getParameters().getVm()); // Setting VM from params, for logging purposes // No point in trying to end action again, as the imported VM does not exist in the DB. getReturnValue().setEndActionTryAgain(false); } } private void removeVmSnapshots(VM vm) { Collection<String> memoriesOfRemovedSnapshots = new SnapshotsManager().removeSnapshots(vm.getId()); new MemoryImageRemover(vm, this).removeMemoryVolumes(memoriesOfRemovedSnapshots); } protected void removeVmNetworkInterfaces() { new VmInterfaceManager().removeAll(getVmId()); } protected void endImportCommand() { endActionOnAllImageGroups(); endVmRelatedOps(); setSucceeded(true); } private void endVmRelatedOps() { setVm(null); if (getVm() != null) { VmHandler.UnLockVm(getVm()); } else { setCommandShouldBeLogged(false); log.warn("ImportVmCommand::EndImportCommand: Vm is null - not performing full EndAction"); } } @Override public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? AuditLogType.IMPORTEXPORT_STARTING_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_SUCCESS: return getSucceeded() ? AuditLogType.IMPORTEXPORT_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_FAILURE: return AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; } return super.getAuditLogTypeValue(); } @Override protected List<Class<?>> getValidationGroups() { if (getParameters().isImportAsNewEntity()) { return addValidationGroup(ImportClonedEntity.class); } return addValidationGroup(ImportEntity.class); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); // special permission is needed to use custom properties if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getVm().getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; } @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), (getVmName() == null) ? "" : getVmName()); jobProperties.put(VdcObjectType.VdsGroups.name().toLowerCase(), getVdsGroupName()); } return jobProperties; } @Override protected AuditLogType getAuditLogTypeForInvalidInterfaces() { return AuditLogType.IMPORTEXPORT_IMPORT_VM_INVALID_INTERFACES; } @Override public VDSGroup getVdsGroup() { return super.getVdsGroup(); } @Override public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); for (Disk disk : getParameters().getVm().getDiskMap().values()) { //TODO: handle import more than once; if(disk instanceof DiskImage){ DiskImage diskImage = (DiskImage)disk; list.add(new QuotaStorageConsumptionParameter( diskImage.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, imageToDestinationDomainMap.get(diskImage.getId()), (double)diskImage.getSizeInGigabytes())); } } return list; } /////////////////////////////////////// // TaskHandlerCommand Implementation // /////////////////////////////////////// public ImportVmParameters getParameters() { return super.getParameters(); } public VdcActionType getActionType() { return super.getActionType(); } public VdcReturnValueBase getReturnValue() { return super.getReturnValue(); } public ExecutionContext getExecutionContext() { return super.getExecutionContext(); } public void setExecutionContext(ExecutionContext executionContext) { super.setExecutionContext(executionContext); } public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, VdcObjectType entityType, Guid... entityIds) { return super.createTaskInCurrentTransaction(taskId, asyncTaskCreationInfo, parentCommand, entityType, entityIds); } public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand) { return super.createTask(taskId, asyncTaskCreationInfo, parentCommand); } public ArrayList<Guid> getTaskIdList() { return super.getTaskIdList(); } public void preventRollback() { throw new NotImplementedException(); } public Guid persistAsyncTaskPlaceHolder() { return super.persistAsyncTaskPlaceHolder(getActionType()); } public Guid persistAsyncTaskPlaceHolder(String taskKey) { return super.persistAsyncTaskPlaceHolder(getActionType(), taskKey); } }
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ImportVmCommand.java
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.job.ExecutionContext; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.bll.memory.MemoryImageRemover; import org.ovirt.engine.core.bll.network.MacPoolManager; import org.ovirt.engine.core.bll.network.VmInterfaceManager; import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter; import org.ovirt.engine.core.bll.quota.QuotaStorageDependent; import org.ovirt.engine.core.bll.snapshots.SnapshotsManager; import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.DiskImagesValidator; import org.ovirt.engine.core.bll.validator.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.ImportVmParameters; import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo; import org.ovirt.engine.core.common.asynctasks.EntityInfo; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.CopyVolumeType; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.DiskImageDynamic; import org.ovirt.engine.core.common.businessentities.DiskInterface; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus; import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmStatistics; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmTemplateStatus; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.validation.group.ImportClonedEntity; import org.ovirt.engine.core.common.validation.group.ImportEntity; import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NotImplementedException; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.utils.GuidUtils; import org.ovirt.engine.core.utils.linq.Function; import org.ovirt.engine.core.utils.linq.LinqUtils; import org.ovirt.engine.core.utils.linq.Predicate; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.ovf.OvfLogEventHandler; import org.ovirt.engine.core.utils.ovf.VMStaticOvfLogHandler; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @DisableInPrepareMode @NonTransactiveCommandAttribute(forceCompensation = true) @LockIdNameAttribute public class ImportVmCommand extends MoveOrCopyTemplateCommand<ImportVmParameters> implements QuotaStorageDependent, TaskHandlerCommand<ImportVmParameters> { private static final Log log = LogFactory.getLog(ImportVmCommand.class); private static VmStatic vmStaticForDefaultValues = new VmStatic(); private List<DiskImage> imageList; private final List<Guid> diskGuidList = new ArrayList<Guid>(); private final List<Guid> imageGuidList = new ArrayList<Guid>(); private final List<String> macsAdded = new ArrayList<String>(); public ImportVmCommand(ImportVmParameters parameters) { super(parameters); setVmId(parameters.getContainerId()); setVm(parameters.getVm()); setVdsGroupId(parameters.getVdsGroupId()); if (parameters.getVm() != null && getVm().getDiskMap() != null) { imageList = new ArrayList<DiskImage>(); for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { imageList.add((DiskImage) disk); } } } ensureDomainMap(imageList, getParameters().getDestDomainId()); } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { if (!StringUtils.isBlank(getParameters().getVm().getName())) { return Collections.singletonMap(getParameters().getVm().getName(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_NAME, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } return null; } protected ImportVmCommand(Guid commandId) { super(commandId); } @Override public Guid getVmId() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm().getId(); } return super.getVmId(); } @Override public VM getVm() { if (getParameters().isImportAsNewEntity()) { return getParameters().getVm(); } return super.getVm(); } @Override protected boolean canDoAction() { Map<Guid, StorageDomain> domainsMap = new HashMap<Guid, StorageDomain>(); if (!canDoActionBeforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); } return canDoActionAfterCloneVm(domainsMap); } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); } private void initImportClonedVm() { Guid guid = Guid.newGuid(); getVm().setId(guid); setVmId(guid); getVm().setName(getParameters().getVm().getName()); getVm().setStoragePoolId(getParameters().getStoragePoolId()); getParameters().setVm(getVm()); for (VmNetworkInterface iface : getVm().getInterfaces()) { iface.setId(Guid.newGuid()); } } private boolean canDoActionBeforeCloneVm(Map<Guid, StorageDomain> domainsMap) { List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); if (getVm() != null) { setDescription(getVmName()); } if (!checkStoragePool()) { return false; } Set<Guid> destGuids = new HashSet<Guid>(imageToDestinationDomainMap.values()); for (Guid destGuid : destGuids) { StorageDomain storageDomain = getStorageDomain(destGuid); StorageDomainValidator validator = new StorageDomainValidator(storageDomain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } domainsMap.put(destGuid, storageDomain); } if (getParameters().isImportAsNewEntity() && !getParameters().getCopyCollapse()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORT_CLONE_NOT_COLLAPSED); } setSourceDomainId(getParameters().getSourceDomainId()); StorageDomainValidator validator = new StorageDomainValidator(getSourceDomain()); if (validator.isDomainExistAndActive().isValid() && getSourceDomain().getStorageDomainType() != StorageDomainType.ImportExport) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); } List<VM> vms = getVmsFromExportDomain(); if (vms == null) { return false; } VM vm = LinqUtils.firstOrNull(vms, new Predicate<VM>() { @Override public boolean eval(VM evalVm) { return evalVm.getId().equals(getParameters().getVm().getId()); } }); if (vm != null) { // At this point we should work with the VM that was read from // the OVF setVm(vm); // Iterate over all the VM images (active image and snapshots) for (DiskImage image : getVm().getImages()) { if (Guid.Empty.equals(image.getVmSnapshotId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CORRUPTED_VM_SNAPSHOT_ID); } if (getParameters().getCopyCollapse()) { // If copy collapse sent then iterate over the images got from the parameters, until we got // a match with the image from the VM. for (DiskImage p : imageList) { // copy the new disk volume format/type if provided, // only if requested by the user if (p.getImageId().equals(image.getImageId())) { if (p.getVolumeFormat() != null) { image.setvolumeFormat(p.getVolumeFormat()); } if (p.getVolumeType() != null) { image.setVolumeType(p.getVolumeType()); } // Validate the configuration of the image got from the parameters. if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } break; } } } else { // If no copy collapse sent, validate each image configuration (snapshot or active image). if (!validateImageConfig(canDoActionMessages, domainsMap, image)) { return false; } } image.setStoragePoolId(getParameters().getStoragePoolId()); // we put the source domain id in order that copy will // work properly. // we fix it to DestDomainId in // MoveOrCopyAllImageGroups(); image.setStorageIds(new ArrayList<Guid>(Arrays.asList(getParameters().getSourceDomainId()))); } Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getVm().getImages()); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { Guid id = entry.getKey(); List<DiskImage> diskList = entry.getValue(); getVm().getDiskMap().put(id, diskList.get(diskList.size() - 1)); } } return true; } /** * Load images from Import/Export domain. * @return A {@link List} of {@link VM}s, or <code>null</code> if the query to the export domain failed. */ protected List<VM> getVmsFromExportDomain() { GetAllFromExportDomainQueryParameters p = new GetAllFromExportDomainQueryParameters (getParameters().getStoragePoolId(), getParameters().getSourceDomainId()); VdcQueryReturnValue qRetVal = getBackend().runInternalQuery(VdcQueryType.GetVmsFromExportDomain, p); if (!qRetVal.getSucceeded()) { return null; } return (List<VM>) qRetVal.getReturnValue(); } private boolean validateImageConfig(List<String> canDoActionMessages, Map<Guid, StorageDomain> domainsMap, DiskImage image) { return ImagesHandler.CheckImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(image.getId())) .getStorageStaticData(), image, canDoActionMessages); } private boolean canDoActionAfterCloneVm(Map<Guid, StorageDomain> domainsMap) { VM vm = getParameters().getVm(); // check that the imported vm guid is not in engine if (!validateNoDuplicateVm()) { return false; } if (!validateNoDuplicateDiskImages(imageList)) { return false; } if (!validateDiskInterface(imageList)) { return false; } setVmTemplateId(getVm().getVmtGuid()); if (!templateExists() || !checkTemplateInStorageDomain() || !checkImagesGUIDsLegal() || !canAddVm()) { return false; } if (!VmTemplateHandler.BlankVmTemplateId.equals(getVm().getVmtGuid()) && getVmTemplate() != null && getVmTemplate().getStatus() == VmTemplateStatus.Locked) { return failCanDoAction(VdcBllMessages.VM_TEMPLATE_IMAGE_IS_LOCKED); } if (getParameters().getCopyCollapse() && vm.getDiskMap() != null) { for (Disk disk : vm.getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage key = (DiskImage) getVm().getDiskMap().get(disk.getId()); if (key != null) { if (!ImagesHandler.CheckImageConfiguration(domainsMap.get(imageToDestinationDomainMap.get(key.getId())) .getStorageStaticData(), (DiskImageBase) disk, getReturnValue().getCanDoActionMessages())) { return false; } } } } } // if collapse true we check that we have the template on source // (backup) domain if (getParameters().getCopyCollapse() && !templateExistsOnExportDomain()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_IMPORTED_TEMPLATE_IS_MISSING); addCanDoActionMessage(String.format("$DomainName %1$s", getStorageDomainStaticDAO().get(getParameters().getSourceDomainId()).getStorageName())); return false; } if (!validateVdsCluster()) { return false; } Map<StorageDomain, Integer> domainMap = getSpaceRequirementsForStorageDomains(imageList); if (!setDomainsForMemoryImages(domainMap)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } for (Map.Entry<StorageDomain, Integer> entry : domainMap.entrySet()) { if (!doesStorageDomainhaveSpaceForRequest(entry.getKey(), entry.getValue())) { return false; } } if (!validateUsbPolicy()) { return false; } if (!validateMacAddress(getVm().getInterfaces())) { return false; } return true; } private Set<String> getMemoryVolumesToBeImported() { Set<String> memories = new HashSet<String>(); for (Snapshot snapshot : getVm().getSnapshots()) { memories.add(snapshot.getMemoryVolume()); } memories.remove(StringUtils.EMPTY); return memories; } /** * This method fills the given map of domain to the required size for storing memory images * within it, and also update the memory volume in each snapshot that has memory volume with * the right storage pool and storage domain where it is going to be imported. * * @param domain2requiredSize * Maps domain to size required for storing memory volumes in it * @return true if we managed to assign storage domain for every memory volume, false otherwise */ private boolean setDomainsForMemoryImages(Map<StorageDomain, Integer> domain2requiredSize) { Map<String, String> handledMemoryVolumes = new HashMap<String, String>(); for (Snapshot snapshot : getVm().getSnapshots()) { String memoryVolume = snapshot.getMemoryVolume(); if (memoryVolume.isEmpty()) { continue; } if (handledMemoryVolumes.containsKey(memoryVolume)) { // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(handledMemoryVolumes.get(memoryVolume)); continue; } VM vm = getVmFromSnapshot(snapshot); int requiredSizeForMemory = (int) Math.ceil((vm.getTotalMemorySizeInBytes() + HibernateVmCommand.META_DATA_SIZE_IN_BYTES) * 1.0 / BYTES_IN_GB); StorageDomain storageDomain = VmHandler.findStorageDomainForMemory( getParameters().getStoragePoolId(),requiredSizeForMemory, domain2requiredSize); if (storageDomain == null) { return false; } domain2requiredSize.put(storageDomain, domain2requiredSize.get(storageDomain) + requiredSizeForMemory); String modifiedMemoryVolume = createMemoryVolumeStringWithGivenDomainAndPool( memoryVolume, storageDomain, getParameters().getStoragePoolId()); // replace the volume representation with the one with the correct domain & pool snapshot.setMemoryVolume(modifiedMemoryVolume); // save it in case we'll find other snapshots with the same memory volume handledMemoryVolumes.put(memoryVolume, modifiedMemoryVolume); } return true; } /** * Modified the given memory volume String representation to have the given storage * pool and storage domain */ private String createMemoryVolumeStringWithGivenDomainAndPool(String originalMemoryVolume, StorageDomain storageDomain, Guid storagePoolId) { List<Guid> guids = GuidUtils.getGuidListFromString(originalMemoryVolume); return String.format("%1$s,%2$s,%3$s,%4$s,%5$s,%6$s", storageDomain.getId().toString(), storagePoolId.toString(), guids.get(2), guids.get(3), guids.get(4), guids.get(5)); } /** * Validates that there is no duplicate VM. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateNoDuplicateVm() { VmStatic duplicateVm = getVmStaticDAO().get(getVm().getId()); if (duplicateVm != null) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_IMPORT_VM_EXISTS); addCanDoActionMessage(String.format("$VmName %1$s", duplicateVm.getName())); return false; } return true; } protected boolean isDiskExists(Guid id) { return getBaseDiskDao().exists(id); } protected boolean validateDiskInterface(Iterable<DiskImage> images) { for (DiskImage diskImage : images) { if (diskImage.getDiskInterface() == DiskInterface.VirtIO_SCSI && !FeatureSupported.virtIoScsi(getVdsGroup().getcompatibility_version())) { addCanDoActionMessage(VdcBllMessages.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); return false; } } return true; } protected boolean validateNoDuplicateDiskImages(Iterable<DiskImage> images) { if (!getParameters().isImportAsNewEntity()) { DiskImagesValidator diskImagesValidator = new DiskImagesValidator(images); return validate(diskImagesValidator.diskImagesAlreadyExist()); } return true; } /** * Validates that that the required cluster exists. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateVdsCluster() { List<VDSGroup> groups = getVdsGroupDAO().getAllForStoragePool(getParameters().getStoragePoolId()); for (VDSGroup group : groups) { if (group.getId().equals(getParameters().getVdsGroupId())) { return true; } } return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } /** * Validates the USB policy. * @return <code>true</code> if the validation passes, <code>false</code> otherwise. */ protected boolean validateUsbPolicy() { VM vm = getParameters().getVm(); VmHandler.updateImportedVmUsbPolicy(vm.getStaticData()); return VmHandler.isUsbPolicyLegal(vm.getUsbPolicy(), vm.getOs(), getVdsGroup(), getReturnValue().getCanDoActionMessages()); } private boolean templateExistsOnExportDomain() { boolean retVal = false; if (!VmTemplateHandler.BlankVmTemplateId.equals(getParameters().getVm().getVmtGuid())) { GetAllFromExportDomainQueryParameters tempVar = new GetAllFromExportDomainQueryParameters(getParameters() .getStoragePoolId(), getParameters().getSourceDomainId()); VdcQueryReturnValue qretVal = Backend.getInstance().runInternalQuery( VdcQueryType.GetTemplatesFromExportDomain, tempVar); if (qretVal.getSucceeded()) { Map templates = (Map) qretVal.getReturnValue(); for (Object template : templates.keySet()) { if (getParameters().getVm().getVmtGuid().equals(((VmTemplate) template).getId())) { retVal = true; break; } } } } else { retVal = true; } return retVal; } protected boolean checkTemplateInStorageDomain() { boolean retValue = getParameters().isImportAsNewEntity() || checkIfDisksExist(imageList); if (retValue && !VmTemplateHandler.BlankVmTemplateId.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { List<StorageDomain> domains = (List<StorageDomain>) Backend .getInstance() .runInternalQuery(VdcQueryType.GetStorageDomainsByVmTemplateId, new IdQueryParameters(getVm().getVmtGuid())).getReturnValue(); List<Guid> domainsId = LinqUtils.foreach(domains, new Function<StorageDomain, Guid>() { @Override public Guid eval(StorageDomain storageDomainStatic) { return storageDomainStatic.getId(); } }); if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { retValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } return retValue; } private boolean templateExists() { if (getVmTemplate() == null && !getParameters().getCopyCollapse()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); return false; } return true; } protected boolean checkImagesGUIDsLegal() { for (DiskImage image : getVm().getImages()) { Guid imageGUID = image.getImageId(); Guid storagePoolId = image.getStoragePoolId() != null ? image.getStoragePoolId() : Guid.Empty; Guid storageDomainId = getParameters().getSourceDomainId(); Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; VDSReturnValue retValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DoesImageExist, new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId, imageGUID)); if (Boolean.FALSE.equals(retValue.getReturnValue())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); return false; } } return true; } protected boolean canAddVm() { // Checking if a desktop with same name already exists boolean exists = VmHandler.isVmWithSameNameExistStatic(getVm().getName()); if (exists) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_IMPORT_VM_NAME_EXISTS); } return !exists; } @Override protected void executeCommand() { try { addVmToDb(); processImages(); // if there aren't tasks - we can just perform the end // vm related ops if (getReturnValue().getVdsmTaskIdList().isEmpty()) { endVmRelatedOps(); } } catch (RuntimeException e) { MacPoolManager.getInstance().freeMacs(macsAdded); throw e; } setSucceeded(true); } private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmInterfaces(); addVmStatistics(); getCompensationContext().stateChanged(); return null; } }); freeLock(); } private void processImages() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmImagesAndSnapshots(); updateSnapshotsFromExport(); moveOrCopyAllImageGroups(); VmDeviceUtils.addImportedDevices(getVm().getStaticData(), getParameters().isImportAsNewEntity()); VmHandler.LockVm(getVm().getId()); if (getParameters().isImportAsNewEntity()) { getParameters().setVm(getVm()); setVmId(getVm().getId()); } return null; } }); } @Override protected void moveOrCopyAllImageGroups() { moveOrCopyAllImageGroups(getVm().getId(), ImagesHandler.filterImageDisks(getVm().getDiskMap().values(), false, false)); copyAllMemoryImages(getVm().getId()); } private void copyAllMemoryImages(Guid containerId) { for (String memoryVolumes : getMemoryVolumesToBeImported()) { List<Guid> guids = GuidUtils.getGuidListFromString(memoryVolumes); // copy the memory dump image VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryDumpImage( containerId, guids.get(0), guids.get(2), guids.get(3)), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); // copy the memory configuration (of the VM) image vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForMemoryConfImage( containerId, guids.get(0), guids.get(4), guids.get(5)), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "Failed during ExportVmCommand"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setParentParameters(getParameters()); if (getStoragePool().getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Preallocated); params.setVolumeFormat(VolumeFormat.RAW); } return params; } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryConfImage(Guid containerID, Guid storageId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, imageId, volumeId, storageId, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); // This volume is always of type 'sparse' and format 'cow' so no need to convert, // and there're no snapshots for it so no reason to use copy collapse params.setUseCopyCollapse(false); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setParentParameters(getParameters()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); return params; } @Override protected void moveOrCopyAllImageGroups(Guid containerID, Iterable<DiskImage> disks) { int i = 0; for (DiskImage disk : disks) { VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction( VdcActionType.CopyImageGroup, buildMoveOrCopyImageGroupParametersForDisk(disk, containerID, i++), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!vdcRetValue.getSucceeded()) { throw new VdcBLLException(vdcRetValue.getFault().getError(), "ImportVmCommand::MoveOrCopyAllImageGroups: Failed to copy disk!"); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } } private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForDisk(DiskImage disk, Guid containerID, int i) { Guid destinationDomain = imageToDestinationDomainMap.get(diskGuidList.get(i)); MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, diskGuidList.get(i), imageGuidList.get(i), disk.getId(), disk.getImageId(), destinationDomain, getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setUseCopyCollapse(getParameters().getCopyCollapse()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(getParameters().getSourceDomainId()); params.setStoragePoolId(getParameters().getStoragePoolId()); params.setImportEntity(true); params.setEntityInfo(new EntityInfo(VdcObjectType.VM, getVm().getId())); params.setQuotaId(disk.getQuotaId() != null ? disk.getQuotaId() : getParameters().getQuotaId()); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(diskGuidList.get(i))) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(diskGuidList.get(i)); params.setVolumeType(diskImageBase.getVolumeType()); params.setVolumeFormat(diskImageBase.getVolumeFormat()); } params.setParentParameters(getParameters()); return params; } protected void addVmImagesAndSnapshots() { Map<Guid, List<DiskImage>> images = ImagesHandler.getImagesLeaf(getVm().getImages()); if (getParameters().getCopyCollapse()) { Guid snapshotId = Guid.newGuid(); int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = diskList.get(diskList.size() - 1); disk.setParentId(VmTemplateHandler.BlankVmTemplateId); disk.setImageTemplateId(VmTemplateHandler.BlankVmTemplateId); disk.setVmSnapshotId(snapshotId); disk.setActive(true); if (getParameters().getVm().getDiskMap() != null && getParameters().getVm().getDiskMap().containsKey(disk.getId())) { DiskImageBase diskImageBase = (DiskImageBase) getParameters().getVm().getDiskMap().get(disk.getId()); disk.setvolumeFormat(diskImageBase.getVolumeFormat()); disk.setVolumeType(diskImageBase.getVolumeType()); } setDiskStorageDomainInfo(disk); diskGuidList.add(disk.getId()); imageGuidList.add(disk.getImageId()); if (getParameters().isImportAsNewEntity()) { disk.setId(Guid.newGuid()); disk.setImageId(Guid.newGuid()); for (int i = 0; i < diskList.size() - 1; i++) { diskList.get(i).setId(disk.getId()); } } disk.setCreationDate(new Date()); saveImage(disk); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); saveBaseDisk(disk); saveDiskImageDynamic(disk); } Snapshot snapshot = addActiveSnapshot(snapshotId); getVm().setSnapshots(Arrays.asList(snapshot)); } else { Guid snapshotId = null; for (DiskImage disk : getVm().getImages()) { disk.setActive(false); setDiskStorageDomainInfo(disk); saveImage(disk); snapshotId = disk.getVmSnapshotId(); saveSnapshotIfNotExists(snapshotId, disk); saveDiskImageDynamic(disk); } int aliasCounter = 0; for (List<DiskImage> diskList : images.values()) { DiskImage disk = diskList.get(diskList.size() - 1); diskGuidList.add(disk.getId()); imageGuidList.add(disk.getImageId()); snapshotId = disk.getVmSnapshotId(); disk.setActive(true); ImagesHandler.setDiskAlias(disk, getVm(), ++aliasCounter); updateImage(disk); saveBaseDisk(disk); } // Update active snapshot's data, since it was inserted as a regular snapshot. updateActiveSnapshot(snapshotId); } } private void setDiskStorageDomainInfo(DiskImage disk) { ArrayList<Guid> storageDomain = new ArrayList<Guid>(); storageDomain.add(imageToDestinationDomainMap.get(disk.getId())); disk.setStorageIds(storageDomain); } /** Saves the base disk object */ protected void saveBaseDisk(DiskImage disk) { getBaseDiskDao().save(disk); } /** Save the entire image, including it's storage mapping */ protected void saveImage(DiskImage disk) { BaseImagesCommand.saveImage(disk); } /** Updates an image of a disk */ protected void updateImage(DiskImage disk) { getImageDao().update(disk.getImage()); } /** * Generates and saves a {@link DiskImageDynamic} for the given {@link #disk}. * @param disk The imported disk **/ protected void saveDiskImageDynamic(DiskImage disk) { DiskImageDynamic diskDynamic = new DiskImageDynamic(); diskDynamic.setId(disk.getImageId()); diskDynamic.setactual_size(disk.getActualSizeInBytes()); getDiskImageDynamicDAO().save(diskDynamic); } /** * Saves a new active snapshot for the VM * @param snapshotId The ID to assign to the snapshot * @return The generated snapshot */ protected Snapshot addActiveSnapshot(Guid snapshotId) { return new SnapshotsManager(). addActiveSnapshot(snapshotId, getVm(), getMemoryVolumeForNewActiveSnapshot(), getCompensationContext()); } private String getMemoryVolumeForNewActiveSnapshot() { return getParameters().isImportAsNewEntity() ? // We currently don't support using memory that was // saved when a snapshot was taken for VM with different id StringUtils.EMPTY : getMemoryVolumeFromActiveSnapshotInExportDomain(); } private String getMemoryVolumeFromActiveSnapshotInExportDomain() { for (Snapshot snapshot : getVm().getSnapshots()) { if (snapshot.getType() == SnapshotType.ACTIVE) return snapshot.getMemoryVolume(); } log.warnFormat("VM {0} doesn't have active snapshot in export domain", getVmId()); return StringUtils.EMPTY; } /** * Go over the snapshots that were read from the export data. If the snapshot exists (since it was added for the * images), it will be updated. If it doesn't exist, it will be saved. */ private void updateSnapshotsFromExport() { if (getVm().getSnapshots() != null) { for (Snapshot snapshot : getVm().getSnapshots()) { if (getSnapshotDao().exists(getVm().getId(), snapshot.getId())) { getSnapshotDao().update(snapshot); } else { getSnapshotDao().save(snapshot); } } } } /** * Save a snapshot if it does not exist in the database. * @param snapshotId The snapshot to save. * @param disk The disk containing the snapshot's information. */ protected void saveSnapshotIfNotExists(Guid snapshotId, DiskImage disk) { if (!getSnapshotDao().exists(getVm().getId(), snapshotId)) { getSnapshotDao().save( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.REGULAR, disk.getDescription(), disk.getLastModifiedDate(), disk.getAppList())); } } /** * Update a snapshot and make it the active snapshot. * @param snapshotId The snapshot to update. */ protected void updateActiveSnapshot(Guid snapshotId) { getSnapshotDao().update( new Snapshot(snapshotId, SnapshotStatus.OK, getVm().getId(), null, SnapshotType.ACTIVE, "Active VM snapshot", new Date(), null)); } protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); } private int computeMinAllocatedMem() { int vmMem = getVm().getMemSizeMb(); int minAllocatedMem = vmMem; if (getVm().getMinAllocatedMem() > 0) { minAllocatedMem = getVm().getMinAllocatedMem(); } else { // first get cluster memory over commit value VDSGroup vdsGroup = getVdsGroupDAO().get(getVm().getVdsGroupId()); if (vdsGroup != null && vdsGroup.getmax_vds_memory_over_commit() > 0) { minAllocatedMem = (vmMem * 100) / vdsGroup.getmax_vds_memory_over_commit(); } } return minAllocatedMem; } private void logImportEvents() { // Some values at the OVF file are used for creating events at the GUI // for the sake of providing information on the content of the VM that // was exported, // but not setting it in the imported VM VmStatic vmStaticFromOvf = getVm().getStaticData(); OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(vmStaticFromOvf); Map<String, String> aliasesValuesMap = handler.getAliasesValuesMap(); for (Map.Entry<String, String> entry : aliasesValuesMap.entrySet()) { String fieldName = entry.getKey(); String fieldValue = entry.getValue(); logField(vmStaticFromOvf, fieldName, fieldValue); } handler.resetDefaults(vmStaticForDefaultValues); } private static void logField(VmStatic vmStaticFromOvf, String fieldName, String fieldValue) { String vmName = vmStaticFromOvf.getName(); AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("FieldName", fieldName); logable.addCustomValue("VmName", vmName); logable.addCustomValue("FieldValue", fieldValue); AuditLogDirector.log(logable, AuditLogType.VM_IMPORT_INFO); } protected void addVmInterfaces() { VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); List<String> invalidNetworkNames = new ArrayList<String>(); List<String> invalidIfaceNames = new ArrayList<String>(); Map<String, Network> networksInClusterByName = Entities.entitiesByName(getNetworkDAO().getAllForCluster(getVm().getVdsGroupId())); for (VmNetworkInterface iface : getVm().getInterfaces()) { initInterface(iface); if (!vmInterfaceManager.isValidVmNetwork(iface, networksInClusterByName)) { invalidNetworkNames.add(iface.getNetworkName()); invalidIfaceNames.add(iface.getName()); iface.setNetworkName(null); } vmInterfaceManager.add(iface, getCompensationContext(), getParameters().isImportAsNewEntity(), getVdsGroup().getcompatibility_version()); macsAdded.add(iface.getMacAddress()); } auditInvalidInterfaces(invalidNetworkNames, invalidIfaceNames); } private void initInterface(VmNetworkInterface iface) { if (iface.getId() == null) { iface.setId(Guid.newGuid()); } fillMacAddressIfMissing(iface); iface.setVmTemplateId(null); iface.setVmId(getVmId()); iface.setVmName(getVm().getName()); } private void addVmDynamic() { VmDynamic tempVar = new VmDynamic(); tempVar.setId(getVmId()); tempVar.setStatus(VMStatus.ImageLocked); tempVar.setVmHost(""); tempVar.setVmIp(""); tempVar.setAppList(getParameters().getVm().getDynamicData().getAppList()); getVmDynamicDAO().save(tempVar); getCompensationContext().snapshotNewEntity(tempVar); } private void addVmStatistics() { VmStatistics stats = new VmStatistics(); stats.setId(getVmId()); getVmStatisticsDAO().save(stats); getCompensationContext().snapshotNewEntity(stats); getCompensationContext().stateChanged(); } @Override protected void endSuccessfully() { endImportCommand(); } @Override protected void endActionOnAllImageGroups() { for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(getParameters().getTaskGroupSuccess()); getBackend().EndAction(getImagesActionType(), p); } } @Override protected void endWithFailure() { // Going to try and refresh the VM by re-loading it form DB setVm(null); if (getVm() != null) { endActionOnAllImageGroups(); removeVmNetworkInterfaces(); removeVmSnapshots(getVm()); getVmDynamicDAO().remove(getVmId()); getVmStatisticsDAO().remove(getVmId()); getVmStaticDAO().remove(getVmId()); setSucceeded(true); } else { setVm(getParameters().getVm()); // Setting VM from params, for logging purposes // No point in trying to end action again, as the imported VM does not exist in the DB. getReturnValue().setEndActionTryAgain(false); } } private void removeVmSnapshots(VM vm) { Collection<String> memoriesOfRemovedSnapshots = new SnapshotsManager().removeSnapshots(vm.getId()); new MemoryImageRemover(vm, this).removeMemoryVolumes(memoriesOfRemovedSnapshots); } protected void removeVmNetworkInterfaces() { new VmInterfaceManager().removeAll(getVmId()); } protected void endImportCommand() { endActionOnAllImageGroups(); endVmRelatedOps(); setSucceeded(true); } private void endVmRelatedOps() { setVm(null); if (getVm() != null) { VmHandler.UnLockVm(getVm()); } else { setCommandShouldBeLogged(false); log.warn("ImportVmCommand::EndImportCommand: Vm is null - not performing full EndAction"); } } @Override public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? AuditLogType.IMPORTEXPORT_STARTING_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_SUCCESS: return getSucceeded() ? AuditLogType.IMPORTEXPORT_IMPORT_VM : AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; case END_FAILURE: return AuditLogType.IMPORTEXPORT_IMPORT_VM_FAILED; } return super.getAuditLogTypeValue(); } @Override protected List<Class<?>> getValidationGroups() { if (getParameters().isImportAsNewEntity()) { return addValidationGroup(ImportClonedEntity.class); } return addValidationGroup(ImportEntity.class); } @Override public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); // special permission is needed to use custom properties if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getVm().getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; } @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), (getVmName() == null) ? "" : getVmName()); jobProperties.put(VdcObjectType.VdsGroups.name().toLowerCase(), getVdsGroupName()); } return jobProperties; } @Override protected AuditLogType getAuditLogTypeForInvalidInterfaces() { return AuditLogType.IMPORTEXPORT_IMPORT_VM_INVALID_INTERFACES; } @Override public VDSGroup getVdsGroup() { return super.getVdsGroup(); } @Override public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); for (Disk disk : getParameters().getVm().getDiskMap().values()) { //TODO: handle import more than once; if(disk instanceof DiskImage){ DiskImage diskImage = (DiskImage)disk; list.add(new QuotaStorageConsumptionParameter( diskImage.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, imageToDestinationDomainMap.get(diskImage.getId()), (double)diskImage.getSizeInGigabytes())); } } return list; } /////////////////////////////////////// // TaskHandlerCommand Implementation // /////////////////////////////////////// public ImportVmParameters getParameters() { return super.getParameters(); } public VdcActionType getActionType() { return super.getActionType(); } public VdcReturnValueBase getReturnValue() { return super.getReturnValue(); } public ExecutionContext getExecutionContext() { return super.getExecutionContext(); } public void setExecutionContext(ExecutionContext executionContext) { super.setExecutionContext(executionContext); } public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, VdcObjectType entityType, Guid... entityIds) { return super.createTaskInCurrentTransaction(taskId, asyncTaskCreationInfo, parentCommand, entityType, entityIds); } public Guid createTask(Guid taskId, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand) { return super.createTask(taskId, asyncTaskCreationInfo, parentCommand); } public ArrayList<Guid> getTaskIdList() { return super.getTaskIdList(); } public void preventRollback() { throw new NotImplementedException(); } public Guid persistAsyncTaskPlaceHolder() { return super.persistAsyncTaskPlaceHolder(getActionType()); } public Guid persistAsyncTaskPlaceHolder(String taskKey) { return super.persistAsyncTaskPlaceHolder(getActionType(), taskKey); } }
core: some cleanup in ImportVmCommand - Replace AddCanDoActionMessage calls and 'return false' right after them with calls to failCanDoAction - Refactor templateExistsOnExportDomain method to reduce the number of nested levels in it - Rename templateExistsOnExportDomain to isTemplateExistsOnExportDomain - Refactor updateSnapshotsFromExport method to reduce the number of nested levels in it - Simplified canAddVm method by removing the 'exists' field Change-Id: Ibfdb7bba0758cfccb55bc237f22659cb1993cc00 Signed-off-by: Arik Hadas <[email protected]>
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ImportVmCommand.java
core: some cleanup in ImportVmCommand
<ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ImportVmCommand.java <ide> new GetAllFromExportDomainQueryParameters <ide> (getParameters().getStoragePoolId(), getParameters().getSourceDomainId()); <ide> VdcQueryReturnValue qRetVal = getBackend().runInternalQuery(VdcQueryType.GetVmsFromExportDomain, p); <del> <del> if (!qRetVal.getSucceeded()) { <del> return null; <del> } <del> <del> return (List<VM>) qRetVal.getReturnValue(); <add> return qRetVal.getSucceeded() ? (List<VM>) qRetVal.getReturnValue() : null; <ide> } <ide> <ide> private boolean validateImageConfig(List<String> canDoActionMessages, <ide> <ide> // if collapse true we check that we have the template on source <ide> // (backup) domain <del> if (getParameters().getCopyCollapse() && !templateExistsOnExportDomain()) { <add> if (getParameters().getCopyCollapse() && !isTemplateExistsOnExportDomain()) { <ide> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_IMPORTED_TEMPLATE_IS_MISSING); <ide> addCanDoActionMessage(String.format("$DomainName %1$s", <ide> getStorageDomainStaticDAO().get(getParameters().getSourceDomainId()).getStorageName())); <ide> for (DiskImage diskImage : images) { <ide> if (diskImage.getDiskInterface() == DiskInterface.VirtIO_SCSI && <ide> !FeatureSupported.virtIoScsi(getVdsGroup().getcompatibility_version())) { <del> addCanDoActionMessage(VdcBllMessages.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); <del> return false; <add> return failCanDoAction(VdcBllMessages.VIRTIO_SCSI_INTERFACE_IS_NOT_AVAILABLE_FOR_CLUSTER_LEVEL); <ide> } <ide> } <ide> <ide> getReturnValue().getCanDoActionMessages()); <ide> } <ide> <del> private boolean templateExistsOnExportDomain() { <del> boolean retVal = false; <del> if (!VmTemplateHandler.BlankVmTemplateId.equals(getParameters().getVm().getVmtGuid())) { <del> GetAllFromExportDomainQueryParameters tempVar = new GetAllFromExportDomainQueryParameters(getParameters() <del> .getStoragePoolId(), getParameters().getSourceDomainId()); <del> VdcQueryReturnValue qretVal = Backend.getInstance().runInternalQuery( <del> VdcQueryType.GetTemplatesFromExportDomain, tempVar); <del> <del> if (qretVal.getSucceeded()) { <del> Map templates = (Map) qretVal.getReturnValue(); <del> <del> for (Object template : templates.keySet()) { <del> if (getParameters().getVm().getVmtGuid().equals(((VmTemplate) template).getId())) { <del> retVal = true; <del> break; <del> } <add> private boolean isTemplateExistsOnExportDomain() { <add> if (VmTemplateHandler.BlankVmTemplateId.equals(getParameters().getVm().getVmtGuid())) { <add> return true; <add> } <add> <add> VdcQueryReturnValue qRetVal = Backend.getInstance().runInternalQuery( <add> VdcQueryType.GetTemplatesFromExportDomain, <add> new GetAllFromExportDomainQueryParameters(getParameters().getStoragePoolId(), <add> getParameters().getSourceDomainId())); <add> <add> if (qRetVal.getSucceeded()) { <add> Map<VmTemplate, ?> templates = (Map<VmTemplate, ?>) qRetVal.getReturnValue(); <add> <add> for (VmTemplate template : templates.keySet()) { <add> if (getParameters().getVm().getVmtGuid().equals(template.getId())) { <add> return true; <ide> } <ide> } <del> } else { <del> retVal = true; <del> } <del> return retVal; <del> <add> } <add> return false; <ide> } <ide> <ide> protected boolean checkTemplateInStorageDomain() { <ide> }); <ide> <ide> if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { <del> retValue = false; <del> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); <add> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); <ide> } <ide> } <ide> return retValue; <ide> <ide> private boolean templateExists() { <ide> if (getVmTemplate() == null && !getParameters().getCopyCollapse()) { <del> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); <del> return false; <add> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); <ide> } <ide> return true; <ide> } <ide> imageGUID)); <ide> <ide> if (Boolean.FALSE.equals(retValue.getReturnValue())) { <del> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); <del> return false; <add> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); <ide> } <ide> } <ide> return true; <ide> <ide> protected boolean canAddVm() { <ide> // Checking if a desktop with same name already exists <del> boolean exists = VmHandler.isVmWithSameNameExistStatic(getVm().getName()); <del> <del> if (exists) { <del> addCanDoActionMessage(VdcBllMessages.VM_CANNOT_IMPORT_VM_NAME_EXISTS); <del> } <del> return !exists; <add> if (VmHandler.isVmWithSameNameExistStatic(getVm().getName())) { <add> return failCanDoAction(VdcBllMessages.VM_CANNOT_IMPORT_VM_NAME_EXISTS); <add> } <add> return true; <ide> } <ide> <ide> @Override <ide> * images), it will be updated. If it doesn't exist, it will be saved. <ide> */ <ide> private void updateSnapshotsFromExport() { <del> if (getVm().getSnapshots() != null) { <del> for (Snapshot snapshot : getVm().getSnapshots()) { <del> if (getSnapshotDao().exists(getVm().getId(), snapshot.getId())) { <del> getSnapshotDao().update(snapshot); <del> } else { <del> getSnapshotDao().save(snapshot); <del> } <add> if (getVm().getSnapshots() == null) { <add> return; <add> } <add> <add> for (Snapshot snapshot : getVm().getSnapshots()) { <add> if (getSnapshotDao().exists(getVm().getId(), snapshot.getId())) { <add> getSnapshotDao().update(snapshot); <add> } else { <add> getSnapshotDao().save(snapshot); <ide> } <ide> } <ide> }
Java
mit
dcc4b0de281c3a2ae30b1ee288019ce54e3e341c
0
akkessler/ElixirCounter
package io.akessler.elixircounter; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.CountDownTimer; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; /** * Created by Andy on 9/14/2017. */ public class OverlayService extends Service { private final static int ONGOING_NOTIFICATION_ID = 1337; private final static String EXIT_ACTION = "io.akessler.elixircounter.action.exit"; WindowManager windowManager; Button[] counterButtons; Button startButton; CountDownTimer regularElixirTimer, doubleElixirTimer; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); ElixirStore.createInstance(this, windowManager); // TODO Revisit this design pattern... initNotificationIntent(); initTimers(); initStartButton(); // TODO initStopButton(); initCounterButtons(); } @Override public void onDestroy() { super.onDestroy(); regularElixirTimer.cancel(); doubleElixirTimer.cancel(); windowManager.removeView(startButton); for(int i = 0; i < counterButtons.length; i++) { Button b = counterButtons[i]; if(counterButtons[i] != null) { windowManager.removeView(b); } } // TODO Refactor? windowManager.removeView(ElixirStore.getTextView()); ElixirStore.destroy(); // needed? } private void initTimers() { doubleElixirTimer = new CountDownTimer(120000, 1400) { public void onTick(long millisUntilFinished) { ElixirStore.add(1); } public void onFinish() { Toast.makeText(OverlayService.this, R.string.timer_elixir2, Toast.LENGTH_SHORT).show(); } }; regularElixirTimer = new CountDownTimer(120000, 2800) { public void onTick(long millisUntilFinished) { ElixirStore.add(1); } public void onFinish() { Toast.makeText(OverlayService.this, R.string.timer_elixir1, Toast.LENGTH_SHORT).show(); ElixirStore.add(1); doubleElixirTimer.start(); } }; } private void initStartButton() { startButton = new Button(this); startButton.setText(R.string.button_start); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { regularElixirTimer.start(); startButton.setEnabled(false); startButton.setVisibility(View.GONE); } }); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.CENTER; buttonParams.x = 0; buttonParams.y = 0; windowManager.addView(startButton, buttonParams); } private void initCounterButtons() { counterButtons = new Button[11]; for(int i = 0; i < counterButtons.length; i++) { int counterValue = i != 0 ? -i : 1; // FIXME There might be a cleaner way... counterButtons[i] = new CounterButton(this, counterValue); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.LEFT | Gravity.TOP; // FIXME Change these values to be dynamic, based on dimensions of screen buttonParams.x = 25; buttonParams.y = (counterButtons.length - i) * 150; windowManager.addView(counterButtons[i], buttonParams); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(EXIT_ACTION.equals(intent.getAction())) { stopForeground(true); stopSelf(); } return START_STICKY; } private void initNotificationIntent() { Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, notificationIntent, 0); Intent exitIntent = new Intent(this, OverlayService.class); exitIntent.setAction(EXIT_ACTION); PendingIntent exitPendingIntent = PendingIntent.getService( this, 0, exitIntent, 0); NotificationCompat.Action exitAction = new NotificationCompat.Action.Builder( android.R.drawable.ic_delete, getText(R.string.button_exit), exitPendingIntent).build(); Notification notification = new NotificationCompat.Builder(this) .setContentTitle(getText(R.string.notification_title)) .setContentText(getText(R.string.notification_message)) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pendingIntent) .setOngoing(true) .setColor(0xFF00FF) .addAction(exitAction) .build(); startForeground(ONGOING_NOTIFICATION_ID, notification); } }
app/src/main/java/io/akessler/elixircounter/OverlayService.java
package io.akessler.elixircounter; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.CountDownTimer; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; /** * Created by Andy on 9/14/2017. */ public class OverlayService extends Service { private final static int ONGOING_NOTIFICATION_ID = 1337; private final static String EXIT_ACTION = "io.akessler.elixircounter.action.exit"; WindowManager windowManager; Button[] counterButtons; Button startButton, exitButton; CountDownTimer regularElixirTimer, doubleElixirTimer; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); ElixirStore.createInstance(this, windowManager); // TODO Revisit this design pattern... initNotificationIntent(); initTimers(); initStartButton(); // TODO initStopButton(); initExitButton(); initCounterButtons(); } @Override public void onDestroy() { super.onDestroy(); regularElixirTimer.cancel(); doubleElixirTimer.cancel(); windowManager.removeView(startButton); windowManager.removeView(exitButton); for(int i = 0; i < counterButtons.length; i++) { Button b = counterButtons[i]; if(counterButtons[i] != null) { windowManager.removeView(b); } } // TODO Refactor? windowManager.removeView(ElixirStore.getTextView()); ElixirStore.destroy(); // needed? } private void initTimers() { doubleElixirTimer = new CountDownTimer(120000, 1400) { public void onTick(long millisUntilFinished) { ElixirStore.add(1); } public void onFinish() { Toast.makeText(OverlayService.this, R.string.timer_elixir2, Toast.LENGTH_SHORT).show(); } }; regularElixirTimer = new CountDownTimer(120000, 2800) { public void onTick(long millisUntilFinished) { ElixirStore.add(1); } public void onFinish() { Toast.makeText(OverlayService.this, R.string.timer_elixir1, Toast.LENGTH_SHORT).show(); ElixirStore.add(1); doubleElixirTimer.start(); } }; } private void initStartButton() { startButton = new Button(this); startButton.setText(R.string.button_start); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { regularElixirTimer.start(); startButton.setEnabled(false); startButton.setVisibility(View.GONE); } }); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.CENTER; buttonParams.x = 0; buttonParams.y = 0; windowManager.addView(startButton, buttonParams); } private void initExitButton() { exitButton = new Button(this); exitButton.setText(R.string.button_exit); exitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OverlayService.this.stopSelf(); OverlayService.this.stopForeground(true); } }); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; buttonParams.x = 0; buttonParams.y = 0; windowManager.addView(exitButton, buttonParams); } private void initCounterButtons() { counterButtons = new Button[11]; for(int i = 0; i < counterButtons.length; i++) { int counterValue = i != 0 ? -i : 1; // FIXME There might be a cleaner way... counterButtons[i] = new CounterButton(this, counterValue); WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT ); buttonParams.gravity = Gravity.LEFT | Gravity.TOP; // FIXME Change these values to be dynamic, based on dimensions of screen buttonParams.x = 25; buttonParams.y = (counterButtons.length - i) * 150; windowManager.addView(counterButtons[i], buttonParams); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(EXIT_ACTION.equals(intent.getAction())) { stopForeground(true); stopSelf(); } return START_STICKY; } private void initNotificationIntent() { Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, notificationIntent, 0); Intent exitIntent = new Intent(this, OverlayService.class); exitIntent.setAction(EXIT_ACTION); PendingIntent exitPendingIntent = PendingIntent.getService( this, 0, exitIntent, 0); NotificationCompat.Action exitAction = new NotificationCompat.Action.Builder( android.R.drawable.ic_delete, getText(R.string.button_exit), exitPendingIntent).build(); Notification notification = new NotificationCompat.Builder(this) .setContentTitle(getText(R.string.notification_title)) .setContentText(getText(R.string.notification_message)) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pendingIntent) .setOngoing(true) .setColor(0xFF00FF) .addAction(exitAction) .build(); startForeground(ONGOING_NOTIFICATION_ID, notification); } }
Remove exit button since notifcation can do it now
app/src/main/java/io/akessler/elixircounter/OverlayService.java
Remove exit button since notifcation can do it now
<ide><path>pp/src/main/java/io/akessler/elixircounter/OverlayService.java <ide> <ide> Button[] counterButtons; <ide> <del> Button startButton, exitButton; <add> Button startButton; <ide> <ide> CountDownTimer regularElixirTimer, doubleElixirTimer; <ide> <ide> <ide> initTimers(); <ide> initStartButton(); // TODO initStopButton(); <del> initExitButton(); <ide> initCounterButtons(); <ide> } <ide> <ide> doubleElixirTimer.cancel(); <ide> <ide> windowManager.removeView(startButton); <del> windowManager.removeView(exitButton); <ide> <ide> for(int i = 0; i < counterButtons.length; i++) { <ide> Button b = counterButtons[i]; <ide> windowManager.addView(startButton, buttonParams); <ide> } <ide> <del> private void initExitButton() { <del> exitButton = new Button(this); <del> exitButton.setText(R.string.button_exit); <del> exitButton.setOnClickListener(new View.OnClickListener() { <del> @Override <del> public void onClick(View v) { <del> OverlayService.this.stopSelf(); <del> OverlayService.this.stopForeground(true); <del> } <del> }); <del> WindowManager.LayoutParams buttonParams = new WindowManager.LayoutParams( <del> WindowManager.LayoutParams.WRAP_CONTENT, <del> WindowManager.LayoutParams.WRAP_CONTENT, <del> WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, // FIXME Acts up on certain API versions <del> WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, <del> PixelFormat.TRANSLUCENT <del> ); <del> buttonParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; <del> buttonParams.x = 0; <del> buttonParams.y = 0; <del> windowManager.addView(exitButton, buttonParams); <del> } <del> <ide> private void initCounterButtons() { <ide> counterButtons = new Button[11]; <ide> for(int i = 0; i < counterButtons.length; i++) {
Java
apache-2.0
97533d342758d2ab6bede7f8bb57e7cdd0a9a738
0
kotcrab/vis-editor,kotcrab/vis-editor,piotr-j/VisEditor,kotcrab/VisEditor,piotr-j/VisEditor
package com.kotcrab.vis.ui.util; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Timer; import com.kotcrab.vis.ui.widget.VisTable; import com.kotcrab.vis.ui.widget.toast.MessageToast; import com.kotcrab.vis.ui.widget.toast.Toast; import com.kotcrab.vis.ui.widget.toast.ToastTable; /** * Utility for displaying toast messages at upper right corner of application screen. Toasts can be closed by users or they * can automatically disappear after a period of time. Typically only one instance of ToastManager is used per * application window. * <p> * To properly support window resize {@link #resize()} must be called when application resize has occurred. * <p> * Most show methods are taking {@link VisTable} however {@link ToastTable} should be preferred because it's provides * access to enclosing {@link Toast} instance. * @author Kotcrab * @see Toast * @see ToastTable * @see MessageToast * @since 1.1.0 */ public class ToastManager { public static final int UNTIL_CLOSED = -1; private Stage stage; private int screenPadding = 20; private int messagePadding = 5; private Array<Toast> toasts = new Array<Toast>(); private ObjectMap<Toast, Timer.Task> timersTasks = new ObjectMap<Toast, Timer.Task>(); public ToastManager (Stage stage) { this.stage = stage; } /** Displays basic toast with provided text as message. Toast will be displayed until it is closed by user. */ public void show (String text) { show(text, UNTIL_CLOSED); } /** Displays basic toast with provided text as message. Toast will be displayed for given amount of seconds. */ public void show (String text, float timeSec) { VisTable table = new VisTable(); table.add(text).grow(); show(table, timeSec); } /** Displays toast with provided table as toast's content. Toast will be displayed until it is closed by user. */ public void show (Table table) { show(table, UNTIL_CLOSED); } /** Displays toast with provided table as toast's content. Toast will be displayed for given amount of seconds. */ public void show (Table table, float timeSec) { show(new Toast(table), timeSec); } /** * Displays toast with provided table as toast's content. If this toast was already displayed then it reuses * stored {@link Toast} instance. * Toast will be displayed until it is closed by user. */ public void show (ToastTable toastTable) { show(toastTable, UNTIL_CLOSED); } /** * Displays toast with provided table as toast's content. If this toast was already displayed then it reuses * stored {@link Toast} instance. * Toast will be displayed for given amount of seconds. */ public void show (ToastTable toastTable, float timeSec) { Toast toast = toastTable.getToast(); if (toast != null) { show(toast, timeSec); } else { show(new Toast(toastTable), timeSec); } } /** Displays toast. Toast will be displayed until it is closed by user. */ public void show (Toast toast) { show(toast, UNTIL_CLOSED); } /** Displays toast. Toast will be displayed for given amount of seconds. */ public void show (final Toast toast, float timeSec) { Table toastMainTable = toast.getMainTable(); if (toastMainTable.getStage() != null) { remove(toast); } toasts.add(toast); toast.setToastManager(this); toast.fadeIn(); toastMainTable.pack(); stage.addActor(toastMainTable); updateToastsPositions(); if (timeSec > 0) { Timer.Task fadeOutTask = new Timer.Task() { @Override public void run () { toast.fadeOut(); timersTasks.remove(toast); } }; timersTasks.put(toast, fadeOutTask); Timer.schedule(fadeOutTask, timeSec); } } /** Must be called after application window resize to properly update toast positions on screen. */ public void resize () { updateToastsPositions(); } /** * Removes toast from screen. * @return true when toast was removed, false otherwise */ public boolean remove (Toast toast) { boolean removed = toasts.removeValue(toast, true); if (removed) { Timer.Task timerTask = timersTasks.remove(toast); if (timerTask != null) timerTask.cancel(); updateToastsPositions(); } return removed; } public void clear () { toasts.clear(); for (Timer.Task task : timersTasks.values()) { task.cancel(); } timersTasks.clear(); } public void toFront () { for (Toast toast : toasts) { toast.getMainTable().toFront(); } } private void updateToastsPositions () { float y = stage.getHeight() - screenPadding; for (Toast toast : toasts) { Table table = toast.getMainTable(); table.setPosition(stage.getWidth() - table.getWidth() - screenPadding, y - table.getHeight()); y = y - table.getHeight() - messagePadding; } } public int getScreenPadding () { return screenPadding; } /** Sets padding of message from window top right corner */ public void setScreenPadding (int screenPadding) { this.screenPadding = screenPadding; updateToastsPositions(); } public int getMessagePadding () { return messagePadding; } /** Sets padding between messages */ public void setMessagePadding (int messagePadding) { this.messagePadding = messagePadding; updateToastsPositions(); } }
ui/src/com/kotcrab/vis/ui/util/ToastManager.java
package com.kotcrab.vis.ui.util; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Timer; import com.kotcrab.vis.ui.widget.VisTable; import com.kotcrab.vis.ui.widget.toast.MessageToast; import com.kotcrab.vis.ui.widget.toast.Toast; import com.kotcrab.vis.ui.widget.toast.ToastTable; /** * Utility for displaying toast messages at upper right corner of application screen. Toasts can be closed by users or they * can automatically disappear after a period of time. Typically only one instance of ToastManager is used per * application window. * <p> * To properly support window resize {@link #resize()} must be called when application resize has occurred. * <p> * Most show methods are taking {@link VisTable} however {@link ToastTable} should be preferred because it's provides * access to enclosing {@link Toast} instance. * @author Kotcrab * @see Toast * @see ToastTable * @see MessageToast * @since 1.1.0 */ public class ToastManager { public static final int UNTIL_CLOSED = -1; private Stage stage; private int screenPadding = 20; private int messagePadding = 5; private Array<Toast> toasts = new Array<Toast>(); private ObjectMap<Toast, Timer.Task> timersTasks = new ObjectMap<Toast, Timer.Task>(); public ToastManager (Stage stage) { this.stage = stage; } /** Displays basic toast with provided text as message. Toast will be displayed until it is closed by user. */ public void show (String text) { show(text, UNTIL_CLOSED); } /** Displays basic toast with provided text as message. Toast will be displayed for given amount of seconds. */ public void show (String text, float timeSec) { VisTable table = new VisTable(); table.add(text).grow(); show(table, timeSec); } /** Displays toast with provided table as toast's content. Toast will be displayed until it is closed by user. */ public void show (Table table) { show(table, UNTIL_CLOSED); } /** Displays toast with provided table as toast's content. Toast will be displayed for given amount of seconds. */ public void show (Table table, float timeSec) { show(new Toast(table), timeSec); } /** * Displays toast with provided table as toast's content. If this toast was already displayed then it reuses * stored {@link Toast} instance. * Toast will be displayed until it is closed by user. */ public void show (ToastTable toastTable) { show(toastTable, UNTIL_CLOSED); } /** * Displays toast with provided table as toast's content. If this toast was already displayed then it reuses * stored {@link Toast} instance. * Toast will be displayed for given amount of seconds. */ public void show (ToastTable toastTable, float timeSec) { Toast toast = toastTable.getToast(); if (toast != null) { show(toast, timeSec); } else { show(new Toast(toastTable), timeSec); } } /** Displays toast. Toast will be displayed until it is closed by user. */ public void show (Toast toast) { show(toast, UNTIL_CLOSED); } /** Displays toast. Toast will be displayed for given amount of seconds. */ public void show (final Toast toast, float timeSec) { Table toastMainTable = toast.getMainTable(); if (toastMainTable.getStage() != null) { remove(toast); } toasts.add(toast); toast.setToastManager(this); toast.fadeIn(); toastMainTable.pack(); stage.addActor(toastMainTable); updateToastsPositions(); if (timeSec > 0) { Timer.Task fadeOutTask = new Timer.Task() { @Override public void run () { toast.fadeOut(); timersTasks.remove(toast); } }; timersTasks.put(toast, fadeOutTask); Timer.schedule(fadeOutTask, timeSec); } } /** Must be called after application window resize to properly update toast positions on screen. */ public void resize () { updateToastsPositions(); } /** * Removes toast from screen. * @return true when toast was removed, false otherwise */ public boolean remove (Toast toast) { boolean removed = toasts.removeValue(toast, true); if (removed) { Timer.Task timerTask = timersTasks.remove(toast); if (timerTask != null) timerTask.cancel(); updateToastsPositions(); } return removed; } public void clear () { toasts.clear(); for (Timer.Task task : timersTasks.values()) { task.cancel(); } timersTasks.clear(); } private void updateToastsPositions () { float y = stage.getHeight() - screenPadding; for (Toast toast : toasts) { Table table = toast.getMainTable(); table.setPosition(stage.getWidth() - table.getWidth() - screenPadding, y - table.getHeight()); y = y - table.getHeight() - messagePadding; } } public int getScreenPadding () { return screenPadding; } /** Sets padding of message from window top right corner */ public void setScreenPadding (int screenPadding) { this.screenPadding = screenPadding; updateToastsPositions(); } public int getMessagePadding () { return messagePadding; } /** Sets padding between messages */ public void setMessagePadding (int messagePadding) { this.messagePadding = messagePadding; updateToastsPositions(); } }
Add ToastManager#toFront
ui/src/com/kotcrab/vis/ui/util/ToastManager.java
Add ToastManager#toFront
<ide><path>i/src/com/kotcrab/vis/ui/util/ToastManager.java <ide> timersTasks.clear(); <ide> } <ide> <add> public void toFront () { <add> for (Toast toast : toasts) { <add> toast.getMainTable().toFront(); <add> } <add> } <add> <ide> private void updateToastsPositions () { <ide> float y = stage.getHeight() - screenPadding; <ide>
Java
apache-2.0
e453e0fd0ed3d46df727c537e28abe0116e36db0
0
atsolakid/jena,apache/jena,adrapereira/jena,apache/jena,apache/jena,atsolakid/jena,jianglili007/jena,kamir/jena,tr3vr/jena,samaitra/jena,CesarPantoja/jena,tr3vr/jena,apache/jena,atsolakid/jena,tr3vr/jena,samaitra/jena,kidaa/jena,adrapereira/jena,CesarPantoja/jena,samaitra/jena,adrapereira/jena,atsolakid/jena,adrapereira/jena,kamir/jena,CesarPantoja/jena,CesarPantoja/jena,kidaa/jena,samaitra/jena,samaitra/jena,CesarPantoja/jena,kidaa/jena,apache/jena,atsolakid/jena,samaitra/jena,jianglili007/jena,apache/jena,tr3vr/jena,kidaa/jena,kidaa/jena,tr3vr/jena,kamir/jena,apache/jena,samaitra/jena,kamir/jena,atsolakid/jena,adrapereira/jena,tr3vr/jena,kidaa/jena,kidaa/jena,CesarPantoja/jena,adrapereira/jena,adrapereira/jena,kamir/jena,jianglili007/jena,jianglili007/jena,kamir/jena,jianglili007/jena,apache/jena,atsolakid/jena,kamir/jena,CesarPantoja/jena,jianglili007/jena,tr3vr/jena,jianglili007/jena
/* * 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.hp.hpl.jena.n3; import java.io.*; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.*; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.rdf.model.impl.Util ; import com.hp.hpl.jena.util.iterator.ClosableIterator; import com.hp.hpl.jena.util.iterator.WrappedIterator; import com.hp.hpl.jena.JenaRuntime; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.XSD; /** Common framework for implementing N3 writers. */ public class N3JenaWriterCommon implements RDFWriter { static Logger logger = LoggerFactory.getLogger(N3JenaWriterCommon.class) ; // N3 writing proceeds in 2 stages. // First, it analysis the model to be written to extract information // that is going to be specially formatted (RDF lists, one ref anon nodes) // Second do the writing walk. // The simple N3 writer does nothing during preparation. protected Map<String, Object> writerPropertyMap = null ; // BaseURI - <#> // final boolean doAbbreviatedBaseURIref = getBooleanValue("abbrevBaseURI", true) ; protected boolean alwaysAllocateBNodeLabel = false ; // Common variables protected RDFErrorHandler errorHandler = null; protected Map<String, String> prefixMap = new HashMap<>() ; // Prefixes to actually use protected Map<String, String> reversePrefixMap = new HashMap<>() ; // URI->prefix protected Map<Resource, String> bNodesMap = null ; // BNodes seen. protected int bNodeCounter = 0 ; // Specific properties that have a short form. // Not Turtle. protected static final String NS_W3_log = "http://www.w3.org/2000/10/swap/log#" ; protected static Map<String, String> wellKnownPropsMapN3 = new HashMap<>() ; static { wellKnownPropsMapN3.put(NS_W3_log+"implies", "=>" ) ; wellKnownPropsMapN3.put(OWL.sameAs.getURI(), "=" ) ; wellKnownPropsMapN3.put(RDF.type.getURI(), "a" ) ; } protected static Map<String, String> wellKnownPropsMapTurtle = new HashMap<>() ; static { //wellKnownPropsMapTurtle.put(OWL.sameAs.getURI(), "=" ) ; wellKnownPropsMapTurtle.put(RDF.type.getURI(), "a" ) ; } protected Map<String, String> wellKnownPropsMap = wellKnownPropsMapN3 ; // Work variables controlling the output protected N3IndentedWriter out = null ; //Removed base URI specials - look for "// BaseURI - <#>" & doAbbreviatedBaseURIref //String baseURIref = null ; //String baseURIrefHash = null ; // Min spacing of items protected int minGap = getIntValue("minGap", 1) ; protected String minGapStr = pad(minGap) ; // Gap from subject to property protected int indentProperty = getIntValue("indentProperty", 6) ; // Width of property before wrapping. // This is not necessarily a control of total width // e.g. the pretty writer may be writing properties inside indented one ref bNodes protected int widePropertyLen = getIntValue("widePropertyLen", 20) ; // Column for property when an object follows a property on the same line protected int propertyCol = getIntValue("propertyColumn", 8) ; // Minimum gap from property to object when object on a new line. protected int indentObject = propertyCol ; // If a subject is shorter than this, the first property may go on same line. protected int subjectColumn = getIntValue("subjectColumn", indentProperty) ; // Require shortSubject < subjectCol (strict less than) protected int shortSubject = subjectColumn-minGap; protected boolean useWellKnownPropertySymbols = getBooleanValue("usePropertySymbols", true) ; protected boolean allowTripleQuotedStrings = getBooleanValue("useTripleQuotedStrings", true) ; protected boolean allowDoubles = getBooleanValue("useDoubles", true) ; protected boolean allowDecimals = getBooleanValue("useDecimals", true) ; // ---------------------------------------------------- // Jena RDFWriter interface @Override public RDFErrorHandler setErrorHandler(RDFErrorHandler errHandler) { RDFErrorHandler old = errorHandler; errorHandler = errHandler; return old; } @Override public Object setProperty(String propName, Object propValue) { if ( ! ( propValue instanceof String ) ) { logger.warn("N3.setProperty: Property for '"+propName+"' is not a string") ; propValue = propValue.toString() ; } // Store absolute name of property propName = absolutePropName(propName) ; if ( writerPropertyMap == null ) writerPropertyMap = new HashMap<>() ; Object oldValue = writerPropertyMap.get(propName); writerPropertyMap.put(propName, propValue); return oldValue; } /** Write the model out in N3. The writer should be one suitable for UTF-8 which * excludes a PrintWriter or a FileWriter which use default character set. * * Examples: * <pre> * try { * Writer w = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")) ; * model.write(w, base) ; * try { w.flush() ; } catch (IOException ioEx) {...} * } catch (java.io.UnsupportedEncodingException ex) {} //UTF-8 is required so can't happen * </pre> * or * <pre> * try { * OutputStream out = new FileOutputStream(file) ; * Writer w = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")) ; * model.write(w, base) ; * } * catch (java.io.UnsupportedEncodingException ex) {} * catch (java.io.FileNotFoundException noFileEx) { ... } * </pre> * @see #write(Model,Writer,String) */ @Override public void write(Model baseModel, Writer _out, String base) { if (!(_out instanceof BufferedWriter)) _out = new BufferedWriter(_out); out = new N3IndentedWriter(_out); // BaseURI - <#> // if ( base != null ) // { // baseURIref = base ; // if ( !base.endsWith("#") &&! isOpaque(base) ) // baseURIrefHash = baseURIref+"#" ; // } processModel(baseModel) ; } /** Write the model out in N3, encoded in in UTF-8 * @see #write(Model,Writer,String) */ @Override public synchronized void write(Model model, OutputStream output, String base) { try { Writer w = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")) ; write(model, w, base) ; try { w.flush() ; } catch (IOException ioEx) { throw new JenaException(ioEx) ; } } catch (java.io.UnsupportedEncodingException ex) { System.err.println("Failed to create UTF-8 writer") ; } } // ---------------------------------------------------- // The assumed processing model is: // Writing N3 involves ordering the graph into: // -- Subjects // -- Property lists within subjects // -- Object lists with in properties // A derived class may choose to intercept and implement at any of these levels. // Standard layout is: // subject // property1 value1 ; // property2 value2 ; // property3 value3 . // Normal hook points for subclasses. protected void startWriting() {} protected void finishWriting() {} protected void prepare(Model model) {} protected void processModel(Model model) { prefixMap = model.getNsPrefixMap() ; bNodesMap = new HashMap<>() ; // PrefixMapping (to Jena 2.5.7 at least) // is specialized to XML-isms and Turle prefixed names aren't quite qnames. // Build temporary maps of acceptable prefixes and URIs. // If no base defined for the model, but one given to writer, // then use this. String base2 = prefixMap.get("") ; // BaseURI - <#> // if ( base2 == null && baseURIrefHash != null ) // prefixMap.put("", baseURIrefHash) ; for ( Iterator<Entry<String, String>> iter = prefixMap.entrySet().iterator() ; iter.hasNext() ; ) { Entry<String, String> e = iter.next() ; String prefix = e.getKey() ; String uri = e.getValue(); // XML namespaces name can include '.' // Turtle prefixed names can't. if ( ! checkPrefixPart(prefix) ) iter.remove() ; else { if ( checkPrefixPart(prefix) ) // Build acceptable reverse mapping reversePrefixMap.put(uri, prefix) ; } } startWriting() ; prepare(model) ; writeHeader(model) ; writePrefixes(model) ; if (prefixMap.size() != 0) out.println(); // Do the output. writeModel(model) ; // Release intermediate memory - allows reuse of a writer finishWriting() ; bNodesMap = null ; } protected void writeModel(Model model) { // Needed only for no prefixes, no blank first line. boolean doingFirst = true; ResIterator rIter = listSubjects(model); for (; rIter.hasNext();) { // Subject: // First - it is something we will write out as a structure in an object field? // That is, a RDF list or the object of exactly one statement. Resource subject = rIter.nextResource(); if ( skipThisSubject(subject) ) { if (N3JenaWriter.DEBUG) out.println("# Skipping: " + formatResource(subject)); continue; } // We really are going to print something via writeTriples if (doingFirst) doingFirst = false; else out.println(); writeOneGraphNode(subject) ; } rIter.close(); } protected ResIterator listSubjects(Model model) { return model.listSubjects(); } protected void writeOneGraphNode(Resource subject) { // New top level item. // Does not take effect until newline. out.incIndent(indentProperty) ; writeSubject(subject); ClosableIterator<Property> iter = preparePropertiesForSubject(subject); writePropertiesForSubject(subject, iter) ; out.decIndent(indentProperty) ; out.println(" ."); } protected void writePropertiesForSubject(Resource subj, ClosableIterator<Property> iter) { // For each property. for (; iter.hasNext();) { Property property = iter.next(); // Object list writeObjectList(subj, property); if (iter.hasNext()) out.println(" ;"); } iter.close(); } // Hook called on every resource. // Since there is spacing bewteen resource frames, need to know // whether an item will cause any output. protected boolean skipThisSubject(Resource r) { return false ; } // This is the hook called within writeModel. // NB May not be at the top level (indent = 0) protected void writeSubject(Resource subject) { String subjStr = formatResource(subject); out.print(subjStr); // May be very short : if so, stay on this line. // Currently at end of subject. // NB shortSubject is (subjectColumn-minGap) so there is a gap. if (subjStr.length() < shortSubject ) { out.print(pad(subjectColumn - subjStr.length()) ); } else // Does not fit this line. out.println(); } protected void writeHeader(Model model) { // BaseURI - <#> // if (baseURIref != null && !baseURIref.equals("") ) // out.println("# Base: " + baseURIref); } protected N3IndentedWriter getOutput() { return out ; } protected Map<String, String> getPrefixes() { return prefixMap ; } protected void writePrefixes(Model model) { for ( String p : prefixMap.keySet() ) { String u = prefixMap.get( p ); // BaseURI - <#> // // Special cases: N3 handling of base names. // if (doAbbreviatedBaseURIref && p.equals("")) // { // if (baseURIrefHash != null && u.equals(baseURIrefHash)) // u = "#"; // if (baseURIref != null && u.equals(baseURIref)) // u = ""; // } String tmp = "@prefix " + p + ": "; out.print( tmp ); out.print( pad( 16 - tmp.length() ) ); // NB Starts with a space to ensure a gap. out.println( " <" + u + "> ." ); } } protected void writeObjectList(Resource subject, Property property) { String propStr = formatProperty(property) ; // if (wellKnownPropsMap.containsKey(property.getURI())) // propStr = (String) wellKnownPropsMap.get(property.getURI()); // else // propStr = formatResource(property); // Write with object lists as clusters of statements with the same property // Looks more like a machine did it but fewer bad cases. StmtIterator sIter = subject.listProperties(property); for (; sIter.hasNext();) { Statement stmt = sIter.nextStatement() ; String objStr = formatNode(stmt.getObject()) ; out.print(propStr); out.incIndent(indentObject); if ( (propStr.length()+minGap) <= widePropertyLen ) { // Property col allows for min gap but widePropertyLen > propertyCol // (which looses alignment - this is intentional. // Ensure there is at least min gap. int padding = calcPropertyPadding(propStr) ; out.print(pad(padding)) ; // if ( propStr.length() < propertyWidth ) // out.print( pad(propertyCol-minGap-propStr.length()) ) ; // out.print(minGapStr) ; } else // Does not fit this line. out.println(); // Write one object - simple writing. out.print(objStr) ; out.decIndent(indentObject); if ( sIter.hasNext() ) { out.println(" ;") ; } } sIter.close() ; } protected String formatNode(RDFNode node) { if (node instanceof Literal) return formatLiteral((Literal) node); else return formatResource((Resource)node) ; } protected void writeObject(RDFNode node) { if (node instanceof Literal) { writeLiteral((Literal) node); return; } Resource rObj = (Resource) node; out.print(formatResource(rObj)); } protected void writeLiteral(Literal literal) { out.print(formatLiteral(literal)) ; } protected ClosableIterator<Property> preparePropertiesForSubject(Resource r) { // Properties to do. Set<Property> properties = new HashSet<>() ; StmtIterator sIter = r.listProperties(); for ( ; sIter.hasNext() ; ) properties.add(sIter.nextStatement().getPredicate()) ; sIter.close() ; return WrappedIterator.create(properties.iterator()) ; } // Utility operations protected String formatResource(Resource r) { if ( r.isAnon() ) { if ( ! alwaysAllocateBNodeLabel ) { // Does anything point to it? StmtIterator sIter = r.getModel().listStatements(null, null, r) ; if ( ! sIter.hasNext() ) { sIter.close() ; // This bNode is not referenced so don't need the bNode Id. // Must be a subject - indent better be zero! // This only happens for subjects because object bNodes // referred to once (the other case for [] syntax) // are handled elsewhere (by oneRef set) // Later: use [ prop value ] for this. return "[]" ; } sIter.close() ; } if ( ! bNodesMap.containsKey(r) ) bNodesMap.put(r, "_:b"+(++bNodeCounter)) ; return bNodesMap.get(r) ; } // It has a URI. if ( r.equals(RDF.nil) ) return "()" ; return formatURI(r.getURI()) ; } protected String formatLiteral(Literal literal) { String datatype = literal.getDatatypeURI() ; String lang = literal.getLanguage() ; String s = literal.getLexicalForm() ; if ( datatype != null ) { // Special form we know how to handle? // Assume valid text if ( datatype.equals(XSD.integer.getURI()) ) { try { new java.math.BigInteger(s) ; return s ; } catch (NumberFormatException nfe) {} // No luck. Continue. // Continuing is always safe. } if ( datatype.equals(XSD.decimal.getURI()) ) { // Must have ., can't have e or E if ( s.indexOf('.') >= 0 && s.indexOf('e') == -1 && s.indexOf('E') == -1 ) { // Turtle - N3 does not allow .3 +.3 or -.3 // See if parsable. try { BigDecimal d = new BigDecimal(s) ; return s ; } catch (NumberFormatException nfe) {} } } if ( this.allowDoubles && datatype.equals(XSD.xdouble.getURI()) ) { // Must have 'e' or 'E' (N3 and Turtle now read 2.3 as a decimal). if ( s.indexOf('e') >= 0 || s.indexOf('E') >= 0 ) { try { // Validate it. Double.parseDouble(s) ; return s ; } catch (NumberFormatException nfe) {} // No luck. Continue. } } } // Format the text - with escaping. StringBuffer sbuff = new StringBuffer() ; boolean singleQuoteLiteral = true ; String quoteMarks = "\"" ; // Things that force the use of """ strings if ( this.allowTripleQuotedStrings && ( s.indexOf("\n") != -1 || s.indexOf("\r") != -1 || s.indexOf("\f") != -1 ) ) { quoteMarks = "\"\"\"" ; singleQuoteLiteral = false ; } sbuff.append(quoteMarks); string(sbuff, s, singleQuoteLiteral) ; sbuff.append(quoteMarks); if ( Util.isLangString(literal) ) { sbuff.append("@") ; sbuff.append(lang) ; } else if ( ! Util.isSimpleString(literal) ) { sbuff.append("^^") ; sbuff.append(formatURI(datatype)) ; } return sbuff.toString() ; } protected String formatProperty(Property p) { String prop = p.getURI() ; if ( this.useWellKnownPropertySymbols && wellKnownPropsMap.containsKey(prop) ) return wellKnownPropsMap.get(prop); return formatURI(prop) ; } protected String formatURI(String uriStr) { String matchURI = "" ; String matchPrefix = null ; // BaseURI - <#> // if ( doAbbreviatedBaseURIref && uriStr.equals(baseURIref) ) // return "<>" ; // Try for a prefix and write as prefixed name. // 1/ Try splitting as a prefixed name // 2/ Search for possibilities // Stage 1. int idx = splitIdx(uriStr) ; // Depends on legal URIs. if ( idx >= 0 ) { // Include the # itself. String x = uriStr.substring(0,idx+1) ; String prefix = reversePrefixMap.get(x) ; if ( prefix != null ) { String localPart = uriStr.substring(idx+1) ; if ( checkNamePart(localPart) ) return prefix+':'+localPart ; } } // Unsplit. Could just return here. // // Find the longest if several. // // Possible optimization: split URI and have URI=> ns: map. // // Ordering prefixes by length, then first hit is better. // // // // Also: could just assume that the split is on / or # // // Means we need to find a prefix just once. // for ( Iterator<String> pIter = prefixMap.keySet().iterator() ; pIter.hasNext() ; ) // { // String p = pIter.next() ; // String u = prefixMap.get(p) ; // if ( uriStr.startsWith(u) ) // if ( matchURI.length() < u.length() ) // { // matchPrefix = p ; // matchURI = u ; // } // } // if ( matchPrefix != null ) // { // String localname = uriStr.substring(matchURI.length()) ; // // if ( checkPrefixedName(matchPrefix, localname) ) // return matchPrefix+":"+localname ; // // // Continue and return quoted URIref // } // Not as a prefixed name - write as a quoted URIref // It should be right - the writer should be UTF-8 on output. return "<"+uriStr+">" ; } protected static int splitIdx(String uriStr) { int idx = uriStr.lastIndexOf('#') ; if ( idx >= 0 ) return idx ; // No # - try for / idx = uriStr.lastIndexOf('/') ; return idx ; } // Checks of prefixed names // These tests must agree, or be more restrictive, than the parser. protected static boolean checkPrefixedName(String ns, String local) { return checkPrefixPart(ns) && checkNamePart(local) ; } /* http://www.w3.org/TeamSubmission/turtle/#sec-grammar-grammar * [27] qname ::= prefixName? ':' name? * [30] nameStartChar ::= [A-Z] | "_" | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] * [31] nameChar ::= nameStartChar | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] * [32] name ::= nameStartChar nameChar* * [33] prefixName ::= ( nameStartChar - '_' ) nameChar* */ protected static boolean checkPrefixPart(String s) { if ( s.length() == 0 ) return true; CharacterIterator cIter = new StringCharacterIterator(s) ; char ch = cIter.first() ; if ( ! checkNameStartChar(ch) ) return false ; if ( ch == '_' ) // Can't start with _ (bnodes labels handled separately) return false ; return checkNameTail(cIter) ; } protected static boolean checkNamePart(String s) { if ( s.length() == 0 ) return true; CharacterIterator cIter = new StringCharacterIterator(s) ; char ch = cIter.first() ; if ( ! checkNameStartChar(ch) ) return false ; return checkNameTail(cIter) ; } private static boolean checkNameTail(CharacterIterator cIter) { // Assumes cIter.first already called but nothing else. // Skip first char. char ch = cIter.next() ; for ( ; ch != java.text.CharacterIterator.DONE ; ch = cIter.next() ) { if ( ! checkNameChar(ch) ) return false ; } return true ; } protected static boolean checkNameStartChar(char ch) { if ( Character.isLetter(ch) ) return true ; if ( ch == '_' ) return true ; return false ; } protected static boolean checkNameChar(char ch) { if ( Character.isLetterOrDigit(ch) ) return true ; if ( ch == '_' ) return true ; if ( ch == '-' ) return true ; return false ; } protected final static String WS = "\n\r\t" ; protected static void string(StringBuffer sbuff, String s, boolean singleQuoteLiteral) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // Escape escapes and quotes if (c == '\\' || c == '"' ) { sbuff.append('\\') ; sbuff.append(c) ; continue ; } // Characters to literally output. // This would generate 7-bit safe files // if (c >= 32 && c < 127) // { // sbuff.append(c) ; // continue; // } // Whitespace if ( singleQuoteLiteral && ( c == '\n' || c == '\r' || c == '\f' ) ) { if (c == '\n') sbuff.append("\\n"); if (c == '\t') sbuff.append("\\t"); if (c == '\r') sbuff.append("\\r"); if (c == '\f') sbuff.append("\\f"); continue ; } // Output as is (subject to UTF-8 encoding on output that is) sbuff.append(c) ; // // Unicode escapes // // c < 32, c >= 127, not whitespace or other specials // String hexstr = Integer.toHexString(c).toUpperCase(); // int pad = 4 - hexstr.length(); // sbuff.append("\\u"); // for (; pad > 0; pad--) // sbuff.append("0"); // sbuff.append(hexstr); } } protected int calcPropertyPadding(String propStr) { int padding = propertyCol - propStr.length(); if (padding < minGap) padding = minGap; return padding ; } protected static String pad(int cols) { StringBuffer sb = new StringBuffer() ; for ( int i = 0 ; i < cols ; i++ ) sb.append(' ') ; return sb.toString() ; } // Utilities protected int countProperties(Resource r) { int numProp = 0 ; StmtIterator sIter = r.listProperties() ; for ( ; sIter.hasNext() ; ) { sIter.nextStatement() ; numProp++ ; } sIter.close() ; return numProp ; } protected int countProperties(Resource r, Property p) { int numProp = 0 ; StmtIterator sIter = r.listProperties(p) ; for ( ; sIter.hasNext() ; ) { sIter.nextStatement() ; numProp++ ; } sIter.close() ; return numProp ; } protected int countArcsTo(Resource resource) { return countArcsTo(null, resource) ; } protected int countArcsTo(Property prop, Resource resource) { int numArcs = 0 ; StmtIterator sIter = resource.getModel().listStatements(null, prop, resource) ; for ( ; sIter.hasNext() ; ) { sIter.nextStatement() ; numArcs++ ; } sIter.close() ; return numArcs ; } protected Iterator<RDFNode> rdfListIterator(Resource r) { List<RDFNode> list = new ArrayList<>() ; for ( ; ! r.equals(RDF.nil); ) { StmtIterator sIter = r.getModel().listStatements(r, RDF.first, (RDFNode)null) ; list.add(sIter.nextStatement().getObject()) ; if ( sIter.hasNext() ) // @@ need to cope with this (unusual) case throw new JenaException("N3: Multi valued list item") ; sIter = r.getModel().listStatements(r, RDF.rest, (RDFNode)null) ; r = (Resource)sIter.nextStatement().getObject() ; if ( sIter.hasNext() ) throw new JenaException("N3: List has two tails") ; } return list.iterator() ; } // Convenience operations for accessing system properties. protected String getStringValue(String prop, String defaultValue) { String p = getPropValue(prop) ; if ( p == null ) return defaultValue ; return p ; } protected boolean getBooleanValue(String prop, boolean defaultValue) { String p = getPropValue(prop) ; if ( p == null ) return defaultValue ; if ( p.equalsIgnoreCase("true") ) return true ; if ( p.equals("1") ) return true ; return false ; } protected int getIntValue(String prop, int defaultValue) { String p = getPropValue(prop) ; if ( p == null ) return defaultValue ; try { return Integer.parseInt(p) ; } catch (NumberFormatException ex) { logger.warn("Format error for property: "+prop) ; return defaultValue ; } } // May be the absolute or local form of the property name protected String getPropValue(String prop) { prop = absolutePropName(prop) ; if ( writerPropertyMap != null && writerPropertyMap.containsKey(prop) ) { Object obj = writerPropertyMap.get(prop) ; if ( ! ( obj instanceof String ) ) logger.warn("getPropValue: N3 Property for '"+prop+"' is not a string") ; return (String)obj ; } String s = JenaRuntime.getSystemProperty(prop) ; if ( s == null ) s = JenaRuntime.getSystemProperty(localPropName(prop)) ; return s ; } protected String absolutePropName(String propName) { if ( propName.indexOf(':') == -1 ) return N3JenaWriter.propBase + propName ; return propName ; } protected String localPropName(String propName) { if ( propName.startsWith(N3JenaWriter.propBase) ) propName = propName.substring(N3JenaWriter.propBase.length()) ; return propName ; } private boolean isOpaque(String uri) { try { return new URI(uri).isOpaque() ; } catch (URISyntaxException ex) { return true ; } } }
jena-core/src/main/java/com/hp/hpl/jena/n3/N3JenaWriterCommon.java
/* * 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.hp.hpl.jena.n3; import java.io.*; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.*; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.util.iterator.ClosableIterator; import com.hp.hpl.jena.util.iterator.WrappedIterator; import com.hp.hpl.jena.JenaRuntime; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.XSD; /** Common framework for implementing N3 writers. */ public class N3JenaWriterCommon implements RDFWriter { static Logger logger = LoggerFactory.getLogger(N3JenaWriterCommon.class) ; // N3 writing proceeds in 2 stages. // First, it analysis the model to be written to extract information // that is going to be specially formatted (RDF lists, one ref anon nodes) // Second do the writing walk. // The simple N3 writer does nothing during preparation. protected Map<String, Object> writerPropertyMap = null ; // BaseURI - <#> // final boolean doAbbreviatedBaseURIref = getBooleanValue("abbrevBaseURI", true) ; protected boolean alwaysAllocateBNodeLabel = false ; // Common variables protected RDFErrorHandler errorHandler = null; protected Map<String, String> prefixMap = new HashMap<>() ; // Prefixes to actually use protected Map<String, String> reversePrefixMap = new HashMap<>() ; // URI->prefix protected Map<Resource, String> bNodesMap = null ; // BNodes seen. protected int bNodeCounter = 0 ; // Specific properties that have a short form. // Not Turtle. protected static final String NS_W3_log = "http://www.w3.org/2000/10/swap/log#" ; protected static Map<String, String> wellKnownPropsMapN3 = new HashMap<>() ; static { wellKnownPropsMapN3.put(NS_W3_log+"implies", "=>" ) ; wellKnownPropsMapN3.put(OWL.sameAs.getURI(), "=" ) ; wellKnownPropsMapN3.put(RDF.type.getURI(), "a" ) ; } protected static Map<String, String> wellKnownPropsMapTurtle = new HashMap<>() ; static { //wellKnownPropsMapTurtle.put(OWL.sameAs.getURI(), "=" ) ; wellKnownPropsMapTurtle.put(RDF.type.getURI(), "a" ) ; } protected Map<String, String> wellKnownPropsMap = wellKnownPropsMapN3 ; // Work variables controlling the output protected N3IndentedWriter out = null ; //Removed base URI specials - look for "// BaseURI - <#>" & doAbbreviatedBaseURIref //String baseURIref = null ; //String baseURIrefHash = null ; // Min spacing of items protected int minGap = getIntValue("minGap", 1) ; protected String minGapStr = pad(minGap) ; // Gap from subject to property protected int indentProperty = getIntValue("indentProperty", 6) ; // Width of property before wrapping. // This is not necessarily a control of total width // e.g. the pretty writer may be writing properties inside indented one ref bNodes protected int widePropertyLen = getIntValue("widePropertyLen", 20) ; // Column for property when an object follows a property on the same line protected int propertyCol = getIntValue("propertyColumn", 8) ; // Minimum gap from property to object when object on a new line. protected int indentObject = propertyCol ; // If a subject is shorter than this, the first property may go on same line. protected int subjectColumn = getIntValue("subjectColumn", indentProperty) ; // Require shortSubject < subjectCol (strict less than) protected int shortSubject = subjectColumn-minGap; protected boolean useWellKnownPropertySymbols = getBooleanValue("usePropertySymbols", true) ; protected boolean allowTripleQuotedStrings = getBooleanValue("useTripleQuotedStrings", true) ; protected boolean allowDoubles = getBooleanValue("useDoubles", true) ; protected boolean allowDecimals = getBooleanValue("useDecimals", true) ; // ---------------------------------------------------- // Jena RDFWriter interface @Override public RDFErrorHandler setErrorHandler(RDFErrorHandler errHandler) { RDFErrorHandler old = errorHandler; errorHandler = errHandler; return old; } @Override public Object setProperty(String propName, Object propValue) { if ( ! ( propValue instanceof String ) ) { logger.warn("N3.setProperty: Property for '"+propName+"' is not a string") ; propValue = propValue.toString() ; } // Store absolute name of property propName = absolutePropName(propName) ; if ( writerPropertyMap == null ) writerPropertyMap = new HashMap<>() ; Object oldValue = writerPropertyMap.get(propName); writerPropertyMap.put(propName, propValue); return oldValue; } /** Write the model out in N3. The writer should be one suitable for UTF-8 which * excludes a PrintWriter or a FileWriter which use default character set. * * Examples: * <pre> * try { * Writer w = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")) ; * model.write(w, base) ; * try { w.flush() ; } catch (IOException ioEx) {...} * } catch (java.io.UnsupportedEncodingException ex) {} //UTF-8 is required so can't happen * </pre> * or * <pre> * try { * OutputStream out = new FileOutputStream(file) ; * Writer w = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")) ; * model.write(w, base) ; * } * catch (java.io.UnsupportedEncodingException ex) {} * catch (java.io.FileNotFoundException noFileEx) { ... } * </pre> * @see #write(Model,Writer,String) */ @Override public void write(Model baseModel, Writer _out, String base) { if (!(_out instanceof BufferedWriter)) _out = new BufferedWriter(_out); out = new N3IndentedWriter(_out); // BaseURI - <#> // if ( base != null ) // { // baseURIref = base ; // if ( !base.endsWith("#") &&! isOpaque(base) ) // baseURIrefHash = baseURIref+"#" ; // } processModel(baseModel) ; } /** Write the model out in N3, encoded in in UTF-8 * @see #write(Model,Writer,String) */ @Override public synchronized void write(Model model, OutputStream output, String base) { try { Writer w = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")) ; write(model, w, base) ; try { w.flush() ; } catch (IOException ioEx) { throw new JenaException(ioEx) ; } } catch (java.io.UnsupportedEncodingException ex) { System.err.println("Failed to create UTF-8 writer") ; } } // ---------------------------------------------------- // The assumed processing model is: // Writing N3 involves ordering the graph into: // -- Subjects // -- Property lists within subjects // -- Object lists with in properties // A derived class may choose to intercept and implement at any of these levels. // Standard layout is: // subject // property1 value1 ; // property2 value2 ; // property3 value3 . // Normal hook points for subclasses. protected void startWriting() {} protected void finishWriting() {} protected void prepare(Model model) {} protected void processModel(Model model) { prefixMap = model.getNsPrefixMap() ; bNodesMap = new HashMap<>() ; // PrefixMapping (to Jena 2.5.7 at least) // is specialized to XML-isms and Turle prefixed names aren't quite qnames. // Build temporary maps of acceptable prefixes and URIs. // If no base defined for the model, but one given to writer, // then use this. String base2 = prefixMap.get("") ; // BaseURI - <#> // if ( base2 == null && baseURIrefHash != null ) // prefixMap.put("", baseURIrefHash) ; for ( Iterator<Entry<String, String>> iter = prefixMap.entrySet().iterator() ; iter.hasNext() ; ) { Entry<String, String> e = iter.next() ; String prefix = e.getKey() ; String uri = e.getValue(); // XML namespaces name can include '.' // Turtle prefixed names can't. if ( ! checkPrefixPart(prefix) ) iter.remove() ; else { if ( checkPrefixPart(prefix) ) // Build acceptable reverse mapping reversePrefixMap.put(uri, prefix) ; } } startWriting() ; prepare(model) ; writeHeader(model) ; writePrefixes(model) ; if (prefixMap.size() != 0) out.println(); // Do the output. writeModel(model) ; // Release intermediate memory - allows reuse of a writer finishWriting() ; bNodesMap = null ; } protected void writeModel(Model model) { // Needed only for no prefixes, no blank first line. boolean doingFirst = true; ResIterator rIter = listSubjects(model); for (; rIter.hasNext();) { // Subject: // First - it is something we will write out as a structure in an object field? // That is, a RDF list or the object of exactly one statement. Resource subject = rIter.nextResource(); if ( skipThisSubject(subject) ) { if (N3JenaWriter.DEBUG) out.println("# Skipping: " + formatResource(subject)); continue; } // We really are going to print something via writeTriples if (doingFirst) doingFirst = false; else out.println(); writeOneGraphNode(subject) ; } rIter.close(); } protected ResIterator listSubjects(Model model) { return model.listSubjects(); } protected void writeOneGraphNode(Resource subject) { // New top level item. // Does not take effect until newline. out.incIndent(indentProperty) ; writeSubject(subject); ClosableIterator<Property> iter = preparePropertiesForSubject(subject); writePropertiesForSubject(subject, iter) ; out.decIndent(indentProperty) ; out.println(" ."); } protected void writePropertiesForSubject(Resource subj, ClosableIterator<Property> iter) { // For each property. for (; iter.hasNext();) { Property property = iter.next(); // Object list writeObjectList(subj, property); if (iter.hasNext()) out.println(" ;"); } iter.close(); } // Hook called on every resource. // Since there is spacing bewteen resource frames, need to know // whether an item will cause any output. protected boolean skipThisSubject(Resource r) { return false ; } // This is the hook called within writeModel. // NB May not be at the top level (indent = 0) protected void writeSubject(Resource subject) { String subjStr = formatResource(subject); out.print(subjStr); // May be very short : if so, stay on this line. // Currently at end of subject. // NB shortSubject is (subjectColumn-minGap) so there is a gap. if (subjStr.length() < shortSubject ) { out.print(pad(subjectColumn - subjStr.length()) ); } else // Does not fit this line. out.println(); } protected void writeHeader(Model model) { // BaseURI - <#> // if (baseURIref != null && !baseURIref.equals("") ) // out.println("# Base: " + baseURIref); } protected N3IndentedWriter getOutput() { return out ; } protected Map<String, String> getPrefixes() { return prefixMap ; } protected void writePrefixes(Model model) { for ( String p : prefixMap.keySet() ) { String u = prefixMap.get( p ); // BaseURI - <#> // // Special cases: N3 handling of base names. // if (doAbbreviatedBaseURIref && p.equals("")) // { // if (baseURIrefHash != null && u.equals(baseURIrefHash)) // u = "#"; // if (baseURIref != null && u.equals(baseURIref)) // u = ""; // } String tmp = "@prefix " + p + ": "; out.print( tmp ); out.print( pad( 16 - tmp.length() ) ); // NB Starts with a space to ensure a gap. out.println( " <" + u + "> ." ); } } protected void writeObjectList(Resource subject, Property property) { String propStr = formatProperty(property) ; // if (wellKnownPropsMap.containsKey(property.getURI())) // propStr = (String) wellKnownPropsMap.get(property.getURI()); // else // propStr = formatResource(property); // Write with object lists as clusters of statements with the same property // Looks more like a machine did it but fewer bad cases. StmtIterator sIter = subject.listProperties(property); for (; sIter.hasNext();) { Statement stmt = sIter.nextStatement() ; String objStr = formatNode(stmt.getObject()) ; out.print(propStr); out.incIndent(indentObject); if ( (propStr.length()+minGap) <= widePropertyLen ) { // Property col allows for min gap but widePropertyLen > propertyCol // (which looses alignment - this is intentional. // Ensure there is at least min gap. int padding = calcPropertyPadding(propStr) ; out.print(pad(padding)) ; // if ( propStr.length() < propertyWidth ) // out.print( pad(propertyCol-minGap-propStr.length()) ) ; // out.print(minGapStr) ; } else // Does not fit this line. out.println(); // Write one object - simple writing. out.print(objStr) ; out.decIndent(indentObject); if ( sIter.hasNext() ) { out.println(" ;") ; } } sIter.close() ; } protected String formatNode(RDFNode node) { if (node instanceof Literal) return formatLiteral((Literal) node); else return formatResource((Resource)node) ; } protected void writeObject(RDFNode node) { if (node instanceof Literal) { writeLiteral((Literal) node); return; } Resource rObj = (Resource) node; out.print(formatResource(rObj)); } protected void writeLiteral(Literal literal) { out.print(formatLiteral(literal)) ; } protected ClosableIterator<Property> preparePropertiesForSubject(Resource r) { // Properties to do. Set<Property> properties = new HashSet<>() ; StmtIterator sIter = r.listProperties(); for ( ; sIter.hasNext() ; ) properties.add(sIter.nextStatement().getPredicate()) ; sIter.close() ; return WrappedIterator.create(properties.iterator()) ; } // Utility operations protected String formatResource(Resource r) { if ( r.isAnon() ) { if ( ! alwaysAllocateBNodeLabel ) { // Does anything point to it? StmtIterator sIter = r.getModel().listStatements(null, null, r) ; if ( ! sIter.hasNext() ) { sIter.close() ; // This bNode is not referenced so don't need the bNode Id. // Must be a subject - indent better be zero! // This only happens for subjects because object bNodes // referred to once (the other case for [] syntax) // are handled elsewhere (by oneRef set) // Later: use [ prop value ] for this. return "[]" ; } sIter.close() ; } if ( ! bNodesMap.containsKey(r) ) bNodesMap.put(r, "_:b"+(++bNodeCounter)) ; return bNodesMap.get(r) ; } // It has a URI. if ( r.equals(RDF.nil) ) return "()" ; return formatURI(r.getURI()) ; } protected String formatLiteral(Literal literal) { String datatype = literal.getDatatypeURI() ; String lang = literal.getLanguage() ; String s = literal.getLexicalForm() ; if ( datatype != null ) { // Special form we know how to handle? // Assume valid text if ( datatype.equals(XSD.integer.getURI()) ) { try { new java.math.BigInteger(s) ; return s ; } catch (NumberFormatException nfe) {} // No luck. Continue. // Continuing is always safe. } if ( datatype.equals(XSD.decimal.getURI()) ) { // Must have ., can't have e or E if ( s.indexOf('.') >= 0 && s.indexOf('e') == -1 && s.indexOf('E') == -1 ) { // Turtle - N3 does not allow .3 +.3 or -.3 // See if parsable. try { BigDecimal d = new BigDecimal(s) ; return s ; } catch (NumberFormatException nfe) {} } } if ( this.allowDoubles && datatype.equals(XSD.xdouble.getURI()) ) { // Must have 'e' or 'E' (N3 and Turtle now read 2.3 as a decimal). if ( s.indexOf('e') >= 0 || s.indexOf('E') >= 0 ) { try { // Validate it. Double.parseDouble(s) ; return s ; } catch (NumberFormatException nfe) {} // No luck. Continue. } } } // Format the text - with escaping. StringBuffer sbuff = new StringBuffer() ; boolean singleQuoteLiteral = true ; String quoteMarks = "\"" ; // Things that force the use of """ strings if ( this.allowTripleQuotedStrings && ( s.indexOf("\n") != -1 || s.indexOf("\r") != -1 || s.indexOf("\f") != -1 ) ) { quoteMarks = "\"\"\"" ; singleQuoteLiteral = false ; } sbuff.append(quoteMarks); string(sbuff, s, singleQuoteLiteral) ; sbuff.append(quoteMarks); // Format the language tag if ( lang != null && lang.length()>0) { sbuff.append("@") ; sbuff.append(lang) ; } // Format the datatype if ( datatype != null ) { sbuff.append("^^") ; sbuff.append(formatURI(datatype)) ; } return sbuff.toString() ; } protected String formatProperty(Property p) { String prop = p.getURI() ; if ( this.useWellKnownPropertySymbols && wellKnownPropsMap.containsKey(prop) ) return wellKnownPropsMap.get(prop); return formatURI(prop) ; } protected String formatURI(String uriStr) { String matchURI = "" ; String matchPrefix = null ; // BaseURI - <#> // if ( doAbbreviatedBaseURIref && uriStr.equals(baseURIref) ) // return "<>" ; // Try for a prefix and write as prefixed name. // 1/ Try splitting as a prefixed name // 2/ Search for possibilities // Stage 1. int idx = splitIdx(uriStr) ; // Depends on legal URIs. if ( idx >= 0 ) { // Include the # itself. String x = uriStr.substring(0,idx+1) ; String prefix = reversePrefixMap.get(x) ; if ( prefix != null ) { String localPart = uriStr.substring(idx+1) ; if ( checkNamePart(localPart) ) return prefix+':'+localPart ; } } // Unsplit. Could just return here. // // Find the longest if several. // // Possible optimization: split URI and have URI=> ns: map. // // Ordering prefixes by length, then first hit is better. // // // // Also: could just assume that the split is on / or # // // Means we need to find a prefix just once. // for ( Iterator<String> pIter = prefixMap.keySet().iterator() ; pIter.hasNext() ; ) // { // String p = pIter.next() ; // String u = prefixMap.get(p) ; // if ( uriStr.startsWith(u) ) // if ( matchURI.length() < u.length() ) // { // matchPrefix = p ; // matchURI = u ; // } // } // if ( matchPrefix != null ) // { // String localname = uriStr.substring(matchURI.length()) ; // // if ( checkPrefixedName(matchPrefix, localname) ) // return matchPrefix+":"+localname ; // // // Continue and return quoted URIref // } // Not as a prefixed name - write as a quoted URIref // It should be right - the writer should be UTF-8 on output. return "<"+uriStr+">" ; } protected static int splitIdx(String uriStr) { int idx = uriStr.lastIndexOf('#') ; if ( idx >= 0 ) return idx ; // No # - try for / idx = uriStr.lastIndexOf('/') ; return idx ; } // Checks of prefixed names // These tests must agree, or be more restrictive, than the parser. protected static boolean checkPrefixedName(String ns, String local) { return checkPrefixPart(ns) && checkNamePart(local) ; } /* http://www.w3.org/TeamSubmission/turtle/#sec-grammar-grammar * [27] qname ::= prefixName? ':' name? * [30] nameStartChar ::= [A-Z] | "_" | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] * [31] nameChar ::= nameStartChar | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] * [32] name ::= nameStartChar nameChar* * [33] prefixName ::= ( nameStartChar - '_' ) nameChar* */ protected static boolean checkPrefixPart(String s) { if ( s.length() == 0 ) return true; CharacterIterator cIter = new StringCharacterIterator(s) ; char ch = cIter.first() ; if ( ! checkNameStartChar(ch) ) return false ; if ( ch == '_' ) // Can't start with _ (bnodes labels handled separately) return false ; return checkNameTail(cIter) ; } protected static boolean checkNamePart(String s) { if ( s.length() == 0 ) return true; CharacterIterator cIter = new StringCharacterIterator(s) ; char ch = cIter.first() ; if ( ! checkNameStartChar(ch) ) return false ; return checkNameTail(cIter) ; } private static boolean checkNameTail(CharacterIterator cIter) { // Assumes cIter.first already called but nothing else. // Skip first char. char ch = cIter.next() ; for ( ; ch != java.text.CharacterIterator.DONE ; ch = cIter.next() ) { if ( ! checkNameChar(ch) ) return false ; } return true ; } protected static boolean checkNameStartChar(char ch) { if ( Character.isLetter(ch) ) return true ; if ( ch == '_' ) return true ; return false ; } protected static boolean checkNameChar(char ch) { if ( Character.isLetterOrDigit(ch) ) return true ; if ( ch == '_' ) return true ; if ( ch == '-' ) return true ; return false ; } protected final static String WS = "\n\r\t" ; protected static void string(StringBuffer sbuff, String s, boolean singleQuoteLiteral) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // Escape escapes and quotes if (c == '\\' || c == '"' ) { sbuff.append('\\') ; sbuff.append(c) ; continue ; } // Characters to literally output. // This would generate 7-bit safe files // if (c >= 32 && c < 127) // { // sbuff.append(c) ; // continue; // } // Whitespace if ( singleQuoteLiteral && ( c == '\n' || c == '\r' || c == '\f' ) ) { if (c == '\n') sbuff.append("\\n"); if (c == '\t') sbuff.append("\\t"); if (c == '\r') sbuff.append("\\r"); if (c == '\f') sbuff.append("\\f"); continue ; } // Output as is (subject to UTF-8 encoding on output that is) sbuff.append(c) ; // // Unicode escapes // // c < 32, c >= 127, not whitespace or other specials // String hexstr = Integer.toHexString(c).toUpperCase(); // int pad = 4 - hexstr.length(); // sbuff.append("\\u"); // for (; pad > 0; pad--) // sbuff.append("0"); // sbuff.append(hexstr); } } protected int calcPropertyPadding(String propStr) { int padding = propertyCol - propStr.length(); if (padding < minGap) padding = minGap; return padding ; } protected static String pad(int cols) { StringBuffer sb = new StringBuffer() ; for ( int i = 0 ; i < cols ; i++ ) sb.append(' ') ; return sb.toString() ; } // Utilities protected int countProperties(Resource r) { int numProp = 0 ; StmtIterator sIter = r.listProperties() ; for ( ; sIter.hasNext() ; ) { sIter.nextStatement() ; numProp++ ; } sIter.close() ; return numProp ; } protected int countProperties(Resource r, Property p) { int numProp = 0 ; StmtIterator sIter = r.listProperties(p) ; for ( ; sIter.hasNext() ; ) { sIter.nextStatement() ; numProp++ ; } sIter.close() ; return numProp ; } protected int countArcsTo(Resource resource) { return countArcsTo(null, resource) ; } protected int countArcsTo(Property prop, Resource resource) { int numArcs = 0 ; StmtIterator sIter = resource.getModel().listStatements(null, prop, resource) ; for ( ; sIter.hasNext() ; ) { sIter.nextStatement() ; numArcs++ ; } sIter.close() ; return numArcs ; } protected Iterator<RDFNode> rdfListIterator(Resource r) { List<RDFNode> list = new ArrayList<>() ; for ( ; ! r.equals(RDF.nil); ) { StmtIterator sIter = r.getModel().listStatements(r, RDF.first, (RDFNode)null) ; list.add(sIter.nextStatement().getObject()) ; if ( sIter.hasNext() ) // @@ need to cope with this (unusual) case throw new JenaException("N3: Multi valued list item") ; sIter = r.getModel().listStatements(r, RDF.rest, (RDFNode)null) ; r = (Resource)sIter.nextStatement().getObject() ; if ( sIter.hasNext() ) throw new JenaException("N3: List has two tails") ; } return list.iterator() ; } // Convenience operations for accessing system properties. protected String getStringValue(String prop, String defaultValue) { String p = getPropValue(prop) ; if ( p == null ) return defaultValue ; return p ; } protected boolean getBooleanValue(String prop, boolean defaultValue) { String p = getPropValue(prop) ; if ( p == null ) return defaultValue ; if ( p.equalsIgnoreCase("true") ) return true ; if ( p.equals("1") ) return true ; return false ; } protected int getIntValue(String prop, int defaultValue) { String p = getPropValue(prop) ; if ( p == null ) return defaultValue ; try { return Integer.parseInt(p) ; } catch (NumberFormatException ex) { logger.warn("Format error for property: "+prop) ; return defaultValue ; } } // May be the absolute or local form of the property name protected String getPropValue(String prop) { prop = absolutePropName(prop) ; if ( writerPropertyMap != null && writerPropertyMap.containsKey(prop) ) { Object obj = writerPropertyMap.get(prop) ; if ( ! ( obj instanceof String ) ) logger.warn("getPropValue: N3 Property for '"+prop+"' is not a string") ; return (String)obj ; } String s = JenaRuntime.getSystemProperty(prop) ; if ( s == null ) s = JenaRuntime.getSystemProperty(localPropName(prop)) ; return s ; } protected String absolutePropName(String propName) { if ( propName.indexOf(':') == -1 ) return N3JenaWriter.propBase + propName ; return propName ; } protected String localPropName(String propName) { if ( propName.startsWith(N3JenaWriter.propBase) ) propName = propName.substring(N3JenaWriter.propBase.length()) ; return propName ; } private boolean isOpaque(String uri) { try { return new URI(uri).isOpaque() ; } catch (URISyntaxException ex) { return true ; } } }
JENA-816 : Fix for deprecated N3 writer.
jena-core/src/main/java/com/hp/hpl/jena/n3/N3JenaWriterCommon.java
JENA-816 : Fix for deprecated N3 writer.
<ide><path>ena-core/src/main/java/com/hp/hpl/jena/n3/N3JenaWriterCommon.java <ide> import org.slf4j.LoggerFactory; <ide> <ide> import com.hp.hpl.jena.rdf.model.*; <del> <add>import com.hp.hpl.jena.rdf.model.impl.Util ; <ide> import com.hp.hpl.jena.util.iterator.ClosableIterator; <ide> import com.hp.hpl.jena.util.iterator.WrappedIterator; <del> <ide> import com.hp.hpl.jena.JenaRuntime; <ide> import com.hp.hpl.jena.shared.JenaException; <ide> import com.hp.hpl.jena.vocabulary.OWL; <ide> string(sbuff, s, singleQuoteLiteral) ; <ide> sbuff.append(quoteMarks); <ide> <del> // Format the language tag <del> if ( lang != null && lang.length()>0) <del> { <add> if ( Util.isLangString(literal) ) { <ide> sbuff.append("@") ; <ide> sbuff.append(lang) ; <del> } <del> <del> // Format the datatype <del> if ( datatype != null ) <del> { <add> } else if ( ! Util.isSimpleString(literal) ) { <ide> sbuff.append("^^") ; <ide> sbuff.append(formatURI(datatype)) ; <ide> }
Java
apache-2.0
96ee76fb89c0e4b25273159ce24a09f028c3b06b
0
venusdrogon/feilong-servlet,venusdrogon/feilong-servlet
/* * Copyright (C) 2008 feilong * * 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.feilong.servlet.http; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feilong.core.Validator; import com.feilong.core.bean.PropertyUtil; import com.feilong.servlet.http.entity.CookieEntity; import com.feilong.tools.jsonlib.JsonUtil; /** * {@link javax.servlet.http.Cookie Cookie} 工具类. * * <p> * 注意:该类创建Cookie仅支持Servlet3以上的版本 * </p> * * <h3>使用说明:</h3> * * <h4> * case:创建Cookie * </h4> * * <blockquote> * <p> * 1.创建一个name名字是shopName,value是feilong的 Cookie (通常出于安全起见,存放到Cookie的值需要加密或者混淆,此处为了举例方便使用原码)<br> * 可以调用{@link #addCookie(String, String, HttpServletResponse)}<br> * 如: * <p> * <code>CookieUtil.addCookie("shopName","feilong",response)</code> * </p> * 注意:该方法创建的cookie,有效期是默认值 -1,即浏览器退出就删除 * </p> * * <p> * 2.如果想给该cookie加个过期时间,有效期一天,可以调用 {@link #addCookie(String, String, int, HttpServletResponse)}<br> * 如: * <p> * <code>CookieUtil.addCookie("shopName","feilong", TimeInterval.SECONDS_PER_DAY,response)</code> * </p> * </p> * * <p> * 3.如果还想给该cookie加上httpOnly等标识,可以调用 {@link #addCookie(CookieEntity, HttpServletResponse)}<br> * 如: * * <pre> {@code CookieEntity cookieEntity=new CookieEntity("shopName","feilong",TimeInterval.SECONDS_PER_DAY); cookieEntity.setHttpOnly(true); CookieUtil.addCookie(cookieEntity,response) } * </pre> * * 此外,如果有特殊需求,还可以对cookieEntity设置 path,domain等属性 * </p> * </blockquote> * * <h4> * case:获取Cookie * </h4> * * <blockquote> * * <p> * 1.可以使用 {@link #getCookie(HttpServletRequest, String)}来获得 {@link Cookie}对象 * <br> * 如: * <p> * <code>CookieUtil.getCookie(request, "shopName")</code> * </p> * </p> * * <p> * 2.更多的时候,可以使用 {@link #getCookieValue(HttpServletRequest, String)}来获得Cookie对象的值 * <br> * 如: * <p> * <code>CookieUtil.getCookieValue(request, "shopName")</code> * </p> * * 返回 "feilong" 字符串 * </p> * * * <p> * 3.当然,你也可以使用 {@link #getCookieMap(HttpServletRequest)}来获得 所有的Cookie name和value组成的map * <br> * 如: * <p> * <code>CookieUtil.getCookieMap(request)</code> * </p> * * 使用场景,如 {@link com.feilong.servlet.http.RequestLogBuilder#build()} * </p> * </blockquote> * * * * <h4> * case:删除Cookie * </h4> * * <blockquote> * * <p> * 1.可以使用 {@link #deleteCookie(String, HttpServletResponse)}来删除Cookie * <br> * 如: * <p> * <code>CookieUtil.deleteCookie(request, "shopName")</code> * </p> * </p> * * <p> * 2.特殊时候,由于Cookie原先保存时候设置了path属性,可以使用 {@link #deleteCookie(CookieEntity, HttpServletResponse)}来删除Cookie * <br> * 如: * * <p> * * <pre> {@code CookieEntity cookieEntity=new CookieEntity("shopName","feilong"); cookieEntity.setPath("/member/account"); CookieUtil.deleteCookie(request, "shopName") } * </pre> * </p> * * </p> * * </blockquote> * * @author feilong * @version 2010-6-24 上午08:05:32 * @version 2012-5-18 14:53 * @see javax.servlet.http.Cookie * @see "org.springframework.web.util.CookieGenerator" * @see com.feilong.servlet.http.entity.CookieEntity * @since 1.0.0 */ public final class CookieUtil{ /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(CookieUtil.class); /** Don't let anyone instantiate this class. */ private CookieUtil(){ //AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化. //see 《Effective Java》 2nd throw new AssertionError("No " + getClass().getName() + " instances for you!"); } //******************************************************************** /** * 取到Cookie值. * * @param request * HttpServletRequest * @param cookieName * cookie名字,{@link Cookie#getName()} * @return 如果取不到cookie,返回 <code>null</code>;<br> * 否则,返回 {@link Cookie#getValue()} * @see #getCookie(HttpServletRequest, String) * @see Cookie#getValue() */ public static String getCookieValue(HttpServletRequest request,String cookieName){ Cookie cookie = getCookie(request, cookieName); return null == cookie ? null : cookie.getValue(); } /** * 获得 {@link Cookie}对象. * * <p> * 循环遍历 {@link HttpServletRequest#getCookies()},找到 {@link Cookie#getName()}是 <code>cookieName</code> 的 {@link Cookie} * </p> * * @param request * the request * @param cookieName * the cookie name * @return 如果 {@link HttpServletRequest#getCookies()}是 null,则返回null;<br> * 如果通过 <code>cookieName</code> 找不到指定的 {@link Cookie},也返回null * @see javax.servlet.http.HttpServletRequest#getCookies() * @see javax.servlet.http.Cookie#getName() */ public static Cookie getCookie(HttpServletRequest request,String cookieName){ Cookie[] cookies = request.getCookies(); if (Validator.isNullOrEmpty(cookies)){ LOGGER.info("request's cookies is null or empty!!"); return null; } for (Cookie cookie : cookies){ if (cookie.getName().equals(cookieName)){ if (LOGGER.isDebugEnabled()){ LOGGER.debug("getCookie,cookieName:[{}],cookie info:[{}]", cookieName, JsonUtil.format(cookie)); } return cookie; } } LOGGER.info("can't find the cookie:[{}]", cookieName); return null; } /** * 将cookie的 key 和value转成 map(TreeMap). * * @param request * the request * @return 如果没有 {@link HttpServletRequest#getCookies()},返回 {@link Collections#emptyMap()};<br> * 否则,返回 loop cookies,取到 {@link Cookie#getName()}以及 {@link Cookie#getValue()} 设置成map 返回 * @see HttpServletRequest#getCookies() * @see javax.servlet.http.Cookie#getName() * @see javax.servlet.http.Cookie#getValue() */ public static Map<String, String> getCookieMap(HttpServletRequest request){ Cookie[] cookies = request.getCookies(); if (Validator.isNullOrEmpty(cookies)){ return Collections.emptyMap(); } Map<String, String> map = new TreeMap<String, String>(); for (Cookie cookie : cookies){ map.put(cookie.getName(), cookie.getValue()); } return map; } //********************************************************************************* /** * 删除cookie. * * <p style="color:red"> * 删除Cookie的时候,path必须保持一致;<br> * 如果path不一致,请使用 {@link CookieUtil#deleteCookie(CookieEntity, HttpServletResponse)} * </p> * * @param cookieName * the cookie name * @param response * the response * @see #deleteCookie(CookieEntity, HttpServletResponse) */ public static void deleteCookie(String cookieName,HttpServletResponse response){ CookieEntity cookieEntity = new CookieEntity(cookieName, ""); deleteCookie(cookieEntity, response); } /** * 删除cookie. * * <p style="color:red"> * 删除 Cookie的时候,path必须保持一致 * </p> * * @param cookieEntity * the cookie entity * @param response * the response * @see #addCookie(CookieEntity, HttpServletResponse) * @since 1.5.0 */ public static void deleteCookie(CookieEntity cookieEntity,HttpServletResponse response){ Validate.notNull(cookieEntity, "cookieEntity can't be null!"); cookieEntity.setMaxAge(0);// 设置为0为立即删除该Cookie addCookie(cookieEntity, response); LOGGER.debug("deleteCookie,cookieName:[{}]", cookieEntity.getName()); } //**************************************************************************************************** /** * 创建cookie. * * <p> * 注意:该方法创建的cookie,有效期是默认值 -1,即浏览器退出就删除 * </p> * * @param cookieName * the cookie name * @param value * cookie的值,更多说明,参见 {@link CookieEntity#getValue()} * <p style="color:red"> * 注意:如果值长度超过4K,浏览器会忽略,不会执行记录的操作 * </p> * @param response * response * @see CookieUtil#addCookie(CookieEntity, HttpServletResponse) * @since 1.5.0 */ public static void addCookie(String cookieName,String value,HttpServletResponse response){ Validate.notEmpty(cookieName, "cookieName can't be null/empty!"); CookieEntity cookieEntity = new CookieEntity(cookieName, value); addCookie(cookieEntity, response); } /** * 创建cookie. * * @param cookieName * the cookie name * @param value * cookie的值,更多说明,参见 {@link CookieEntity#getValue()} * <p style="color:red"> * 注意:如果值长度超过4K,浏览器会忽略,不会执行记录的操作 * </p> * @param maxAge * 设置以秒计的cookie的最大存活时间,可以使用 {@link com.feilong.core.TimeInterval TimeInterval}相关常量 * @param response * response * @see CookieUtil#addCookie(CookieEntity, HttpServletResponse) * @since 1.5.0 */ public static void addCookie(String cookieName,String value,int maxAge,HttpServletResponse response){ Validate.notEmpty(cookieName, "cookieName can't be null/empty!"); CookieEntity cookieEntity = new CookieEntity(cookieName, value, maxAge); addCookie(cookieEntity, response); } /** * 创建cookie. * * @param cookieEntity * cookieEntity * @param response * response * @see "org.apache.catalina.connector.Response#generateCookieString(Cookie, boolean)" */ public static void addCookie(CookieEntity cookieEntity,HttpServletResponse response){ //校验 validateCookieEntity(cookieEntity); Cookie cookie = toCookie(cookieEntity); if (LOGGER.isDebugEnabled()){ LOGGER.debug("input cookieEntity info:[{}],response.addCookie", JsonUtil.format(cookieEntity)); } response.addCookie(cookie); } /** * To cookie. * * @param cookieEntity * the cookie entity * @return the cookie * @since 1.5.3 */ private static Cookie toCookie(CookieEntity cookieEntity){ Cookie cookie = new Cookie(cookieEntity.getName(), cookieEntity.getValue()); PropertyUtil.copyProperties(cookie, cookieEntity // , "maxAge"//设置以秒计的cookie的最大存活时间。 , "secure"//指定是否cookie应该只通过安全协议,例如HTTPS或SSL,传送给浏览器。 , "version"//设置本cookie遵循的cookie的协议的版本 , "httpOnly"//@since Servlet 3.0 ); PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "comment", cookieEntity.getComment());//指定一个注释来描述cookie的目的。 //NullPointerException at javax.servlet.http.Cookie.setDomain(Cookie.java:213) ~[servlet-api-6.0.37.jar:na] PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "domain", cookieEntity.getDomain());// 指明cookie应当被声明的域。 PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "path", cookieEntity.getPath());//指定客户端将cookie返回的cookie的路径。 return cookie; } /** * Validate cookie entity. * * @param cookieEntity * the cookie entity * @since 1.5.0 */ private static void validateCookieEntity(CookieEntity cookieEntity){ Validate.notNull(cookieEntity, "cookieEntity can't be null!"); String cookieName = cookieEntity.getName(); Validate.notEmpty(cookieName, "cookieName can't be null/empty!"); String value = cookieEntity.getValue(); //如果长度超过4000,浏览器可能不支持 if (Validator.isNotNullOrEmpty(value) && value.length() > 4000){ LOGGER.warn( "cookie value:{},length:{},more than 4000!!!some browser may be not support!!!!!,cookieEntity info :{}", value, value.length(), JsonUtil.format(cookieEntity)); } } }
src/main/java/com/feilong/servlet/http/CookieUtil.java
/* * Copyright (C) 2008 feilong * * 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.feilong.servlet.http; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feilong.core.Validator; import com.feilong.servlet.http.entity.CookieEntity; import com.feilong.tools.jsonlib.JsonUtil; /** * {@link javax.servlet.http.Cookie} 工具 类. * * * <h3>cookie适用场合:</h3> * * cookie机制将信息存储于用户硬盘,因此可以作为全局变量,这是它最大的一个优点。 * * <blockquote> * <ol> * <li>保存用户登录状态。<br> * 例如将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了,现在很多论坛和社区都提供这样的功能。<br> * cookie还可以设置过期时间,当超过时间期限后,cookie就会自动消失。<br> * 因此,系统往往可以提示用户保持登录状态的时间: 常见选项有一个月、三个月、一年等。</li> * <li> * 跟踪用户行为。<br> * 例如一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。<br> * 如果每次都需要选择所在地是烦琐的,当利用了cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。<br> * 因为一切都是在后台完成 ,所以这样的页面就像为某个用户所定制的一样,使用起来非常方便。</li> * <li>定制页面。<br> * 如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用户的选项,例如:背景色、分辨率等。<br> * 当用户下次访问时,仍然可以保存上一次访问的界面风格。</li> * <li>创建购物车。<br> * 正如在前面的例子中使用cookie来记录用户需要购买的商品一样,在结账的时候可以统一提交。<br> * 例如淘宝网就使用cookie记录了用户曾经浏览过的商品,方便随时进行比较。</li> * </ol> * * </blockquote> * * <h3>cookie的缺点主要集中于安全性和隐私保护:</h3> * * <blockquote> * <ol> * <li>cookie可能被禁用。<br> * 当用户非常注重个人隐私保护时,他很可能禁用浏览器的cookie功能;</li> * <li>cookie是与浏览器相关的。<br> * 这意味着即使访问的是同一个页面,不同浏览器之间所保存的cookie也是不能互相访问的;</li> * <li>cookie可能被删除。<br> * 因为每个cookie都是硬盘上的一个文件,因此很有可能被用户删除;</li> * <li>cookie安全性不够高。<br> * 所有的cookie都是以纯文本的形式记录于文件中,因此如果要保存用户名密码等信息时,最好事先经过加密处理。</li> * </ol> * </blockquote> * * @author feilong * @version 2010-6-24 上午08:05:32 * @version 2012-5-18 14:53 * @see javax.servlet.http.Cookie * @see "org.springframework.web.util.CookieGenerator" * @since 1.0.0 */ public final class CookieUtil{ /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(CookieUtil.class); /** Don't let anyone instantiate this class. */ private CookieUtil(){ //AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化. //see 《Effective Java》 2nd throw new AssertionError("No " + getClass().getName() + " instances for you!"); } //******************************************************************** /** * 取到Cookie值. * * @param request * HttpServletRequest * @param cookieName * cookie名字,{@link Cookie#getName()} * @return 如果取不到cookie,返回 <code>null</code>;<br> * 否则,返回 {@link Cookie#getValue()} * @see #getCookie(HttpServletRequest, String) * @see Cookie#getValue() */ public static String getCookieValue(HttpServletRequest request,String cookieName){ Cookie cookie = getCookie(request, cookieName); return null == cookie ? null : cookie.getValue(); } /** * 获得cookie. * * <p> * 循环遍历 {@link HttpServletRequest#getCookies()},找到 {@link Cookie#getName()}是 <code>cookieName</code> 的 {@link Cookie} * </p> * * @param request * the request * @param cookieName * the cookie name * @return 如果 {@link HttpServletRequest#getCookies()}是 null,则返回null;<br> * 如果通过 <code>cookieName</code> 找不到指定的 {@link Cookie},也返回null * @see javax.servlet.http.HttpServletRequest#getCookies() * @see javax.servlet.http.Cookie#getName() */ public static Cookie getCookie(HttpServletRequest request,String cookieName){ Cookie[] cookies = request.getCookies(); if (Validator.isNullOrEmpty(cookies)){ LOGGER.info("request's cookies is null or empty!!"); return null; } for (Cookie cookie : cookies){ if (cookie.getName().equals(cookieName)){ if (LOGGER.isDebugEnabled()){ LOGGER.debug("getCookie,cookieName:[{}],cookie info:[{}]", cookieName, JsonUtil.format(cookie)); } return cookie; } } LOGGER.info("can't find the cookie:[{}]", cookieName); return null; } /** * 将cookie的 key 和value转成 map(TreeMap). * * @param request * the request * @return 如果没有 {@link HttpServletRequest#getCookies()},返回 {@link Collections#emptyMap()};<br> * 否则,返回 loop cookies,取到 {@link Cookie#getName()}以及 {@link Cookie#getValue()} 设置成map 返回 * @see HttpServletRequest#getCookies() * @see javax.servlet.http.Cookie#getName() * @see javax.servlet.http.Cookie#getValue() */ public static Map<String, String> getCookieMap(HttpServletRequest request){ Cookie[] cookies = request.getCookies(); if (Validator.isNullOrEmpty(cookies)){ return Collections.emptyMap(); } Map<String, String> map = new TreeMap<String, String>(); for (Cookie cookie : cookies){ map.put(cookie.getName(), cookie.getValue()); } return map; } //********************************************************************************* /** * 删除cookie. * * <p style="color:red"> * 删除Cookie的时候,path必须保持一致;<br> * 如果path不一致,请使用 {@link CookieUtil#deleteCookie(CookieEntity, HttpServletResponse)} * </p> * * @param cookieName * the cookie name * @param response * the response * @see #deleteCookie(CookieEntity, HttpServletResponse) */ public static void deleteCookie(String cookieName,HttpServletResponse response){ CookieEntity cookieEntity = new CookieEntity(cookieName, ""); deleteCookie(cookieEntity, response); } /** * 删除cookie. * * <p style="color:red"> * 删除 Cookie的时候,path必须保持一致 * </p> * * @param cookieEntity * the cookie entity * @param response * the response * @see #addCookie(CookieEntity, HttpServletResponse) * @since 1.5.0 */ public static void deleteCookie(CookieEntity cookieEntity,HttpServletResponse response){ Validate.notNull(cookieEntity, "cookieEntity can't be null!"); cookieEntity.setMaxAge(0);// 设置为0为立即删除该Cookie addCookie(cookieEntity, response); LOGGER.debug("deleteCookie,cookieName:[{}]", cookieEntity.getName()); } //**************************************************************************************************** /** * 创建个cookie. * * @param cookieName * the cookie name * @param value * cookie的值,更多说明,参见 {@link CookieEntity#getValue()} * <p style="color:red"> * 注意:如果值长度超过4K,浏览器会忽略,不会执行记录的操作 * </p> * @param response * response * @see CookieUtil#addCookie(CookieEntity, HttpServletResponse) * @since 1.5.0 */ public static void addCookie(String cookieName,String value,HttpServletResponse response){ Validate.notEmpty(cookieName, "cookieName can't be null/empty!"); CookieEntity cookieEntity = new CookieEntity(cookieName, value); addCookie(cookieEntity, response); } /** * 创建个cookie. * * @param cookieName * the cookie name * @param value * cookie的值,更多说明,参见 {@link CookieEntity#getValue()} * <p style="color:red"> * 注意:如果值长度超过4K,浏览器会忽略,不会执行记录的操作 * </p> * @param maxAge * 设置以秒计的cookie的最大存活时间,可以使用 {@link com.feilong.core.TimeInterval TimeInterval}相关常量 * @param response * response * @see CookieUtil#addCookie(CookieEntity, HttpServletResponse) * @since 1.5.0 */ public static void addCookie(String cookieName,String value,int maxAge,HttpServletResponse response){ Validate.notEmpty(cookieName, "cookieName can't be null/empty!"); CookieEntity cookieEntity = new CookieEntity(cookieName, value, maxAge); addCookie(cookieEntity, response); } /** * 创建cookie. * * @param cookieEntity * cookieEntity * @param response * response * @see "org.apache.catalina.connector.Response#generateCookieString(Cookie, boolean)" */ public static void addCookie(CookieEntity cookieEntity,HttpServletResponse response){ //校验 validateCookieEntity(cookieEntity); String cookieName = cookieEntity.getName(); String value = cookieEntity.getValue(); //**************************************************************************** Cookie cookie = new Cookie(cookieName, value); cookie.setMaxAge(cookieEntity.getMaxAge());//设置以秒计的cookie的最大存活时间。 String comment = cookieEntity.getComment(); if (Validator.isNotNullOrEmpty(comment)){ cookie.setComment(comment);//指定一个注释来描述cookie的目的。 } // 指明cookie应当被声明的域。 String domain = cookieEntity.getDomain(); if (Validator.isNotNullOrEmpty(domain)){ //NullPointerException at javax.servlet.http.Cookie.setDomain(Cookie.java:213) ~[servlet-api-6.0.37.jar:na] cookie.setDomain(domain); } //指定客户端将cookie返回的cookie的路径。 String path = cookieEntity.getPath(); if (Validator.isNotNullOrEmpty(path)){ cookie.setPath(path); } //指定是否cookie应该只通过安全协议,例如HTTPS或SSL,传送给浏览器。 cookie.setSecure(cookieEntity.getSecure()); //设置本cookie遵循的cookie的协议的版本 cookie.setVersion(cookieEntity.getVersion()); //HttpOnly cookies are not supposed to be exposed to client-side scripting code, //and may therefore help mitigate certain kinds of cross-site scripting attacks. cookie.setHttpOnly(cookieEntity.getHttpOnly()); //@since Servlet 3.0 if (LOGGER.isDebugEnabled()){ LOGGER.debug("input cookieEntity info:[{}],response.addCookie", JsonUtil.format(cookieEntity)); } response.addCookie(cookie); } /** * Validate cookie entity. * * @param cookieEntity * the cookie entity * @since 1.5.0 */ private static void validateCookieEntity(CookieEntity cookieEntity){ Validate.notNull(cookieEntity, "cookieEntity can't be null!"); String cookieName = cookieEntity.getName(); Validate.notEmpty(cookieName, "cookieName can't be null/empty!"); String value = cookieEntity.getValue(); //如果长度超过4000,浏览器可能不支持 if (Validator.isNotNullOrEmpty(value) && value.length() > 4000){ LOGGER.warn( "cookie value:{},length:{},more than 4000!!!some browser may be not support!!!!!,cookieEntity info :{}", value, value.length(), JsonUtil.format(cookieEntity)); } } }
update javadoc
src/main/java/com/feilong/servlet/http/CookieUtil.java
update javadoc
<ide><path>rc/main/java/com/feilong/servlet/http/CookieUtil.java <ide> import org.slf4j.LoggerFactory; <ide> <ide> import com.feilong.core.Validator; <add>import com.feilong.core.bean.PropertyUtil; <ide> import com.feilong.servlet.http.entity.CookieEntity; <ide> import com.feilong.tools.jsonlib.JsonUtil; <ide> <ide> /** <del> * {@link javax.servlet.http.Cookie} 工具 类. <del> * <del> * <del> * <h3>cookie适用场合:</h3> <del> * <del> * cookie机制将信息存储于用户硬盘,因此可以作为全局变量,这是它最大的一个优点。 <add> * {@link javax.servlet.http.Cookie Cookie} 工具类. <add> * <add> * <p> <add> * 注意:该类创建Cookie仅支持Servlet3以上的版本 <add> * </p> <add> * <add> * <h3>使用说明:</h3> <add> * <add> * <h4> <add> * case:创建Cookie <add> * </h4> <ide> * <ide> * <blockquote> <del> * <ol> <del> * <li>保存用户登录状态。<br> <del> * 例如将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了,现在很多论坛和社区都提供这样的功能。<br> <del> * cookie还可以设置过期时间,当超过时间期限后,cookie就会自动消失。<br> <del> * 因此,系统往往可以提示用户保持登录状态的时间: 常见选项有一个月、三个月、一年等。</li> <del> * <li> <del> * 跟踪用户行为。<br> <del> * 例如一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。<br> <del> * 如果每次都需要选择所在地是烦琐的,当利用了cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。<br> <del> * 因为一切都是在后台完成 ,所以这样的页面就像为某个用户所定制的一样,使用起来非常方便。</li> <del> * <li>定制页面。<br> <del> * 如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用户的选项,例如:背景色、分辨率等。<br> <del> * 当用户下次访问时,仍然可以保存上一次访问的界面风格。</li> <del> * <li>创建购物车。<br> <del> * 正如在前面的例子中使用cookie来记录用户需要购买的商品一样,在结账的时候可以统一提交。<br> <del> * 例如淘宝网就使用cookie记录了用户曾经浏览过的商品,方便随时进行比较。</li> <del> * </ol> <del> * <add> * <p> <add> * 1.创建一个name名字是shopName,value是feilong的 Cookie (通常出于安全起见,存放到Cookie的值需要加密或者混淆,此处为了举例方便使用原码)<br> <add> * 可以调用{@link #addCookie(String, String, HttpServletResponse)}<br> <add> * 如: <add> * <p> <add> * <code>CookieUtil.addCookie("shopName","feilong",response)</code> <add> * </p> <add> * 注意:该方法创建的cookie,有效期是默认值 -1,即浏览器退出就删除 <add> * </p> <add> * <add> * <p> <add> * 2.如果想给该cookie加个过期时间,有效期一天,可以调用 {@link #addCookie(String, String, int, HttpServletResponse)}<br> <add> * 如: <add> * <p> <add> * <code>CookieUtil.addCookie("shopName","feilong", TimeInterval.SECONDS_PER_DAY,response)</code> <add> * </p> <add> * </p> <add> * <add> * <p> <add> * 3.如果还想给该cookie加上httpOnly等标识,可以调用 {@link #addCookie(CookieEntity, HttpServletResponse)}<br> <add> * 如: <add> * <add> * <pre> <add>{@code <add>CookieEntity cookieEntity=new CookieEntity("shopName","feilong",TimeInterval.SECONDS_PER_DAY); <add>cookieEntity.setHttpOnly(true); <add>CookieUtil.addCookie(cookieEntity,response) <add>} <add> * </pre> <add> * <add> * 此外,如果有特殊需求,还可以对cookieEntity设置 path,domain等属性 <add> * </p> <ide> * </blockquote> <ide> * <del> * <h3>cookie的缺点主要集中于安全性和隐私保护:</h3> <add> * <h4> <add> * case:获取Cookie <add> * </h4> <ide> * <ide> * <blockquote> <del> * <ol> <del> * <li>cookie可能被禁用。<br> <del> * 当用户非常注重个人隐私保护时,他很可能禁用浏览器的cookie功能;</li> <del> * <li>cookie是与浏览器相关的。<br> <del> * 这意味着即使访问的是同一个页面,不同浏览器之间所保存的cookie也是不能互相访问的;</li> <del> * <li>cookie可能被删除。<br> <del> * 因为每个cookie都是硬盘上的一个文件,因此很有可能被用户删除;</li> <del> * <li>cookie安全性不够高。<br> <del> * 所有的cookie都是以纯文本的形式记录于文件中,因此如果要保存用户名密码等信息时,最好事先经过加密处理。</li> <del> * </ol> <add> * <add> * <p> <add> * 1.可以使用 {@link #getCookie(HttpServletRequest, String)}来获得 {@link Cookie}对象 <add> * <br> <add> * 如: <add> * <p> <add> * <code>CookieUtil.getCookie(request, "shopName")</code> <add> * </p> <add> * </p> <add> * <add> * <p> <add> * 2.更多的时候,可以使用 {@link #getCookieValue(HttpServletRequest, String)}来获得Cookie对象的值 <add> * <br> <add> * 如: <add> * <p> <add> * <code>CookieUtil.getCookieValue(request, "shopName")</code> <add> * </p> <add> * <add> * 返回 "feilong" 字符串 <add> * </p> <add> * <add> * <add> * <p> <add> * 3.当然,你也可以使用 {@link #getCookieMap(HttpServletRequest)}来获得 所有的Cookie name和value组成的map <add> * <br> <add> * 如: <add> * <p> <add> * <code>CookieUtil.getCookieMap(request)</code> <add> * </p> <add> * <add> * 使用场景,如 {@link com.feilong.servlet.http.RequestLogBuilder#build()} <add> * </p> <ide> * </blockquote> <del> * <add> * <add> * <add> * <add> * <h4> <add> * case:删除Cookie <add> * </h4> <add> * <add> * <blockquote> <add> * <add> * <p> <add> * 1.可以使用 {@link #deleteCookie(String, HttpServletResponse)}来删除Cookie <add> * <br> <add> * 如: <add> * <p> <add> * <code>CookieUtil.deleteCookie(request, "shopName")</code> <add> * </p> <add> * </p> <add> * <add> * <p> <add> * 2.特殊时候,由于Cookie原先保存时候设置了path属性,可以使用 {@link #deleteCookie(CookieEntity, HttpServletResponse)}来删除Cookie <add> * <br> <add> * 如: <add> * <add> * <p> <add> * <add> * <pre> <add>{@code <add>CookieEntity cookieEntity=new CookieEntity("shopName","feilong"); <add>cookieEntity.setPath("/member/account"); <add>CookieUtil.deleteCookie(request, "shopName") <add>} <add> * </pre> <add> * </p> <add> * <add> * </p> <add> * <add> * </blockquote> <add> * <ide> * @author feilong <ide> * @version 2010-6-24 上午08:05:32 <ide> * @version 2012-5-18 14:53 <ide> * @see javax.servlet.http.Cookie <ide> * @see "org.springframework.web.util.CookieGenerator" <add> * @see com.feilong.servlet.http.entity.CookieEntity <ide> * @since 1.0.0 <ide> */ <ide> public final class CookieUtil{ <ide> } <ide> <ide> /** <del> * 获得cookie. <add> * 获得 {@link Cookie}对象. <ide> * <ide> * <p> <ide> * 循环遍历 {@link HttpServletRequest#getCookies()},找到 {@link Cookie#getName()}是 <code>cookieName</code> 的 {@link Cookie} <ide> //**************************************************************************************************** <ide> <ide> /** <del> * 创建个cookie. <add> * 创建cookie. <add> * <add> * <p> <add> * 注意:该方法创建的cookie,有效期是默认值 -1,即浏览器退出就删除 <add> * </p> <ide> * <ide> * @param cookieName <ide> * the cookie name <ide> } <ide> <ide> /** <del> * 创建个cookie. <add> * 创建cookie. <ide> * <ide> * @param cookieName <ide> * the cookie name <ide> //校验 <ide> validateCookieEntity(cookieEntity); <ide> <del> String cookieName = cookieEntity.getName(); <del> String value = cookieEntity.getValue(); <del> <del> //**************************************************************************** <del> Cookie cookie = new Cookie(cookieName, value); <del> <del> cookie.setMaxAge(cookieEntity.getMaxAge());//设置以秒计的cookie的最大存活时间。 <del> <del> String comment = cookieEntity.getComment(); <del> if (Validator.isNotNullOrEmpty(comment)){ <del> cookie.setComment(comment);//指定一个注释来描述cookie的目的。 <del> } <del> <del> // 指明cookie应当被声明的域。 <del> String domain = cookieEntity.getDomain(); <del> if (Validator.isNotNullOrEmpty(domain)){ //NullPointerException at javax.servlet.http.Cookie.setDomain(Cookie.java:213) ~[servlet-api-6.0.37.jar:na] <del> cookie.setDomain(domain); <del> } <del> <del> //指定客户端将cookie返回的cookie的路径。 <del> String path = cookieEntity.getPath(); <del> if (Validator.isNotNullOrEmpty(path)){ <del> cookie.setPath(path); <del> } <del> <del> //指定是否cookie应该只通过安全协议,例如HTTPS或SSL,传送给浏览器。 <del> cookie.setSecure(cookieEntity.getSecure()); <del> <del> //设置本cookie遵循的cookie的协议的版本 <del> cookie.setVersion(cookieEntity.getVersion()); <del> <del> //HttpOnly cookies are not supposed to be exposed to client-side scripting code, <del> //and may therefore help mitigate certain kinds of cross-site scripting attacks. <del> cookie.setHttpOnly(cookieEntity.getHttpOnly()); //@since Servlet 3.0 <add> Cookie cookie = toCookie(cookieEntity); <ide> <ide> if (LOGGER.isDebugEnabled()){ <ide> LOGGER.debug("input cookieEntity info:[{}],response.addCookie", JsonUtil.format(cookieEntity)); <ide> } <ide> response.addCookie(cookie); <add> } <add> <add> /** <add> * To cookie. <add> * <add> * @param cookieEntity <add> * the cookie entity <add> * @return the cookie <add> * @since 1.5.3 <add> */ <add> private static Cookie toCookie(CookieEntity cookieEntity){ <add> Cookie cookie = new Cookie(cookieEntity.getName(), cookieEntity.getValue()); <add> <add> PropertyUtil.copyProperties(cookie, cookieEntity // <add> , "maxAge"//设置以秒计的cookie的最大存活时间。 <add> , "secure"//指定是否cookie应该只通过安全协议,例如HTTPS或SSL,传送给浏览器。 <add> , "version"//设置本cookie遵循的cookie的协议的版本 <add> , "httpOnly"//@since Servlet 3.0 <add> ); <add> PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "comment", cookieEntity.getComment());//指定一个注释来描述cookie的目的。 <add> <add> //NullPointerException at javax.servlet.http.Cookie.setDomain(Cookie.java:213) ~[servlet-api-6.0.37.jar:na] <add> PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "domain", cookieEntity.getDomain());// 指明cookie应当被声明的域。 <add> PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "path", cookieEntity.getPath());//指定客户端将cookie返回的cookie的路径。 <add> return cookie; <ide> } <ide> <ide> /**
Java
apache-2.0
3df09968936118ce9a36ac438a8d0a6bf498990b
0
ilgrosso/syncope,apache/syncope,ilgrosso/syncope,ilgrosso/syncope,ilgrosso/syncope,apache/syncope,apache/syncope,apache/syncope
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.client.console.wizards.any; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.cxf.common.util.StringUtils; import org.apache.syncope.client.console.rest.AnyTypeClassRestClient; import org.apache.syncope.client.console.rest.GroupRestClient; import org.apache.syncope.client.console.rest.SchemaRestClient; import org.apache.syncope.common.lib.to.AbstractSchemaTO; import org.apache.syncope.common.lib.to.AnyTO; import org.apache.syncope.common.lib.to.AttrTO; import org.apache.syncope.common.lib.to.EntityTO; import org.apache.syncope.common.lib.to.GroupTO; import org.apache.syncope.common.lib.to.MembershipTO; import org.apache.syncope.common.lib.types.SchemaType; import org.apache.wicket.PageReference; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.core.util.lang.PropertyResolver; import org.apache.wicket.extensions.wizard.WizardModel.ICondition; import org.apache.wicket.extensions.wizard.WizardStep; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.util.ListModel; public abstract class AbstractAttrs<S extends AbstractSchemaTO> extends WizardStep implements ICondition { private static final long serialVersionUID = -5387344116983102292L; private final SchemaRestClient schemaRestClient = new SchemaRestClient(); private final AnyTypeClassRestClient anyTypeClassRestClient = new AnyTypeClassRestClient(); private final GroupRestClient groupRestClient = new GroupRestClient(); protected final AnyTO anyTO; private final List<String> whichAttrs; protected final Map<String, S> schemas = new LinkedHashMap<>(); protected final Map<String, Map<String, S>> membershipSchemas = new LinkedHashMap<>(); protected final IModel<List<AttrTO>> attrTOs; protected final IModel<List<MembershipTO>> membershipTOs; private final List<String> anyTypeClasses; public AbstractAttrs( final AnyWrapper<?> modelObject, final List<String> anyTypeClasses, final List<String> whichAttrs) { super(); this.anyTypeClasses = anyTypeClasses; this.attrTOs = new ListModel<>(Collections.<AttrTO>emptyList()); this.membershipTOs = new ListModel<>(Collections.<MembershipTO>emptyList()); this.setOutputMarkupId(true); this.anyTO = modelObject.getInnerObject(); this.whichAttrs = whichAttrs; } private List<AttrTO> loadAttrTOs() { List<String> classes = new ArrayList<>(anyTypeClasses); classes.addAll(anyTypeClassRestClient.list(anyTO.getAuxClasses()).stream(). map(EntityTO::getKey).collect(Collectors.toList())); setSchemas(classes); setAttrs(); return AbstractAttrs.this.getAttrsFromTO(); } @SuppressWarnings("unchecked") private List<MembershipTO> loadMembershipAttrTOs() { List<MembershipTO> memberships = new ArrayList<>(); try { membershipSchemas.clear(); for (MembershipTO membership : (List<MembershipTO>) PropertyResolver.getPropertyField( "memberships", anyTO).get(anyTO)) { setSchemas(membership.getGroupKey(), anyTypeClassRestClient.list(getMembershipAuxClasses(membership, anyTO.getType())). stream().map(EntityTO::getKey).collect(Collectors.toList())); setAttrs(membership); if (AbstractAttrs.this instanceof PlainAttrs && !membership.getPlainAttrs().isEmpty()) { memberships.add(membership); } else if (AbstractAttrs.this instanceof DerAttrs && !membership.getDerAttrs().isEmpty()) { memberships.add(membership); } else if (AbstractAttrs.this instanceof VirAttrs && !membership.getVirAttrs().isEmpty()) { memberships.add(membership); } } } catch (WicketRuntimeException | IllegalArgumentException | IllegalAccessException ex) { // ignore } return memberships; } protected boolean reoderSchemas() { return !whichAttrs.isEmpty(); } protected abstract SchemaType getSchemaType(); private void setSchemas(final String membership, final List<String> anyTypeClasses) { final Map<String, S> mscs; if (membershipSchemas.containsKey(membership)) { mscs = membershipSchemas.get(membership); } else { mscs = new LinkedHashMap<>(); membershipSchemas.put(membership, mscs); } setSchemas(anyTypeClasses, mscs); } private void setSchemas(final List<String> anyTypeClasses) { setSchemas(anyTypeClasses, schemas); } private void setSchemas(final List<String> anyTypeClasses, final Map<String, S> scs) { final List<S> allSchemas; if (anyTypeClasses.isEmpty()) { allSchemas = Collections.emptyList(); } else { allSchemas = schemaRestClient.getSchemas(getSchemaType(), anyTypeClasses.toArray(new String[] {})); } scs.clear(); if (reoderSchemas()) { // 1. remove attributes not selected for display allSchemas.removeAll(allSchemas.stream(). filter(schemaTO -> !whichAttrs.contains(schemaTO.getKey())).collect(Collectors.toSet())); } allSchemas.forEach(schemaTO -> { scs.put(schemaTO.getKey(), schemaTO); }); } @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); if (org.apache.cxf.common.util.CollectionUtils.isEmpty(attrTOs.getObject()) && org.apache.cxf.common.util.CollectionUtils.isEmpty(membershipTOs.getObject())) { response.render(OnDomReadyHeaderItem.forScript( String.format("$('#emptyPlaceholder').append(\"%s\"); $('#attributes').hide();", getString("attribute.empty.list")))); } } protected abstract void setAttrs(); protected abstract void setAttrs(final MembershipTO membershipTO); protected abstract List<AttrTO> getAttrsFromTO(); protected abstract List<AttrTO> getAttrsFromTO(final MembershipTO membershipTO); protected List<String> getMembershipAuxClasses(final MembershipTO membershipTO, final String anyType) { try { final GroupTO groupTO = groupRestClient.read(membershipTO.getGroupKey()); return groupTO.getTypeExtension(anyType).get().getAuxClasses(); } catch (Exception e) { return Collections.emptyList(); } } @Override public boolean evaluate() { this.attrTOs.setObject(loadAttrTOs()); this.membershipTOs.setObject(loadMembershipAttrTOs()); return !attrTOs.getObject().isEmpty() || !membershipTOs.getObject().isEmpty(); } public PageReference getPageReference() { // SYNCOPE-1213 // default implementation does not requier to pass page reference, override this method of want otherwise return null; } protected class AttrComparator implements Comparator<AttrTO>, Serializable { private static final long serialVersionUID = -5105030477767941060L; @Override public int compare(final AttrTO left, final AttrTO right) { if (left == null || StringUtils.isEmpty(left.getSchema())) { return -1; } if (right == null || StringUtils.isEmpty(right.getSchema())) { return 1; } else if (AbstractAttrs.this.reoderSchemas()) { int leftIndex = AbstractAttrs.this.whichAttrs.indexOf(left.getSchema()); int rightIndex = AbstractAttrs.this.whichAttrs.indexOf(right.getSchema()); if (leftIndex > rightIndex) { return 1; } else if (leftIndex < rightIndex) { return -1; } else { return 0; } } else { return left.getSchema().compareTo(right.getSchema()); } } } public class Schemas extends Panel { private static final long serialVersionUID = -2447602429647965090L; public Schemas(final String id) { super(id); } } }
client/console/src/main/java/org/apache/syncope/client/console/wizards/any/AbstractAttrs.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.client.console.wizards.any; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.cxf.common.util.StringUtils; import org.apache.syncope.client.console.rest.AnyTypeClassRestClient; import org.apache.syncope.client.console.rest.GroupRestClient; import org.apache.syncope.client.console.rest.SchemaRestClient; import org.apache.syncope.common.lib.to.AbstractSchemaTO; import org.apache.syncope.common.lib.to.AnyTO; import org.apache.syncope.common.lib.to.AttrTO; import org.apache.syncope.common.lib.to.EntityTO; import org.apache.syncope.common.lib.to.GroupTO; import org.apache.syncope.common.lib.to.MembershipTO; import org.apache.syncope.common.lib.types.SchemaType; import org.apache.wicket.PageReference; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.core.util.lang.PropertyResolver; import org.apache.wicket.extensions.wizard.WizardModel.ICondition; import org.apache.wicket.extensions.wizard.WizardStep; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.util.ListModel; public abstract class AbstractAttrs<S extends AbstractSchemaTO> extends WizardStep implements ICondition { private static final long serialVersionUID = -5387344116983102292L; private final SchemaRestClient schemaRestClient = new SchemaRestClient(); private final AnyTypeClassRestClient anyTypeClassRestClient = new AnyTypeClassRestClient(); private final GroupRestClient groupRestClient = new GroupRestClient(); protected final AnyTO anyTO; private final List<String> whichAttrs; protected final Map<String, S> schemas = new LinkedHashMap<>(); protected final Map<String, Map<String, S>> membershipSchemas = new LinkedHashMap<>(); protected final IModel<List<AttrTO>> attrTOs; protected final IModel<List<MembershipTO>> membershipTOs; private final List<String> anyTypeClasses; public AbstractAttrs( final AnyWrapper<?> modelObject, final List<String> anyTypeClasses, final List<String> whichAttrs) { super(); this.anyTypeClasses = anyTypeClasses; this.attrTOs = new ListModel<>(Collections.<AttrTO>emptyList()); this.membershipTOs = new ListModel<>(Collections.<MembershipTO>emptyList()); this.setOutputMarkupId(true); this.anyTO = modelObject.getInnerObject(); this.whichAttrs = whichAttrs; } private List<AttrTO> loadAttrTOs() { List<String> classes = new ArrayList<>(anyTypeClasses); classes.addAll(anyTypeClassRestClient.list(anyTO.getAuxClasses()).stream(). map(EntityTO::getKey).collect(Collectors.toList())); setSchemas(classes); setAttrs(); return AbstractAttrs.this.getAttrsFromTO(); } @SuppressWarnings("unchecked") private List<MembershipTO> loadMembershipAttrTOs() { List<MembershipTO> memberships = new ArrayList<>(); try { membershipSchemas.clear(); for (MembershipTO membership : (List<MembershipTO>) PropertyResolver.getPropertyField( "memberships", anyTO).get(anyTO)) { setSchemas(membership.getGroupKey(), anyTypeClassRestClient.list(getMembershipAuxClasses(membership, anyTO.getType())). stream().map(EntityTO::getKey).collect(Collectors.toList())); setAttrs(membership); if (AbstractAttrs.this instanceof PlainAttrs && !membership.getPlainAttrs().isEmpty()) { memberships.add(membership); } else if (AbstractAttrs.this instanceof DerAttrs && !membership.getDerAttrs().isEmpty()) { memberships.add(membership); } else if (AbstractAttrs.this instanceof VirAttrs && !membership.getVirAttrs().isEmpty()) { memberships.add(membership); } } } catch (WicketRuntimeException | IllegalArgumentException | IllegalAccessException ex) { // ignore } return memberships; } protected boolean reoderSchemas() { return !whichAttrs.isEmpty(); } protected abstract SchemaType getSchemaType(); private void setSchemas(final String membership, final List<String> anyTypeClasses) { final Map<String, S> mscs; if (membershipSchemas.containsKey(membership)) { mscs = membershipSchemas.get(membership); } else { mscs = new LinkedHashMap<>(); membershipSchemas.put(membership, mscs); } setSchemas(anyTypeClasses, mscs); } private void setSchemas(final List<String> anyTypeClasses) { setSchemas(anyTypeClasses, schemas); } private void setSchemas(final List<String> anyTypeClasses, final Map<String, S> scs) { final List<S> allSchemas; if (anyTypeClasses.isEmpty()) { allSchemas = Collections.emptyList(); } else { allSchemas = schemaRestClient.getSchemas(getSchemaType(), anyTypeClasses.toArray(new String[] {})); } scs.clear(); if (reoderSchemas()) { // 1. remove attributes not selected for display allSchemas.removeAll(allSchemas.stream(). filter(schemaTO -> !whichAttrs.contains(schemaTO.getKey())).collect(Collectors.toSet())); allSchemas.forEach(schemaTO -> { scs.put(schemaTO.getKey(), schemaTO); }); } } @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); if (org.apache.cxf.common.util.CollectionUtils.isEmpty(attrTOs.getObject()) && org.apache.cxf.common.util.CollectionUtils.isEmpty(membershipTOs.getObject())) { response.render(OnDomReadyHeaderItem.forScript( String.format("$('#emptyPlaceholder').append(\"%s\"); $('#attributes').hide();", getString("attribute.empty.list")))); } } protected abstract void setAttrs(); protected abstract void setAttrs(final MembershipTO membershipTO); protected abstract List<AttrTO> getAttrsFromTO(); protected abstract List<AttrTO> getAttrsFromTO(final MembershipTO membershipTO); protected List<String> getMembershipAuxClasses(final MembershipTO membershipTO, final String anyType) { try { final GroupTO groupTO = groupRestClient.read(membershipTO.getGroupKey()); return groupTO.getTypeExtension(anyType).get().getAuxClasses(); } catch (Exception e) { return Collections.emptyList(); } } @Override public boolean evaluate() { this.attrTOs.setObject(loadAttrTOs()); this.membershipTOs.setObject(loadMembershipAttrTOs()); return !attrTOs.getObject().isEmpty() || !membershipTOs.getObject().isEmpty(); } public PageReference getPageReference() { // SYNCOPE-1213 // default implementation does not requier to pass page reference, override this method of want otherwise return null; } protected class AttrComparator implements Comparator<AttrTO>, Serializable { private static final long serialVersionUID = -5105030477767941060L; @Override public int compare(final AttrTO left, final AttrTO right) { if (left == null || StringUtils.isEmpty(left.getSchema())) { return -1; } if (right == null || StringUtils.isEmpty(right.getSchema())) { return 1; } else if (AbstractAttrs.this.reoderSchemas()) { int leftIndex = AbstractAttrs.this.whichAttrs.indexOf(left.getSchema()); int rightIndex = AbstractAttrs.this.whichAttrs.indexOf(right.getSchema()); if (leftIndex > rightIndex) { return 1; } else if (leftIndex < rightIndex) { return -1; } else { return 0; } } else { return left.getSchema().compareTo(right.getSchema()); } } } public class Schemas extends Panel { private static final long serialVersionUID = -2447602429647965090L; public Schemas(final String id) { super(id); } } }
[SYNCOPE-1250] fix bad merge
client/console/src/main/java/org/apache/syncope/client/console/wizards/any/AbstractAttrs.java
[SYNCOPE-1250] fix bad merge
<ide><path>lient/console/src/main/java/org/apache/syncope/client/console/wizards/any/AbstractAttrs.java <ide> // 1. remove attributes not selected for display <ide> allSchemas.removeAll(allSchemas.stream(). <ide> filter(schemaTO -> !whichAttrs.contains(schemaTO.getKey())).collect(Collectors.toSet())); <del> <add> } <add> <ide> allSchemas.forEach(schemaTO -> { <ide> scs.put(schemaTO.getKey(), schemaTO); <del> }); <del> } <add> }); <ide> } <ide> <ide> @Override
JavaScript
mit
13a6ef94eba20d25463643403689bd3e15426fc9
0
jcampanell-cablelabs/lora-app-server,brocaar/lora-app-server,brocaar/lora-app-server,brocaar/lora-app-server,brocaar/lora-app-server,jcampanell-cablelabs/lora-app-server,jcampanell-cablelabs/lora-app-server,jcampanell-cablelabs/lora-app-server
import React, { Component } from 'react'; import { Link } from 'react-router'; import NodeSessionStore from "../../stores/NodeSessionStore"; import NodeSessionForm from "../../components/NodeSessionForm"; import NodeStore from "../../stores/NodeStore"; import ChannelStore from "../../stores/ChannelStore"; class NodeSessionDetails extends Component { static contextTypes = { router: React.PropTypes.object.isRequired }; constructor() { super(); this.state = { session: {}, node: {}, sessionExists: false, channels: [], }; this.submitHandler = this.submitHandler.bind(this); this.deleteHandler = this.deleteHandler.bind(this); } componentWillMount() { NodeSessionStore.getNodeSession(this.props.params.devEUI, (session) => { this.setState({ session: session, sessionExists: true, }); }); NodeStore.getNode(this.props.params.devEUI, (node) => { this.setState({node: node}); if(node.channelListID !== 0) { ChannelStore.getChannelList(node.channelListID, (list) => { this.setState({channels: list.channels}); }); } }); } submitHandler(session) { session.devEUI = this.state.node.devEUI; session.appEUI = this.state.node.appEUI; session.rxWindow = this.state.node.rxWindow; session.rxDelay = this.state.node.rxDelay; session.rx1DROffset = this.state.node.rx1DROffset; session.rx2DR = this.state.node.rx2DR; session.cFList = this.state.channels; if (this.state.sessionExists) { NodeSessionStore.updateNodeSession(this.props.params.devEUI, session, (responseData) => { this.context.router.push("/nodes/"+this.props.params.devEUI); }); } else { NodeSessionStore.createNodeSession(session, (responseData) => { this.context.router.push("/nodes/"+ this.props.params.devEUI); }); } } deleteHandler() { if (confirm("Are you sure you want to delete this node-session (this does not delete the node)?")) { NodeSessionStore.deleteNodeSession(this.props.params.devEUI, (responseData) => { this.context.router.push("/nodes/"+this.props.params.devEUI); }); } } render() { let deleteButton; if(this.state.sessionExists) { deleteButton = <Link><button type="button" className="btn btn-danger" onClick={this.deleteHandler}>Delete</button></Link>; } return( <div> <ol className="breadcrumb"> <li><Link to="/">Dashboard</Link></li> <li>Nodes</li> <li><Link to={`/nodes/${this.props.params.devEUI}`}>{this.props.params.devEUI}</Link></li> <li className="active">node-session</li> </ol> <div className="clearfix"> <div className="btn-group pull-right" role="group" aria-label="..."> {deleteButton} </div> </div> <hr /> <div className="panel panel-default"> <div className="panel-body"> <NodeSessionForm session={this.state.session} onSubmit={this.submitHandler} /> </div> </div> </div> ); } } export default NodeSessionDetails;
ui/src/views/nodes/NodeSessionDetails.js
import React, { Component } from 'react'; import { Link } from 'react-router'; import NodeSessionStore from "../../stores/NodeSessionStore"; import NodeSessionForm from "../../components/NodeSessionForm"; import NodeStore from "../../stores/NodeStore"; class NodeSessionDetails extends Component { static contextTypes = { router: React.PropTypes.object.isRequired }; constructor() { super(); this.state = { session: {}, node: {}, sessionExists: false, }; this.submitHandler = this.submitHandler.bind(this); this.deleteHandler = this.deleteHandler.bind(this); } componentWillMount() { NodeSessionStore.getNodeSession(this.props.params.devEUI, (session) => { this.setState({ session: session, sessionExists: true, }); }); NodeStore.getNode(this.props.params.devEUI, (node) => { this.setState({node: node}); }); } submitHandler(session) { session.devEUI = this.state.node.devEUI; session.appEUI = this.state.node.appEUI; session.rxWindow = this.state.node.rxWindow; session.rxDelay = this.state.node.rxDelay; session.rx1DROffset = this.state.node.rx1DROffset; session.rx2DR = this.state.node.rx2DR; if (this.state.sessionExists) { NodeSessionStore.updateNodeSession(this.props.params.devEUI, session, (responseData) => { this.context.router.push("/nodes/"+this.props.params.devEUI); }); } else { NodeSessionStore.createNodeSession(session, (responseData) => { this.context.router.push("/nodes/"+ this.props.params.devEUI); }); } } deleteHandler() { if (confirm("Are you sure you want to delete this node-session (this does not delete the node)?")) { NodeSessionStore.deleteNodeSession(this.props.params.devEUI, (responseData) => { this.context.router.push("/nodes/"+this.props.params.devEUI); }); } } render() { let deleteButton; if(this.state.sessionExists) { deleteButton = <Link><button type="button" className="btn btn-danger" onClick={this.deleteHandler}>Delete</button></Link>; } return( <div> <ol className="breadcrumb"> <li><Link to="/">Dashboard</Link></li> <li>Nodes</li> <li><Link to={`/nodes/${this.props.params.devEUI}`}>{this.props.params.devEUI}</Link></li> <li className="active">node-session</li> </ol> <div className="clearfix"> <div className="btn-group pull-right" role="group" aria-label="..."> {deleteButton} </div> </div> <hr /> <div className="panel panel-default"> <div className="panel-body"> <NodeSessionForm session={this.state.session} onSubmit={this.submitHandler} /> </div> </div> </div> ); } } export default NodeSessionDetails;
Set node-session channels.
ui/src/views/nodes/NodeSessionDetails.js
Set node-session channels.
<ide><path>i/src/views/nodes/NodeSessionDetails.js <ide> import NodeSessionStore from "../../stores/NodeSessionStore"; <ide> import NodeSessionForm from "../../components/NodeSessionForm"; <ide> import NodeStore from "../../stores/NodeStore"; <add>import ChannelStore from "../../stores/ChannelStore"; <ide> <ide> class NodeSessionDetails extends Component { <ide> static contextTypes = { <ide> session: {}, <ide> node: {}, <ide> sessionExists: false, <add> channels: [], <ide> }; <ide> <ide> this.submitHandler = this.submitHandler.bind(this); <ide> <ide> NodeStore.getNode(this.props.params.devEUI, (node) => { <ide> this.setState({node: node}); <add> <add> if(node.channelListID !== 0) { <add> ChannelStore.getChannelList(node.channelListID, (list) => { <add> this.setState({channels: list.channels}); <add> }); <add> } <ide> }); <ide> } <ide> <ide> session.rxDelay = this.state.node.rxDelay; <ide> session.rx1DROffset = this.state.node.rx1DROffset; <ide> session.rx2DR = this.state.node.rx2DR; <add> session.cFList = this.state.channels; <ide> <ide> if (this.state.sessionExists) { <ide> NodeSessionStore.updateNodeSession(this.props.params.devEUI, session, (responseData) => {
Java
apache-2.0
367fc17f832c1e94937a128a4b2322a5afd38ca1
0
asashour/framework,asashour/framework,kironapublic/vaadin,Legioth/vaadin,sitexa/vaadin,shahrzadmn/vaadin,mittop/vaadin,asashour/framework,shahrzadmn/vaadin,jdahlstrom/vaadin.react,udayinfy/vaadin,shahrzadmn/vaadin,mstahv/framework,fireflyc/vaadin,Scarlethue/vaadin,asashour/framework,udayinfy/vaadin,oalles/vaadin,shahrzadmn/vaadin,travisfw/vaadin,Legioth/vaadin,oalles/vaadin,cbmeeks/vaadin,Darsstar/framework,Legioth/vaadin,synes/vaadin,kironapublic/vaadin,Peppe/vaadin,synes/vaadin,Scarlethue/vaadin,mstahv/framework,fireflyc/vaadin,Scarlethue/vaadin,magi42/vaadin,udayinfy/vaadin,Darsstar/framework,Flamenco/vaadin,peterl1084/framework,Darsstar/framework,synes/vaadin,bmitc/vaadin,synes/vaadin,Scarlethue/vaadin,carrchang/vaadin,sitexa/vaadin,carrchang/vaadin,Flamenco/vaadin,bmitc/vaadin,fireflyc/vaadin,carrchang/vaadin,kironapublic/vaadin,Scarlethue/vaadin,kironapublic/vaadin,mstahv/framework,Legioth/vaadin,asashour/framework,mittop/vaadin,travisfw/vaadin,carrchang/vaadin,Peppe/vaadin,jdahlstrom/vaadin.react,Legioth/vaadin,mittop/vaadin,cbmeeks/vaadin,Flamenco/vaadin,peterl1084/framework,kironapublic/vaadin,magi42/vaadin,bmitc/vaadin,jdahlstrom/vaadin.react,magi42/vaadin,fireflyc/vaadin,sitexa/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,synes/vaadin,Flamenco/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,Darsstar/framework,fireflyc/vaadin,travisfw/vaadin,Peppe/vaadin,udayinfy/vaadin,shahrzadmn/vaadin,magi42/vaadin,oalles/vaadin,oalles/vaadin,mittop/vaadin,travisfw/vaadin,bmitc/vaadin,peterl1084/framework,mstahv/framework,Darsstar/framework,Peppe/vaadin,sitexa/vaadin,cbmeeks/vaadin,oalles/vaadin,mstahv/framework,udayinfy/vaadin,travisfw/vaadin,cbmeeks/vaadin,magi42/vaadin,Peppe/vaadin,sitexa/vaadin
/* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.event.dd; import java.util.Map; import com.vaadin.ui.Component; /** * DropTarget is an interface for components supporting drop operations. A * component that wants to receive drop events should implement this interface * and provide a {@link DropHandler} which will handle the actual drop event. * * @since 6.3 */ public interface DropTarget extends Component { /** * @return the drop hanler that will receive the dragged data or null if * drops are not currently accepted */ public DropHandler getDropHandler(); /** * Called before the {@link DragAndDropEvent} is passed to * {@link DropHandler}. Implementation may for example translate the drop * target details provided by the client side (drop target) to meaningful * server side values. If null is returned the terminal implementation will * automatically create a {@link TargetDetails} with raw client side data. * * @see DragSource#getTransferable(Map) * * @param clientVariables * data passed from the DropTargets client side counterpart. * @return A DropTargetDetails object with the translated data or null to * use a default implementation. */ public TargetDetails translateDropTargetDetails( Map<String, Object> clientVariables); }
src/com/vaadin/event/dd/DropTarget.java
/* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.event.dd; import java.util.Map; import com.vaadin.ui.Component; /** * DropTarget is an interface for components supporting drop operations. A * component that wants to receive drop events should implement this interface * and provide a {@link DropHandler} which will handle the actual drop event. * * @since 6.3 */ public interface DropTarget extends Component { /** * @return the drop hanler that will receive the dragged data or null if * drops are not currently accepted */ public DropHandler getDropHandler(); /** * Called before the {@link DragAndDropEvent} is passed to * {@link DropHandler}. Implementation may for exmaple translate the drop * target details provided by the client side (drop target) to meaningful * server side values. If null is returned the terminal implementation will * automatically create a {@link TargetDetails} with raw client side data. * * @see DragSource#getTransferable(Map) * * @param clientVariables * data passed from the DropTargets client side counterpart. * @return A DropTargetDetails object with the translated data or null to * use a default implementation. */ public TargetDetails translateDropTargetDetails( Map<String, Object> clientVariables); }
Javadoc typo correction svn changeset:13466/svn branch:6.3
src/com/vaadin/event/dd/DropTarget.java
Javadoc typo correction
<ide><path>rc/com/vaadin/event/dd/DropTarget.java <ide> <ide> /** <ide> * Called before the {@link DragAndDropEvent} is passed to <del> * {@link DropHandler}. Implementation may for exmaple translate the drop <add> * {@link DropHandler}. Implementation may for example translate the drop <ide> * target details provided by the client side (drop target) to meaningful <ide> * server side values. If null is returned the terminal implementation will <ide> * automatically create a {@link TargetDetails} with raw client side data.
Java
apache-2.0
546124228c99c080ad0f0a7f23d58adec4a8f7b4
0
anjlab/eclipse-tapestry5-plugin,anjlab/eclipse-tapestry5-plugin,anjlab/eclipse-tapestry5-plugin
package com.anjlab.eclipse.tapestry5; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.Manifest; import org.apache.commons.lang.StringUtils; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IJarEntryResource; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import com.anjlab.eclipse.tapestry5.TapestryModule.ModuleReference; import com.anjlab.eclipse.tapestry5.TapestryModule.ObjectCallback; import com.anjlab.eclipse.tapestry5.watchdog.WebXmlReader.WebXml; public class TapestryProject { private IProject project; private volatile List<TapestryModule> modules; public TapestryProject(IProject project) { this.project = project; } public IProject getProject() { return project; } public List<TapestryModule> modules() { if (modules == null) { initialize(new NullProgressMonitor()); } return modules; } public void initialize(IProgressMonitor monitor) { findModules(monitor); markOverrides(); } private void markOverrides() { Map<String, List<JavaScriptStack>> stacks = new HashMap<String, List<JavaScriptStack>>(); for (TapestryModule module : modules()) { for (JavaScriptStack stack : module.javaScriptStacks()) { List<JavaScriptStack> configs = stacks.get(stack.getName()); if (configs == null) { configs = new ArrayList<JavaScriptStack>(); stacks.put(stack.getName(), configs); } configs.add(stack); } } for (String stackName : stacks.keySet()) { List<JavaScriptStack> configs = stacks.get(stackName); boolean hasOverride = false; for (JavaScriptStack stack : configs) { if (stack.isOverrides()) { hasOverride = true; } } if (hasOverride) { for (JavaScriptStack stack : configs) { if (!stack.isOverrides()) { stack.setOverridden(true); } } } } } private synchronized void findModules(IProgressMonitor monitor) { if (modules != null) { return; } modules = new ArrayList<TapestryModule>(); String appPackage = TapestryUtils.getAppPackage(project); if (appPackage == null) { return; } final WebXml webXml = Activator.getDefault().getWebXml(project); if (webXml == null) { return; } for (String filterName : webXml.getFilterNames()) { final String localFilterName = filterName; TapestryModule appModule = addModule(monitor, modules, project, appPackage + ".services." + StringUtils.capitalize(filterName) + "Module", new ModuleReference() { @Override public String getLabel() { return "Your Application's Module (via " + webXml.getFilterClassName(localFilterName) + " in web.xml)"; } }, new ObjectCallback<TapestryModule>() { @Override public void callback(TapestryModule module) { module.setAppModule(true); } }); if (appModule != null) { break; } } for (String paramName : webXml.getParamNames()) { if (paramName.matches("tapestry\\.[^-]+-modules")) { final String tapestryModeModules = paramName; String modeModules = webXml.getParamValue(tapestryModeModules); for (String moduleClassName : modeModules.split(",")) { addModule(monitor, modules, project, moduleClassName.trim(), new ModuleReference() { @Override public String getLabel() { return "via " + tapestryModeModules + " in web.xml"; } }, null); } } } // Handle new t5.4 TapestryModule class location ModuleReference coreModuleReference = new ModuleReference() { @Override public String getLabel() { return "Tapestry Core Module"; } }; ObjectCallback<TapestryModule> coreObjectCallback = new ObjectCallback<TapestryModule>() { @Override public void callback(TapestryModule module) { module.setTapestryCoreModule(true); } }; // t5.3 addModule(monitor, modules, project, "org.apache.tapestry5.services.TapestryModule", coreModuleReference, coreObjectCallback); // t5.4 addModule(monitor, modules, project, "org.apache.tapestry5.modules.TapestryModule", coreModuleReference, coreObjectCallback); try { for (IPackageFragmentRoot root : JavaCore.create(project).getAllPackageFragmentRoots()) { findModules(monitor, modules, root); } } catch (CoreException e) { Activator.getDefault().logError("Error searching tapestry modules", e); } } private void findModules(IProgressMonitor monitor, List<TapestryModule> modules, final IPackageFragmentRoot root) throws CoreException { monitor.subTask("Reading " + root.getElementName() + "..."); for (Object obj : root.getNonJavaResources()) { if (obj instanceof IJarEntryResource) { IJarEntryResource jarEntry = (IJarEntryResource) obj; if ("META-INF".equals(jarEntry.getName())) { for (IJarEntryResource child : jarEntry.getChildren()) { if ("MANIFEST.MF".equals(child.getName())) { InputStream contents = child.getContents(); try { Manifest manifest = new Manifest(contents); String classes = manifest.getMainAttributes().getValue("Tapestry-Module-Classes"); if (classes != null) { for (String className : classes.split(",")) { addModule(monitor, modules, project, className, new ModuleReference() { @Override public String getLabel() { return "via " + root.getElementName() + "/META-INF/MANIFEST.MF"; } }, null); } } } catch (IOException e) { if (contents != null) { try { contents.close(); } catch (IOException t) { } } } } } } } } } private TapestryModule addModule(IProgressMonitor monitor, List<TapestryModule> modules, IProject project, String moduleClassName, ModuleReference reference, ObjectCallback<TapestryModule> moduleCreated) { if (monitor.isCanceled()) { return null; } monitor.subTask("Locating " + moduleClassName + "..."); IType moduleClass = EclipseUtils.findTypeDeclaration(project, moduleClassName); if (moduleClass == null) { return null; } TapestryModule module = TapestryModule.createTapestryModule(this, moduleClass, reference); if (moduleCreated != null) { moduleCreated.callback(module); } addModule(monitor, modules, module); return module; } private void addModule(IProgressMonitor monitor, List<TapestryModule> modules, TapestryModule module) { if (monitor.isCanceled()) { return; } if (modules.contains(module)) { return; } module.initialize(monitor); modules.add(module); for (TapestryModule subModule : module.subModules()) { addModule(monitor, modules, subModule); } } public boolean contains(IProject project) { for (TapestryModule module : modules()) { if (project.equals(module.getModuleClass().getJavaProject().getProject())) { return true; } } return false; } public TapestryContext findComponentContext(String componentName) throws JavaModelException { String libraryPrefix = ""; String componentNameWithoutPrefix = componentName; int index = componentName.indexOf('.'); if (index < 0) { index = componentName.indexOf('/'); } if (index >= 0) { libraryPrefix = componentName.substring(0, index); if (index + 1 >= componentName.length()) { return null; } componentNameWithoutPrefix = componentName.substring(index + 1); } for (TapestryModule module : modules) { if (module.isAppModule()) { TapestryContext context = findComponentContext( module, TapestryUtils.getComponentsPackage(module.getEclipseProject()), componentName); if (context != null) { return context; } } for (LibraryMapping mapping : module.libraryMappings()) { if (libraryPrefix.equals(mapping.getPathPrefix())) { TapestryContext context = findComponentContext( module, mapping.getRootPackage() + ".components", componentNameWithoutPrefix); if (context != null) { return context; } } } } if ("".equals(libraryPrefix)) { return findComponentContext("core/" + componentNameWithoutPrefix); } return null; } private TapestryContext findComponentContext(TapestryModule module, String appPackage, String componentNameWithoutPrefix) { // subpackage.componentName String componentPath = getComponentPath(module, appPackage, componentNameWithoutPrefix); // TODO Look in module.getComponents() instead? It's cached TapestryFile file = module.findClasspathFileCaseInsensitive(componentPath); if (file == null) { File parentFile = new File(componentPath).getParentFile(); if (parentFile != null) { // subpackage.componentNameSubpackage componentPath = getComponentPath(module, appPackage, componentNameWithoutPrefix + parentFile.getName()); file = module.findClasspathFileCaseInsensitive(componentPath); if (file == null) { // subpackage.subpackageComponentName componentPath = getComponentPath(module, appPackage, prepend(componentNameWithoutPrefix, parentFile.getName())); file = module.findClasspathFileCaseInsensitive(componentPath); } } } return file != null ? file.getContext() : null; } private String prepend(String componentNameWithoutPrefix, String parentName) { StringBuilder builder = new StringBuilder(componentNameWithoutPrefix); int index = componentNameWithoutPrefix.lastIndexOf("."); return builder.insert(index + 1, parentName).toString(); } protected String getComponentPath(TapestryModule module, String appPackage, String componentNameWithoutPrefix) { return TapestryUtils.joinPath(appPackage.replace('.', '/'), componentNameWithoutPrefix.replace('.', '/') + (module instanceof LocalTapestryModule ? ".java" : ".class")); } public JavaScriptStack findStack(String stackName) { List<JavaScriptStack> stacks = new ArrayList<JavaScriptStack>(); for (TapestryModule module : modules()) { for (JavaScriptStack stack : module.javaScriptStacks()) { if (stackName.equals(stack.getName())) { stacks.add(stack); } } } // Find first overridden stack (if any) for (JavaScriptStack stack : stacks) { if (stack.isOverrides()) { return stack; } } return stacks.isEmpty() ? null : stacks.get(0); } }
com.anjlab.eclipse.tapestry5/src/com/anjlab/eclipse/tapestry5/TapestryProject.java
package com.anjlab.eclipse.tapestry5; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.Manifest; import org.apache.commons.lang.StringUtils; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IJarEntryResource; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import com.anjlab.eclipse.tapestry5.TapestryModule.ModuleReference; import com.anjlab.eclipse.tapestry5.TapestryModule.ObjectCallback; import com.anjlab.eclipse.tapestry5.watchdog.WebXmlReader.WebXml; public class TapestryProject { private IProject project; private volatile List<TapestryModule> modules; public TapestryProject(IProject project) { this.project = project; } public IProject getProject() { return project; } public List<TapestryModule> modules() { if (modules == null) { initialize(new NullProgressMonitor()); } return modules; } public void initialize(IProgressMonitor monitor) { findModules(monitor); markOverrides(); } private void markOverrides() { Map<String, List<JavaScriptStack>> stacks = new HashMap<String, List<JavaScriptStack>>(); for (TapestryModule module : modules()) { for (JavaScriptStack stack : module.javaScriptStacks()) { List<JavaScriptStack> configs = stacks.get(stack.getName()); if (configs == null) { configs = new ArrayList<JavaScriptStack>(); stacks.put(stack.getName(), configs); } configs.add(stack); } } for (String stackName : stacks.keySet()) { List<JavaScriptStack> configs = stacks.get(stackName); boolean hasOverride = false; for (JavaScriptStack stack : configs) { if (stack.isOverrides()) { hasOverride = true; } } if (hasOverride) { for (JavaScriptStack stack : configs) { if (!stack.isOverrides()) { stack.setOverridden(true); } } } } } private synchronized void findModules(IProgressMonitor monitor) { if (modules != null) { return; } modules = new ArrayList<TapestryModule>(); String appPackage = TapestryUtils.getAppPackage(project); if (appPackage == null) { return; } final WebXml webXml = Activator.getDefault().getWebXml(project); if (webXml == null) { return; } for (String filterName : webXml.getFilterNames()) { final String localFilterName = filterName; TapestryModule appModule = addModule(monitor, modules, project, appPackage + ".services." + StringUtils.capitalize(filterName) + "Module", new ModuleReference() { @Override public String getLabel() { return "Your Application's Module (via " + webXml.getFilterClassName(localFilterName) + " in web.xml)"; } }, new ObjectCallback<TapestryModule>() { @Override public void callback(TapestryModule module) { module.setAppModule(true); } }); if (appModule != null) { break; } } for (String paramName : webXml.getParamNames()) { if (paramName.matches("tapestry\\.[^-]+-modules")) { final String tapestryModeModules = paramName; String modeModules = webXml.getParamValue(tapestryModeModules); for (String moduleClassName : modeModules.split(",")) { addModule(monitor, modules, project, moduleClassName.trim(), new ModuleReference() { @Override public String getLabel() { return "via " + tapestryModeModules + " in web.xml"; } }, null); } } } // Handle new t5.4 TapestryModule class location ModuleReference coreModuleReference =new ModuleReference() { @Override public String getLabel() { return "Tapestry Core Module"; } }; ObjectCallback<TapestryModule> coreObjectCallback = new ObjectCallback<TapestryModule>() { @Override public void callback(TapestryModule module) { module.setTapestryCoreModule(true); } }; // t5.3 addModule(monitor, modules, project, "org.apache.tapestry5.services.TapestryModule", coreModuleReference, coreObjectCallback); // t5.4 addModule(monitor, modules, project, "org.apache.tapestry5.modules.TapestryModule", coreModuleReference, coreObjectCallback); try { for (IPackageFragmentRoot root : JavaCore.create(project).getAllPackageFragmentRoots()) { findModules(monitor, modules, root); } } catch (CoreException e) { Activator.getDefault().logError("Error searching tapestry modules", e); } } private void findModules(IProgressMonitor monitor, List<TapestryModule> modules, final IPackageFragmentRoot root) throws CoreException { monitor.subTask("Reading " + root.getElementName() + "..."); for (Object obj : root.getNonJavaResources()) { if (obj instanceof IJarEntryResource) { IJarEntryResource jarEntry = (IJarEntryResource) obj; if ("META-INF".equals(jarEntry.getName())) { for (IJarEntryResource child : jarEntry.getChildren()) { if ("MANIFEST.MF".equals(child.getName())) { InputStream contents = child.getContents(); try { Manifest manifest = new Manifest(contents); String classes = manifest.getMainAttributes().getValue("Tapestry-Module-Classes"); if (classes != null) { for (String className : classes.split(",")) { addModule(monitor, modules, project, className, new ModuleReference() { @Override public String getLabel() { return "via " + root.getElementName() + "/META-INF/MANIFEST.MF"; } }, null); } } } catch (IOException e) { if (contents != null) { try { contents.close(); } catch (IOException t) { } } } } } } } } } private TapestryModule addModule(IProgressMonitor monitor, List<TapestryModule> modules, IProject project, String moduleClassName, ModuleReference reference, ObjectCallback<TapestryModule> moduleCreated) { if (monitor.isCanceled()) { return null; } monitor.subTask("Locating " + moduleClassName + "..."); IType moduleClass = EclipseUtils.findTypeDeclaration(project, moduleClassName); if (moduleClass == null) { return null; } TapestryModule module = TapestryModule.createTapestryModule(this, moduleClass, reference); if (moduleCreated != null) { moduleCreated.callback(module); } addModule(monitor, modules, module); return module; } private void addModule(IProgressMonitor monitor, List<TapestryModule> modules, TapestryModule module) { if (monitor.isCanceled()) { return; } if (modules.contains(module)) { return; } module.initialize(monitor); modules.add(module); for (TapestryModule subModule : module.subModules()) { addModule(monitor, modules, subModule); } } public boolean contains(IProject project) { for (TapestryModule module : modules()) { if (project.equals(module.getModuleClass().getJavaProject().getProject())) { return true; } } return false; } public TapestryContext findComponentContext(String componentName) throws JavaModelException { String libraryPrefix = ""; String componentNameWithoutPrefix = componentName; int index = componentName.indexOf('.'); if (index < 0) { index = componentName.indexOf('/'); } if (index >= 0) { libraryPrefix = componentName.substring(0, index); if (index + 1 >= componentName.length()) { return null; } componentNameWithoutPrefix = componentName.substring(index + 1); } for (TapestryModule module : modules) { if (module.isAppModule()) { TapestryContext context = findComponentContext( module, TapestryUtils.getComponentsPackage(module.getEclipseProject()), componentName); if (context != null) { return context; } } for (LibraryMapping mapping : module.libraryMappings()) { if (libraryPrefix.equals(mapping.getPathPrefix())) { TapestryContext context = findComponentContext( module, mapping.getRootPackage() + ".components", componentNameWithoutPrefix); if (context != null) { return context; } } } } if ("".equals(libraryPrefix)) { return findComponentContext("core/" + componentNameWithoutPrefix); } return null; } private TapestryContext findComponentContext(TapestryModule module, String appPackage, String componentNameWithoutPrefix) { // subpackage.componentName String componentPath = getComponentPath(module, appPackage, componentNameWithoutPrefix); // TODO Look in module.getComponents() instead? It's cached TapestryFile file = module.findClasspathFileCaseInsensitive(componentPath); if (file == null) { File parentFile = new File(componentPath).getParentFile(); if (parentFile != null) { // subpackage.componentNameSubpackage componentPath = getComponentPath(module, appPackage, componentNameWithoutPrefix + parentFile.getName()); file = module.findClasspathFileCaseInsensitive(componentPath); if (file == null) { // subpackage.subpackageComponentName componentPath = getComponentPath(module, appPackage, prepend(componentNameWithoutPrefix, parentFile.getName())); file = module.findClasspathFileCaseInsensitive(componentPath); } } } return file != null ? file.getContext() : null; } private String prepend(String componentNameWithoutPrefix, String parentName) { StringBuilder builder = new StringBuilder(componentNameWithoutPrefix); int index = componentNameWithoutPrefix.lastIndexOf("."); return builder.insert(index + 1, parentName).toString(); } protected String getComponentPath(TapestryModule module, String appPackage, String componentNameWithoutPrefix) { return TapestryUtils.joinPath(appPackage.replace('.', '/'), componentNameWithoutPrefix.replace('.', '/') + (module instanceof LocalTapestryModule ? ".java" : ".class")); } public JavaScriptStack findStack(String stackName) { List<JavaScriptStack> stacks = new ArrayList<JavaScriptStack>(); for (TapestryModule module : modules()) { for (JavaScriptStack stack : module.javaScriptStacks()) { if (stackName.equals(stack.getName())) { stacks.add(stack); } } } // Find first overridden stack (if any) for (JavaScriptStack stack : stacks) { if (stack.isOverrides()) { return stack; } } return stacks.isEmpty() ? null : stacks.get(0); } }
Fix formatting
com.anjlab.eclipse.tapestry5/src/com/anjlab/eclipse/tapestry5/TapestryProject.java
Fix formatting
<ide><path>om.anjlab.eclipse.tapestry5/src/com/anjlab/eclipse/tapestry5/TapestryProject.java <ide> } <ide> <ide> // Handle new t5.4 TapestryModule class location <del> ModuleReference coreModuleReference =new ModuleReference() <add> ModuleReference coreModuleReference = new ModuleReference() <ide> { <ide> @Override <ide> public String getLabel()
Java
apache-2.0
30b89d1aa04aa84d25ec360d1b6608df08eed7a9
0
hekate-io/hekate
/* * Copyright 2020 The Hekate Project * * The Hekate 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.hekate.coordinate.internal; import io.hekate.cluster.ClusterTopology; import io.hekate.cluster.event.ClusterEvent; import io.hekate.cluster.event.ClusterEventType; import io.hekate.codec.CodecFactory; import io.hekate.codec.CodecService; import io.hekate.coordinate.CoordinationConfigProvider; import io.hekate.coordinate.CoordinationFuture; import io.hekate.coordinate.CoordinationProcess; import io.hekate.coordinate.CoordinationProcessConfig; import io.hekate.coordinate.CoordinationService; import io.hekate.coordinate.CoordinationServiceFactory; import io.hekate.coordinate.internal.CoordinationProtocol.RequestBase; import io.hekate.core.HekateException; import io.hekate.core.ServiceInfo; import io.hekate.core.internal.util.ArgAssert; import io.hekate.core.internal.util.ConfigCheck; import io.hekate.core.internal.util.HekateThreadFactory; import io.hekate.core.internal.util.Utils; import io.hekate.core.report.ConfigReporter; import io.hekate.core.service.ConfigurationContext; import io.hekate.core.service.CoreService; import io.hekate.core.service.DependencyContext; import io.hekate.core.service.InitializationContext; import io.hekate.messaging.Message; import io.hekate.messaging.MessagingChannel; import io.hekate.messaging.MessagingChannelConfig; import io.hekate.messaging.MessagingConfigProvider; import io.hekate.messaging.MessagingService; import io.hekate.util.StateGuard; import io.hekate.util.async.AsyncUtils; import io.hekate.util.async.Waiting; import io.hekate.util.format.ToString; import io.hekate.util.format.ToStringIgnore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.hekate.core.internal.util.StreamUtils.nullSafe; import static java.util.stream.Collectors.toList; public class DefaultCoordinationService implements CoordinationService, CoreService, MessagingConfigProvider { private static final Logger log = LoggerFactory.getLogger(DefaultCoordinationProcess.class); private static final boolean DEBUG = log.isDebugEnabled(); private static final String COORDINATION_CHANNEL = "hekate.coordination"; private final long retryDelay; private final int nioThreads; private final long idleSocketTimeout; @ToStringIgnore private final StateGuard guard = new StateGuard(CoordinationService.class); @ToStringIgnore private final List<CoordinationProcessConfig> processesConfigs = new ArrayList<>(); @ToStringIgnore private final Map<String, DefaultCoordinationProcess> processes = new HashMap<>(); @ToStringIgnore private MessagingService messaging; @ToStringIgnore private CodecService defaultCodec; public DefaultCoordinationService(CoordinationServiceFactory factory) { ArgAssert.notNull(factory, "Factory"); ConfigCheck check = ConfigCheck.get(CoordinationServiceFactory.class); check.positive(factory.getRetryInterval(), "retry interval"); this.nioThreads = factory.getNioThreads(); this.retryDelay = factory.getRetryInterval(); this.idleSocketTimeout = factory.getIdleSocketTimeout(); nullSafe(factory.getProcesses()).forEach(processesConfigs::add); } @Override public void resolve(DependencyContext ctx) { messaging = ctx.require(MessagingService.class); defaultCodec = ctx.require(CodecService.class); } @Override public void configure(ConfigurationContext ctx) { // Collect configurations from providers. nullSafe(ctx.findComponents(CoordinationConfigProvider.class)).forEach(provider -> nullSafe(provider.configureCoordination()).forEach(processesConfigs::add) ); // Validate configs. ConfigCheck check = ConfigCheck.get(CoordinationProcessConfig.class); Set<String> uniqueNames = new HashSet<>(); processesConfigs.forEach(cfg -> { check.notEmpty(cfg.getName(), "name"); check.validSysName(cfg.getName(), "name"); check.notNull(cfg.getHandler(), "handler"); String name = cfg.getName().trim(); check.unique(name, uniqueNames, "name"); uniqueNames.add(name); }); // Register process names as service property. processesConfigs.forEach(cfg -> ctx.setBoolProperty(propertyName(cfg.getName().trim()), true) ); } @Override public Collection<MessagingChannelConfig<?>> configureMessaging() { // Skip configuration is there are no registered processes. if (processesConfigs.isEmpty()) { return Collections.emptyList(); } // Map processes to codecs. Map<String, CodecFactory<Object>> codecs = new HashMap<>(); processesConfigs.forEach(cfg -> { String name = cfg.getName().trim(); if (cfg.getMessageCodec() == null) { codecs.put(name, defaultCodec.codecFactory()); } else { codecs.put(name, cfg.getMessageCodec()); } }); // Prepare codec factory. CodecFactory<CoordinationProtocol> codecFactory = () -> new CoordinationProtocolCodec(codecs); // Messaging channel configuration. return Collections.singleton( MessagingChannelConfig.of(CoordinationProtocol.class) .withName(COORDINATION_CHANNEL) .withClusterFilter(node -> node.hasService(CoordinationService.class)) .withNioThreads(nioThreads) .withIdleSocketTimeout(idleSocketTimeout) .withMessageCodec(codecFactory) .withLogCategory(CoordinationProtocol.class.getName()) .withRetryPolicy(retry -> retry .withFixedDelay(retryDelay) ) .withReceiver(this::handleMessage) ); } @Override public void initialize(InitializationContext ctx) throws HekateException { if (DEBUG) { log.debug("Initializing..."); } guard.becomeInitialized(() -> { if (!processesConfigs.isEmpty()) { // Get coordination messaging channel (shared among all coordination processes). MessagingChannel<CoordinationProtocol> channel = messaging.channel(COORDINATION_CHANNEL, CoordinationProtocol.class); // Register cluster listener to trigger coordination. channel.cluster().addListener(this::processTopologyChange, ClusterEventType.JOIN, ClusterEventType.CHANGE); // Initialize coordination processes. for (CoordinationProcessConfig cfg : processesConfigs) { initializeProcess(cfg, ctx, channel); } } }); if (DEBUG) { log.debug("Initialized."); } } @Override public void report(ConfigReporter report) { guard.withReadLockIfInitialized(() -> { if (!processes.isEmpty()) { report.section("coordination", coordinationSec -> { coordinationSec.value("retry-delay", retryDelay); for (DefaultCoordinationProcess process : processes.values()) { coordinationSec.section("process", processSec -> { processSec.value("name", process.name()); processSec.value("async-init", process.isAsyncInit()); processSec.value("handler", process.handler()); }); } }); } }); } @Override public void preTerminate() throws HekateException { if (DEBUG) { log.debug("Pre-terminating."); } Waiting done = guard.becomeTerminating(() -> processes.values().stream() .map(DefaultCoordinationProcess::terminate) .collect(toList()) ); done.awaitUninterruptedly(); if (DEBUG) { log.debug("Pre-terminated."); } } @Override public void terminate() throws HekateException { if (DEBUG) { log.debug("Terminating."); } Waiting done = guard.becomeTerminated(() -> { List<Waiting> waiting = processes.values().stream() .map(DefaultCoordinationProcess::terminate) .collect(toList()); processes.clear(); return waiting; }); done.awaitUninterruptedly(); if (DEBUG) { log.debug("Terminated."); } } @Override public List<CoordinationProcess> allProcesses() { return guard.withReadLockAndStateCheck(() -> new ArrayList<>(processes.values()) ); } @Override public CoordinationProcess process(String name) { ArgAssert.notNull(name, "Process name"); return guard.withReadLockAndStateCheck(() -> { DefaultCoordinationProcess process = processes.get(name); ArgAssert.check(process != null, "Coordination process not configured [name=" + name + ']'); return process; }); } @Override public boolean hasProcess(String name) { return guard.withReadLockAndStateCheck(() -> processes.containsKey(name) ); } @Override public CoordinationFuture futureOf(String process) { return process(process).future(); } private void initializeProcess( CoordinationProcessConfig cfg, InitializationContext ctx, MessagingChannel<CoordinationProtocol> channel ) throws HekateException { assert guard.isWriteLocked() : "Thread must hold write lock."; if (DEBUG) { log.debug("Registering new process [configuration={}]", cfg); } String name = cfg.getName().trim(); // Prepare worker thread. ExecutorService async = Executors.newSingleThreadExecutor(new HekateThreadFactory("Coordination-" + name)); // Instantiate and register. DefaultCoordinationProcess process = new DefaultCoordinationProcess( name, ctx.hekate(), cfg.getHandler(), cfg.isAsyncInit(), async, channel ); processes.put(name, process); // Register initial coordination future. if (!process.isAsyncInit()) { ctx.cluster().addSyncFuture(process.future()); } // Initialize. try { AsyncUtils.getUninterruptedly(process.initialize()); } catch (ExecutionException e) { throw new HekateException("Failed to initialize coordination handler [process=" + name + ']', e.getCause()); } } private void handleMessage(Message<CoordinationProtocol> msg) { RequestBase req = msg.payload(RequestBase.class); DefaultCoordinationProcess process = null; guard.lockRead(); try { if (guard.isInitialized()) { process = processes.get(req.processName()); if (process == null) { throw new IllegalStateException("Received coordination request for unknown process: " + req); } } } finally { guard.unlockRead(); } if (process == null) { if (DEBUG) { log.debug("Rejecting coordination message since service is not initialized [message={}]", req); } msg.reply(CoordinationProtocol.Reject.INSTANCE); } else { process.processMessage(msg); } } private void processTopologyChange(ClusterEvent event) { guard.withReadLockIfInitialized(() -> { processes.values().forEach(process -> { ClusterTopology topology = event.topology().filter(node -> { ServiceInfo service = node.service(CoordinationService.class); return service.property(propertyName(process.name())) != null; }); process.processTopologyChange(topology); }); }); } private static String propertyName(String process) { return "process." + process; } @Override public String toString() { return CoordinationService.class.getSimpleName() + '[' + ToString.formatProperties(this) + ", processes=" + Utils.toString(processesConfigs, CoordinationProcessConfig::getName) + ']'; } }
hekate-core/src/main/java/io/hekate/coordinate/internal/DefaultCoordinationService.java
/* * Copyright 2020 The Hekate Project * * The Hekate 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.hekate.coordinate.internal; import io.hekate.cluster.ClusterNodeFilter; import io.hekate.cluster.ClusterService; import io.hekate.cluster.ClusterTopology; import io.hekate.cluster.ClusterView; import io.hekate.cluster.event.ClusterEvent; import io.hekate.cluster.event.ClusterEventType; import io.hekate.codec.CodecFactory; import io.hekate.codec.CodecService; import io.hekate.coordinate.CoordinationConfigProvider; import io.hekate.coordinate.CoordinationFuture; import io.hekate.coordinate.CoordinationProcess; import io.hekate.coordinate.CoordinationProcessConfig; import io.hekate.coordinate.CoordinationService; import io.hekate.coordinate.CoordinationServiceFactory; import io.hekate.core.Hekate; import io.hekate.core.HekateException; import io.hekate.core.ServiceInfo; import io.hekate.core.internal.util.ArgAssert; import io.hekate.core.internal.util.ConfigCheck; import io.hekate.core.internal.util.HekateThreadFactory; import io.hekate.core.internal.util.StreamUtils; import io.hekate.core.internal.util.Utils; import io.hekate.core.report.ConfigReporter; import io.hekate.core.service.ConfigurationContext; import io.hekate.core.service.CoreService; import io.hekate.core.service.DependencyContext; import io.hekate.core.service.InitializationContext; import io.hekate.messaging.Message; import io.hekate.messaging.MessagingChannel; import io.hekate.messaging.MessagingChannelConfig; import io.hekate.messaging.MessagingConfigProvider; import io.hekate.messaging.MessagingService; import io.hekate.util.StateGuard; import io.hekate.util.async.AsyncUtils; import io.hekate.util.async.Waiting; import io.hekate.util.format.ToString; import io.hekate.util.format.ToStringIgnore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toList; public class DefaultCoordinationService implements CoordinationService, CoreService, MessagingConfigProvider { private static final Logger log = LoggerFactory.getLogger(DefaultCoordinationProcess.class); private static final boolean DEBUG = log.isDebugEnabled(); private static final String CHANNEL_NAME = "hekate.coordination"; private static final ClusterNodeFilter HAS_COORDINATION_FILTER = node -> node.hasService(CoordinationService.class); private final long retryDelay; private final int nioThreads; private final long idleSocketTimeout; @ToStringIgnore private final StateGuard guard = new StateGuard(CoordinationService.class); @ToStringIgnore private final List<CoordinationProcessConfig> processesConfig = new ArrayList<>(); @ToStringIgnore private final Map<String, DefaultCoordinationProcess> processes = new HashMap<>(); @ToStringIgnore private Hekate hekate; @ToStringIgnore private MessagingService messaging; @ToStringIgnore private ClusterView cluster; @ToStringIgnore private CodecService defaultCodec; public DefaultCoordinationService(CoordinationServiceFactory factory) { ArgAssert.notNull(factory, "Factory"); ConfigCheck check = ConfigCheck.get(CoordinationServiceFactory.class); check.positive(factory.getRetryInterval(), "retry interval"); this.nioThreads = factory.getNioThreads(); this.retryDelay = factory.getRetryInterval(); this.idleSocketTimeout = factory.getIdleSocketTimeout(); StreamUtils.nullSafe(factory.getProcesses()).forEach(processesConfig::add); } @Override public void resolve(DependencyContext ctx) { hekate = ctx.hekate(); messaging = ctx.require(MessagingService.class); cluster = ctx.require(ClusterService.class).filter(HAS_COORDINATION_FILTER); defaultCodec = ctx.require(CodecService.class); } @Override public void configure(ConfigurationContext ctx) { // Collect configurations from providers. Collection<CoordinationConfigProvider> providers = ctx.findComponents(CoordinationConfigProvider.class); StreamUtils.nullSafe(providers).forEach(provider -> { Collection<CoordinationProcessConfig> processesCfg = provider.configureCoordination(); StreamUtils.nullSafe(processesCfg).forEach(processesConfig::add); }); // Validate configs. ConfigCheck check = ConfigCheck.get(CoordinationProcessConfig.class); Set<String> uniqueNames = new HashSet<>(); processesConfig.forEach(cfg -> { check.notEmpty(cfg.getName(), "name"); check.validSysName(cfg.getName(), "name"); check.notNull(cfg.getHandler(), "handler"); String name = cfg.getName().trim(); check.unique(name, uniqueNames, "name"); uniqueNames.add(name); }); // Register process names as service property. processesConfig.forEach(cfg -> ctx.setBoolProperty(propertyName(cfg.getName().trim()), true) ); } @Override public Collection<MessagingChannelConfig<?>> configureMessaging() { if (processesConfig.isEmpty()) { return Collections.emptyList(); } Map<String, CodecFactory<Object>> processCodecs = new HashMap<>(); processesConfig.forEach(cfg -> { String name = cfg.getName().trim(); if (cfg.getMessageCodec() == null) { processCodecs.put(name, defaultCodec.codecFactory()); } else { processCodecs.put(name, cfg.getMessageCodec()); } }); return Collections.singleton( MessagingChannelConfig.of(CoordinationProtocol.class) .withName(CHANNEL_NAME) .withClusterFilter(HAS_COORDINATION_FILTER) .withNioThreads(nioThreads) .withIdleSocketTimeout(idleSocketTimeout) .withRetryPolicy(retry -> retry.withFixedDelay(retryDelay) ) .withLogCategory(CoordinationProtocol.class.getName()) .withMessageCodec(() -> new CoordinationProtocolCodec(processCodecs)) .withReceiver(this::handleMessage) ); } @Override public void initialize(InitializationContext ctx) throws HekateException { if (DEBUG) { log.debug("Initializing..."); } guard.becomeInitialized(() -> { if (!processesConfig.isEmpty()) { // Register cluster listener to trigger coordination. cluster.addListener(this::processTopologyChange, ClusterEventType.JOIN, ClusterEventType.CHANGE); // Get coordination messaging channel (shared among all coordination processes). MessagingChannel<CoordinationProtocol> channel = messaging.channel(CHANNEL_NAME, CoordinationProtocol.class); // Initialize coordination processes. for (CoordinationProcessConfig cfg : processesConfig) { initializeProcess(cfg, ctx, channel); } } }); if (DEBUG) { log.debug("Initialized."); } } @Override public void report(ConfigReporter report) { guard.withReadLockIfInitialized(() -> { if (!processes.isEmpty()) { report.section("coordination", coordinationSec -> { coordinationSec.value("retry-delay", retryDelay); for (DefaultCoordinationProcess process : processes.values()) { coordinationSec.section("process", processSec -> { processSec.value("name", process.name()); processSec.value("async-init", process.isAsyncInit()); processSec.value("handler", process.handler()); }); } }); } }); } @Override public void preTerminate() throws HekateException { if (DEBUG) { log.debug("Pre-terminating."); } Waiting done = guard.becomeTerminating(() -> processes.values().stream() .map(DefaultCoordinationProcess::terminate) .collect(toList()) ); done.awaitUninterruptedly(); if (DEBUG) { log.debug("Pre-terminated."); } } @Override public void terminate() throws HekateException { if (DEBUG) { log.debug("Terminating."); } Waiting done = guard.becomeTerminated(() -> { List<Waiting> waiting = processes.values().stream() .map(DefaultCoordinationProcess::terminate) .collect(toList()); processes.clear(); return waiting; }); done.awaitUninterruptedly(); if (DEBUG) { log.debug("Terminated."); } } @Override public List<CoordinationProcess> allProcesses() { guard.lockReadWithStateCheck(); try { return new ArrayList<>(processes.values()); } finally { guard.unlockRead(); } } @Override public CoordinationProcess process(String name) { DefaultCoordinationProcess process; guard.lockReadWithStateCheck(); try { process = processes.get(name); } finally { guard.unlockRead(); } ArgAssert.check(process != null, "Coordination process not configured [name=" + name + ']'); return process; } @Override public boolean hasProcess(String name) { guard.lockReadWithStateCheck(); try { return processes.containsKey(name); } finally { guard.unlockRead(); } } @Override public CoordinationFuture futureOf(String process) { return process(process).future(); } private void initializeProcess( CoordinationProcessConfig cfg, InitializationContext ctx, MessagingChannel<CoordinationProtocol> channel ) throws HekateException { assert guard.isWriteLocked() : "Thread must hold write lock."; if (DEBUG) { log.debug("Registering new process [configuration={}]", cfg); } String name = cfg.getName().trim(); // Prepare worker thread. ExecutorService async = Executors.newSingleThreadExecutor(new HekateThreadFactory("Coordination-" + name)); // Instantiate and register. DefaultCoordinationProcess process = new DefaultCoordinationProcess( name, hekate, cfg.getHandler(), cfg.isAsyncInit(), async, channel ); processes.put(name, process); // Register initial coordination future. if (!process.isAsyncInit()) { ctx.cluster().addSyncFuture(process.future()); } // Initialize. try { AsyncUtils.getUninterruptedly(process.initialize()); } catch (ExecutionException e) { throw new HekateException("Failed to initialize coordination handler [process=" + name + ']', e.getCause()); } } private void handleMessage(Message<CoordinationProtocol> msg) { DefaultCoordinationProcess process = null; CoordinationProtocol.RequestBase request = msg.payload(CoordinationProtocol.RequestBase.class); guard.lockRead(); try { if (guard.isInitialized()) { process = processes.get(request.processName()); if (process == null) { throw new IllegalStateException("Received coordination request for unknown process: " + request); } } } finally { guard.unlockRead(); } if (process == null) { if (DEBUG) { log.debug("Rejecting coordination message since service is not initialized [message={}]", request); } msg.reply(CoordinationProtocol.Reject.INSTANCE); } else { process.processMessage(msg); } } private void processTopologyChange(ClusterEvent event) { guard.lockRead(); try { if (guard.isInitialized()) { processes.values().forEach(process -> { ClusterTopology topology = event.topology().filter(node -> { ServiceInfo service = node.service(CoordinationService.class); return service.property(propertyName(process.name())) != null; }); process.processTopologyChange(topology); }); } } finally { guard.unlockRead(); } } private static String propertyName(String process) { return "process." + process; } @Override public String toString() { return CoordinationService.class.getSimpleName() + '[' + ToString.formatProperties(this) + ", processes=" + Utils.toString(processesConfig, CoordinationProcessConfig::getName) + ']'; } }
Code readability improvements.
hekate-core/src/main/java/io/hekate/coordinate/internal/DefaultCoordinationService.java
Code readability improvements.
<ide><path>ekate-core/src/main/java/io/hekate/coordinate/internal/DefaultCoordinationService.java <ide> <ide> package io.hekate.coordinate.internal; <ide> <del>import io.hekate.cluster.ClusterNodeFilter; <del>import io.hekate.cluster.ClusterService; <ide> import io.hekate.cluster.ClusterTopology; <del>import io.hekate.cluster.ClusterView; <ide> import io.hekate.cluster.event.ClusterEvent; <ide> import io.hekate.cluster.event.ClusterEventType; <ide> import io.hekate.codec.CodecFactory; <ide> import io.hekate.coordinate.CoordinationProcessConfig; <ide> import io.hekate.coordinate.CoordinationService; <ide> import io.hekate.coordinate.CoordinationServiceFactory; <del>import io.hekate.core.Hekate; <add>import io.hekate.coordinate.internal.CoordinationProtocol.RequestBase; <ide> import io.hekate.core.HekateException; <ide> import io.hekate.core.ServiceInfo; <ide> import io.hekate.core.internal.util.ArgAssert; <ide> import io.hekate.core.internal.util.ConfigCheck; <ide> import io.hekate.core.internal.util.HekateThreadFactory; <del>import io.hekate.core.internal.util.StreamUtils; <ide> import io.hekate.core.internal.util.Utils; <ide> import io.hekate.core.report.ConfigReporter; <ide> import io.hekate.core.service.ConfigurationContext; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <add>import static io.hekate.core.internal.util.StreamUtils.nullSafe; <ide> import static java.util.stream.Collectors.toList; <ide> <ide> public class DefaultCoordinationService implements CoordinationService, CoreService, MessagingConfigProvider { <ide> <ide> private static final boolean DEBUG = log.isDebugEnabled(); <ide> <del> private static final String CHANNEL_NAME = "hekate.coordination"; <del> <del> private static final ClusterNodeFilter HAS_COORDINATION_FILTER = node -> node.hasService(CoordinationService.class); <add> private static final String COORDINATION_CHANNEL = "hekate.coordination"; <ide> <ide> private final long retryDelay; <ide> <ide> private final StateGuard guard = new StateGuard(CoordinationService.class); <ide> <ide> @ToStringIgnore <del> private final List<CoordinationProcessConfig> processesConfig = new ArrayList<>(); <add> private final List<CoordinationProcessConfig> processesConfigs = new ArrayList<>(); <ide> <ide> @ToStringIgnore <ide> private final Map<String, DefaultCoordinationProcess> processes = new HashMap<>(); <ide> <ide> @ToStringIgnore <del> private Hekate hekate; <del> <del> @ToStringIgnore <ide> private MessagingService messaging; <del> <del> @ToStringIgnore <del> private ClusterView cluster; <ide> <ide> @ToStringIgnore <ide> private CodecService defaultCodec; <ide> this.retryDelay = factory.getRetryInterval(); <ide> this.idleSocketTimeout = factory.getIdleSocketTimeout(); <ide> <del> StreamUtils.nullSafe(factory.getProcesses()).forEach(processesConfig::add); <add> nullSafe(factory.getProcesses()).forEach(processesConfigs::add); <ide> } <ide> <ide> @Override <ide> public void resolve(DependencyContext ctx) { <del> hekate = ctx.hekate(); <del> <ide> messaging = ctx.require(MessagingService.class); <del> cluster = ctx.require(ClusterService.class).filter(HAS_COORDINATION_FILTER); <ide> defaultCodec = ctx.require(CodecService.class); <ide> } <ide> <ide> @Override <ide> public void configure(ConfigurationContext ctx) { <ide> // Collect configurations from providers. <del> Collection<CoordinationConfigProvider> providers = ctx.findComponents(CoordinationConfigProvider.class); <del> <del> StreamUtils.nullSafe(providers).forEach(provider -> { <del> Collection<CoordinationProcessConfig> processesCfg = provider.configureCoordination(); <del> <del> StreamUtils.nullSafe(processesCfg).forEach(processesConfig::add); <del> }); <add> nullSafe(ctx.findComponents(CoordinationConfigProvider.class)).forEach(provider -> <add> nullSafe(provider.configureCoordination()).forEach(processesConfigs::add) <add> ); <ide> <ide> // Validate configs. <ide> ConfigCheck check = ConfigCheck.get(CoordinationProcessConfig.class); <ide> <ide> Set<String> uniqueNames = new HashSet<>(); <ide> <del> processesConfig.forEach(cfg -> { <add> processesConfigs.forEach(cfg -> { <ide> check.notEmpty(cfg.getName(), "name"); <ide> check.validSysName(cfg.getName(), "name"); <ide> check.notNull(cfg.getHandler(), "handler"); <ide> }); <ide> <ide> // Register process names as service property. <del> processesConfig.forEach(cfg -> <add> processesConfigs.forEach(cfg -> <ide> ctx.setBoolProperty(propertyName(cfg.getName().trim()), true) <ide> ); <ide> } <ide> <ide> @Override <ide> public Collection<MessagingChannelConfig<?>> configureMessaging() { <del> if (processesConfig.isEmpty()) { <add> // Skip configuration is there are no registered processes. <add> if (processesConfigs.isEmpty()) { <ide> return Collections.emptyList(); <ide> } <ide> <del> Map<String, CodecFactory<Object>> processCodecs = new HashMap<>(); <del> <del> processesConfig.forEach(cfg -> { <add> // Map processes to codecs. <add> Map<String, CodecFactory<Object>> codecs = new HashMap<>(); <add> <add> processesConfigs.forEach(cfg -> { <ide> String name = cfg.getName().trim(); <ide> <ide> if (cfg.getMessageCodec() == null) { <del> processCodecs.put(name, defaultCodec.codecFactory()); <add> codecs.put(name, defaultCodec.codecFactory()); <ide> } else { <del> processCodecs.put(name, cfg.getMessageCodec()); <add> codecs.put(name, cfg.getMessageCodec()); <ide> } <ide> }); <ide> <add> // Prepare codec factory. <add> CodecFactory<CoordinationProtocol> codecFactory = () -> new CoordinationProtocolCodec(codecs); <add> <add> // Messaging channel configuration. <ide> return Collections.singleton( <ide> MessagingChannelConfig.of(CoordinationProtocol.class) <del> .withName(CHANNEL_NAME) <del> .withClusterFilter(HAS_COORDINATION_FILTER) <add> .withName(COORDINATION_CHANNEL) <add> .withClusterFilter(node -> node.hasService(CoordinationService.class)) <ide> .withNioThreads(nioThreads) <ide> .withIdleSocketTimeout(idleSocketTimeout) <del> .withRetryPolicy(retry -> <del> retry.withFixedDelay(retryDelay) <add> .withMessageCodec(codecFactory) <add> .withLogCategory(CoordinationProtocol.class.getName()) <add> .withRetryPolicy(retry -> retry <add> .withFixedDelay(retryDelay) <ide> ) <del> .withLogCategory(CoordinationProtocol.class.getName()) <del> .withMessageCodec(() -> new CoordinationProtocolCodec(processCodecs)) <ide> .withReceiver(this::handleMessage) <ide> ); <ide> } <ide> } <ide> <ide> guard.becomeInitialized(() -> { <del> if (!processesConfig.isEmpty()) { <add> if (!processesConfigs.isEmpty()) { <add> // Get coordination messaging channel (shared among all coordination processes). <add> MessagingChannel<CoordinationProtocol> channel = messaging.channel(COORDINATION_CHANNEL, CoordinationProtocol.class); <add> <ide> // Register cluster listener to trigger coordination. <del> cluster.addListener(this::processTopologyChange, ClusterEventType.JOIN, ClusterEventType.CHANGE); <del> <del> // Get coordination messaging channel (shared among all coordination processes). <del> MessagingChannel<CoordinationProtocol> channel = messaging.channel(CHANNEL_NAME, CoordinationProtocol.class); <add> channel.cluster().addListener(this::processTopologyChange, ClusterEventType.JOIN, ClusterEventType.CHANGE); <ide> <ide> // Initialize coordination processes. <del> for (CoordinationProcessConfig cfg : processesConfig) { <add> for (CoordinationProcessConfig cfg : processesConfigs) { <ide> initializeProcess(cfg, ctx, channel); <ide> } <ide> } <ide> <ide> @Override <ide> public List<CoordinationProcess> allProcesses() { <del> guard.lockReadWithStateCheck(); <del> <del> try { <del> return new ArrayList<>(processes.values()); <del> } finally { <del> guard.unlockRead(); <del> } <add> return guard.withReadLockAndStateCheck(() -> <add> new ArrayList<>(processes.values()) <add> ); <ide> } <ide> <ide> @Override <ide> public CoordinationProcess process(String name) { <del> DefaultCoordinationProcess process; <del> <del> guard.lockReadWithStateCheck(); <del> <del> try { <del> process = processes.get(name); <del> } finally { <del> guard.unlockRead(); <del> } <del> <del> ArgAssert.check(process != null, "Coordination process not configured [name=" + name + ']'); <del> <del> return process; <add> ArgAssert.notNull(name, "Process name"); <add> <add> return guard.withReadLockAndStateCheck(() -> { <add> DefaultCoordinationProcess process = processes.get(name); <add> <add> ArgAssert.check(process != null, "Coordination process not configured [name=" + name + ']'); <add> <add> return process; <add> }); <ide> } <ide> <ide> @Override <ide> public boolean hasProcess(String name) { <del> guard.lockReadWithStateCheck(); <del> <del> try { <del> return processes.containsKey(name); <del> } finally { <del> guard.unlockRead(); <del> } <add> return guard.withReadLockAndStateCheck(() -> <add> processes.containsKey(name) <add> ); <ide> } <ide> <ide> @Override <ide> // Instantiate and register. <ide> DefaultCoordinationProcess process = new DefaultCoordinationProcess( <ide> name, <del> hekate, <add> ctx.hekate(), <ide> cfg.getHandler(), <ide> cfg.isAsyncInit(), <ide> async, <ide> } <ide> <ide> private void handleMessage(Message<CoordinationProtocol> msg) { <add> RequestBase req = msg.payload(RequestBase.class); <add> <ide> DefaultCoordinationProcess process = null; <del> <del> CoordinationProtocol.RequestBase request = msg.payload(CoordinationProtocol.RequestBase.class); <ide> <ide> guard.lockRead(); <ide> <ide> try { <ide> if (guard.isInitialized()) { <del> process = processes.get(request.processName()); <add> process = processes.get(req.processName()); <ide> <ide> if (process == null) { <del> throw new IllegalStateException("Received coordination request for unknown process: " + request); <add> throw new IllegalStateException("Received coordination request for unknown process: " + req); <ide> } <ide> } <ide> } finally { <ide> <ide> if (process == null) { <ide> if (DEBUG) { <del> log.debug("Rejecting coordination message since service is not initialized [message={}]", request); <add> log.debug("Rejecting coordination message since service is not initialized [message={}]", req); <ide> } <ide> <ide> msg.reply(CoordinationProtocol.Reject.INSTANCE); <ide> } <ide> <ide> private void processTopologyChange(ClusterEvent event) { <del> guard.lockRead(); <del> <del> try { <del> if (guard.isInitialized()) { <del> processes.values().forEach(process -> { <del> ClusterTopology topology = event.topology().filter(node -> { <del> ServiceInfo service = node.service(CoordinationService.class); <del> <del> return service.property(propertyName(process.name())) != null; <del> }); <del> <del> process.processTopologyChange(topology); <add> guard.withReadLockIfInitialized(() -> { <add> processes.values().forEach(process -> { <add> ClusterTopology topology = event.topology().filter(node -> { <add> ServiceInfo service = node.service(CoordinationService.class); <add> <add> return service.property(propertyName(process.name())) != null; <ide> }); <del> } <del> } finally { <del> guard.unlockRead(); <del> } <add> <add> process.processTopologyChange(topology); <add> }); <add> }); <ide> } <ide> <ide> private static String propertyName(String process) { <ide> public String toString() { <ide> return CoordinationService.class.getSimpleName() + '[' <ide> + ToString.formatProperties(this) <del> + ", processes=" + Utils.toString(processesConfig, CoordinationProcessConfig::getName) <add> + ", processes=" + Utils.toString(processesConfigs, CoordinationProcessConfig::getName) <ide> + ']'; <ide> } <ide> }
Java
apache-2.0
9e0b78374c2e08502f68168cee9f9c35f39de63d
0
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.index; import java.util.Iterator; import java.util.NoSuchElementException; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; /** * An {@link Iterator} with additional {@link #size()} and {@link #close()} * methods on it, used for iterating over index query results. It is first and * foremost an {@link Iterator}, but also an {@link Iterable} JUST so that it * can be used in a for-each loop. The <code>iterator()</code> method * <i>always</i> returns <code>this</code>. * * The size is calculated before-hand so that calling it is always fast. * * When you're done with the result and haven't reached the end of the * iteration {@link #close()} must be called. Results which are looped through * entirely closes automatically. Typical use: * * <pre> * IndexHits<Node> hits = index.get( "key", "value" ); * try * { * for ( Node node : hits ) * { * // do something with the hit * } * } * finally * { * hits.close(); * } * </pre> * * @param <T> the type of items in the Iterator. */ public interface IndexHits<T> extends Iterator<T>, Iterable<T> { /** * Returns the size of this iterable, in most scenarios this value is accurate * while in some scenarios near-accurate. * * There's no cost in calling this method. It's considered near-accurate if this * {@link IndexHits} object has been returned when inside a {@link Transaction} * which has index modifications, of a certain nature. Also entities * ({@link Node}s/{@link Relationship}s) which have been deleted from the graph, * but are still in the index will also affect the accuracy of the returned size. * * @return the near-accurate size if this iterable. */ int size(); /** * Closes the underlying search result. This method should be called * whenever you've got what you wanted from the result and won't use it * anymore. It's necessary to call it so that underlying indexes can dispose * of allocated resources for this search result. * * You can however skip to call this method if you loop through the whole * result, then close() will be called automatically. Even if you loop * through the entire result and then call this method it will silently * ignore any consequtive call (for convenience). */ void close(); /** * Returns the first and only item from the result iterator, or {@code null} * if there was none. If there were more than one item in the result a * {@link NoSuchElementException} will be thrown. This method must be called * first in the iteration and will grab the first item from the iteration, * so the result is considered broken after this call. * * @return the first and only item, or {@code null} if none. */ T getSingle(); /** * Returns the score of the most recently fetched item from this iterator * (from {@link #next()}). The range of the returned values is up to the * {@link Index} implementation to dictate. * @return the score of the most recently fetched item from this iterator. */ float currentScore(); }
advanced/kernel/src/main/java/org/neo4j/graphdb/index/IndexHits.java
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.index; import java.util.Iterator; import java.util.NoSuchElementException; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; /** * An {@link Iterator} with additional {@link #size()} and {@link #close()} * methods on it, used for iterating over index query results. It is first and * foremost an {@link Iterator}, but also an {@link Iterable} JUST so that it * can be used in a for-each loop. The <code>iterator()</code> method * <i>always</i> returns <code>this</code>. * * The size is calculated before-hand so that calling it is always fast. * * When you're done with the result and haven't reached the end of the * iteration {@link #close()} must be called. Results which are looped through * entirely closes automatically. * * @param <T> the type of items in the Iterator. */ public interface IndexHits<T> extends Iterator<T>, Iterable<T> { /** * Returns the size of this iterable, in most scenarios this value is accurate * while in some scenarios near-accurate. * * There's no cost in calling this method. It's considered near-accurate if this * {@link IndexHits} object has been returned when inside a {@link Transaction} * which has index modifications, of a certain nature. Also entities * ({@link Node}s/{@link Relationship}s) which have been deleted from the graph, * but are still in the index will also affect the accuracy of the returned size. * * @return the near-accurate size if this iterable. */ int size(); /** * Closes the underlying search result. This method should be called * whenever you've got what you wanted from the result and won't use it * anymore. It's necessary to call it so that underlying indexes can dispose * of allocated resources for this search result. * * You can however skip to call this method if you loop through the whole * result, then close() will be called automatically. Even if you loop * through the entire result and then call this method it will silently * ignore any consequtive call (for convenience). */ void close(); /** * Returns the first and only item from the result iterator, or {@code null} * if there was none. If there were more than one item in the result a * {@link NoSuchElementException} will be thrown. This method must be called * first in the iteration and will grab the first item from the iteration, * so the result is considered broken after this call. * * @return the first and only item, or {@code null} if none. */ T getSingle(); /** * Returns the score of the most recently fetched item from this iterator * (from {@link #next()}). The range of the returned values is up to the * {@link Index} implementation to dictate. * @return the score of the most recently fetched item from this iterator. */ float currentScore(); }
Added a typical use to the documentation (the try-finally clause)
advanced/kernel/src/main/java/org/neo4j/graphdb/index/IndexHits.java
Added a typical use to the documentation (the try-finally clause)
<ide><path>dvanced/kernel/src/main/java/org/neo4j/graphdb/index/IndexHits.java <ide> * <ide> * When you're done with the result and haven't reached the end of the <ide> * iteration {@link #close()} must be called. Results which are looped through <del> * entirely closes automatically. <add> * entirely closes automatically. Typical use: <add> * <add> * <pre> <add> * IndexHits<Node> hits = index.get( "key", "value" ); <add> * try <add> * { <add> * for ( Node node : hits ) <add> * { <add> * // do something with the hit <add> * } <add> * } <add> * finally <add> * { <add> * hits.close(); <add> * } <add> * </pre> <ide> * <ide> * @param <T> the type of items in the Iterator. <ide> */
Java
apache-2.0
b0209fdaac22c4dc57ac9a2275e7fe451ff1e7c6
0
aemay2/hapi-fhir,aemay2/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir
package ca.uhn.fhir.jpa.bulk.job; /*- * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2021 Smile CDR, 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% */ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.context.RuntimeSearchParam; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.api.dao.DaoRegistry; import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.batch.log.Logs; import ca.uhn.fhir.jpa.dao.IResultIterator; import ca.uhn.fhir.jpa.dao.ISearchBuilder; import ca.uhn.fhir.jpa.dao.SearchBuilderFactory; import ca.uhn.fhir.jpa.dao.data.IBulkExportJobDao; import ca.uhn.fhir.jpa.entity.BulkExportJobEntity; import ca.uhn.fhir.jpa.model.search.SearchRuntimeDetails; import ca.uhn.fhir.jpa.model.util.JpaConstants; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.jpa.util.QueryChunker; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.api.server.storage.ResourcePersistentId; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.HasParam; import ca.uhn.fhir.util.UrlUtil; import org.hl7.fhir.instance.model.api.IBaseResource; import org.slf4j.Logger; import org.springframework.batch.item.ItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import javax.annotation.Nonnull; import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; public class GroupBulkItemReader implements ItemReader<List<ResourcePersistentId>> { private static final Logger ourLog = Logs.getBatchTroubleshootingLog(); Iterator<ResourcePersistentId> myPidIterator; @Value("#{stepExecutionContext['resourceType']}") private String myResourceType; @Value("#{jobParameters['" + BulkExportJobConfig.GROUP_ID_PARAMETER + "']}") private String myGroupId; @Value("#{jobParameters['"+ BulkExportJobConfig.JOB_UUID_PARAMETER+"']}") private String myJobUUID; @Value("#{jobParameters['" + BulkExportJobConfig.READ_CHUNK_PARAMETER + "']}") private Long myReadChunkSize; @Autowired private IBulkExportJobDao myBulkExportJobDao; @Autowired private DaoRegistry myDaoRegistry; @Autowired private FhirContext myContext; @Autowired private SearchBuilderFactory mySearchBuilderFactory; @Autowired private EntityManager myEntityManager; private void loadResourcePids() { Optional<BulkExportJobEntity> jobOpt = myBulkExportJobDao.findByJobId(myJobUUID); if (!jobOpt.isPresent()) { ourLog.warn("Job appears to be deleted"); return; } BulkExportJobEntity jobEntity = jobOpt.get(); ourLog.info("Group Bulk export starting generation for batch export job: [{}] with resourceType [{}] and UUID [{}]", jobEntity, myResourceType, myJobUUID); //Fetch all the pids given the query. ISearchBuilder searchBuilder = getSearchBuilder(); //Build complex-ish _has query with a revincludes which allows lookup by group membership SearchParameterMap searchParameterMap = getSearchParameterMap(jobEntity); IResultIterator resultIterator = searchBuilder.createQuery( searchParameterMap, new SearchRuntimeDetails(null, myJobUUID), null, RequestPartitionId.allPartitions() ); List<ResourcePersistentId> myReadPids = new ArrayList<>(); while (resultIterator.hasNext()) { myReadPids.add(resultIterator.next()); } //Given that databases explode when you have an IN clause with >1000 resources, we use the QueryChunker to break this into multiple queries. List<ResourcePersistentId> revIncludePids = new ArrayList<>(); QueryChunker<ResourcePersistentId> chunker = new QueryChunker<>(); chunker.chunk(myReadPids, pidChunk -> { revIncludePids.addAll(searchBuilder.loadIncludes(myContext, myEntityManager, pidChunk, searchParameterMap.getRevIncludes(), true, searchParameterMap.getLastUpdated(), myJobUUID, null)); }); myPidIterator = revIncludePids.iterator(); } //For all group revinclude queries, you need to perform the search on the Patient DAO, which is why this is hardcoded here. private ISearchBuilder getSearchBuilder() { IFhirResourceDao<?> dao = myDaoRegistry.getResourceDao("Patient"); RuntimeResourceDefinition def = myContext.getResourceDefinition("Patient"); Class<? extends IBaseResource> nextTypeClass = def.getImplementingClass(); return mySearchBuilderFactory.newSearchBuilder(dao, "Patient", nextTypeClass); } @Nonnull private SearchParameterMap getSearchParameterMap(BulkExportJobEntity jobEntity) { SearchParameterMap searchParameterMap = new SearchParameterMap(); searchParameterMap.add("_has", new HasParam("Group", "member", "_id", myGroupId)); String revIncludeString = buildRevIncludeString(); searchParameterMap.addRevInclude(new Include(revIncludeString).toLocked()); if (jobEntity.getSince() != null) { searchParameterMap.setLastUpdated(new DateRangeParam(jobEntity.getSince(), null)); } searchParameterMap.setLoadSynchronous(true); return searchParameterMap; } /** * Given the resource type of the job, fetch its patient compartment name, formatted for usage in an Include. * e.g. Immunization -> Immunization:patient * * @return A string which can be dropped directly into an Include. */ private String buildRevIncludeString() { RuntimeResourceDefinition runtimeResourceDefinition = myContext.getResourceDefinition(myResourceType); RuntimeSearchParam patientSearchParam = runtimeResourceDefinition.getSearchParam("patient"); if (patientSearchParam == null) { patientSearchParam = runtimeResourceDefinition.getSearchParam("subject"); if (patientSearchParam == null) { patientSearchParam = getRuntimeSearchParamByCompartment(runtimeResourceDefinition); } } String includeString = runtimeResourceDefinition.getName() + ":" + patientSearchParam.getName(); return includeString; } /** * Search the resource definition for a compartment named 'patient' and return its related Search Parameter. */ private RuntimeSearchParam getRuntimeSearchParamByCompartment(RuntimeResourceDefinition runtimeResourceDefinition) { RuntimeSearchParam patientSearchParam; List<RuntimeSearchParam> searchParams = runtimeResourceDefinition.getSearchParamsForCompartmentName("Patient"); if (searchParams == null || searchParams.size() == 0) { String errorMessage = String.format("Resource type [%s] is not eligible for Group Bulk export, as it contains no Patient compartment, and no `patient` or `subject` search parameter", myResourceType); throw new IllegalArgumentException(errorMessage); } else if (searchParams.size() == 1) { patientSearchParam = searchParams.get(0); } else { String errorMessage = String.format("Resource type [%s] is not eligible for Group Bulk export, as we are unable to disambiguate which patient search parameter we should be searching by.", myResourceType); throw new IllegalArgumentException(errorMessage); } return patientSearchParam; } @Override public List<ResourcePersistentId> read() { if (myPidIterator == null) { loadResourcePids(); } int count = 0; List<ResourcePersistentId> outgoing = new ArrayList<>(); while (myPidIterator.hasNext() && count < myReadChunkSize) { outgoing.add(myPidIterator.next()); count += 1; } return outgoing.size() == 0 ? null : outgoing; } }
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/job/GroupBulkItemReader.java
package ca.uhn.fhir.jpa.bulk.job; /*- * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2021 Smile CDR, 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% */ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.context.RuntimeSearchParam; import ca.uhn.fhir.interceptor.model.RequestPartitionId; import ca.uhn.fhir.jpa.api.dao.DaoRegistry; import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.batch.log.Logs; import ca.uhn.fhir.jpa.dao.IResultIterator; import ca.uhn.fhir.jpa.dao.ISearchBuilder; import ca.uhn.fhir.jpa.dao.SearchBuilderFactory; import ca.uhn.fhir.jpa.dao.data.IBulkExportJobDao; import ca.uhn.fhir.jpa.entity.BulkExportJobEntity; import ca.uhn.fhir.jpa.model.search.SearchRuntimeDetails; import ca.uhn.fhir.jpa.model.util.JpaConstants; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.jpa.util.QueryChunker; import ca.uhn.fhir.model.api.Include; import ca.uhn.fhir.rest.api.server.storage.ResourcePersistentId; import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.param.HasParam; import ca.uhn.fhir.util.UrlUtil; import org.hl7.fhir.instance.model.api.IBaseResource; import org.slf4j.Logger; import org.springframework.batch.item.ItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import javax.annotation.Nonnull; import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; public class GroupBulkItemReader implements ItemReader<List<ResourcePersistentId>> { private static final Logger ourLog = Logs.getBatchTroubleshootingLog(); Iterator<ResourcePersistentId> myPidIterator; @Value("#{stepExecutionContext['resourceType']}") private String myResourceType; @Value("#{jobParameters['" + BulkExportJobConfig.GROUP_ID_PARAMETER + "']}") private String myGroupId; @Value("#{jobParameters['"+ BulkExportJobConfig.JOB_UUID_PARAMETER+"']}") private String myJobUUID; @Value("#{jobParameters['" + BulkExportJobConfig.READ_CHUNK_PARAMETER + "']}") private Long myReadChunkSize; @Autowired private IBulkExportJobDao myBulkExportJobDao; @Autowired private DaoRegistry myDaoRegistry; @Autowired private FhirContext myContext; @Autowired private SearchBuilderFactory mySearchBuilderFactory; @Autowired private EntityManager myEntityManager; private void loadResourcePids() { Optional<BulkExportJobEntity> jobOpt = myBulkExportJobDao.findByJobId(myJobUUID); if (!jobOpt.isPresent()) { ourLog.warn("Job appears to be deleted"); return; } BulkExportJobEntity jobEntity = jobOpt.get(); ourLog.info("Group Bulk export starting generation for batch export job: [{}] with resourceType [{}] and UUID [{}]", jobEntity, myResourceType, myJobUUID); //Fetch all the pids given the query. ISearchBuilder searchBuilder = getSearchBuilder(); //Build complex-ish _has query with a revincludes which allows lookup by group membership SearchParameterMap searchParameterMap = getSearchParameterMap(jobEntity); IResultIterator resultIterator = searchBuilder.createQuery( searchParameterMap, new SearchRuntimeDetails(null, myJobUUID), null, RequestPartitionId.allPartitions() ); List<ResourcePersistentId> myReadPids = new ArrayList<>(); while (resultIterator.hasNext()) { myReadPids.add(resultIterator.next()); } //Given that databases explode when you have an IN clause with >1000 resources, we use the QueryChunker to break this into multiple queries. List<ResourcePersistentId> revIncludePids = new ArrayList<>(); QueryChunker<ResourcePersistentId> chunker = new QueryChunker<>(); chunker.chunk(myReadPids, pidChunk -> { revIncludePids.addAll(searchBuilder.loadIncludes(myContext, myEntityManager, pidChunk, searchParameterMap.getRevIncludes(), true, searchParameterMap.getLastUpdated(), myJobUUID, null)); }); myPidIterator = revIncludePids.iterator(); } //For all group revinclude queries, you need to perform the search on the Patient DAO, which is why this is hardcoded here. private ISearchBuilder getSearchBuilder() { IFhirResourceDao<?> dao = myDaoRegistry.getResourceDao("Patient"); RuntimeResourceDefinition def = myContext.getResourceDefinition("Patient"); Class<? extends IBaseResource> nextTypeClass = def.getImplementingClass(); return mySearchBuilderFactory.newSearchBuilder(dao, "Patient", nextTypeClass); } @Nonnull private SearchParameterMap getSearchParameterMap(BulkExportJobEntity jobEntity) { SearchParameterMap searchParameterMap = new SearchParameterMap(); searchParameterMap.add("_has", new HasParam("Group", "member", "_id", myGroupId)); String revIncludeString = buildRevIncludeString(); searchParameterMap.addRevInclude(new Include(revIncludeString).toLocked()); if (jobEntity.getSince() != null) { searchParameterMap.setLastUpdated(new DateRangeParam(jobEntity.getSince(), null)); } searchParameterMap.setLoadSynchronous(true); return searchParameterMap; } /** * Given the resource type of the job, fetch its patient compartment name, formatted for usage in an Include. * e.g. Immunization -> Immunization:patient * * @return A string which can be dropped directly into an Include. */ private String buildRevIncludeString() { RuntimeResourceDefinition runtimeResourceDefinition = myContext.getResourceDefinition(myResourceType); List<RuntimeSearchParam> searchParams = runtimeResourceDefinition.getSearchParamsForCompartmentName("Patient"); if (searchParams == null || searchParams.size() == 0) { String errorMessage = String.format("Resource type [%s] is not eligible for Group Bulk export, as it contains no Patient compartment", myResourceType); throw new IllegalArgumentException(errorMessage); } else { //The reason we grab the first here is that even if there _are_ multiple search params, they end up pointing to the same patient compartment. //So we can safely just grab the first. RuntimeSearchParam runtimeSearchParam = searchParams.get(0); String includeString = runtimeResourceDefinition.getName() + ":" + runtimeSearchParam.getName(); return includeString; } } private String getGroupIdFromRequest(BulkExportJobEntity theJobEntity) { Map<String, String[]> requestUrl = UrlUtil.parseQueryStrings(theJobEntity.getRequest()); String[] groupId= requestUrl.get(JpaConstants.PARAM_EXPORT_GROUP_ID); if (groupId != null) { return Arrays.stream(groupId).collect(Collectors.joining(",")); } else { throw new IllegalStateException("You cannot run a Group export job without a " + JpaConstants.PARAM_EXPORT_GROUP_ID + " parameter as part of the request."); } } @Override public List<ResourcePersistentId> read() { if (myPidIterator == null) { loadResourcePids(); } int count = 0; List<ResourcePersistentId> outgoing = new ArrayList<>(); while (myPidIterator.hasNext() && count < myReadChunkSize) { outgoing.add(myPidIterator.next()); count += 1; } return outgoing.size() == 0 ? null : outgoing; } }
Fix multi search parameter issue
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/job/GroupBulkItemReader.java
Fix multi search parameter issue
<ide><path>api-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/bulk/job/GroupBulkItemReader.java <ide> */ <ide> private String buildRevIncludeString() { <ide> RuntimeResourceDefinition runtimeResourceDefinition = myContext.getResourceDefinition(myResourceType); <add> RuntimeSearchParam patientSearchParam = runtimeResourceDefinition.getSearchParam("patient"); <add> if (patientSearchParam == null) { <add> patientSearchParam = runtimeResourceDefinition.getSearchParam("subject"); <add> if (patientSearchParam == null) { <add> patientSearchParam = getRuntimeSearchParamByCompartment(runtimeResourceDefinition); <add> } <add> } <add> String includeString = runtimeResourceDefinition.getName() + ":" + patientSearchParam.getName(); <add> return includeString; <add> } <add> <add> /** <add> * Search the resource definition for a compartment named 'patient' and return its related Search Parameter. <add> */ <add> private RuntimeSearchParam getRuntimeSearchParamByCompartment(RuntimeResourceDefinition runtimeResourceDefinition) { <add> RuntimeSearchParam patientSearchParam; <ide> List<RuntimeSearchParam> searchParams = runtimeResourceDefinition.getSearchParamsForCompartmentName("Patient"); <ide> if (searchParams == null || searchParams.size() == 0) { <del> String errorMessage = String.format("Resource type [%s] is not eligible for Group Bulk export, as it contains no Patient compartment", myResourceType); <add> String errorMessage = String.format("Resource type [%s] is not eligible for Group Bulk export, as it contains no Patient compartment, and no `patient` or `subject` search parameter", myResourceType); <ide> throw new IllegalArgumentException(errorMessage); <add> } else if (searchParams.size() == 1) { <add> patientSearchParam = searchParams.get(0); <ide> } else { <del> //The reason we grab the first here is that even if there _are_ multiple search params, they end up pointing to the same patient compartment. <del> //So we can safely just grab the first. <del> RuntimeSearchParam runtimeSearchParam = searchParams.get(0); <del> String includeString = runtimeResourceDefinition.getName() + ":" + runtimeSearchParam.getName(); <del> return includeString; <del> <add> String errorMessage = String.format("Resource type [%s] is not eligible for Group Bulk export, as we are unable to disambiguate which patient search parameter we should be searching by.", myResourceType); <add> throw new IllegalArgumentException(errorMessage); <ide> } <del> } <del> <del> private String getGroupIdFromRequest(BulkExportJobEntity theJobEntity) { <del> Map<String, String[]> requestUrl = UrlUtil.parseQueryStrings(theJobEntity.getRequest()); <del> String[] groupId= requestUrl.get(JpaConstants.PARAM_EXPORT_GROUP_ID); <del> if (groupId != null) { <del> return Arrays.stream(groupId).collect(Collectors.joining(",")); <del> } else { <del> throw new IllegalStateException("You cannot run a Group export job without a " + JpaConstants.PARAM_EXPORT_GROUP_ID + " parameter as part of the request."); <del> } <add> return patientSearchParam; <ide> } <ide> <ide> @Override
Java
mit
a03bd2f13ed9d20f4c82ae1e73a4afa281fe2e9a
0
javache/react-native,javache/react-native,javache/react-native,facebook/react-native,facebook/react-native,javache/react-native,javache/react-native,facebook/react-native,facebook/react-native,janicduplessis/react-native,facebook/react-native,facebook/react-native,javache/react-native,javache/react-native,janicduplessis/react-native,janicduplessis/react-native,janicduplessis/react-native,facebook/react-native,janicduplessis/react-native,facebook/react-native,janicduplessis/react-native,javache/react-native,facebook/react-native,javache/react-native,janicduplessis/react-native,janicduplessis/react-native
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.devsupport; import android.content.Context; import android.widget.Toast; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.debug.holder.PrinterHolder; import com.facebook.debug.tags.ReactDebugOverlayTags; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JavaJSExecutor; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.SurfaceDelegateFactory; import com.facebook.react.common.futures.SimpleSettableFuture; import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener; import com.facebook.react.devsupport.interfaces.DevOptionHandler; import com.facebook.react.devsupport.interfaces.DevSplitBundleCallback; import com.facebook.react.packagerconnection.RequestHandler; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Interface for accessing and interacting with development features. Following features * are supported through this manager class: * 1) Displaying JS errors (aka RedBox) * 2) Displaying developers menu (Reload JS, Debug JS) * 3) Communication with developer server in order to download updated JS bundle * 4) Starting/stopping broadcast receiver for js reload signals * 5) Starting/stopping motion sensor listener that recognize shake gestures which in turn may * trigger developers menu. * 6) Launching developers settings view * * This class automatically monitors the state of registered views and activities to which they are * bound to make sure that we don't display overlay or that we we don't listen for sensor events * when app is backgrounded. * * {@link com.facebook.react.ReactInstanceManager} implementation is responsible for instantiating * this class as well as for populating with a reference to {@link CatalystInstance} whenever * instance manager recreates it (through {@link #onNewReactContextCreated). Also, instance manager * is responsible for enabling/disabling dev support in case when app is backgrounded or when all * the views has been detached from the instance (through {@link #setDevSupportEnabled} method). * * IMPORTANT: In order for developer support to work correctly it is required that the * manifest of your application contain the following entries: * {@code <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>} * {@code <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>} */ public final class BridgeDevSupportManager extends DevSupportManagerBase { private boolean mIsSamplingProfilerEnabled = false; public BridgeDevSupportManager( Context applicationContext, ReactInstanceDevHelper reactInstanceManagerHelper, @Nullable String packagerPathForJSBundleName, boolean enableOnCreate, @Nullable RedBoxHandler redBoxHandler, @Nullable DevBundleDownloadListener devBundleDownloadListener, int minNumShakes, @Nullable Map<String, RequestHandler> customPackagerCommandHandlers, @Nullable SurfaceDelegateFactory surfaceDelegateFactory) { super( applicationContext, reactInstanceManagerHelper, packagerPathForJSBundleName, enableOnCreate, redBoxHandler, devBundleDownloadListener, minNumShakes, customPackagerCommandHandlers, surfaceDelegateFactory); if (getDevSettings().isStartSamplingProfilerOnInit()) { // Only start the profiler. If its already running, there is an error if (!mIsSamplingProfilerEnabled) { toggleJSSamplingProfiler(); } else { Toast.makeText( applicationContext, "JS Sampling Profiler was already running, so did not start the sampling profiler", Toast.LENGTH_LONG) .show(); } } addCustomDevOption( mIsSamplingProfilerEnabled ? "Disable Sampling Profiler" : "Enable Sampling Profiler", new DevOptionHandler() { @Override public void onOptionSelected() { toggleJSSamplingProfiler(); } }); if (!getDevSettings().isDeviceDebugEnabled()) { // For remote debugging, we open up Chrome running the app in a web worker. // Note that this requires async communication, which will not work for Turbo Modules. addCustomDevOption( getDevSettings().isRemoteJSDebugEnabled() ? applicationContext.getString(com.facebook.react.R.string.catalyst_debug_stop) : applicationContext.getString(com.facebook.react.R.string.catalyst_debug), new DevOptionHandler() { @Override public void onOptionSelected() { getDevSettings().setRemoteJSDebugEnabled(!getDevSettings().isRemoteJSDebugEnabled()); handleReloadJS(); } }); } } @Override protected String getUniqueTag() { return "Bridge"; } @Override public void loadSplitBundleFromServer( final String bundlePath, final DevSplitBundleCallback callback) { fetchSplitBundleAndCreateBundleLoader( bundlePath, new CallbackWithBundleLoader() { @Override public void onSuccess(JSBundleLoader bundleLoader) { bundleLoader.loadScript(getCurrentContext().getCatalystInstance()); getCurrentContext() .getJSModule(HMRClient.class) .registerBundle(getDevServerHelper().getDevServerSplitBundleURL(bundlePath)); callback.onSuccess(); } @Override public void onError(String url, Throwable cause) { callback.onError(url, cause); } }); } private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( final SimpleSettableFuture<Boolean> future) { return new WebsocketJavaScriptExecutor.JSExecutorConnectCallback() { @Override public void onSuccess() { future.set(true); hideDevLoadingView(); } @Override public void onFailure(final Throwable cause) { hideDevLoadingView(); FLog.e(ReactConstants.TAG, "Failed to connect to debugger!", cause); future.setException( new IOException( getApplicationContext().getString(com.facebook.react.R.string.catalyst_debug_error), cause)); } }; } private void reloadJSInProxyMode() { // When using js proxy, there is no need to fetch JS bundle as proxy executor will do that // anyway getDevServerHelper().launchJSDevtools(); JavaJSExecutor.Factory factory = new JavaJSExecutor.Factory() { @Override public JavaJSExecutor create() throws Exception { WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor(); SimpleSettableFuture<Boolean> future = new SimpleSettableFuture<>(); executor.connect( getDevServerHelper().getWebsocketProxyURL(), getExecutorConnectCallback(future)); // TODO(t9349129) Don't use timeout try { future.get(90, TimeUnit.SECONDS); return executor; } catch (ExecutionException e) { throw (Exception) e.getCause(); } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } } }; getReactInstanceDevHelper().onReloadWithJSDebugger(factory); } @Override public void handleReloadJS() { UiThreadUtil.assertOnUiThread(); ReactMarker.logMarker( ReactMarkerConstants.RELOAD, getDevSettings().getPackagerConnectionSettings().getDebugServerHost()); // dismiss redbox if exists hideRedboxDialog(); if (getDevSettings().isRemoteJSDebugEnabled()) { PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Proxy"); showDevLoadingViewForRemoteJSEnabled(); reloadJSInProxyMode(); } else { PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server"); String bundleURL = getDevServerHelper() .getDevServerBundleURL(Assertions.assertNotNull(getJSAppBundleName())); reloadJSFromServer(bundleURL); } } /** Starts of stops the sampling profiler */ private void toggleJSSamplingProfiler() { JavaScriptExecutorFactory javaScriptExecutorFactory = getReactInstanceDevHelper().getJavaScriptExecutorFactory(); if (!mIsSamplingProfilerEnabled) { try { javaScriptExecutorFactory.startSamplingProfiler(); Toast.makeText(getApplicationContext(), "Starting Sampling Profiler", Toast.LENGTH_SHORT) .show(); } catch (UnsupportedOperationException e) { Toast.makeText( getApplicationContext(), javaScriptExecutorFactory.toString() + " does not support Sampling Profiler", Toast.LENGTH_LONG) .show(); } finally { mIsSamplingProfilerEnabled = true; } } else { try { final String outputPath = File.createTempFile( "sampling-profiler-trace", ".cpuprofile", getApplicationContext().getCacheDir()) .getPath(); javaScriptExecutorFactory.stopSamplingProfiler(outputPath); Toast.makeText( getApplicationContext(), "Saved results from Profiler to " + outputPath, Toast.LENGTH_LONG) .show(); } catch (IOException e) { FLog.e( ReactConstants.TAG, "Could not create temporary file for saving results from Sampling Profiler"); } catch (UnsupportedOperationException e) { Toast.makeText( getApplicationContext(), javaScriptExecutorFactory.toString() + "does not support Sampling Profiler", Toast.LENGTH_LONG) .show(); } finally { mIsSamplingProfilerEnabled = false; } } } }
ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.devsupport; import android.content.Context; import android.widget.Toast; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.debug.holder.PrinterHolder; import com.facebook.debug.tags.ReactDebugOverlayTags; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JavaJSExecutor; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.SurfaceDelegateFactory; import com.facebook.react.common.futures.SimpleSettableFuture; import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener; import com.facebook.react.devsupport.interfaces.DevOptionHandler; import com.facebook.react.devsupport.interfaces.DevSplitBundleCallback; import com.facebook.react.packagerconnection.RequestHandler; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Interface for accessing and interacting with development features. Following features * are supported through this manager class: * 1) Displaying JS errors (aka RedBox) * 2) Displaying developers menu (Reload JS, Debug JS) * 3) Communication with developer server in order to download updated JS bundle * 4) Starting/stopping broadcast receiver for js reload signals * 5) Starting/stopping motion sensor listener that recognize shake gestures which in turn may * trigger developers menu. * 6) Launching developers settings view * * This class automatically monitors the state of registered views and activities to which they are * bound to make sure that we don't display overlay or that we we don't listen for sensor events * when app is backgrounded. * * {@link com.facebook.react.ReactInstanceManager} implementation is responsible for instantiating * this class as well as for populating with a reference to {@link CatalystInstance} whenever * instance manager recreates it (through {@link #onNewReactContextCreated). Also, instance manager * is responsible for enabling/disabling dev support in case when app is backgrounded or when all * the views has been detached from the instance (through {@link #setDevSupportEnabled} method). * * IMPORTANT: In order for developer support to work correctly it is required that the * manifest of your application contain the following entries: * {@code <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>} * {@code <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>} */ public final class BridgeDevSupportManager extends DevSupportManagerBase { private boolean mIsSamplingProfilerEnabled = false; public BridgeDevSupportManager( Context applicationContext, ReactInstanceDevHelper reactInstanceManagerHelper, @Nullable String packagerPathForJSBundleName, boolean enableOnCreate, @Nullable RedBoxHandler redBoxHandler, @Nullable DevBundleDownloadListener devBundleDownloadListener, int minNumShakes, @Nullable Map<String, RequestHandler> customPackagerCommandHandlers, @Nullable SurfaceDelegateFactory surfaceDelegateFactory) { super( applicationContext, reactInstanceManagerHelper, packagerPathForJSBundleName, enableOnCreate, redBoxHandler, devBundleDownloadListener, minNumShakes, customPackagerCommandHandlers, surfaceDelegateFactory); if (getDevSettings().isStartSamplingProfilerOnInit()) { // Only start the profiler. If its already running, there is an error if (!mIsSamplingProfilerEnabled) { toggleJSSamplingProfiler(); } else { Toast.makeText( applicationContext, "JS Sampling Profiler was already running, so did not start the sampling profiler", Toast.LENGTH_LONG) .show(); } } addCustomDevOption( mIsSamplingProfilerEnabled ? applicationContext.getString( com.facebook.react.R.string.catalyst_sample_profiler_disable) : applicationContext.getString( com.facebook.react.R.string.catalyst_sample_profiler_enable), new DevOptionHandler() { @Override public void onOptionSelected() { toggleJSSamplingProfiler(); } }); if (!getDevSettings().isDeviceDebugEnabled()) { // For remote debugging, we open up Chrome running the app in a web worker. // Note that this requires async communication, which will not work for Turbo Modules. addCustomDevOption( getDevSettings().isRemoteJSDebugEnabled() ? applicationContext.getString(com.facebook.react.R.string.catalyst_debug_stop) : applicationContext.getString(com.facebook.react.R.string.catalyst_debug), new DevOptionHandler() { @Override public void onOptionSelected() { getDevSettings().setRemoteJSDebugEnabled(!getDevSettings().isRemoteJSDebugEnabled()); handleReloadJS(); } }); } } @Override protected String getUniqueTag() { return "Bridge"; } @Override public void loadSplitBundleFromServer( final String bundlePath, final DevSplitBundleCallback callback) { fetchSplitBundleAndCreateBundleLoader( bundlePath, new CallbackWithBundleLoader() { @Override public void onSuccess(JSBundleLoader bundleLoader) { bundleLoader.loadScript(getCurrentContext().getCatalystInstance()); getCurrentContext() .getJSModule(HMRClient.class) .registerBundle(getDevServerHelper().getDevServerSplitBundleURL(bundlePath)); callback.onSuccess(); } @Override public void onError(String url, Throwable cause) { callback.onError(url, cause); } }); } private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( final SimpleSettableFuture<Boolean> future) { return new WebsocketJavaScriptExecutor.JSExecutorConnectCallback() { @Override public void onSuccess() { future.set(true); hideDevLoadingView(); } @Override public void onFailure(final Throwable cause) { hideDevLoadingView(); FLog.e(ReactConstants.TAG, "Failed to connect to debugger!", cause); future.setException( new IOException( getApplicationContext().getString(com.facebook.react.R.string.catalyst_debug_error), cause)); } }; } private void reloadJSInProxyMode() { // When using js proxy, there is no need to fetch JS bundle as proxy executor will do that // anyway getDevServerHelper().launchJSDevtools(); JavaJSExecutor.Factory factory = new JavaJSExecutor.Factory() { @Override public JavaJSExecutor create() throws Exception { WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor(); SimpleSettableFuture<Boolean> future = new SimpleSettableFuture<>(); executor.connect( getDevServerHelper().getWebsocketProxyURL(), getExecutorConnectCallback(future)); // TODO(t9349129) Don't use timeout try { future.get(90, TimeUnit.SECONDS); return executor; } catch (ExecutionException e) { throw (Exception) e.getCause(); } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } } }; getReactInstanceDevHelper().onReloadWithJSDebugger(factory); } @Override public void handleReloadJS() { UiThreadUtil.assertOnUiThread(); ReactMarker.logMarker( ReactMarkerConstants.RELOAD, getDevSettings().getPackagerConnectionSettings().getDebugServerHost()); // dismiss redbox if exists hideRedboxDialog(); if (getDevSettings().isRemoteJSDebugEnabled()) { PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Proxy"); showDevLoadingViewForRemoteJSEnabled(); reloadJSInProxyMode(); } else { PrinterHolder.getPrinter() .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server"); String bundleURL = getDevServerHelper() .getDevServerBundleURL(Assertions.assertNotNull(getJSAppBundleName())); reloadJSFromServer(bundleURL); } } /** Starts of stops the sampling profiler */ private void toggleJSSamplingProfiler() { JavaScriptExecutorFactory javaScriptExecutorFactory = getReactInstanceDevHelper().getJavaScriptExecutorFactory(); if (!mIsSamplingProfilerEnabled) { try { javaScriptExecutorFactory.startSamplingProfiler(); Toast.makeText(getApplicationContext(), "Starting Sampling Profiler", Toast.LENGTH_SHORT) .show(); } catch (UnsupportedOperationException e) { Toast.makeText( getApplicationContext(), javaScriptExecutorFactory.toString() + " does not support Sampling Profiler", Toast.LENGTH_LONG) .show(); } finally { mIsSamplingProfilerEnabled = true; } } else { try { final String outputPath = File.createTempFile( "sampling-profiler-trace", ".cpuprofile", getApplicationContext().getCacheDir()) .getPath(); javaScriptExecutorFactory.stopSamplingProfiler(outputPath); Toast.makeText( getApplicationContext(), "Saved results from Profiler to " + outputPath, Toast.LENGTH_LONG) .show(); } catch (IOException e) { FLog.e( ReactConstants.TAG, "Could not create temporary file for saving results from Sampling Profiler"); } catch (UnsupportedOperationException e) { Toast.makeText( getApplicationContext(), javaScriptExecutorFactory.toString() + "does not support Sampling Profiler", Toast.LENGTH_LONG) .show(); } finally { mIsSamplingProfilerEnabled = false; } } } }
A quick fix for inital fb4a_debug launch crashes due to fetching string `com.facebook.react.R.string.catalyst_sample_profiler_enable` Summary: Changelog: [Android][Internal] - a quick fix for inital fb4a_debug launch crashes due to fetching string `com.facebook.react.R.string.catalyst_sample_profiler_enable` Reviewed By: paveldudka Differential Revision: D33410712 fbshipit-source-id: f63e4b7e9aba3e79d4aa11983d68fee7341972bb
ReactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java
A quick fix for inital fb4a_debug launch crashes due to fetching string `com.facebook.react.R.string.catalyst_sample_profiler_enable`
<ide><path>eactAndroid/src/main/java/com/facebook/react/devsupport/BridgeDevSupportManager.java <ide> } <ide> <ide> addCustomDevOption( <del> mIsSamplingProfilerEnabled <del> ? applicationContext.getString( <del> com.facebook.react.R.string.catalyst_sample_profiler_disable) <del> : applicationContext.getString( <del> com.facebook.react.R.string.catalyst_sample_profiler_enable), <add> mIsSamplingProfilerEnabled ? "Disable Sampling Profiler" : "Enable Sampling Profiler", <ide> new DevOptionHandler() { <ide> @Override <ide> public void onOptionSelected() {
Java
apache-2.0
error: pathspec 'source/pygmy-app/src/com/dev/pygmy/EntityView.java' did not match any file(s) known to git
e660d3e0c64f9b81789cb3922d1f53693ffb705d
1
elyas-bhy/pygmy,elyas-bhy/pygmy,elyas-bhy/pygmy
package com.dev.pygmy; import android.content.Context; import android.graphics.Canvas; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class EntityView extends View { private String TAG="EntityView"; private Entity[] entities; // array that holds the entities private int entityID = 0; // variable to know what entity is being dragged private boolean initial = true; public EntityView(Context context) { super(context); Log.d(TAG, "Constructor"); setFocusable(true); //necessary for getting the touch events int numberOfEntities = 3; entities = new Entity[numberOfEntities]; // declare each entity with the Entity class createGameEntities(context, entities); } private void createGameEntities(Context context, Entity [] entities) { entities[0] = new Entity(context,R.drawable.black_bishop); entities[1] = new Entity(context,R.drawable.black_king); entities[2] = new Entity(context,R.drawable.black_pawn); } // the method that draws the entities @Override protected void onDraw(Canvas canvas) { //canvas.drawColor(0xFFCCCCCC); //if you want another background color // setting the start point for the entities if (initial) { initial = false; // FIXME: fix this bad hack int [][] coordXY = GameBoardView.getRectCoord(); for (int index=0; index<entities.length; index++) { entities[index].setX(coordXY[index+1][0]); entities[index].setY(coordXY[index+1][1]); } } //draw the entity on the canvas for (Entity ent : entities) { canvas.drawBitmap(ent.getBitmap(), ent.getX(), ent.getY(), null); } } // events when touching the screen public boolean onTouchEvent(MotionEvent event) { int eventaction = event.getAction(); int X = (int)event.getX(); int Y = (int)event.getY(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on an entity entityID = 0; for (Entity ent : entities) { // check all the bounds of the entity if (X > ent.getX() && X < ent.getX()+50 && Y > ent.getY() && Y < ent.getY()+50){ entityID = ent.getID(); break; } } break; case MotionEvent.ACTION_MOVE: // touch drag with the entity // move the entities the same as the finger if (entityID > 0) { entities[entityID-1].setX(X-25); entities[entityID-1].setY(Y-25); } break; case MotionEvent.ACTION_UP: break; } // redraw the canvas invalidate(); return true; } }
source/pygmy-app/src/com/dev/pygmy/EntityView.java
EntityView class represents the canvas containing game pieces
source/pygmy-app/src/com/dev/pygmy/EntityView.java
EntityView class represents the canvas containing game pieces
<ide><path>ource/pygmy-app/src/com/dev/pygmy/EntityView.java <add>package com.dev.pygmy; <add> <add>import android.content.Context; <add>import android.graphics.Canvas; <add>import android.util.Log; <add>import android.view.MotionEvent; <add>import android.view.View; <add> <add>public class EntityView extends View { <add> private String TAG="EntityView"; <add> private Entity[] entities; // array that holds the entities <add> private int entityID = 0; // variable to know what entity is being dragged <add> private boolean initial = true; <add> <add> public EntityView(Context context) { <add> super(context); <add> Log.d(TAG, "Constructor"); <add> setFocusable(true); //necessary for getting the touch events <add> <add> int numberOfEntities = 3; <add> entities = new Entity[numberOfEntities]; <add> <add> // declare each entity with the Entity class <add> createGameEntities(context, entities); <add> } <add> <add> private void createGameEntities(Context context, Entity [] entities) { <add> entities[0] = new Entity(context,R.drawable.black_bishop); <add> entities[1] = new Entity(context,R.drawable.black_king); <add> entities[2] = new Entity(context,R.drawable.black_pawn); <add> } <add> <add> // the method that draws the entities <add> @Override <add> protected void onDraw(Canvas canvas) { <add> //canvas.drawColor(0xFFCCCCCC); //if you want another background color <add> <add> // setting the start point for the entities <add> if (initial) { <add> initial = false; <add> // FIXME: fix this bad hack <add> int [][] coordXY = GameBoardView.getRectCoord(); <add> <add> for (int index=0; index<entities.length; index++) { <add> entities[index].setX(coordXY[index+1][0]); <add> entities[index].setY(coordXY[index+1][1]); <add> } <add> } <add> <add> //draw the entity on the canvas <add> for (Entity ent : entities) { <add> canvas.drawBitmap(ent.getBitmap(), ent.getX(), ent.getY(), null); <add> } <add> } <add> <add> // events when touching the screen <add> public boolean onTouchEvent(MotionEvent event) { <add> int eventaction = event.getAction(); <add> <add> int X = (int)event.getX(); <add> int Y = (int)event.getY(); <add> <add> switch (eventaction) { <add> <add> case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on an entity <add> entityID = 0; <add> for (Entity ent : entities) { <add> // check all the bounds of the entity <add> if (X > ent.getX() && X < ent.getX()+50 && Y > ent.getY() && Y < ent.getY()+50){ <add> entityID = ent.getID(); <add> break; <add> } <add> } <add> break; <add> <add> <add> case MotionEvent.ACTION_MOVE: // touch drag with the entity <add> // move the entities the same as the finger <add> if (entityID > 0) { <add> entities[entityID-1].setX(X-25); <add> entities[entityID-1].setY(Y-25); <add> } <add> <add> break; <add> <add> case MotionEvent.ACTION_UP: <add> break; <add> } <add> // redraw the canvas <add> invalidate(); <add> return true; <add> <add> } <add>}
Java
apache-2.0
f7be08640721c9a26a1b7f01ef0a8b62702aa068
0
cscorley/solr-only-mirror,cscorley/solr-only-mirror,cscorley/solr-only-mirror
package org.apache.solr.cloud; /* * 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.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import javax.xml.parsers.ParserConfigurationException; import org.apache.lucene.util.LuceneTestCase.Slow; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.cloud.CloudState; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.handler.component.HttpShardHandlerFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.data.Stat; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; @Slow public class OverseerTest extends SolrTestCaseJ4 { static final int TIMEOUT = 10000; private static final boolean DEBUG = false; public static class MockZKController{ private final SolrZkClient zkClient; private final ZkStateReader zkStateReader; private final String nodeName; private final String collection; private final LeaderElector elector; private final Map<String, ElectionContext> electionContext = Collections.synchronizedMap(new HashMap<String, ElectionContext>()); public MockZKController(String zkAddress, String nodeName, String collection) throws InterruptedException, TimeoutException, IOException, KeeperException { this.nodeName = nodeName; this.collection = collection; zkClient = new SolrZkClient(zkAddress, TIMEOUT); zkStateReader = new ZkStateReader(zkClient); zkStateReader.createClusterStateWatchersAndUpdate(); // live node final String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName; zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true); elector = new LeaderElector(zkClient); } private void deleteNode(final String path) { try { Stat stat = zkClient.exists(path, null, false); if (stat != null) { zkClient.delete(path, stat.getVersion(), false); } } catch (KeeperException e) { fail("Unexpected KeeperException!" + e); } catch (InterruptedException e) { fail("Unexpected InterruptedException!" + e); } } public void close(){ try { deleteNode(ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName); zkClient.close(); } catch (InterruptedException e) { //e.printStackTrace(); } } public void publishState(String coreName, String stateName, int numShards) throws KeeperException, InterruptedException, IOException { if (stateName == null) { ElectionContext ec = electionContext.remove(coreName); if (ec != null) { ec.cancelElection(); } ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "deletecore", ZkStateReader.NODE_NAME_PROP, nodeName, ZkStateReader.CORE_NAME_PROP, coreName, ZkStateReader.COLLECTION_PROP, collection); DistributedQueue q = Overseer.getInQueue(zkClient); q.offer(ZkStateReader.toJSON(m)); } else { ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.STATE_PROP, stateName, ZkStateReader.NODE_NAME_PROP, nodeName, ZkStateReader.CORE_NAME_PROP, coreName, ZkStateReader.COLLECTION_PROP, collection, ZkStateReader.NUM_SHARDS_PROP, Integer.toString(numShards), ZkStateReader.BASE_URL_PROP, "http://" + nodeName + "/solr/"); DistributedQueue q = Overseer.getInQueue(zkClient); q.offer(ZkStateReader.toJSON(m)); } for (int i = 0; i < 30; i++) { String shardId = getShardId(coreName); if (shardId != null) { try { zkClient.makePath("/collections/" + collection + "/leader_elect/" + shardId + "/election", true); } catch (NodeExistsException nee) {} ZkNodeProps props = new ZkNodeProps(ZkStateReader.BASE_URL_PROP, "http://" + nodeName + "/solr/", ZkStateReader.NODE_NAME_PROP, nodeName, ZkStateReader.CORE_NAME_PROP, coreName, ZkStateReader.SHARD_ID_PROP, shardId, ZkStateReader.COLLECTION_PROP, collection); ShardLeaderElectionContextBase ctx = new ShardLeaderElectionContextBase( elector, shardId, collection, nodeName + "_" + coreName, props, zkStateReader); elector.joinElection(ctx); break; } Thread.sleep(200); } } private String getShardId(final String coreName) { Map<String,Slice> slices = zkStateReader.getCloudState().getSlices( collection); if (slices != null) { for (Slice slice : slices.values()) { if (slice.getShards().containsKey(nodeName + "_" + coreName)) { return slice.getName(); } } } return null; } } @BeforeClass public static void beforeClass() throws Exception { System.setProperty("solrcloud.skip.autorecovery", "true"); initCore(); } @AfterClass public static void afterClass() throws Exception { System.clearProperty("solrcloud.skip.autorecovery"); initCore(); } @Test public void testShardAssignment() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); ZkController zkController = null; SolrZkClient zkClient = null; try { server.run(); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); zkClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); ZkStateReader reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); zkController = new ZkController(null, server.getZkAddress(), TIMEOUT, 10000, "localhost", "8983", "solr", new CurrentCoreDescriptorProvider() { @Override public List<CoreDescriptor> getCurrentDescriptors() { // do nothing return null; } }); System.setProperty("bootstrap_confdir", getFile("solr/collection1/conf") .getAbsolutePath()); final int numShards=6; final String[] ids = new String[numShards]; for (int i = 0; i < numShards; i++) { CloudDescriptor collection1Desc = new CloudDescriptor(); collection1Desc.setNumShards(3); collection1Desc.setCollectionName("collection1"); CoreDescriptor desc1 = new CoreDescriptor(null, "core" + (i + 1), ""); desc1.setCloudDescriptor(collection1Desc); zkController.preRegister(desc1); ids[i] = zkController.register("core" + (i + 1), desc1); } assertEquals("shard1", ids[0]); assertEquals("shard2", ids[1]); assertEquals("shard3", ids[2]); assertEquals("shard1", ids[3]); assertEquals("shard2", ids[4]); assertEquals("shard3", ids[5]); waitForCollections(reader, "collection1"); //make sure leaders are in cloud state assertNotNull(reader.getLeaderUrl("collection1", "shard1", 15000)); assertNotNull(reader.getLeaderUrl("collection1", "shard2", 15000)); assertNotNull(reader.getLeaderUrl("collection1", "shard3", 15000)); } finally { System.clearProperty("bootstrap_confdir"); if (DEBUG) { if (zkController != null) { zkClient.printLayoutToStdOut(); } } close(zkClient); if (zkController != null) { zkController.close(); } server.shutdown(); } } @Test public void testShardAssignmentBigger() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; final int nodeCount = random().nextInt(50)+50; //how many simulated nodes (num of threads) final int coreCount = random().nextInt(100)+100; //how many cores to register final int sliceCount = random().nextInt(20)+1; //how many slices ZkTestServer server = new ZkTestServer(zkDir); System.setProperty(ZkStateReader.NUM_SHARDS_PROP, Integer.toString(sliceCount)); SolrZkClient zkClient = null; ZkStateReader reader = null; final ZkController[] controllers = new ZkController[nodeCount]; final ExecutorService[] nodeExecutors = new ExecutorService[nodeCount]; try { server.run(); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); zkClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); for (int i = 0; i < nodeCount; i++) { controllers[i] = new ZkController(null, server.getZkAddress(), TIMEOUT, 10000, "localhost", "898" + i, "solr", new CurrentCoreDescriptorProvider() { @Override public List<CoreDescriptor> getCurrentDescriptors() { // do nothing return null; } }); } System.setProperty("bootstrap_confdir", getFile("solr/collection1/conf") .getAbsolutePath()); for (int i = 0; i < nodeCount; i++) { nodeExecutors[i] = Executors.newFixedThreadPool(1); } final String[] ids = new String[coreCount]; //register total of coreCount cores for (int i = 0; i < coreCount; i++) { final int slot = i; Runnable coreStarter = new Runnable() { @Override public void run() { final CloudDescriptor collection1Desc = new CloudDescriptor(); collection1Desc.setCollectionName("collection1"); collection1Desc.setNumShards(sliceCount); final String coreName = "core" + slot; final CoreDescriptor desc = new CoreDescriptor(null, coreName, ""); desc.setCloudDescriptor(collection1Desc); try { controllers[slot % nodeCount].preRegister(desc); ids[slot] = controllers[slot % nodeCount] .register(coreName, desc); } catch (Throwable e) { e.printStackTrace(); fail("register threw exception:" + e.getClass()); } } }; nodeExecutors[i % nodeCount].submit(coreStarter); } for (int i = 0; i < nodeCount; i++) { nodeExecutors[i].shutdown(); } for (int i = 0; i < nodeCount; i++) { while (!nodeExecutors[i].awaitTermination(100, TimeUnit.MILLISECONDS)); } // make sure all cores have been assigned a id in cloudstate for (int i = 0; i < 40; i++) { reader.updateCloudState(true); CloudState state = reader.getCloudState(); Map<String,Slice> slices = state.getSlices("collection1"); int count = 0; for (String name : slices.keySet()) { count += slices.get(name).getShards().size(); } if (coreCount == count) break; Thread.sleep(200); } // make sure all cores have been returned a id for (int i = 0; i < 90; i++) { int assignedCount = 0; for (int j = 0; j < coreCount; j++) { if (ids[j] != null) { assignedCount++; } } if (coreCount == assignedCount) { break; } Thread.sleep(500); } final HashMap<String, AtomicInteger> counters = new HashMap<String,AtomicInteger>(); for (int i = 1; i < sliceCount+1; i++) { counters.put("shard" + i, new AtomicInteger()); } for (int i = 0; i < coreCount; i++) { final AtomicInteger ai = counters.get(ids[i]); assertNotNull("could not find counter for shard:" + ids[i], ai); ai.incrementAndGet(); } for (String counter: counters.keySet()) { int count = counters.get(counter).intValue(); int expectedCount = coreCount / sliceCount; int min = expectedCount - 1; int max = expectedCount + 1; if (count < min || count > max) { fail("Unevenly assigned shard ids, " + counter + " had " + count + ", expected: " + min + "-" + max); } } //make sure leaders are in cloud state for (int i = 0; i < sliceCount; i++) { assertNotNull(reader.getLeaderUrl("collection1", "shard" + (i + 1)), 15000); } } finally { System.clearProperty(ZkStateReader.NUM_SHARDS_PROP); System.clearProperty("bootstrap_confdir"); if (DEBUG) { if (controllers[0] != null) { zkClient.printLayoutToStdOut(); } } close(zkClient); close(reader); for (int i = 0; i < controllers.length; i++) if (controllers[i] != null) { controllers[i].close(); } server.shutdown(); for (int i = 0; i < nodeCount; i++) { if (nodeExecutors[i] != null) { nodeExecutors[i].shutdownNow(); } } } } //wait until collections are available private void waitForCollections(ZkStateReader stateReader, String... collections) throws InterruptedException, KeeperException { int maxIterations = 100; while (0 < maxIterations--) { stateReader.updateCloudState(true); final CloudState state = stateReader.getCloudState(); Set<String> availableCollections = state.getCollections(); int availableCount = 0; for(String requiredCollection: collections) { if(availableCollections.contains(requiredCollection)) { availableCount++; } if(availableCount == collections.length) return; Thread.sleep(50); } } log.warn("Timeout waiting for collections: " + Arrays.asList(collections) + " state:" + stateReader.getCloudState()); } @Test public void testStateChange() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient zkClient = null; ZkStateReader reader = null; SolrZkClient overseerClient = null; try { server.run(); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient.makePath("/live_nodes", true); reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); overseerClient = electNewOverseer(server.getZkAddress()); DistributedQueue q = Overseer.getInQueue(zkClient); ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core1", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); q.offer(ZkStateReader.toJSON(m)); waitForCollections(reader, "collection1"); assertEquals(reader.getCloudState().toString(), ZkStateReader.RECOVERING, reader.getCloudState().getSlice("collection1", "shard1").getShards() .get("node1_core1").get(ZkStateReader.STATE_PROP)); //publish node state (active) m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core1", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.ACTIVE); q.offer(ZkStateReader.toJSON(m)); verifyStatus(reader, ZkStateReader.ACTIVE); } finally { close(zkClient); close(overseerClient); close(reader); server.shutdown(); } } private void verifyStatus(ZkStateReader reader, String expectedState) throws InterruptedException { int maxIterations = 100; String coreState = null; while(maxIterations-->0) { Slice slice = reader.getCloudState().getSlice("collection1", "shard1"); if(slice!=null) { coreState = slice.getShards().get("node1_core1").get(ZkStateReader.STATE_PROP); if(coreState.equals(expectedState)) { return; } } Thread.sleep(50); } fail("Illegal state, was:" + coreState + " expected:" + expectedState + "cloudState:" + reader.getCloudState()); } private void verifyShardLeader(ZkStateReader reader, String collection, String shard, String expectedCore) throws InterruptedException, KeeperException { int maxIterations = 100; while(maxIterations-->0) { reader.updateCloudState(true); // poll state ZkNodeProps props = reader.getCloudState().getLeader(collection, shard); if(props!=null) { if(expectedCore.equals(props.get(ZkStateReader.CORE_NAME_PROP))) { return; } } Thread.sleep(100); } assertEquals("Unexpected shard leader coll:" + collection + " shard:" + shard, expectedCore, (reader.getCloudState().getLeader(collection, shard)!=null)?reader.getCloudState().getLeader(collection, shard).get(ZkStateReader.CORE_NAME_PROP):null); } @Test public void testOverseerFailure() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; MockZKController mockController = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(controllerClient); reader.createClusterStateWatchersAndUpdate(); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); overseerClient = electNewOverseer(server.getZkAddress()); Thread.sleep(1000); mockController.publishState("core1", ZkStateReader.RECOVERING, 1); waitForCollections(reader, "collection1"); verifyStatus(reader, ZkStateReader.RECOVERING); int version = getCloudStateVersion(controllerClient); mockController.publishState("core1", ZkStateReader.ACTIVE, 1); while(version == getCloudStateVersion(controllerClient)); verifyStatus(reader, ZkStateReader.ACTIVE); version = getCloudStateVersion(controllerClient); overseerClient.close(); Thread.sleep(1000); //wait for overseer to get killed mockController.publishState("core1", ZkStateReader.RECOVERING, 1); version = getCloudStateVersion(controllerClient); overseerClient = electNewOverseer(server.getZkAddress()); while(version == getCloudStateVersion(controllerClient)); verifyStatus(reader, ZkStateReader.RECOVERING); assertEquals("Live nodes count does not match", 1, reader.getCloudState() .getLiveNodes().size()); assertEquals("Shard count does not match", 1, reader.getCloudState() .getSlice("collection1", "shard1").getShards().size()); version = getCloudStateVersion(controllerClient); mockController.publishState("core1", null,1); while(version == getCloudStateVersion(controllerClient)); Thread.sleep(500); assertFalse("collection1 should be gone after publishing the null state", reader.getCloudState().getCollections().contains("collection1")); } finally { close(mockController); close(overseerClient); close(controllerClient); close(reader); server.shutdown(); } } private AtomicInteger killCounter = new AtomicInteger(); private class OverseerRestarter implements Runnable{ SolrZkClient overseerClient = null; public volatile boolean run = true; private final String zkAddress; public OverseerRestarter(String zkAddress) { this.zkAddress = zkAddress; } @Override public void run() { try { overseerClient = electNewOverseer(zkAddress); Random rnd = random(); while (run) { if (killCounter.get()>0) { try { killCounter.decrementAndGet(); log.info("Killing overseer."); overseerClient.close(); overseerClient = electNewOverseer(zkAddress); } catch (Throwable e) { // e.printStackTrace(); } } try { Thread.sleep(100); } catch (Throwable e) { // e.printStackTrace(); } } } catch (Throwable t) { // ignore } finally { if (overseerClient != null) { try { overseerClient.close(); } catch (Throwable t) { // ignore } } } } } @Test public void testShardLeaderChange() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; final ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; ZkStateReader reader = null; MockZKController mockController = null; MockZKController mockController2 = null; OverseerRestarter killer = null; Thread killerThread = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); killer = new OverseerRestarter(server.getZkAddress()); killerThread = new Thread(killer); killerThread.start(); reader = new ZkStateReader(controllerClient); //no watches, we'll poll for (int i = 0; i < atLeast(4); i++) { killCounter.incrementAndGet(); //for each round allow 1 kill mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); mockController.publishState("core1", "state1",1); if(mockController2!=null) { mockController2.close(); mockController2 = null; } mockController.publishState("core1", "state2",1); mockController2 = new MockZKController(server.getZkAddress(), "node2", "collection1"); mockController.publishState("core1", "state1",1); verifyShardLeader(reader, "collection1", "shard1", "core1"); mockController2.publishState("core4", "state2" ,1); mockController.close(); mockController = null; verifyShardLeader(reader, "collection1", "shard1", "core4"); } } finally { if (killer != null) { killer.run = false; if (killerThread != null) { killerThread.join(); } } close(mockController); close(mockController2); close(controllerClient); close(reader); server.shutdown(); } } @Test public void testDoubleAssignment() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; MockZKController mockController = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(controllerClient); reader.createClusterStateWatchersAndUpdate(); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); overseerClient = electNewOverseer(server.getZkAddress()); mockController.publishState("core1", ZkStateReader.RECOVERING, 1); waitForCollections(reader, "collection1"); verifyStatus(reader, ZkStateReader.RECOVERING); mockController.close(); int version = getCloudStateVersion(controllerClient); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); mockController.publishState("core1", ZkStateReader.RECOVERING, 1); while (version == getCloudStateVersion(controllerClient)); reader.updateCloudState(true); CloudState state = reader.getCloudState(); int numFound = 0; for (Map<String,Slice> collection : state.getCollectionStates().values()) { for (Slice slice : collection.values()) { if (slice.getShards().get("node1_core1") != null) { numFound++; } } } assertEquals("Shard was found in more than 1 times in CloudState", 1, numFound); } finally { close(overseerClient); close(mockController); close(controllerClient); close(reader); server.shutdown(); } } @Test public void testPlaceholders() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; MockZKController mockController = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(controllerClient); reader.createClusterStateWatchersAndUpdate(); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); overseerClient = electNewOverseer(server.getZkAddress()); mockController.publishState("core1", ZkStateReader.RECOVERING, 12); waitForCollections(reader, "collection1"); assertEquals("Slicecount does not match", 12, reader.getCloudState().getSlices("collection1").size()); } finally { close(overseerClient); close(mockController); close(controllerClient); close(reader); server.shutdown(); } } private void close(MockZKController mockController) { if (mockController != null) { mockController.close(); } } @Test public void testReplay() throws Exception{ String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient zkClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; try { server.run(); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); //prepopulate work queue with some items to emulate previous overseer died before persisting state DistributedQueue queue = Overseer.getInternalQueue(zkClient); ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.SHARD_ID_PROP, "s1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core1", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); queue.offer(ZkStateReader.toJSON(m)); m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.SHARD_ID_PROP, "s1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core2", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); queue.offer(ZkStateReader.toJSON(m)); overseerClient = electNewOverseer(server.getZkAddress()); //submit to proper queue queue = Overseer.getInQueue(zkClient); m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.SHARD_ID_PROP, "s1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core3", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); queue.offer(ZkStateReader.toJSON(m)); for(int i=0;i<100;i++) { Slice s = reader.getCloudState().getSlice("collection1", "s1"); if(s!=null && s.getShards().size()==3) break; Thread.sleep(100); } assertNotNull(reader.getCloudState().getSlice("collection1", "s1")); assertEquals(3, reader.getCloudState().getSlice("collection1", "s1").getShards().size()); } finally { close(overseerClient); close(zkClient); close(reader); server.shutdown(); } } private void close(ZkStateReader reader) { if (reader != null) { reader.close(); } } private void close(SolrZkClient overseerClient) throws InterruptedException { if (overseerClient != null) { overseerClient.close(); } } private int getCloudStateVersion(SolrZkClient controllerClient) throws KeeperException, InterruptedException { return controllerClient.exists(ZkStateReader.CLUSTER_STATE, null, false).getVersion(); } private SolrZkClient electNewOverseer(String address) throws InterruptedException, TimeoutException, IOException, KeeperException, ParserConfigurationException, SAXException { SolrZkClient zkClient = new SolrZkClient(address, TIMEOUT); ZkStateReader reader = new ZkStateReader(zkClient); LeaderElector overseerElector = new LeaderElector(zkClient); // TODO: close Overseer Overseer overseer = new Overseer( new HttpShardHandlerFactory().getShardHandler(), "/admin/cores", reader); ElectionContext ec = new OverseerElectionContext(zkClient, overseer, address.replaceAll("/", "_")); overseerElector.setup(ec); overseerElector.joinElection(ec); return zkClient; } }
core/src/test/org/apache/solr/cloud/OverseerTest.java
package org.apache.solr.cloud; /* * 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.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import javax.xml.parsers.ParserConfigurationException; import org.apache.lucene.util.LuceneTestCase.Slow; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.cloud.CloudState; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.handler.component.HttpShardHandlerFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.data.Stat; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; @Slow public class OverseerTest extends SolrTestCaseJ4 { static final int TIMEOUT = 10000; private static final boolean DEBUG = false; public static class MockZKController{ private final SolrZkClient zkClient; private final ZkStateReader zkStateReader; private final String nodeName; private final String collection; private final LeaderElector elector; private final Map<String, ElectionContext> electionContext = Collections.synchronizedMap(new HashMap<String, ElectionContext>()); public MockZKController(String zkAddress, String nodeName, String collection) throws InterruptedException, TimeoutException, IOException, KeeperException { this.nodeName = nodeName; this.collection = collection; zkClient = new SolrZkClient(zkAddress, TIMEOUT); zkStateReader = new ZkStateReader(zkClient); zkStateReader.createClusterStateWatchersAndUpdate(); // live node final String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName; zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true); elector = new LeaderElector(zkClient); } private void deleteNode(final String path) { try { Stat stat = zkClient.exists(path, null, false); if (stat != null) { zkClient.delete(path, stat.getVersion(), false); } } catch (KeeperException e) { fail("Unexpected KeeperException!" + e); } catch (InterruptedException e) { fail("Unexpected InterruptedException!" + e); } } public void close(){ try { deleteNode(ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName); zkClient.close(); } catch (InterruptedException e) { //e.printStackTrace(); } } public void publishState(String coreName, String stateName, int numShards) throws KeeperException, InterruptedException, IOException { if (stateName == null) { ElectionContext ec = electionContext.remove(coreName); if (ec != null) { ec.cancelElection(); } ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "deletecore", ZkStateReader.NODE_NAME_PROP, nodeName, ZkStateReader.CORE_NAME_PROP, coreName, ZkStateReader.COLLECTION_PROP, collection); DistributedQueue q = Overseer.getInQueue(zkClient); q.offer(ZkStateReader.toJSON(m)); } else { ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.STATE_PROP, stateName, ZkStateReader.NODE_NAME_PROP, nodeName, ZkStateReader.CORE_NAME_PROP, coreName, ZkStateReader.COLLECTION_PROP, collection, ZkStateReader.NUM_SHARDS_PROP, Integer.toString(numShards), ZkStateReader.BASE_URL_PROP, "http://" + nodeName + "/solr/"); DistributedQueue q = Overseer.getInQueue(zkClient); q.offer(ZkStateReader.toJSON(m)); } for (int i = 0; i < 30; i++) { String shardId = getShardId(coreName); if (shardId != null) { try { zkClient.makePath("/collections/" + collection + "/leader_elect/" + shardId + "/election", true); } catch (NodeExistsException nee) {} ZkNodeProps props = new ZkNodeProps(ZkStateReader.BASE_URL_PROP, "http://" + nodeName + "/solr/", ZkStateReader.NODE_NAME_PROP, nodeName, ZkStateReader.CORE_NAME_PROP, coreName, ZkStateReader.SHARD_ID_PROP, shardId, ZkStateReader.COLLECTION_PROP, collection); ShardLeaderElectionContextBase ctx = new ShardLeaderElectionContextBase( elector, shardId, collection, nodeName + "_" + coreName, props, zkStateReader); elector.joinElection(ctx); break; } Thread.sleep(200); } } private String getShardId(final String coreName) { Map<String,Slice> slices = zkStateReader.getCloudState().getSlices( collection); if (slices != null) { for (Slice slice : slices.values()) { if (slice.getShards().containsKey(nodeName + "_" + coreName)) { return slice.getName(); } } } return null; } } @BeforeClass public static void beforeClass() throws Exception { System.setProperty("solrcloud.skip.autorecovery", "true"); initCore(); } @AfterClass public static void afterClass() throws Exception { System.clearProperty("solrcloud.skip.autorecovery"); initCore(); } @Test public void testShardAssignment() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); ZkController zkController = null; SolrZkClient zkClient = null; try { server.run(); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); zkClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); ZkStateReader reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); zkController = new ZkController(null, server.getZkAddress(), TIMEOUT, 10000, "localhost", "8983", "solr", new CurrentCoreDescriptorProvider() { @Override public List<CoreDescriptor> getCurrentDescriptors() { // do nothing return null; } }); System.setProperty("bootstrap_confdir", getFile("solr/collection1/conf") .getAbsolutePath()); final int numShards=6; final String[] ids = new String[numShards]; for (int i = 0; i < numShards; i++) { CloudDescriptor collection1Desc = new CloudDescriptor(); collection1Desc.setNumShards(3); collection1Desc.setCollectionName("collection1"); CoreDescriptor desc1 = new CoreDescriptor(null, "core" + (i + 1), ""); desc1.setCloudDescriptor(collection1Desc); zkController.preRegister(desc1); ids[i] = zkController.register("core" + (i + 1), desc1); } assertEquals("shard1", ids[0]); assertEquals("shard2", ids[1]); assertEquals("shard3", ids[2]); assertEquals("shard1", ids[3]); assertEquals("shard2", ids[4]); assertEquals("shard3", ids[5]); waitForCollections(reader, "collection1"); //make sure leaders are in cloud state assertNotNull(reader.getLeaderUrl("collection1", "shard1", 15000)); assertNotNull(reader.getLeaderUrl("collection1", "shard2", 15000)); assertNotNull(reader.getLeaderUrl("collection1", "shard3", 15000)); } finally { System.clearProperty("bootstrap_confdir"); if (DEBUG) { if (zkController != null) { zkClient.printLayoutToStdOut(); } } close(zkClient); if (zkController != null) { zkController.close(); } server.shutdown(); } } @Test public void testShardAssignmentBigger() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; final int nodeCount = random().nextInt(50)+50; //how many simulated nodes (num of threads) final int coreCount = random().nextInt(100)+100; //how many cores to register final int sliceCount = random().nextInt(20)+1; //how many slices ZkTestServer server = new ZkTestServer(zkDir); System.setProperty(ZkStateReader.NUM_SHARDS_PROP, Integer.toString(sliceCount)); SolrZkClient zkClient = null; ZkStateReader reader = null; final ZkController[] controllers = new ZkController[nodeCount]; final ExecutorService[] nodeExecutors = new ExecutorService[nodeCount]; try { server.run(); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); zkClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); for (int i = 0; i < nodeCount; i++) { controllers[i] = new ZkController(null, server.getZkAddress(), TIMEOUT, 10000, "localhost", "898" + i, "solr", new CurrentCoreDescriptorProvider() { @Override public List<CoreDescriptor> getCurrentDescriptors() { // do nothing return null; } }); } System.setProperty("bootstrap_confdir", getFile("solr/collection1/conf") .getAbsolutePath()); for (int i = 0; i < nodeCount; i++) { nodeExecutors[i] = Executors.newFixedThreadPool(1); } final String[] ids = new String[coreCount]; //register total of coreCount cores for (int i = 0; i < coreCount; i++) { final int slot = i; Runnable coreStarter = new Runnable() { @Override public void run() { final CloudDescriptor collection1Desc = new CloudDescriptor(); collection1Desc.setCollectionName("collection1"); collection1Desc.setNumShards(sliceCount); final String coreName = "core" + slot; final CoreDescriptor desc = new CoreDescriptor(null, coreName, ""); desc.setCloudDescriptor(collection1Desc); try { controllers[slot % nodeCount].preRegister(desc); ids[slot] = controllers[slot % nodeCount] .register(coreName, desc); } catch (Throwable e) { e.printStackTrace(); fail("register threw exception:" + e.getClass()); } } }; nodeExecutors[i % nodeCount].submit(coreStarter); } for (int i = 0; i < nodeCount; i++) { nodeExecutors[i].shutdown(); } for (int i = 0; i < nodeCount; i++) { while (!nodeExecutors[i].awaitTermination(100, TimeUnit.MILLISECONDS)); } // make sure all cores have been assigned a id in cloudstate for (int i = 0; i < 40; i++) { reader.updateCloudState(true); CloudState state = reader.getCloudState(); Map<String,Slice> slices = state.getSlices("collection1"); int count = 0; for (String name : slices.keySet()) { count += slices.get(name).getShards().size(); } if (coreCount == count) break; Thread.sleep(200); } // make sure all cores have been returned a id for (int i = 0; i < 90; i++) { int assignedCount = 0; for (int j = 0; j < coreCount; j++) { if (ids[j] != null) { assignedCount++; } } if (coreCount == assignedCount) { break; } Thread.sleep(500); } final HashMap<String, AtomicInteger> counters = new HashMap<String,AtomicInteger>(); for (int i = 1; i < sliceCount+1; i++) { counters.put("shard" + i, new AtomicInteger()); } for (int i = 0; i < coreCount; i++) { final AtomicInteger ai = counters.get(ids[i]); assertNotNull("could not find counter for shard:" + ids[i], ai); ai.incrementAndGet(); } for (String counter: counters.keySet()) { int count = counters.get(counter).intValue(); int expectedCount = coreCount / sliceCount; int min = expectedCount - 1; int max = expectedCount + 1; if (count < min || count > max) { fail("Unevenly assigned shard ids, " + counter + " had " + count + ", expected: " + min + "-" + max); } } //make sure leaders are in cloud state for (int i = 0; i < sliceCount; i++) { assertNotNull(reader.getLeaderUrl("collection1", "shard" + (i + 1)), 15000); } } finally { System.clearProperty(ZkStateReader.NUM_SHARDS_PROP); System.clearProperty("bootstrap_confdir"); if (DEBUG) { if (controllers[0] != null) { zkClient.printLayoutToStdOut(); } } close(zkClient); close(reader); for (int i = 0; i < controllers.length; i++) if (controllers[i] != null) { controllers[i].close(); } server.shutdown(); for (int i = 0; i < nodeCount; i++) { if (nodeExecutors[i] != null) { nodeExecutors[i].shutdownNow(); } } } } //wait until collections are available private void waitForCollections(ZkStateReader stateReader, String... collections) throws InterruptedException, KeeperException { int maxIterations = 100; while (0 < maxIterations--) { stateReader.updateCloudState(true); final CloudState state = stateReader.getCloudState(); Set<String> availableCollections = state.getCollections(); int availableCount = 0; for(String requiredCollection: collections) { if(availableCollections.contains(requiredCollection)) { availableCount++; } if(availableCount == collections.length) return; Thread.sleep(50); } } log.warn("Timeout waiting for collections: " + Arrays.asList(collections) + " state:" + stateReader.getCloudState()); } @Test public void testStateChange() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient zkClient = null; ZkStateReader reader = null; SolrZkClient overseerClient = null; try { server.run(); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient.makePath("/live_nodes", true); reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); overseerClient = electNewOverseer(server.getZkAddress()); DistributedQueue q = Overseer.getInQueue(zkClient); ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core1", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); q.offer(ZkStateReader.toJSON(m)); waitForCollections(reader, "collection1"); assertEquals(reader.getCloudState().toString(), ZkStateReader.RECOVERING, reader.getCloudState().getSlice("collection1", "shard1").getShards() .get("node1_core1").get(ZkStateReader.STATE_PROP)); //publish node state (active) m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core1", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.ACTIVE); q.offer(ZkStateReader.toJSON(m)); verifyStatus(reader, ZkStateReader.ACTIVE); } finally { close(zkClient); close(overseerClient); close(reader); server.shutdown(); } } private void verifyStatus(ZkStateReader reader, String expectedState) throws InterruptedException { int maxIterations = 100; String coreState = null; while(maxIterations-->0) { Slice slice = reader.getCloudState().getSlice("collection1", "shard1"); if(slice!=null) { coreState = slice.getShards().get("node1_core1").get(ZkStateReader.STATE_PROP); if(coreState.equals(expectedState)) { return; } } Thread.sleep(50); } fail("Illegal state, was:" + coreState + " expected:" + expectedState + "cloudState:" + reader.getCloudState()); } private void verifyShardLeader(ZkStateReader reader, String collection, String shard, String expectedCore) throws InterruptedException, KeeperException { int maxIterations = 100; while(maxIterations-->0) { reader.updateCloudState(true); // poll state ZkNodeProps props = reader.getCloudState().getLeader(collection, shard); if(props!=null) { if(expectedCore.equals(props.get(ZkStateReader.CORE_NAME_PROP))) { return; } } Thread.sleep(100); } assertEquals("Unexpected shard leader coll:" + collection + " shard:" + shard, expectedCore, (reader.getCloudState().getLeader(collection, shard)!=null)?reader.getCloudState().getLeader(collection, shard).get(ZkStateReader.CORE_NAME_PROP):null); } @Test public void testOverseerFailure() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; MockZKController mockController = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(controllerClient); reader.createClusterStateWatchersAndUpdate(); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); overseerClient = electNewOverseer(server.getZkAddress()); Thread.sleep(1000); mockController.publishState("core1", ZkStateReader.RECOVERING, 1); waitForCollections(reader, "collection1"); verifyStatus(reader, ZkStateReader.RECOVERING); int version = getCloudStateVersion(controllerClient); mockController.publishState("core1", ZkStateReader.ACTIVE, 1); while(version == getCloudStateVersion(controllerClient)); verifyStatus(reader, ZkStateReader.ACTIVE); version = getCloudStateVersion(controllerClient); overseerClient.close(); Thread.sleep(1000); //wait for overseer to get killed mockController.publishState("core1", ZkStateReader.RECOVERING, 1); version = getCloudStateVersion(controllerClient); overseerClient = electNewOverseer(server.getZkAddress()); while(version == getCloudStateVersion(controllerClient)); verifyStatus(reader, ZkStateReader.RECOVERING); assertEquals("Live nodes count does not match", 1, reader.getCloudState() .getLiveNodes().size()); assertEquals("Shard count does not match", 1, reader.getCloudState() .getSlice("collection1", "shard1").getShards().size()); version = getCloudStateVersion(controllerClient); mockController.publishState("core1", null,1); while(version == getCloudStateVersion(controllerClient)); Thread.sleep(500); assertFalse("collection1 should be gone after publishing the null state", reader.getCloudState().getCollections().contains("collection1")); } finally { close(mockController); close(overseerClient); close(controllerClient); close(reader); server.shutdown(); } } private AtomicInteger killCounter = new AtomicInteger(); private class OverseerRestarter implements Runnable{ SolrZkClient overseerClient = null; public volatile boolean run = true; private final String zkAddress; public OverseerRestarter(String zkAddress) { this.zkAddress = zkAddress; } @Override public void run() { try { overseerClient = electNewOverseer(zkAddress); Random rnd = random(); while (run) { if (killCounter.get()>0) { try { killCounter.decrementAndGet(); log.info("Killing overseer."); overseerClient.close(); overseerClient = electNewOverseer(zkAddress); } catch (Throwable e) { // e.printStackTrace(); } } try { Thread.sleep(100); } catch (Throwable e) { // e.printStackTrace(); } } } catch (Throwable t) { // ignore } finally { if (overseerClient != null) { try { overseerClient.close(); } catch (Throwable t) { // ignore } } } } } @Test public void testShardLeaderChange() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; final ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; ZkStateReader reader = null; MockZKController mockController = null; MockZKController mockController2 = null; OverseerRestarter killer = null; Thread killerThread = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); killer = new OverseerRestarter(server.getZkAddress()); killerThread = new Thread(killer); killerThread.start(); reader = new ZkStateReader(controllerClient); //no watches, we'll poll for (int i = 0; i < atLeast(4); i++) { killCounter.incrementAndGet(); //for each round allow 1 kill mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); mockController.publishState("core1", "state1",1); if(mockController2!=null) { mockController2.close(); mockController2 = null; } mockController.publishState("core1", "state2",1); mockController2 = new MockZKController(server.getZkAddress(), "node2", "collection1"); mockController.publishState("core1", "state1",1); verifyShardLeader(reader, "collection1", "shard1", "core1"); mockController2.publishState("core4", "state2" ,1); mockController.close(); mockController = null; verifyShardLeader(reader, "collection1", "shard1", "core4"); } } finally { if (killer != null) { killer.run = false; if (killerThread != null) { killerThread.join(); } } close(mockController); close(mockController2); close(controllerClient); close(reader); server.shutdown(); } } @Test public void testDoubleAssignment() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; MockZKController mockController = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(controllerClient); reader.createClusterStateWatchersAndUpdate(); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); overseerClient = electNewOverseer(server.getZkAddress()); mockController.publishState("core1", ZkStateReader.RECOVERING, 1); waitForCollections(reader, "collection1"); verifyStatus(reader, ZkStateReader.RECOVERING); mockController.close(); int version = getCloudStateVersion(controllerClient); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); mockController.publishState("core1", ZkStateReader.RECOVERING, 1); while (version == getCloudStateVersion(controllerClient)); reader.updateCloudState(true); CloudState state = reader.getCloudState(); int numFound = 0; for (Map<String,Slice> collection : state.getCollectionStates().values()) { for (Slice slice : collection.values()) { if (slice.getShards().get("node1_core1") != null) { numFound++; } } } assertEquals("Shard was found in more than 1 times in CloudState", 1, numFound); } finally { close(overseerClient); close(mockController); close(controllerClient); close(reader); server.shutdown(); } } @Test public void testPlaceholders() throws Exception { String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient controllerClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; MockZKController mockController = null; try { server.run(); controllerClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); controllerClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(controllerClient); reader.createClusterStateWatchersAndUpdate(); mockController = new MockZKController(server.getZkAddress(), "node1", "collection1"); overseerClient = electNewOverseer(server.getZkAddress()); mockController.publishState("core1", ZkStateReader.RECOVERING, 12); waitForCollections(reader, "collection1"); assertEquals("Slicecount does not match", 12, reader.getCloudState().getSlices("collection1").size()); } finally { close(overseerClient); close(mockController); close(controllerClient); close(reader); server.shutdown(); } } private void close(MockZKController mockController) { if (mockController != null) { mockController.close(); } } @Test public void testReplay() throws Exception{ String zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; ZkTestServer server = new ZkTestServer(zkDir); SolrZkClient zkClient = null; SolrZkClient overseerClient = null; ZkStateReader reader = null; try { server.run(); zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost()); AbstractZkTestCase.makeSolrZkNode(server.getZkHost()); zkClient.makePath(ZkStateReader.LIVE_NODES_ZKNODE, true); reader = new ZkStateReader(zkClient); reader.createClusterStateWatchersAndUpdate(); //prepopulate work queue with some items to emulate previous overseer died before persisting state DistributedQueue queue = Overseer.getInternalQueue(zkClient); ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.SHARD_ID_PROP, "s1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core1", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); queue.offer(ZkStateReader.toJSON(m)); m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.SHARD_ID_PROP, "s1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core2", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); queue.offer(ZkStateReader.toJSON(m)); overseerClient = electNewOverseer(server.getZkAddress()); //submit to proper queue queue = Overseer.getInQueue(zkClient); m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state", ZkStateReader.BASE_URL_PROP, "http://127.0.0.1/solr", ZkStateReader.NODE_NAME_PROP, "node1", ZkStateReader.SHARD_ID_PROP, "s1", ZkStateReader.COLLECTION_PROP, "collection1", ZkStateReader.CORE_NAME_PROP, "core3", ZkStateReader.ROLES_PROP, "", ZkStateReader.STATE_PROP, ZkStateReader.RECOVERING); queue.offer(ZkStateReader.toJSON(m)); for(int i=0;i<100;i++) { Slice s = reader.getCloudState().getSlice("collection1", "s1"); if(s!=null && s.getShards().size()==3) break; Thread.sleep(100); } assertNotNull(reader.getCloudState().getSlice("collection1", "s1")); assertEquals(3, reader.getCloudState().getSlice("collection1", "s1").getShards().size()); } finally { close(overseerClient); close(zkClient); close(reader); server.shutdown(); } } private void close(ZkStateReader reader) { if (reader != null) { reader.close(); } } private void close(SolrZkClient overseerClient) throws InterruptedException { if (overseerClient != null) { overseerClient.close(); } } private int getCloudStateVersion(SolrZkClient controllerClient) throws KeeperException, InterruptedException { return controllerClient.exists(ZkStateReader.CLUSTER_STATE, null, false).getVersion(); } private SolrZkClient electNewOverseer(String address) throws InterruptedException, TimeoutException, IOException, KeeperException, ParserConfigurationException, SAXException { SolrZkClient zkClient = new SolrZkClient(address, TIMEOUT); ZkStateReader reader = new ZkStateReader(zkClient); LeaderElector overseerElector = new LeaderElector(zkClient); ElectionContext ec = new OverseerElectionContext(new HttpShardHandlerFactory().getShardHandler(), "/admin/cores", address.replaceAll("/", "_"), reader); overseerElector.setup(ec); overseerElector.joinElection(ec); return zkClient; } }
LUCENE-3985: missed updating test file git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1369241 13f79535-47bb-0310-9956-ffa450edef68
core/src/test/org/apache/solr/cloud/OverseerTest.java
LUCENE-3985: missed updating test file
<ide><path>ore/src/test/org/apache/solr/cloud/OverseerTest.java <ide> <ide> <ide> private SolrZkClient electNewOverseer(String address) throws InterruptedException, <del> TimeoutException, IOException, KeeperException, ParserConfigurationException, SAXException { <del> SolrZkClient zkClient = new SolrZkClient(address, TIMEOUT); <add> TimeoutException, IOException, <add> KeeperException, ParserConfigurationException, SAXException { <add> SolrZkClient zkClient = new SolrZkClient(address, TIMEOUT); <ide> ZkStateReader reader = new ZkStateReader(zkClient); <ide> LeaderElector overseerElector = new LeaderElector(zkClient); <del> ElectionContext ec = new OverseerElectionContext(new HttpShardHandlerFactory().getShardHandler(), "/admin/cores", address.replaceAll("/", "_"), reader); <add> // TODO: close Overseer <add> Overseer overseer = new Overseer( <add> new HttpShardHandlerFactory().getShardHandler(), "/admin/cores", reader); <add> ElectionContext ec = new OverseerElectionContext(zkClient, overseer, address.replaceAll("/", "_")); <ide> overseerElector.setup(ec); <ide> overseerElector.joinElection(ec); <ide> return zkClient;
Java
cc0-1.0
d25c19b0a380f80a6e6ad95fd0103b5048bb61fd
0
mkdadi/SPMS
package spms; public class Spms { public static WelcomePage window; //Database Data public static String dbHost=<host address>; public static int dbPort=3306; public static String dbUser=<db User>; public static String dbPassword=<db User Password>; public static String dbName=<db Name>; //Mail Data public static String managerMailID=<Mail ID>; public static String managerMailHost=<mail SMTP HOST>; public static String managerMailFrom=<Mail ID u want others to see as>; public static String managerMailPass=<Mail ID Password>; //FTP Data public static String FTPHost=<FTP HOST>; public static int FTPPort=21; public static String FTPUser=<FTP USER>; public static String FTPPass=<ftp Password>; }
src/spms/Spms.java
package spms; public class Spms { public static WelcomePage window; //Database Data public static String dbHost="localhost"; public static int dbPort=3306; public static String dbUser="mkdadi"; public static String dbPassword="dnttht@9"; public static String dbName="spms"; //Mail Data public static String managerMailID="[email protected]"; public static String managerMailHost="10.3.100.244"; public static String managerMailFrom="[email protected]"; public static String managerMailPass="DYKWIA@bcf184"; //FTP Data public static String FTPHost="localhost"; public static int FTPPort=21; public static String FTPUser="mkdadi"; public static String FTPPass="dnttht@9"; }
Update Spms.java
src/spms/Spms.java
Update Spms.java
<ide><path>rc/spms/Spms.java <ide> public static WelcomePage window; <ide> <ide> //Database Data <del> public static String dbHost="localhost"; <add> public static String dbHost=<host address>; <ide> public static int dbPort=3306; <del> public static String dbUser="mkdadi"; <del> public static String dbPassword="dnttht@9"; <del> public static String dbName="spms"; <add> public static String dbUser=<db User>; <add> public static String dbPassword=<db User Password>; <add> public static String dbName=<db Name>; <ide> <ide> //Mail Data <del> public static String managerMailID="[email protected]"; <del> public static String managerMailHost="10.3.100.244"; <del> public static String managerMailFrom="[email protected]"; <del> public static String managerMailPass="DYKWIA@bcf184"; <add> public static String managerMailID=<Mail ID>; <add> public static String managerMailHost=<mail SMTP HOST>; <add> public static String managerMailFrom=<Mail ID u want others to see as>; <add> public static String managerMailPass=<Mail ID Password>; <ide> <ide> //FTP Data <del> public static String FTPHost="localhost"; <add> public static String FTPHost=<FTP HOST>; <ide> public static int FTPPort=21; <del> public static String FTPUser="mkdadi"; <del> public static String FTPPass="dnttht@9"; <add> public static String FTPUser=<FTP USER>; <add> public static String FTPPass=<ftp Password>; <ide> }
JavaScript
agpl-3.0
3602fdfae8136be25856ea93fd3c908d6a98defe
0
3drepo/3drepo.io,3drepo/3drepo.io,3drepo/3drepo.io,3drepo/3drepo.io,3drepo/3drepo.io,3drepo/3drepo.io
/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; const express = require('express'); const router = express.Router({mergeParams: true}); const middlewares = require("../middlewares/middlewares"); const systemLogger = require("../logger.js").systemLogger; const httpsGet = require('../libs/httpsReq'); const config = require("../config"); const User = require('../models/user'); router.get("/:model/maps/", listMaps); router.get("/:model/maps/osm/:zoomLevel/:gridx/:gridy.png", getOSMTile); router.get("/:model/maps/here/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereMapsTile); router.get("/:model/maps/hereaerial/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereAerialMapsTile); router.get("/:model/maps/heretraffic/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTrafficTile); router.get("/:model/maps/heretrafficflow/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTrafficFlowTile); router.get("/:model/maps/hereterrain/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTerrainTile); router.get("/:model/maps/herebuildings/:lat/:long/tile.json", middlewares.isHereEnabled, getHereBuildingsFromLongLat); function listMaps(req, res, next) { const teamspace = req.params.account; let maps = [ { name: "Open Street Map", layers: [ { name: "Map Tiles", source: "OSM" } ] } ]; User.isHereEnabled(teamspace).then((hereEnabled) => { if (hereEnabled && (config.here && config.here.appID && config.here.appCode)) { maps = maps.concat([ { name: "Here", layers: [ { name: "Map Tiles", source: "HERE" }, { name: "Traffic Flow", source: "HERE_TRAFFIC_FLOW" } ] }, { name: "Here (Satellite)", layers: [ { name: "Aerial Imagery", source: "HERE_AERIAL" }, { name: "Traffic Flow", source: "HERE_TRAFFIC_FLOW" } ] } ]); } if (maps.length > 0) { res.status(200).json({ maps }); } else { res.status(500).json({ message: "No Maps Available" }); } }); } function requestMapTile(req, res, domain, uri) { httpsGet.get(domain, uri).then(image =>{ res.writeHead(200, {'Content-Type': 'image/png' }); res.write(image); res.end(); }).catch(err => { systemLogger.logError(JSON.stringify(err)); if(err.message){ res.status(500).json({ message: err.message}); } else if (err.resCode){ res.status(err.resCode).json({message: err.message}); } }); } function getOSMTile(req, res, next){ //TODO: we may want to ensure the model has access to tiles //const url = "https://a.tile.openstreetmap.org/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + ".png"; const domain = "a.tile.openstreetmap.org"; const uri = "/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + ".png" systemLogger.logInfo("Fetching osm map tile: " + uri); requestMapTile(req, res, domain, uri); } function getHereMapsTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".base.maps.cit.api.here.com"; let uri = "/maptile/2.1/maptile/newest/normal.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereAerialMapsTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".aerial.maps.cit.api.here.com"; let uri = "/maptile/2.1/maptile/newest/satellite.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereTrafficTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".traffic.maps.cit.api.here.com"; let uri = "/maptile/2.1/traffictile/newest/normal.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here traffic flow map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereTrafficFlowTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".traffic.maps.cit.api.here.com"; let uri = "/maptile/2.1/flowtile/newest/normal.traffic.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here traffic flow map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereTerrainTile(req, res) { const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".aerial.maps.cit.api.here.com"; let uri = "/maptile/2.1/maptile/newest/terrain.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here terrain map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereBuildingsFromLongLat(req, res, next) { const zoomLevel = 13; const tileSize = 180 / Math.pow(2, zoomLevel); const tileX = Math.floor((parseFloat(req.params.long) + 180) / tileSize); const tileY = Math.floor((parseFloat(req.params.lat) + 90) / tileSize); const domain = "pde.api.here.com"; let uri = "/1/tile.json?&layer=BUILDING&level=" + zoomLevel + "&tilex=" + tileX + "&tiley=" + tileY + "&region=WEU"; systemLogger.logInfo("Fetching Here building platform data extensions: " + uri); uri += "&app_id=" + config.here.appID + "&app_code=" + config.here.appCode; httpsGet.get(domain, uri).then(buildings =>{ res.status(200).json(buildings); }).catch(err => { systemLogger.logError(JSON.stringify(err)); if(err.message){ res.status(500).json({ message: err.message}); } else if (err.resCode){ res.status(err.resCode).json({message: err.message}); } }); } module.exports = router;
backend/routes/maps.js
/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; const express = require('express'); const router = express.Router({mergeParams: true}); const middlewares = require("../middlewares/middlewares"); const systemLogger = require("../logger.js").systemLogger; const httpsGet = require('../libs/httpsReq'); const config = require("../config"); const User = require('../models/user'); router.get("/:model/maps/", listMaps); router.get("/:model/maps/osm/:zoomLevel/:gridx/:gridy.png", getOSMTile); router.get("/:model/maps/here/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereMapsTile); router.get("/:model/maps/hereaerial/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereAerialMapsTile); router.get("/:model/maps/heretraffic/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTrafficTile); router.get("/:model/maps/heretrafficflow/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTrafficFlowTile); router.get("/:model/maps/herebuildings/:lat/:long/tile.json", middlewares.isHereEnabled, getHereBuildingsFromLongLat); function listMaps(req, res, next) { const teamspace = req.params.account; let maps = [ { name: "Open Street Map", layers: [ { name: "Map Tiles", source: "OSM" } ] } ]; User.isHereEnabled(teamspace).then((hereEnabled) => { if (hereEnabled && (config.here && config.here.appID && config.here.appCode)) { maps = maps.concat([ { name: "Here", layers: [ { name: "Map Tiles", source: "HERE" }, { name: "Traffic Flow", source: "HERE_TRAFFIC_FLOW" } ] }, { name: "Here (Satellite)", layers: [ { name: "Aerial Imagery", source: "HERE_AERIAL" }, { name: "Traffic Flow", source: "HERE_TRAFFIC_FLOW" } ] } ]); } if (maps.length > 0) { res.status(200).json({ maps }); } else { res.status(500).json({ message: "No Maps Available" }); } }); } function requestMapTile(req, res, domain, uri) { httpsGet.get(domain, uri).then(image =>{ res.writeHead(200, {'Content-Type': 'image/png' }); res.write(image); res.end(); }).catch(err => { systemLogger.logError(JSON.stringify(err)); if(err.message){ res.status(500).json({ message: err.message}); } else if (err.resCode){ res.status(err.resCode).json({message: err.message}); } }); } function getOSMTile(req, res, next){ //TODO: we may want to ensure the model has access to tiles //const url = "https://a.tile.openstreetmap.org/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + ".png"; const domain = "a.tile.openstreetmap.org"; const uri = "/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + ".png" systemLogger.logInfo("Fetching osm map tile: " + uri); requestMapTile(req, res, domain, uri); } function getHereMapsTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".base.maps.cit.api.here.com"; let uri = "/maptile/2.1/maptile/newest/normal.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereAerialMapsTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".aerial.maps.cit.api.here.com"; let uri = "/maptile/2.1/maptile/newest/satellite.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereTrafficTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".traffic.maps.cit.api.here.com"; let uri = "/maptile/2.1/traffictile/newest/normal.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here traffic flow map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereTrafficFlowTile(req, res, next){ const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".traffic.maps.cit.api.here.com"; let uri = "/maptile/2.1/flowtile/newest/normal.traffic.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; systemLogger.logInfo("Fetching Here traffic flow map tile: " + uri); uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; requestMapTile(req, res, domain, uri); } function getHereBuildingsFromLongLat(req, res, next) { const zoomLevel = 13; const tileSize = 180 / Math.pow(2, zoomLevel); const tileX = Math.floor((parseFloat(req.params.long) + 180) / tileSize); const tileY = Math.floor((parseFloat(req.params.lat) + 90) / tileSize); const domain = "pde.api.here.com"; let uri = "/1/tile.json?&layer=BUILDING&level=" + zoomLevel + "&tilex=" + tileX + "&tiley=" + tileY + "&region=WEU"; systemLogger.logInfo("Fetching Here building platform data extensions: " + uri); uri += "&app_id=" + config.here.appID + "&app_code=" + config.here.appCode; httpsGet.get(domain, uri).then(buildings =>{ res.status(200).json(buildings); }).catch(err => { systemLogger.logError(JSON.stringify(err)); if(err.message){ res.status(500).json({ message: err.message}); } else if (err.resCode){ res.status(err.resCode).json({message: err.message}); } }); } module.exports = router;
ISSUE #1057 - HERE Terrain
backend/routes/maps.js
ISSUE #1057 - HERE Terrain
<ide><path>ackend/routes/maps.js <ide> router.get("/:model/maps/hereaerial/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereAerialMapsTile); <ide> router.get("/:model/maps/heretraffic/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTrafficTile); <ide> router.get("/:model/maps/heretrafficflow/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTrafficFlowTile); <add>router.get("/:model/maps/hereterrain/:zoomLevel/:gridx/:gridy.png", middlewares.isHereEnabled, getHereTerrainTile); <ide> router.get("/:model/maps/herebuildings/:lat/:long/tile.json", middlewares.isHereEnabled, getHereBuildingsFromLongLat); <ide> <ide> function listMaps(req, res, next) { <ide> requestMapTile(req, res, domain, uri); <ide> } <ide> <add>function getHereTerrainTile(req, res) { <add> const size = 256; // 256 = [256,256]; 512 = [512,512]; Deprecated: 128 <add> const domain = (1 + ((req.params.gridx + req.params.gridy) % 4)) + ".aerial.maps.cit.api.here.com"; <add> let uri = "/maptile/2.1/maptile/newest/terrain.day/" + req.params.zoomLevel + "/" + req.params.gridx + "/" + req.params.gridy + "/" + size + "/png8"; <add> systemLogger.logInfo("Fetching Here terrain map tile: " + uri); <add> uri += "?app_id=" + config.here.appID + "&app_code=" + config.here.appCode; <add> requestMapTile(req, res, domain, uri); <add>} <add> <ide> function getHereBuildingsFromLongLat(req, res, next) { <ide> const zoomLevel = 13; <ide> const tileSize = 180 / Math.pow(2, zoomLevel);
Java
apache-2.0
793811634054ec15852a23364fd4adc5524c3f40
0
gzxishan/OftenPorter
package cn.xishan.oftenporter.porter.core; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * 响应结果的封装. * <pre> * 1.结果为一个json对象,含有的属性为下面的某几个: * {@linkplain #CODE_FIELD},{@linkplain #RESULT_FIELD},{@linkplain #DESCRIPTION_FIELD} * 2.结果码(code)为0表示成功,其他表示不成功(不同值对应不同意思) * 3.desc属性表示描述;rs表示返回的结果数据;uri表示请求的uri,当发生异常,会自动设置该值。 * * </pre> * * @author Administrator */ public class JResponse { public static class JResponseFormatException extends Exception { /** * */ private static final long serialVersionUID = 1L; public JResponseFormatException() { } public JResponseFormatException(String info) { super(info); } public JResponseFormatException(Throwable throwable) { super(throwable); } } public static final String CODE_FIELD = "code", CODE_NAME_FIELD = "cname"; public static final String RESULT_FIELD = "rs", EXTRA_FIELD = "extra"; public static final String DESCRIPTION_FIELD = "desc"; //public static final String REQUEST_URI_FIELD = "uri"; private ResultCode code = ResultCode.Other; private String description; private Object result, extra; private Throwable exCause; public JResponse(ResultCode code) { setCode(code); } public JResponse(int code) { setCode(code); } public JResponse(ResultCode code,String description) { setCode(code); setDescription(description); } public JResponse(int code,String description) { setCode(code); setDescription(description); } public JResponse() { } private static String getString(JSONObject jsonObject, String name) { if (jsonObject.containsKey(name)) { return jsonObject.getString(name); } else { return null; } } /** * 设置异常原因 * * @param exCause */ public void setExCause(Throwable exCause) { Throwable cause = exCause.getCause(); if (cause == null) { cause = exCause; } this.exCause = cause; } /** * 得到异常原因 */ public Throwable getExCause() { return exCause; } private static Object getResult(JSONObject jsonObject) { Object result = null; if (jsonObject.containsKey(RESULT_FIELD)) { result = jsonObject.get(RESULT_FIELD); if (result instanceof String && ("true".equals(result) || "false".equals(result))) { result = Boolean.parseBoolean(result.toString()); } } return result; } private static Object getExtra(JSONObject jsonObject) { Object result = null; if (jsonObject.containsKey(EXTRA_FIELD)) { result = jsonObject.get(EXTRA_FIELD); if (result instanceof String && ("true".equals(result) || "false".equals(result))) { result = Boolean.parseBoolean(result.toString()); } } return result; } public Object getExtra() { return extra; } public void setExtra(Object extra) { this.extra = extra; } /** * 从对应的json字符转换成JResponse * * @param json * @return * @throws JResponseFormatException */ public static JResponse fromJSON(String json) throws JResponseFormatException { JSONObject jsonObject = JSON.parseObject(json); return fromJSONObject(jsonObject); } /** * 从对应的json转换成JResponse * * @param jsonObject * @return * @throws JResponseFormatException */ public static JResponse fromJSONObject(JSONObject jsonObject) throws JResponseFormatException { try { int code = jsonObject.getIntValue(CODE_FIELD); String desc = getString(jsonObject, DESCRIPTION_FIELD); Object result = getResult(jsonObject); Object extra = getExtra(jsonObject); JResponse jsonResponse = new JResponse(); jsonResponse.setCode(ResultCode.toResponseCode(code)); jsonResponse.setDescription(desc); jsonResponse.setResult(result); jsonResponse.setExtra(extra); return jsonResponse; } catch (Exception e) { throw new JResponseFormatException(e); } } /** * 设置结果码,默认为{@linkplain ResultCode#OK_BUT_FAILED OK_BUT_FAILED}. * * @param code */ public void setCode(ResultCode code) { this.code = code; } public void setCode(int code) { this.code = ResultCode.toResponseCode(code); } /** * 设置描述信息 * * @param description */ public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } /** * 设置结果对象 * * @param result */ public void setResult(Object result) { this.result = result; } public ResultCode getCode() { return code; } public int getIntCode() { return code.toCode(); } /** * 如果异常不为空则,抛出异常。 * * @param <T> * @return */ public <T> T getResult() { _throwExCause(); return (T) result; } /** * 结果为json的情况。 * * @return */ public JSONObject resultJSON() { JSONObject json = getResult(); return json; } public boolean resultBoolean() { boolean is = getResult(); return is; } public int resultInt() { int n = getResult(); return n; } public long resultLong() { long l = getResult(); return l; } public String resultString() { String str = getResult(); return str; } public JSONArray resultJSONArray() { JSONArray jsonArray = getResult(); return jsonArray; } public boolean isSuccess() { return code == ResultCode.SUCCESS || code == ResultCode.OK; } public boolean isNotSuccess() { return code != ResultCode.SUCCESS && code != ResultCode.OK; } /** * 如果异常信息不为空,则抛出。 */ public void throwExCause() { _throwExCause(); } private final void _throwExCause() { if (exCause != null) { RuntimeException runtimeException; if (exCause instanceof RuntimeException) { runtimeException = (RuntimeException) exCause; } else { throw new RuntimeException(exCause); } throw runtimeException; } } @Override public String toString() { return toJSON().toString(); } /** * 转换为json */ public JSONObject toJSON() { JSONObject json = new JSONObject(5); ResultCode resultCode = code != null ? code : ResultCode.Other; json.put(CODE_FIELD, resultCode.toCode()); json.put(CODE_NAME_FIELD, resultCode.name()); json.put(DESCRIPTION_FIELD, description); if (result != null) { json.put(RESULT_FIELD, result); } if (extra != null) { if (extra instanceof JSONObject || extra instanceof JSONArray) { json.put(EXTRA_FIELD, extra); } else { json.put(EXTRA_FIELD, String.valueOf(extra)); } } return json; } public static JResponse success(Object result) { JResponse jResponse = new JResponse(ResultCode.SUCCESS); jResponse.setResult(result); return jResponse; } public static JResponse failed(String desc) { JResponse jResponse = new JResponse(ResultCode.OK_BUT_FAILED); jResponse.setDescription(desc); return jResponse; } }
Porter-Core/src/main/java/cn/xishan/oftenporter/porter/core/JResponse.java
package cn.xishan.oftenporter.porter.core; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * 响应结果的封装. * <pre> * 1.结果为一个json对象,含有的属性为下面的某几个: * {@linkplain #CODE_FIELD},{@linkplain #RESULT_FIELD},{@linkplain #DESCRIPTION_FIELD} * 2.结果码(code)为0表示成功,其他表示不成功(不同值对应不同意思) * 3.desc属性表示描述;rs表示返回的结果数据;uri表示请求的uri,当发生异常,会自动设置该值。 * * </pre> * * @author Administrator */ public class JResponse { public static class JResponseFormatException extends Exception { /** * */ private static final long serialVersionUID = 1L; public JResponseFormatException() { } public JResponseFormatException(String info) { super(info); } public JResponseFormatException(Throwable throwable) { super(throwable); } } public static final String CODE_FIELD = "code", CODE_NAME_FIELD = "cname"; public static final String RESULT_FIELD = "rs", EXTRA_FIELD = "extra"; public static final String DESCRIPTION_FIELD = "desc"; //public static final String REQUEST_URI_FIELD = "uri"; private ResultCode code = ResultCode.Other; private String description; private Object result, extra; private Throwable exCause; public JResponse(ResultCode code) { setCode(code); } public JResponse(int code) { setCode(code); } public JResponse() { } private static String getString(JSONObject jsonObject, String name) { if (jsonObject.containsKey(name)) { return jsonObject.getString(name); } else { return null; } } /** * 设置异常原因 * * @param exCause */ public void setExCause(Throwable exCause) { Throwable cause = exCause.getCause(); if (cause == null) { cause = exCause; } this.exCause = cause; } /** * 得到异常原因 */ public Throwable getExCause() { return exCause; } private static Object getResult(JSONObject jsonObject) { Object result = null; if (jsonObject.containsKey(RESULT_FIELD)) { result = jsonObject.get(RESULT_FIELD); if (result instanceof String && ("true".equals(result) || "false".equals(result))) { result = Boolean.parseBoolean(result.toString()); } } return result; } private static Object getExtra(JSONObject jsonObject) { Object result = null; if (jsonObject.containsKey(EXTRA_FIELD)) { result = jsonObject.get(EXTRA_FIELD); if (result instanceof String && ("true".equals(result) || "false".equals(result))) { result = Boolean.parseBoolean(result.toString()); } } return result; } public Object getExtra() { return extra; } public void setExtra(Object extra) { this.extra = extra; } /** * 从对应的json字符转换成JResponse * * @param json * @return * @throws JResponseFormatException */ public static JResponse fromJSON(String json) throws JResponseFormatException { JSONObject jsonObject = JSON.parseObject(json); return fromJSONObject(jsonObject); } /** * 从对应的json转换成JResponse * * @param jsonObject * @return * @throws JResponseFormatException */ public static JResponse fromJSONObject(JSONObject jsonObject) throws JResponseFormatException { try { int code = jsonObject.getIntValue(CODE_FIELD); String desc = getString(jsonObject, DESCRIPTION_FIELD); Object result = getResult(jsonObject); Object extra = getExtra(jsonObject); JResponse jsonResponse = new JResponse(); jsonResponse.setCode(ResultCode.toResponseCode(code)); jsonResponse.setDescription(desc); jsonResponse.setResult(result); jsonResponse.setExtra(extra); return jsonResponse; } catch (Exception e) { throw new JResponseFormatException(e); } } /** * 设置结果码,默认为{@linkplain ResultCode#OK_BUT_FAILED OK_BUT_FAILED}. * * @param code */ public void setCode(ResultCode code) { this.code = code; } public void setCode(int code) { this.code = ResultCode.toResponseCode(code); } /** * 设置描述信息 * * @param description */ public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } /** * 设置结果对象 * * @param result */ public void setResult(Object result) { this.result = result; } public ResultCode getCode() { return code; } public int getIntCode() { return code.toCode(); } /** * 如果异常不为空则,抛出异常。 * * @param <T> * @return */ public <T> T getResult() { _throwExCause(); return (T) result; } /** * 结果为json的情况。 * * @return */ public JSONObject resultJSON() { JSONObject json = getResult(); return json; } public boolean resultBoolean() { boolean is = getResult(); return is; } public int resultInt() { int n = getResult(); return n; } public long resultLong() { long l = getResult(); return l; } public String resultString() { String str = getResult(); return str; } public JSONArray resultJSONArray() { JSONArray jsonArray = getResult(); return jsonArray; } public boolean isSuccess() { return code == ResultCode.SUCCESS || code == ResultCode.OK; } public boolean isNotSuccess() { return code != ResultCode.SUCCESS && code != ResultCode.OK; } /** * 如果异常信息不为空,则抛出。 */ public void throwExCause() { _throwExCause(); } private final void _throwExCause() { if (exCause != null) { RuntimeException runtimeException; if (exCause instanceof RuntimeException) { runtimeException = (RuntimeException) exCause; } else { throw new RuntimeException(exCause); } throw runtimeException; } } @Override public String toString() { return toJSON().toString(); } /** * 转换为json */ public JSONObject toJSON() { JSONObject json = new JSONObject(5); ResultCode resultCode = code != null ? code : ResultCode.Other; json.put(CODE_FIELD, resultCode.toCode()); json.put(CODE_NAME_FIELD, resultCode.name()); json.put(DESCRIPTION_FIELD, description); if (result != null) { json.put(RESULT_FIELD, result); } if (extra != null) { if (extra instanceof JSONObject || extra instanceof JSONArray) { json.put(EXTRA_FIELD, extra); } else { json.put(EXTRA_FIELD, String.valueOf(extra)); } } return json; } public static JResponse success(Object result) { JResponse jResponse = new JResponse(ResultCode.SUCCESS); jResponse.setResult(result); return jResponse; } public static JResponse failed(String desc) { JResponse jResponse = new JResponse(ResultCode.OK_BUT_FAILED); jResponse.setDescription(desc); return jResponse; } }
完善:JResponse
Porter-Core/src/main/java/cn/xishan/oftenporter/porter/core/JResponse.java
完善:JResponse
<ide><path>orter-Core/src/main/java/cn/xishan/oftenporter/porter/core/JResponse.java <ide> setCode(code); <ide> } <ide> <add> public JResponse(ResultCode code,String description) <add> { <add> setCode(code); <add> setDescription(description); <add> } <add> <add> public JResponse(int code,String description) <add> { <add> setCode(code); <add> setDescription(description); <add> } <add> <ide> public JResponse() <ide> { <ide>
JavaScript
mit
fa71da583b87051c7e103b6926cfbed4a34866cf
0
dirigeants/klasa
const Usage = require('./Usage'); const CommandPrompt = require('./CommandPrompt'); /** * Converts usage strings into objects to compare against later * @extends Usage */ class CommandUsage extends Usage { /** * @since 0.0.1 * @param {KlasaClient} client The klasa client * @param {usageString} usageString The usage string for this command * @param {usageDelim} usageDelim The usage deliminator for this command * @param {Command} command The command this parsed usage is for */ constructor(client, usageString, usageDelim, command) { super(client, usageString, usageDelim); /** * All names and aliases for the command * @since 0.0.1 * @type {string[]} */ this.names = [command.name, ...command.aliases]; /** * The compiled string for all names/aliases in a usage string * @since 0.0.1 * @type {string} */ this.commands = this.names.length === 1 ? this.names[0] : `《${this.names.join('|')}》`; /** * The concatenated string of this.commands and this.deliminatedUsage * @since 0.0.1 * @type {string} */ this.nearlyFullUsage = `${this.commands}${this.deliminatedUsage}`; } /** * Creates a CommandPrompt instance to collect and resolve arguments with * @since 0.5.0 * @param {KlasaMessage} message The message context from the prompt * @param {TextPromptOptions} options The options for the prompt * @returns {CommandPrompt} */ createPrompt(message, options = {}) { return new CommandPrompt(message, this, options); } /** * Creates a full usage string including prefix and commands/aliases for documentation/help purposes * @since 0.0.1 * @param {KlasaMessage} message The message context for which to generate usage for * @returns {string} */ fullUsage(message) { let prefix = message.prefixLength ? message.content.slice(0, message.prefixLength) : message.guildSettings.prefix; if (message.prefix === this.client.monitors.get('commandHandler').prefixMention) prefix = `@${this.client.user.tag}`; else if (Array.isArray(prefix)) [prefix] = prefix; return `${prefix.length !== 1 ? `${prefix} ` : prefix}${this.nearlyFullUsage}`; } /** * Defines to string behavior of this class. * @since 0.5.0 * @returns {string} */ toString() { return this.nearlyFullUsage; } } module.exports = CommandUsage;
src/lib/usage/CommandUsage.js
const Usage = require('./Usage'); const CommandPrompt = require('./CommandPrompt'); /** * Converts usage strings into objects to compare against later * @extends Usage */ class CommandUsage extends Usage { /** * @since 0.0.1 * @param {KlasaClient} client The klasa client * @param {usageString} usageString The usage string for this command * @param {usageDelim} usageDelim The usage deliminator for this command * @param {Command} command The command this parsed usage is for */ constructor(client, usageString, usageDelim, command) { super(client, usageString, usageDelim); /** * All names and aliases for the command * @since 0.0.1 * @type {string[]} */ this.names = [command.name, ...command.aliases]; /** * The compiled string for all names/aliases in a usage string * @since 0.0.1 * @type {string} */ this.commands = this.names.length === 1 ? this.names[0] : `《${this.names.join('|')}》`; /** * The concatenated string of this.commands and this.deliminatedUsage * @since 0.0.1 * @type {string} */ this.nearlyFullUsage = `${this.commands}${this.deliminatedUsage}`; } /** * Creates a CommandPrompt instance to collect and resolve arguments with * @since 0.5.0 * @param {KlasaMessage} message The message context from the prompt * @param {TextPromptOptions} options The options for the prompt * @returns {CommandPrompt} */ createPrompt(message, options = {}) { return new CommandPrompt(message, this, options); } /** * Creates a full usage string including prefix and commands/aliases for documentation/help purposes * @since 0.0.1 * @param {KlasaMessage} message The message context for which to generate usage for * @returns {string} */ fullUsage(message) { let { prefix } = message.guildSettings; if (Array.isArray(prefix)) prefix = message.prefixLength ? message.content.slice(0, message.prefixLength) : prefix[0]; return `${prefix.length !== 1 ? `${prefix} ` : prefix}${this.nearlyFullUsage}`; } /** * Defines to string behavior of this class. * @since 0.5.0 * @returns {string} */ toString() { return this.nearlyFullUsage; } } module.exports = CommandUsage;
fullUsage consistency & improvement (#455) * fullUsage consistency & improvement - changed to slice the prefix regardless of whether it's an array - fixes inconsistency where, with the prefixCaseInsensitive option on, the exact case is only preserved if prefix is array - fixes inconsistency where, when the user used the mention prefix, it would show the first prefix if prefix is array, or <@bot ID here> if prefix is not array - changed to show the mention prefix the way users actually use it, e.g. @username#0000 * simplified a bit, also remembered that I can just check the prefix directly * derp wrong "prefix" * one-lined the declaration * Ao's requested change
src/lib/usage/CommandUsage.js
fullUsage consistency & improvement (#455)
<ide><path>rc/lib/usage/CommandUsage.js <ide> * @returns {string} <ide> */ <ide> fullUsage(message) { <del> let { prefix } = message.guildSettings; <del> if (Array.isArray(prefix)) prefix = message.prefixLength ? message.content.slice(0, message.prefixLength) : prefix[0]; <add> let prefix = message.prefixLength ? message.content.slice(0, message.prefixLength) : message.guildSettings.prefix; <add> if (message.prefix === this.client.monitors.get('commandHandler').prefixMention) prefix = `@${this.client.user.tag}`; <add> else if (Array.isArray(prefix)) [prefix] = prefix; <ide> return `${prefix.length !== 1 ? `${prefix} ` : prefix}${this.nearlyFullUsage}`; <ide> } <ide>
Java
epl-1.0
3f42da84dce53ef98ce3e13279a67d33a74cf1de
0
collaborative-modeling/egit,collaborative-modeling/egit
/******************************************************************************* * Copyright (c) 2013, 2014 Robin Stocker <[email protected]> and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.push; import java.io.IOException; import java.net.URISyntaxException; import java.text.MessageFormat; import java.util.Arrays; import java.util.List; import java.util.Set; import org.eclipse.egit.core.op.PushOperationResult; import org.eclipse.egit.core.op.PushOperationSpecification; import org.eclipse.egit.ui.internal.SecureStoreUtils; import org.eclipse.egit.ui.internal.UIIcons; import org.eclipse.egit.ui.internal.UIText; import org.eclipse.egit.ui.internal.components.RepositorySelection; import org.eclipse.egit.ui.internal.credentials.EGitCredentialsProvider; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; /** * A wizard dedicated to pushing a commit. */ public class PushBranchWizard extends Wizard { private final Repository repository; private final ObjectId commitToPush; /** * In case of detached HEAD, reference is null. */ private final Ref ref; private AddRemotePage addRemotePage; private PushBranchPage pushBranchPage; private ConfirmationPage confirmationPage; /** * @param repository * the repository the ref belongs to * @param ref */ public PushBranchWizard(final Repository repository, Ref ref) { this(repository, ref.getObjectId(), ref); } /** * @param repository * the repository commit belongs to * @param commitToPush */ public PushBranchWizard(final Repository repository, ObjectId commitToPush) { this(repository, commitToPush, null); } private PushBranchWizard(final Repository repository, ObjectId commitToPush, Ref ref) { this.repository = repository; this.commitToPush = commitToPush; this.ref = ref; assert (this.repository != null); assert (this.commitToPush != null); Set<String> remoteNames = repository.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION); if (remoteNames.isEmpty()) addRemotePage = new AddRemotePage(repository); pushBranchPage = new PushBranchPage(repository, commitToPush, ref) { @Override public void setVisible(boolean visible) { if (visible && addRemotePage != null) { setSelectedRemote(addRemotePage.getRemoteName(), addRemotePage.getSelection().getURI()); } super.setVisible(visible); } }; // Don't show button if we're configuring a remote in the first step pushBranchPage.setShowNewRemoteButton(addRemotePage == null); confirmationPage = new ConfirmationPage(repository) { @Override public void setVisible(boolean visible) { setSelection(getRepositorySelection(), getRefSpecs()); AddRemotePage remotePage = getAddRemotePage(); if (remotePage != null) setCredentials(remotePage.getCredentials()); super.setVisible(visible); } }; setDefaultPageImageDescriptor(UIIcons.WIZBAN_PUSH); } @Override public void addPages() { if (addRemotePage != null) addPage(addRemotePage); addPage(pushBranchPage); addPage(confirmationPage); } @Override public String getWindowTitle() { if (ref != null) return MessageFormat.format(UIText.PushBranchWizard_WindowTitle, Repository.shortenRefName(this.ref.getName())); else return UIText.PushCommitHandler_pushCommitTitle; } @Override public boolean canFinish() { return getContainer().getCurrentPage() == confirmationPage && confirmationPage.isPageComplete(); } @Override public boolean performFinish() { try { AddRemotePage remotePage = getAddRemotePage(); if (remotePage != null) { storeCredentials(remotePage); URIish uri = remotePage.getSelection().getURI(); configureNewRemote(uri); } if (pushBranchPage.isConfigureUpstreamSelected()) configureUpstream(); startPush(); } catch (IOException e) { confirmationPage.setErrorMessage(e.getMessage()); return false; } catch (URISyntaxException e) { confirmationPage.setErrorMessage(e.getMessage()); return false; } return true; } private AddRemotePage getAddRemotePage() { if (addRemotePage != null) return addRemotePage; else return pushBranchPage.getAddRemotePage(); } private RepositorySelection getRepositorySelection() { AddRemotePage remotePage = getAddRemotePage(); if (remotePage != null) return remotePage.getSelection(); else return new RepositorySelection(null, pushBranchPage.getRemoteConfig()); } private List<RefSpec> getRefSpecs() { String src = this.ref != null ? this.ref.getName() : this.commitToPush.getName(); String dst = pushBranchPage.getFullRemoteReference(); RefSpec refSpec = new RefSpec().setSourceDestination(src, dst) .setForceUpdate(pushBranchPage.isForceUpdateSelected()); return Arrays.asList(refSpec); } private void storeCredentials(AddRemotePage remotePage) { if (remotePage.getStoreInSecureStore()) { URIish uri = remotePage.getSelection().getURI(); if (uri != null) SecureStoreUtils.storeCredentials( remotePage.getCredentials(), uri); } } private void configureNewRemote(URIish uri) throws URISyntaxException, IOException { StoredConfig config = repository.getConfig(); String remoteName = getRemoteName(); RemoteConfig remoteConfig = new RemoteConfig(config, remoteName); remoteConfig.addURI(uri); RefSpec defaultFetchSpec = new RefSpec().setForceUpdate(true) .setSourceDestination(Constants.R_HEADS + "*", //$NON-NLS-1$ Constants.R_REMOTES + remoteName + "/*"); //$NON-NLS-1$ remoteConfig.addFetchRefSpec(defaultFetchSpec); remoteConfig.update(config); config.save(); } private void configureUpstream() throws IOException { if (this.ref == null) { // Don't configure upstream for detached HEAD return; } String remoteName = getRemoteName(); String fullRemoteBranchName = pushBranchPage.getFullRemoteReference(); String localBranchName = Repository.shortenRefName(this.ref.getName()); StoredConfig config = repository.getConfig(); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_REMOTE, remoteName); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_MERGE, fullRemoteBranchName); if (pushBranchPage.isRebaseSelected()) { config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_REBASE, true); } else { // Make sure we overwrite any previous configuration config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_REBASE); } config.save(); } private void startPush() throws IOException { PushOperationResult result = confirmationPage.getConfirmedResult(); PushOperationSpecification pushSpec = result .deriveSpecification(confirmationPage .isRequireUnchangedSelected()); PushOperationUI pushOperationUI = new PushOperationUI(repository, pushSpec, false); pushOperationUI.setCredentialsProvider(new EGitCredentialsProvider()); pushOperationUI.setShowConfigureButton(false); if (confirmationPage.isShowOnlyIfChangedSelected()) pushOperationUI.setExpectedResult(result); pushOperationUI.start(); } private String getRemoteName() { return pushBranchPage.getRemoteConfig().getName(); } }
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushBranchWizard.java
/******************************************************************************* * Copyright (c) 2013, 2014 Robin Stocker <[email protected]> and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.push; import java.io.IOException; import java.net.URISyntaxException; import java.text.MessageFormat; import java.util.Arrays; import java.util.List; import java.util.Set; import org.eclipse.egit.core.op.PushOperationResult; import org.eclipse.egit.core.op.PushOperationSpecification; import org.eclipse.egit.ui.internal.SecureStoreUtils; import org.eclipse.egit.ui.internal.UIIcons; import org.eclipse.egit.ui.internal.UIText; import org.eclipse.egit.ui.internal.components.RepositorySelection; import org.eclipse.egit.ui.internal.credentials.EGitCredentialsProvider; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; /** * A wizard dedicated to pushing a commit. */ public class PushBranchWizard extends Wizard { private final Repository repository; private final ObjectId commitToPush; /** * In case of detached HEAD, reference is null. */ private final Ref ref; private AddRemotePage addRemotePage; private PushBranchPage pushBranchPage; private ConfirmationPage confirmationPage; /** * @param repository * the repository the ref belongs to * @param ref */ public PushBranchWizard(final Repository repository, Ref ref) { this(repository, ref.getObjectId(), ref); } /** * @param repository * the repository commit belongs to * @param commitToPush */ public PushBranchWizard(final Repository repository, ObjectId commitToPush) { this(repository, commitToPush, null); } private PushBranchWizard(final Repository repository, ObjectId commitToPush, Ref ref) { this.repository = repository; this.commitToPush = commitToPush; this.ref = ref; assert (this.repository != null); assert (this.commitToPush != null); Set<String> remoteNames = repository.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION); if (remoteNames.isEmpty()) addRemotePage = new AddRemotePage(repository); pushBranchPage = new PushBranchPage(repository, commitToPush, ref) { @Override public void setVisible(boolean visible) { if (visible && addRemotePage != null) { setSelectedRemote(addRemotePage.getRemoteName(), addRemotePage.getSelection().getURI()); } super.setVisible(visible); } }; // Don't show button if we're configuring a remote in the first step pushBranchPage.setShowNewRemoteButton(addRemotePage == null); confirmationPage = new ConfirmationPage(repository) { @Override public void setVisible(boolean visible) { setSelection(getRepositorySelection(), getRefSpecs()); AddRemotePage remotePage = getAddRemotePage(); if (remotePage != null) setCredentials(remotePage.getCredentials()); super.setVisible(visible); } }; setDefaultPageImageDescriptor(UIIcons.WIZBAN_PUSH); } @Override public void addPages() { if (addRemotePage != null) addPage(addRemotePage); addPage(pushBranchPage); addPage(confirmationPage); } @Override public String getWindowTitle() { if (ref != null) return MessageFormat.format(UIText.PushBranchWizard_WindowTitle, Repository.shortenRefName(this.ref.getName())); else return UIText.PushCommitHandler_pushCommitTitle; } @Override public boolean canFinish() { return getContainer().getCurrentPage() == confirmationPage; } @Override public boolean performFinish() { try { AddRemotePage remotePage = getAddRemotePage(); if (remotePage != null) { storeCredentials(remotePage); URIish uri = remotePage.getSelection().getURI(); configureNewRemote(uri); } if (pushBranchPage.isConfigureUpstreamSelected()) configureUpstream(); startPush(); } catch (IOException e) { confirmationPage.setErrorMessage(e.getMessage()); return false; } catch (URISyntaxException e) { confirmationPage.setErrorMessage(e.getMessage()); return false; } return true; } private AddRemotePage getAddRemotePage() { if (addRemotePage != null) return addRemotePage; else return pushBranchPage.getAddRemotePage(); } private RepositorySelection getRepositorySelection() { AddRemotePage remotePage = getAddRemotePage(); if (remotePage != null) return remotePage.getSelection(); else return new RepositorySelection(null, pushBranchPage.getRemoteConfig()); } private List<RefSpec> getRefSpecs() { String src = this.ref != null ? this.ref.getName() : this.commitToPush.getName(); String dst = pushBranchPage.getFullRemoteReference(); RefSpec refSpec = new RefSpec().setSourceDestination(src, dst) .setForceUpdate(pushBranchPage.isForceUpdateSelected()); return Arrays.asList(refSpec); } private void storeCredentials(AddRemotePage remotePage) { if (remotePage.getStoreInSecureStore()) { URIish uri = remotePage.getSelection().getURI(); if (uri != null) SecureStoreUtils.storeCredentials( remotePage.getCredentials(), uri); } } private void configureNewRemote(URIish uri) throws URISyntaxException, IOException { StoredConfig config = repository.getConfig(); String remoteName = getRemoteName(); RemoteConfig remoteConfig = new RemoteConfig(config, remoteName); remoteConfig.addURI(uri); RefSpec defaultFetchSpec = new RefSpec().setForceUpdate(true) .setSourceDestination(Constants.R_HEADS + "*", //$NON-NLS-1$ Constants.R_REMOTES + remoteName + "/*"); //$NON-NLS-1$ remoteConfig.addFetchRefSpec(defaultFetchSpec); remoteConfig.update(config); config.save(); } private void configureUpstream() throws IOException { if (this.ref == null) { // Don't configure upstream for detached HEAD return; } String remoteName = getRemoteName(); String fullRemoteBranchName = pushBranchPage.getFullRemoteReference(); String localBranchName = Repository.shortenRefName(this.ref.getName()); StoredConfig config = repository.getConfig(); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_REMOTE, remoteName); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_MERGE, fullRemoteBranchName); if (pushBranchPage.isRebaseSelected()) { config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_REBASE, true); } else { // Make sure we overwrite any previous configuration config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName, ConfigConstants.CONFIG_KEY_REBASE); } config.save(); } private void startPush() throws IOException { PushOperationResult result = confirmationPage.getConfirmedResult(); PushOperationSpecification pushSpec = result .deriveSpecification(confirmationPage .isRequireUnchangedSelected()); PushOperationUI pushOperationUI = new PushOperationUI(repository, pushSpec, false); pushOperationUI.setCredentialsProvider(new EGitCredentialsProvider()); pushOperationUI.setShowConfigureButton(false); if (confirmationPage.isShowOnlyIfChangedSelected()) pushOperationUI.setExpectedResult(result); pushOperationUI.start(); } private String getRemoteName() { return pushBranchPage.getRemoteConfig().getName(); } }
Fix NPE in PushBranchWizard.startPush() Bug: 464421 Change-Id: Ia70db60627298f8017b302b639965134a7d83eae Signed-off-by: Matthias Sohn <[email protected]>
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushBranchWizard.java
Fix NPE in PushBranchWizard.startPush()
<ide><path>rg.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushBranchWizard.java <ide> <ide> @Override <ide> public boolean canFinish() { <del> return getContainer().getCurrentPage() == confirmationPage; <add> return getContainer().getCurrentPage() == confirmationPage <add> && confirmationPage.isPageComplete(); <ide> } <ide> <ide> @Override
Java
apache-2.0
8756f5bd993d08fc55e6eb1d20d015f20ceac330
0
Teino1978-Corp/Teino1978-Corp-helix,dasahcc/helix,OopsOutOfMemory/helix,apache/helix,brandtg/helix,OopsOutOfMemory/helix,jzmq/helix,AyolaJayamaha/helix,kongweihan/helix,jzmq/helix,hdatas/helix,AyolaJayamaha/helix,AyolaJayamaha/helix,kongweihan/helix,kongweihan/helix,lei-xia/helix,fx19880617/helix,brandtg/helix,Teino1978-Corp/Teino1978-Corp-helix,lei-xia/helix,Teino1978-Corp/Teino1978-Corp-helix,dasahcc/helix,dasahcc/helix,dasahcc/helix,fx19880617/helix,lei-xia/helix,lei-xia/helix,hdatas/helix,jzmq/helix,dasahcc/helix,apache/helix,fx19880617/helix,brandtg/helix,apache/helix,hdatas/helix,Teino1978-Corp/Teino1978-Corp-helix,brandtg/helix,lei-xia/helix,OopsOutOfMemory/helix,apache/helix,OopsOutOfMemory/helix,AyolaJayamaha/helix,jzmq/helix,fx19880617/helix,apache/helix,apache/helix,dasahcc/helix,lei-xia/helix
/** * Copyright (C) 2012 LinkedIn Inc <[email protected]> * * 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.linkedin.helix.participant; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import com.linkedin.helix.HelixConstants; import com.linkedin.helix.HelixDataAccessor; import com.linkedin.helix.HelixException; import com.linkedin.helix.HelixManager; import com.linkedin.helix.InstanceType; import com.linkedin.helix.NotificationContext; import com.linkedin.helix.PropertyKey.Builder; import com.linkedin.helix.messaging.handling.HelixStateTransitionHandler; import com.linkedin.helix.messaging.handling.MessageHandler; import com.linkedin.helix.model.CurrentState; import com.linkedin.helix.model.Message; import com.linkedin.helix.model.Message.MessageType; import com.linkedin.helix.model.StateModelDefinition; import com.linkedin.helix.participant.statemachine.StateModel; import com.linkedin.helix.participant.statemachine.StateModelFactory; import com.linkedin.helix.participant.statemachine.StateModelParser; public class HelixStateMachineEngine implements StateMachineEngine { private static Logger logger = Logger.getLogger(HelixStateMachineEngine.class); // StateModelName->FactoryName->StateModelFactory private final Map<String, Map<String, StateModelFactory<? extends StateModel>>> _stateModelFactoryMap = new ConcurrentHashMap<String, Map<String, StateModelFactory<? extends StateModel>>>(); StateModelParser _stateModelParser; private final HelixManager _manager; public StateModelFactory<? extends StateModel> getStateModelFactory(String stateModelName) { return getStateModelFactory(stateModelName, HelixConstants.DEFAULT_STATE_MODEL_FACTORY); } public StateModelFactory<? extends StateModel> getStateModelFactory(String stateModelName, String factoryName) { if (!_stateModelFactoryMap.containsKey(stateModelName)) { return null; } return _stateModelFactoryMap.get(stateModelName).get(factoryName); } public HelixStateMachineEngine(HelixManager manager) { _stateModelParser = new StateModelParser(); _manager = manager; } @Override public boolean registerStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory) { return registerStateModelFactory(stateModelDef, factory, HelixConstants.DEFAULT_STATE_MODEL_FACTORY); } @Override public boolean registerStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory, String factoryName) { if (stateModelDef == null || factory == null || factoryName == null) { throw new HelixException("stateModelDef|stateModelFactory|factoryName cannot be null"); } logger.info("Register state model factory for state model " + stateModelDef + " using factory name " + factoryName + " with " + factory); if (!_stateModelFactoryMap.containsKey(stateModelDef)) { _stateModelFactoryMap.put(stateModelDef, new ConcurrentHashMap<String, StateModelFactory<? extends StateModel>>()); } if (_stateModelFactoryMap.get(stateModelDef).containsKey(factoryName)) { logger.warn("stateModelFactory for " + stateModelDef + " using factoryName " + factoryName + " has already been registered."); return false; } _stateModelFactoryMap.get(stateModelDef).put(factoryName, factory); sendNopMessage(); return true; } // TODO: duplicated code in DefaultMessagingService private void sendNopMessage() { if (_manager.isConnected()) { try { Message nopMsg = new Message(MessageType.NO_OP, UUID.randomUUID().toString()); nopMsg.setSrcName(_manager.getInstanceName()); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); Builder keyBuilder = accessor.keyBuilder(); if (_manager.getInstanceType() == InstanceType.CONTROLLER || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) { nopMsg.setTgtName("Controller"); accessor.setProperty(keyBuilder.controllerMessage(nopMsg.getId()), nopMsg); } if (_manager.getInstanceType() == InstanceType.PARTICIPANT || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) { nopMsg.setTgtName(_manager.getInstanceName()); accessor.setProperty(keyBuilder.message(nopMsg.getTgtName(), nopMsg.getId()), nopMsg); } } catch (Exception e) { logger.error(e); } } } @Override public void reset() { for (Map<String, StateModelFactory<? extends StateModel>> ftyMap : _stateModelFactoryMap.values()) { for (StateModelFactory<? extends StateModel> stateModelFactory : ftyMap.values()) { Map<String, ? extends StateModel> modelMap = stateModelFactory.getStateModelMap(); if (modelMap == null || modelMap.isEmpty()) { continue; } for (String resourceKey : modelMap.keySet()) { StateModel stateModel = modelMap.get(resourceKey); stateModel.reset(); String initialState = _stateModelParser.getInitialState(stateModel.getClass()); stateModel.updateState(initialState); // TODO probably should update the state on ZK. Shi confirm what needs // to be done here. } } } } @Override public MessageHandler createHandler(Message message, NotificationContext context) { String type = message.getMsgType(); if (!type.equals(MessageType.STATE_TRANSITION.toString())) { throw new HelixException("Unexpected msg type for message " + message.getMsgId() + " type:" + message.getMsgType()); } String partitionKey = message.getPartitionName(); String stateModelName = message.getStateModelDef(); String resourceName = message.getResourceName(); if (stateModelName == null) { logger.error("message does not contain stateModelDef"); return null; } String factoryName = message.getStateModelFactoryName(); if (factoryName == null) { factoryName = HelixConstants.DEFAULT_STATE_MODEL_FACTORY; } StateModelFactory stateModelFactory = getStateModelFactory(stateModelName, factoryName); if (stateModelFactory == null) { logger.warn("Cannot find stateModelFactory for model:" + stateModelName + " using factoryName:" + factoryName + " for resourceGroup:" + resourceName); return null; } // create currentStateDelta for this partition HelixManager manager = context.getManager(); // stateModelDefs are in dataAccessor's cache HelixDataAccessor accessor = manager.getHelixDataAccessor(); Builder keyBuilder = accessor.keyBuilder(); Map<String, StateModelDefinition> stateModelDefs = accessor.getChildValuesMap(keyBuilder.stateModelDefs()); if (!stateModelDefs.containsKey(stateModelName)) { throw new HelixException("No State Model Defined for " + stateModelName); } String initState = stateModelDefs.get(stateModelName).getInitialState(); StateModel stateModel = stateModelFactory.getStateModel(partitionKey); if (stateModel == null) { stateModelFactory.createAndAddStateModel(partitionKey); stateModel = stateModelFactory.getStateModel(partitionKey); stateModel.updateState(initState); } CurrentState currentStateDelta = new CurrentState(resourceName); currentStateDelta.setSessionId(manager.getSessionId()); currentStateDelta.setStateModelDefRef(stateModelName); currentStateDelta.setStateModelFactoryName(factoryName); currentStateDelta.setState(partitionKey, (stateModel.getCurrentState() == null) ? initState : stateModel.getCurrentState()); return new HelixStateTransitionHandler(stateModel, message, context, currentStateDelta); } @Override public String getMessageType() { return MessageType.STATE_TRANSITION.toString(); } @Override public boolean removeStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory) { throw new UnsupportedOperationException("Remove not yet supported"); } @Override public boolean removeStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory, String factoryName) { throw new UnsupportedOperationException("Remove not yet supported"); } }
helix-core/src/main/java/com/linkedin/helix/participant/HelixStateMachineEngine.java
/** * Copyright (C) 2012 LinkedIn Inc <[email protected]> * * 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.linkedin.helix.participant; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import com.linkedin.helix.HelixConstants; import com.linkedin.helix.HelixDataAccessor; import com.linkedin.helix.HelixException; import com.linkedin.helix.HelixManager; import com.linkedin.helix.InstanceType; import com.linkedin.helix.NotificationContext; import com.linkedin.helix.PropertyKey.Builder; import com.linkedin.helix.messaging.handling.HelixStateTransitionHandler; import com.linkedin.helix.messaging.handling.MessageHandler; import com.linkedin.helix.model.CurrentState; import com.linkedin.helix.model.Message; import com.linkedin.helix.model.Message.MessageType; import com.linkedin.helix.model.StateModelDefinition; import com.linkedin.helix.participant.statemachine.StateModel; import com.linkedin.helix.participant.statemachine.StateModelFactory; import com.linkedin.helix.participant.statemachine.StateModelParser; public class HelixStateMachineEngine implements StateMachineEngine { private static Logger logger = Logger.getLogger(HelixStateMachineEngine.class); // StateModelName->FactoryName->StateModelFactory private final Map<String, Map<String, StateModelFactory<? extends StateModel>>> _stateModelFactoryMap = new ConcurrentHashMap<String, Map<String, StateModelFactory<? extends StateModel>>>(); StateModelParser _stateModelParser; private final HelixManager _manager; public StateModelFactory<? extends StateModel> getStateModelFactory(String stateModelName) { return getStateModelFactory(stateModelName, HelixConstants.DEFAULT_STATE_MODEL_FACTORY); } public StateModelFactory<? extends StateModel> getStateModelFactory(String stateModelName, String factoryName) { if (!_stateModelFactoryMap.containsKey(stateModelName)) { return null; } return _stateModelFactoryMap.get(stateModelName).get(factoryName); } public HelixStateMachineEngine(HelixManager manager) { _stateModelParser = new StateModelParser(); _manager = manager; } @Override public boolean registerStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory) { return registerStateModelFactory(stateModelDef, factory, HelixConstants.DEFAULT_STATE_MODEL_FACTORY); } @Override public boolean registerStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory, String factoryName) { if (stateModelDef == null || factory == null || factoryName == null) { throw new HelixException("stateModelDef|stateModelFactory|factoryName cannot be null"); } logger.info("Register state model factory for state model " + stateModelDef + " using factory name " + factoryName + " with " + factory); if (!_stateModelFactoryMap.containsKey(stateModelDef)) { _stateModelFactoryMap.put(stateModelDef, new ConcurrentHashMap<String, StateModelFactory<? extends StateModel>>()); } if (_stateModelFactoryMap.get(stateModelDef).containsKey(factoryName)) { logger.warn("stateModelFactory for " + stateModelDef + " using factoryName " + factoryName + " has already been registered."); return false; } _stateModelFactoryMap.get(stateModelDef).put(factoryName, factory); sendNopMessage(); return true; } // TODO: duplicated code in DefaultMessagingService private void sendNopMessage() { if (_manager.isConnected()) { try { Message nopMsg = new Message(MessageType.NO_OP, UUID.randomUUID().toString()); nopMsg.setSrcName(_manager.getInstanceName()); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); Builder keyBuilder = accessor.keyBuilder(); if (_manager.getInstanceType() == InstanceType.CONTROLLER || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) { nopMsg.setTgtName("Controller"); accessor.setProperty(keyBuilder.controllerMessage(nopMsg.getId()), nopMsg); } if (_manager.getInstanceType() == InstanceType.PARTICIPANT || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) { nopMsg.setTgtName(_manager.getInstanceName()); accessor.setProperty(keyBuilder.message(nopMsg.getTgtName(), nopMsg.getId()), nopMsg); } } catch (Exception e) { logger.error(e); } } } @Override public void reset() { for (Map<String, StateModelFactory<? extends StateModel>> ftyMap : _stateModelFactoryMap.values()) { for (StateModelFactory<? extends StateModel> stateModelFactory : ftyMap.values()) { Map<String, ? extends StateModel> modelMap = stateModelFactory.getStateModelMap(); if (modelMap == null || modelMap.isEmpty()) { continue; } for (String resourceKey : modelMap.keySet()) { StateModel stateModel = modelMap.get(resourceKey); stateModel.reset(); String initialState = _stateModelParser.getInitialState(stateModel.getClass()); stateModel.updateState(initialState); // TODO probably should update the state on ZK. Shi confirm what needs // to be done here. } } } } @Override public MessageHandler createHandler(Message message, NotificationContext context) { String type = message.getMsgType(); if (!type.equals(MessageType.STATE_TRANSITION.toString())) { throw new HelixException("Unexpected msg type for message " + message.getMsgId() + " type:" + message.getMsgType()); } String partitionKey = message.getPartitionName(); String stateModelName = message.getStateModelDef(); String resourceName = message.getResourceName(); if (stateModelName == null) { logger.error("message does not contain stateModelDef"); return null; } String factoryName = message.getStateModelFactoryName(); if (factoryName == null) { factoryName = HelixConstants.DEFAULT_STATE_MODEL_FACTORY; } StateModelFactory stateModelFactory = getStateModelFactory(stateModelName, factoryName); if (stateModelFactory == null) { logger.warn("Cannot find stateModelFactory for model:" + stateModelName + " using factoryName:" + factoryName + " for resourceGroup:" + resourceName); return null; } StateModel stateModel = stateModelFactory.getStateModel(partitionKey); if (stateModel == null) { stateModelFactory.createAndAddStateModel(partitionKey); stateModel = stateModelFactory.getStateModel(partitionKey); } // create currentStateDelta for this partition HelixManager manager = context.getManager(); // stateModelDefs are in dataAccessor's cache HelixDataAccessor accessor = manager.getHelixDataAccessor(); Builder keyBuilder = accessor.keyBuilder(); Map<String, StateModelDefinition> stateModelDefs = accessor.getChildValuesMap(keyBuilder.stateModelDefs()); if (!stateModelDefs.containsKey(stateModelName)) { throw new HelixException("No State Model Defined for " + stateModelName); } String initState = stateModelDefs.get(stateModelName).getInitialState(); CurrentState currentStateDelta = new CurrentState(resourceName); currentStateDelta.setSessionId(manager.getSessionId()); currentStateDelta.setStateModelDefRef(stateModelName); currentStateDelta.setStateModelFactoryName(factoryName); currentStateDelta.setState(partitionKey, (stateModel == null || stateModel.getCurrentState() == null) ? initState : stateModel.getCurrentState()); return new HelixStateTransitionHandler(stateModel, message, context, currentStateDelta); } @Override public String getMessageType() { return MessageType.STATE_TRANSITION.toString(); } @Override public boolean removeStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory) { throw new UnsupportedOperationException("Remove not yet supported"); } @Override public boolean removeStateModelFactory(String stateModelDef, StateModelFactory<? extends StateModel> factory, String factoryName) { throw new UnsupportedOperationException("Remove not yet supported"); } }
fix helix state machine engine in dealting with state model of non-offline initial state
helix-core/src/main/java/com/linkedin/helix/participant/HelixStateMachineEngine.java
fix helix state machine engine in dealting with state model of non-offline initial state
<ide><path>elix-core/src/main/java/com/linkedin/helix/participant/HelixStateMachineEngine.java <ide> return null; <ide> } <ide> <del> StateModel stateModel = stateModelFactory.getStateModel(partitionKey); <del> if (stateModel == null) <del> { <del> stateModelFactory.createAndAddStateModel(partitionKey); <del> stateModel = stateModelFactory.getStateModel(partitionKey); <del> <del> } <del> <ide> // create currentStateDelta for this partition <ide> HelixManager manager = context.getManager(); <ide> <ide> } <ide> String initState = stateModelDefs.get(stateModelName).getInitialState(); <ide> <add> StateModel stateModel = stateModelFactory.getStateModel(partitionKey); <add> if (stateModel == null) <add> { <add> stateModelFactory.createAndAddStateModel(partitionKey); <add> stateModel = stateModelFactory.getStateModel(partitionKey); <add> stateModel.updateState(initState); <add> } <add> <ide> CurrentState currentStateDelta = new CurrentState(resourceName); <ide> currentStateDelta.setSessionId(manager.getSessionId()); <ide> currentStateDelta.setStateModelDefRef(stateModelName); <ide> currentStateDelta.setStateModelFactoryName(factoryName); <ide> <del> currentStateDelta.setState(partitionKey, <del> (stateModel == null || stateModel.getCurrentState() == null) <del> ? initState : stateModel.getCurrentState()); <del> <add> currentStateDelta.setState(partitionKey, (stateModel.getCurrentState() == null) <add> ? initState : stateModel.getCurrentState()); <add> <ide> return new HelixStateTransitionHandler(stateModel, <ide> message, <ide> context,
JavaScript
apache-2.0
7716a33c3fb76c1a8c3195271fa5711e8fd5bdb8
0
ahmed-mahran/hue,lumig242/Hue-Integration-with-CDAP,jayceyxc/hue,jounex/hue,epssy/hue,jayceyxc/hue,x303597316/hue,cloudera/hue,hdinsight/hue,Peddle/hue,sanjeevtripurari/hue,ChenJunor/hue,ChenJunor/hue,lumig242/Hue-Integration-with-CDAP,fangxingli/hue,todaychi/hue,mapr/hue,x303597316/hue,cloudera/hue,jounex/hue,sanjeevtripurari/hue,vitan/hue,azureplus/hue,yoer/hue,cloudera/hue,vmax-feihu/hue,kawamon/hue,xiangel/hue,vitan/hue,jounex/hue,pwong-mapr/private-hue,ahmed-mahran/hue,todaychi/hue,pwong-mapr/private-hue,fangxingli/hue,azureplus/hue,todaychi/hue,jounex/hue,dulems/hue,jjmleiro/hue,yoer/hue,todaychi/hue,yongshengwang/hue,lumig242/Hue-Integration-with-CDAP,rahul67/hue,kawamon/hue,vmax-feihu/hue,pwong-mapr/private-hue,x303597316/hue,ChenJunor/hue,Peddle/hue,Peddle/hue,GitHublong/hue,kawamon/hue,kawamon/hue,fangxingli/hue,pwong-mapr/private-hue,ahmed-mahran/hue,ahmed-mahran/hue,xiangel/hue,vitan/hue,cloudera/hue,javachengwc/hue,Peddle/hue,xq262144/hue,jjmleiro/hue,sanjeevtripurari/hue,cloudera/hue,jayceyxc/hue,epssy/hue,jjmleiro/hue,javachengwc/hue,kawamon/hue,rahul67/hue,todaychi/hue,xiangel/hue,xiangel/hue,lumig242/Hue-Integration-with-CDAP,todaychi/hue,xq262144/hue,epssy/hue,epssy/hue,yoer/hue,sanjeevtripurari/hue,jayceyxc/hue,jjmleiro/hue,cloudera/hue,vitan/hue,vitan/hue,erickt/hue,hdinsight/hue,Peddle/hue,nvoron23/hue,sanjeevtripurari/hue,kawamon/hue,fangxingli/hue,jounex/hue,kawamon/hue,sanjeevtripurari/hue,pratikmallya/hue,Peddle/hue,cloudera/hue,yongshengwang/hue,kawamon/hue,vmax-feihu/hue,erickt/hue,vmax-feihu/hue,hdinsight/hue,hdinsight/hue,MobinRanjbar/hue,abhishek-ch/hue,jjmleiro/hue,xq262144/hue,dulems/hue,yoer/hue,rahul67/hue,yongshengwang/hue,cloudera/hue,xiangel/hue,epssy/hue,cloudera/hue,lumig242/Hue-Integration-with-CDAP,xq262144/hue,fangxingli/hue,epssy/hue,xq262144/hue,xq262144/hue,Peddle/hue,dulems/hue,kawamon/hue,jayceyxc/hue,dulems/hue,javachengwc/hue,ChenJunor/hue,GitHublong/hue,nvoron23/hue,GitHublong/hue,vitan/hue,pratikmallya/hue,ChenJunor/hue,pratikmallya/hue,cloudera/hue,nvoron23/hue,erickt/hue,rahul67/hue,kawamon/hue,MobinRanjbar/hue,azureplus/hue,yongshengwang/hue,pwong-mapr/private-hue,hdinsight/hue,GitHublong/hue,erickt/hue,nvoron23/hue,ChenJunor/hue,epssy/hue,pratikmallya/hue,erickt/hue,vitan/hue,abhishek-ch/hue,abhishek-ch/hue,pratikmallya/hue,sanjeevtripurari/hue,vmax-feihu/hue,vmax-feihu/hue,jounex/hue,todaychi/hue,rahul67/hue,mapr/hue,ChenJunor/hue,sanjeevtripurari/hue,xiangel/hue,erickt/hue,ahmed-mahran/hue,lumig242/Hue-Integration-with-CDAP,jjmleiro/hue,MobinRanjbar/hue,yoer/hue,Peddle/hue,mapr/hue,jayceyxc/hue,GitHublong/hue,mapr/hue,MobinRanjbar/hue,fangxingli/hue,jjmleiro/hue,javachengwc/hue,azureplus/hue,MobinRanjbar/hue,GitHublong/hue,nvoron23/hue,hdinsight/hue,rahul67/hue,fangxingli/hue,cloudera/hue,azureplus/hue,dulems/hue,cloudera/hue,kawamon/hue,xiangel/hue,x303597316/hue,cloudera/hue,javachengwc/hue,jayceyxc/hue,rahul67/hue,nvoron23/hue,yongshengwang/hue,azureplus/hue,pwong-mapr/private-hue,cloudera/hue,lumig242/Hue-Integration-with-CDAP,yoer/hue,pratikmallya/hue,kawamon/hue,pratikmallya/hue,jjmleiro/hue,MobinRanjbar/hue,x303597316/hue,jayceyxc/hue,jjmleiro/hue,xiangel/hue,abhishek-ch/hue,kawamon/hue,dulems/hue,cloudera/hue,MobinRanjbar/hue,jounex/hue,yongshengwang/hue,x303597316/hue,MobinRanjbar/hue,abhishek-ch/hue,vmax-feihu/hue,todaychi/hue,yoer/hue,hdinsight/hue,cloudera/hue,yoer/hue,cloudera/hue,lumig242/Hue-Integration-with-CDAP,mapr/hue,yongshengwang/hue,erickt/hue,x303597316/hue,abhishek-ch/hue,yongshengwang/hue,xq262144/hue,javachengwc/hue,kawamon/hue,ahmed-mahran/hue,kawamon/hue,todaychi/hue,dulems/hue,jayceyxc/hue,erickt/hue,rahul67/hue,nvoron23/hue,xq262144/hue,ChenJunor/hue,x303597316/hue,Peddle/hue,pratikmallya/hue,azureplus/hue,jounex/hue,dulems/hue,abhishek-ch/hue,mapr/hue,javachengwc/hue,abhishek-ch/hue,epssy/hue,azureplus/hue,ahmed-mahran/hue,pwong-mapr/private-hue,kawamon/hue,xq262144/hue,GitHublong/hue,ahmed-mahran/hue,GitHublong/hue,vmax-feihu/hue,fangxingli/hue,javachengwc/hue,kawamon/hue,cloudera/hue,lumig242/Hue-Integration-with-CDAP,hdinsight/hue,nvoron23/hue,kawamon/hue,vitan/hue,mapr/hue
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. 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. /* --- description: Enables smooth scrolling for in-page anchors in SplitView. provides: [Behavior.SplitViewScroller] requires: [Widgets/Behavior.SplitView] script: Behavior.SplitViewScroller.js ... */ Behavior.addGlobalPlugin('SplitView', 'SplitViewScroller', function(element, methods) { var splitview = element.retrieve('SplitView'); var el = $(splitview); var sides = splitview.getSides(); var tabAnchorScroller = function(e, link){ var name = link.get('href').split('#')[1]; var anchor = el.getElement('[name=' + name + ']'); if (!anchor) { dbug.warn('warning, link name "%s" found no corresponding anchor', name); return; } var scrollSide; for (sideName in sides) { if (sides[sideName].hasChild(anchor)) scrollSide = sides[sideName]; } if (scrollSide) { var scroller = scrollSide.retrieve('_scroller'); if (!scroller) { scroller = new Fx.Scroll(scrollSide); scrollSide.store('_scroller', scroller); } scroller.toElement(anchor); e.stop(); } }; el.addEvent('click:relay([href*=#])', tabAnchorScroller); this.markForCleanup(element, function() { el.removeEvent('click:relay([href*=#]', tabEnchorScroller); }); });
desktop/core/static/js/Source/BehaviorFilters/Behavior.SplitViewScroller.js
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. 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. /* --- description: Enables smooth scrolling for in-page anchors in SplitView. provides: [Behavior.SplitViewScroller] requires: [Widgets/Behavior.SplitView] script: Behavior.SplitViewScroller.js ... */ Behavior.addGlobalPlugin('SplitView', 'SplitViewScroller', function(element, methods) { var splitview = element.retrieve('SplitView'); var el = $(splitview); var sides = splitview.getSides(); var tabAnchorScroller = function(e, link){ var name = link.get('href').split('#')[1]; var anchor = el.getElement('[name=' + name + ']'); if (!anchor) { dbug.warn('warning, link name "%s" found no corresponding anchor', name); return; } var scrollSide; for (sideName in sides) { if (sides[sideName].hasChild(anchor)) scrollSide = sides[sideName]; } if (scrollSide){ var scroller = scrollSide.retrieve('_scroller'); if (!scroller) { scroller = new Fx.Scroll(scrollSide); scrollSide.store('_scroller', scroller); } scroller.toElement(anchor); e.stop(); } }; el.addEvent('click:relay([href*=#])', tabAnchorScroller); this.markForCleanup(element, function(){ el.removeEvent('click:relay([href*=#]', tabEnchorScroller); }); });
No Ticket. Some indention changes
desktop/core/static/js/Source/BehaviorFilters/Behavior.SplitViewScroller.js
No Ticket. Some indention changes
<ide><path>esktop/core/static/js/Source/BehaviorFilters/Behavior.SplitViewScroller.js <ide> for (sideName in sides) { <ide> if (sides[sideName].hasChild(anchor)) scrollSide = sides[sideName]; <ide> } <del> if (scrollSide){ <add> if (scrollSide) { <ide> var scroller = scrollSide.retrieve('_scroller'); <ide> if (!scroller) { <ide> scroller = new Fx.Scroll(scrollSide); <ide> } <ide> }; <ide> el.addEvent('click:relay([href*=#])', tabAnchorScroller); <del> this.markForCleanup(element, function(){ <add> this.markForCleanup(element, function() { <ide> el.removeEvent('click:relay([href*=#]', tabEnchorScroller); <ide> }); <ide> });
Java
agpl-3.0
36fd9d059ceecad975e6ed9e737f3ad396e935c6
0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
/* * SourceColumnManager.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.dom.client.Element; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import org.rstudio.core.client.*; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.js.JsUtil; import org.rstudio.core.client.widget.ModalDialogBase; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.OperationWithInput; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.FilePathUtils; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.dependencies.DependencyManager; import org.rstudio.studio.client.common.filetypes.*; import org.rstudio.studio.client.common.synctex.Synctex; import org.rstudio.studio.client.events.GetEditorContextEvent; import org.rstudio.studio.client.palette.model.CommandPaletteEntrySource; import org.rstudio.studio.client.palette.model.CommandPaletteItem; import org.rstudio.studio.client.rmarkdown.model.RmdChosenTemplate; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter; import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat; import org.rstudio.studio.client.rmarkdown.model.RmdTemplateData; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.FileMRUList; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.ClientState; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.UnsavedChangesTarget; import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue; import org.rstudio.studio.client.workbench.prefs.model.UserPrefs; import org.rstudio.studio.client.workbench.prefs.model.UserState; import org.rstudio.studio.client.workbench.ui.PaneConfig; import org.rstudio.studio.client.workbench.ui.unsaved.UnsavedChangesDialog; import org.rstudio.studio.client.workbench.views.environment.events.DebugModeChangedEvent; import org.rstudio.studio.client.workbench.views.output.find.events.FindInFilesEvent; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource; import org.rstudio.studio.client.workbench.views.source.editors.codebrowser.CodeBrowserEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.ObjectExplorerEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.model.ObjectExplorerHandle; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Selection; import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditingTargetSelectedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRMarkdownDialog; import org.rstudio.studio.client.workbench.views.source.events.*; import org.rstudio.studio.client.workbench.views.source.model.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @Singleton public class SourceColumnManager implements CommandPaletteEntrySource, SourceExtendedTypeDetectedEvent.Handler, DebugModeChangedEvent.Handler { public interface CPSEditingTargetCommand { void execute(EditingTarget editingTarget, Command continuation); } public static class State extends JavaScriptObject { public static native State createState(JsArrayString names, String activeColumn) /*-{ return { names: names, activeColumn: activeColumn } }-*/; protected State() {} public final String[] getNames() { return JsUtil.toStringArray(getNamesNative()); } public final native String getActiveColumn() /*-{ return this.activeColumn || ""; }-*/; private native JsArrayString getNamesNative() /*-{ return this.names; }-*/; } interface Binder extends CommandBinder<Commands, SourceColumnManager> { } SourceColumnManager() { RStudioGinjector.INSTANCE.injectMembers(this);} @Inject public SourceColumnManager(Binder binder, Source.Display display, SourceServerOperations server, GlobalDisplay globalDisplay, Commands commands, EditingTargetSource editingTargetSource, FileTypeRegistry fileTypeRegistry, EventBus events, DependencyManager dependencyManager, final Session session, Synctex synctex, UserPrefs userPrefs, UserState userState, Provider<FileMRUList> pMruList, SourceWindowManager windowManager) { commands_ = commands; binder.bind(commands_, this); server_ = server; globalDisplay_ = globalDisplay; editingTargetSource_ = editingTargetSource; fileTypeRegistry_ = fileTypeRegistry; events_ = events; dependencyManager_ = dependencyManager; session_ = session; synctex_ = synctex; userPrefs_ = userPrefs; userState_ = userState; pMruList_ = pMruList; windowManager_ = windowManager; rmarkdown_ = new TextEditingTargetRMarkdownHelper(); vimCommands_ = new SourceVimCommands(); columnState_ = null; initDynamicCommands(); events_.addHandler(SourceExtendedTypeDetectedEvent.TYPE, this); events_.addHandler(DebugModeChangedEvent.TYPE, this); events_.addHandler(EditingTargetSelectedEvent.TYPE, new EditingTargetSelectedEvent.Handler() { @Override public void onEditingTargetSelected(EditingTargetSelectedEvent event) { setActive(event.getTarget()); } }); events_.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler() { public void onSourceFileSaved(SourceFileSavedEvent event) { pMruList_.get().add(event.getPath()); } }); events_.addHandler(DocTabActivatedEvent.TYPE, new DocTabActivatedEvent.Handler() { public void onDocTabActivated(DocTabActivatedEvent event) { setActiveDocId(event.getId()); } }); events_.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler() { public void onSwitchToDoc(SwitchToDocEvent event) { ensureVisible(false); activeColumn_.setPhysicalTabIndex(event.getSelectedIndex()); // Fire an activation event just to ensure the activated // tab gets focus commands_.activateSource().execute(); } }); sourceNavigationHistory_.addChangeHandler(event -> manageSourceNavigationCommands()); SourceColumn column = GWT.create(SourceColumn.class); column.loadDisplay(MAIN_SOURCE_NAME, display, this); columnList_.add(column); new JSObjectStateValue("source-column-manager", "column-info", ClientState.PERSISTENT, session_.getSessionInfo().getClientState(), false) { @Override protected void onInit(JsObject value) { if (!userPrefs_.allowSourceColumns().getGlobalValue()) { if (columnList_.size() > 1) { PaneConfig paneConfig = userPrefs_.panes().getValue().cast(); userPrefs_.panes().setGlobalValue(PaneConfig.create( JsArrayUtil.copy(paneConfig.getQuadrants()), paneConfig.getTabSet1(), paneConfig.getTabSet2(), paneConfig.getHiddenTabSet(), paneConfig.getConsoleLeftOnTop(), paneConfig.getConsoleRightOnTop(), 0).cast()); consolidateColumns(1); } return; } if (value == null) { // default to main column name here because we haven't loaded any columns yet columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), MAIN_SOURCE_NAME); return; } State state = value.cast(); for (int i = 0; i < state.getNames().length; i++) { String name = state.getNames()[i]; if (!StringUtil.equals(name, MAIN_SOURCE_NAME)) add(name, false); } } @Override protected JsObject getValue() { return columnState_.cast(); } }; setActive(column.getName()); // register custom focus handler for case where ProseMirror // instance (or element within) had focus ModalDialogBase.registerReturnFocusHandler((Element el) -> { final String sourceClass = ClassIds.getClassId(ClassIds.SOURCE_PANEL); Element sourceEl = DomUtils.findParentElement(el, (Element parent) -> { return parent.hasClassName(sourceClass); }); if (sourceEl != null) { commands_.activateSource().execute(); return true; } return false; }); } public String add() { Source.Display display = GWT.create(SourcePane.class); return add(display, false); } public String add(Source.Display display) { return add(display, false); } public String add(String name, boolean updateState) { return add(name, false, updateState); } public String add (String name, boolean activate, boolean updateState) { Source.Display display = GWT.create(SourcePane.class); return add(name, display, activate, updateState); } public String add(Source.Display display, boolean activate) { return add(display, activate, true); } public String add(Source.Display display, boolean activate, boolean updateState) { return add(COLUMN_PREFIX + StringUtil.makeRandomId(12), display, activate, updateState); } public String add(String name, Source.Display display, boolean activate, boolean updateState) { if (contains(name)) return ""; SourceColumn column = GWT.create(SourceColumn.class); column.loadDisplay(name, display, this); columnList_.add(column); if (activate || activeColumn_ == null) setActive(column); if (updateState) columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); return column.getName(); } public void initialSelect(int index) { SourceColumn lastActive = getByName(columnState_.getActiveColumn()); if (lastActive != null) setActive(getByName(columnState_.getActiveColumn())); getActive().initialSelect(index); } public void setActive(int xpos) { SourceColumn column = findByPosition(xpos); if (column == null) return; setActive(column); } public void setActive(String name) { if (StringUtil.isNullOrEmpty(name) && activeColumn_ != null) { if (hasActiveEditor()) activeColumn_.setActiveEditor(""); activeColumn_ = null; return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); } private void setActive(EditingTarget target) { setActive(findByDocument(target.getId())); activeColumn_.setActiveEditor(target); } public void setActive(SourceColumn column) { SourceColumn prevColumn = activeColumn_; activeColumn_ = column; // If the active column changed, we need to update the active editor if (prevColumn != null && prevColumn != activeColumn_) { prevColumn.setActiveEditor(""); if (!hasActiveEditor()) activeColumn_.setActiveEditor(); manageCommands(true); } columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), activeColumn_ == null ? "" : activeColumn_.getName()); } private void setActiveDocId(String docId) { if (StringUtil.isNullOrEmpty(docId)) return; for (SourceColumn column : columnList_) { EditingTarget target = column.setActiveEditor(docId); if (target != null) { setActive(target); return; } } } public void setDocsRestored() { docsRestored_ = true; } public void setOpeningForSourceNavigation(boolean value) { openingForSourceNavigation_ = value; } public void activateColumn(String name, final Command afterActivation) { if (!StringUtil.isNullOrEmpty(name)) setActive(getByName(name)); if (!hasActiveEditor()) { if (activeColumn_ == null) setActive(MAIN_SOURCE_NAME); newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { setActive(target); doActivateSource(afterActivation); } }); } else { doActivateSource(afterActivation); } } public String getLeftColumnName() { return columnList_.get(columnList_.size() - 1).getName(); } public String getNextColumnName() { int index = columnList_.indexOf(getActive()); if (index < 1) return ""; else return columnList_.get(index - 1).getName(); } public String getPreviousColumnName() { int index = columnList_.indexOf(getActive()); if (index == getSize() - 1) return ""; else return columnList_.get(index + 1).getName(); } // This method sets activeColumn_ to the main column if it is null. It should be used in cases // where it is better for the column to be the main column than null. public SourceColumn getActive() { if (activeColumn_ != null && (!columnList_.get(0).asWidget().isAttached() || activeColumn_.asWidget().isAttached() && activeColumn_.asWidget().getOffsetWidth() > 0)) return activeColumn_; setActive(MAIN_SOURCE_NAME); return activeColumn_; } public String getActiveDocId() { if (hasActiveEditor()) return activeColumn_.getActiveEditor().getId(); return null; } public String getActiveDocPath() { if (hasActiveEditor()) return activeColumn_.getActiveEditor().getPath(); return null; } public boolean hasActiveEditor() { return activeColumn_ != null && activeColumn_.getActiveEditor() != null; } public boolean isActiveEditor(EditingTarget editingTarget) { return hasActiveEditor() && activeColumn_.getActiveEditor() == editingTarget; } public boolean getDocsRestored() { return docsRestored_; } // see if there are additional command palette items made available // by the active editor public List<CommandPaletteItem> getCommandPaletteItems() { if (!hasActiveEditor()) return null; return activeColumn_.getActiveEditor().getCommandPaletteItems(); } public int getTabCount() { return getActive().getTabCount(); } public int getPhysicalTabIndex() { if (getActive() != null) return getActive().getPhysicalTabIndex(); else return -1; } public ArrayList<String> getNames(boolean excludeMain) { ArrayList<String> result = new ArrayList<>(); columnList_.forEach((column) ->{ if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) result.add(column.getName()); }); return result; } public ArrayList<Widget> getWidgets(boolean excludeMain) { ArrayList<Widget> result = new ArrayList<>(); for (SourceColumn column : columnList_) { if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) result.add(column.asWidget()); } return result; } public ArrayList<SourceColumn> getColumnList() { return columnList_; } public Element getActiveElement() { if (activeColumn_ == null) return null; return activeColumn_.asWidget().getElement(); } public Widget getWidget(String name) { return getByName(name) == null ? null : getByName(name).asWidget(); } public Session getSession() { return session_; } public SourceNavigationHistory getSourceNavigationHistory() { return sourceNavigationHistory_; } public void recordCurrentNavigationHistoryPosition() { if (hasActiveEditor()) activeColumn_.getActiveEditor().recordCurrentNavigationPosition(); } public String getEditorPositionString() { if (hasActiveEditor()) return activeColumn_.getActiveEditor().getCurrentStatus(); return "No document tabs open"; } public Synctex getSynctex() { return synctex_; } public UserState getUserState() { return userState_; } public int getSize() { return columnList_.size(); } public SourceColumn get(int index) { if (index >= columnList_.size()) return null; return columnList_.get(index); } public int getUntitledNum(String prefix) { AtomicInteger max = new AtomicInteger(); columnList_.forEach((column) -> max.set(Math.max(max.get(), column.getUntitledNum(prefix)))); return max.intValue(); } public native final int getUntitledNum(String name, String prefix) /*-{ var match = (new RegExp("^" + prefix + "([0-9]{1,5})$")).exec(name); if (!match) return 0; return parseInt(match[1]); }-*/; public void clearSourceNavigationHistory() { if (!hasDoc()) sourceNavigationHistory_.clear(); } public void manageCommands(boolean forceSync) { boolean saveAllEnabled = false; for (SourceColumn column : columnList_) { if (column.isInitialized() && !StringUtil.equals(getActive().getName(), column.getName())) column.manageCommands(forceSync, activeColumn_); // if one document is dirty then we are enabled if (!saveAllEnabled && column.isSaveCommandActive()) saveAllEnabled = true; } // the active column is always managed last because any column can disable a command, but // only the active one can enable a command if (activeColumn_.isInitialized()) activeColumn_.manageCommands(forceSync, activeColumn_); if (!session_.getSessionInfo().getAllowShell()) commands_.sendToTerminal().setVisible(false); // if source windows are open, managing state of the command becomes // complicated, so leave it enabled if (windowManager_.areSourceWindowsOpen()) commands_.saveAllSourceDocs().setEnabled(saveAllEnabled); if (activeColumn_ != null && !StringUtil.equals(activeColumn_.getName(), MAIN_SOURCE_NAME)) commands_.focusSourceColumnSeparator().setEnabled(true); else commands_.focusSourceColumnSeparator().setEnabled(false); manageSourceNavigationCommands(); } private void manageSourceNavigationCommands() { commands_.sourceNavigateBack().setEnabled( sourceNavigationHistory_.isBackEnabled()); commands_.sourceNavigateForward().setEnabled( sourceNavigationHistory_.isForwardEnabled()); } public EditingTarget addTab(SourceDocument doc, int mode, SourceColumn column) { if (column == null) column = getActive(); return column.addTab(doc, mode); } public EditingTarget addTab(SourceDocument doc, boolean atEnd, int mode, SourceColumn column) { if (column == null || getByName(column.getName()) == null) column = getActive(); return column.addTab(doc, atEnd, mode); } public EditingTarget findEditor(String docId) { for (SourceColumn column : columnList_) { EditingTarget target = column.getDoc(docId); if (target != null) return target; } return null; } public EditingTarget findEditorByPath(String path) { if (StringUtil.isNullOrEmpty(path)) return null; for (SourceColumn column : columnList_) { EditingTarget target = column.getEditorWithPath(path); if (target != null) return target; } return null; } public SourceColumn findByDocument(String docId) { for (SourceColumn column : columnList_) { if (column.hasDoc(docId)) return column; } return null; } public SourceColumn findByPosition(int x) { for (SourceColumn column : columnList_) { Widget w = column.asWidget(); int left = w.getAbsoluteLeft(); int right = w.getAbsoluteLeft() + w.getOffsetWidth(); if (x >= left && x <= right) return column; } return null; } public boolean isEmpty(String name) { return getByName(name) == null || getByName(name).getTabCount() == 0; } public boolean attemptTextEditorActivate() { if (!(hasActiveEditor() || activeColumn_.getActiveEditor() instanceof TextEditingTarget)) return false; TextEditingTarget editingTarget = (TextEditingTarget) activeColumn_.getActiveEditor(); editingTarget.ensureTextEditorActive(() -> { getEditorContext( editingTarget.getId(), editingTarget.getPath(), editingTarget.getDocDisplay() ); }); return true; } public void activateCodeBrowser( final String codeBrowserPath, boolean replaceIfActive, final ResultCallback<CodeBrowserEditingTarget, ServerError> callback) { // first check to see if this request can be fulfilled with an existing // code browser tab EditingTarget target = selectTabWithDocPath(codeBrowserPath); if (target != null) { callback.onSuccess((CodeBrowserEditingTarget) target); return; } // then check to see if the active editor is a code browser -- if it is, // we'll use it as is, replacing its contents if (replaceIfActive && hasActiveEditor() && activeColumn_.getActiveEditor() instanceof CodeBrowserEditingTarget) { events_.fireEvent(new CodeBrowserCreatedEvent(activeColumn_.getActiveEditor().getId(), codeBrowserPath)); callback.onSuccess((CodeBrowserEditingTarget) activeColumn_.getActiveEditor()); return; } // create a new one newDoc(FileTypeRegistry.CODEBROWSER, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget arg) { events_.fireEvent(new CodeBrowserCreatedEvent( arg.getId(), codeBrowserPath)); callback.onSuccess((CodeBrowserEditingTarget) arg); } @Override public void onFailure(ServerError error) { callback.onFailure(error); } @Override public void onCancelled() { callback.onCancelled(); } }); } public void activateObjectExplorer(ObjectExplorerHandle handle) { columnList_.forEach((column) -> { for (EditingTarget target : column.getEditors()) { // bail if this isn't an object explorer filetype FileType fileType = target.getFileType(); if (!(fileType instanceof ObjectExplorerFileType)) continue; // check for identical titles if (handle.getTitle() == target.getTitle()) { ((ObjectExplorerEditingTarget) target).update(handle); ensureVisible(false); column.selectTab(target.asWidget()); return; } } }); ensureVisible(true); server_.newDocument( FileTypeRegistry.OBJECT_EXPLORER.getTypeId(), null, (JsObject) handle.cast(), new SimpleRequestCallback<SourceDocument>("Show Object Explorer") { @Override public void onResponseReceived(SourceDocument response) { getActive().addTab(response, Source.OPEN_INTERACTIVE); } }); } public void showOverflowPopout() { ensureVisible(false); getActive().showOverflowPopout(); } public void showDataItem(DataItem data) { for (SourceColumn column : columnList_) { for (EditingTarget target : column.getEditors()) { String path = target.getPath(); if (path != null && path.equals(data.getURI())) { ((DataEditingTarget) target).updateData(data); ensureVisible(false); column.selectTab(target.asWidget()); return; } } } ensureVisible(true); server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), null, (JsObject) data.cast(), new SimpleRequestCallback<SourceDocument>("Show Data Frame") { @Override public void onResponseReceived(SourceDocument response) { getActive().addTab(response, Source.OPEN_INTERACTIVE); } }); } public void showUnsavedChangesDialog( String title, ArrayList<UnsavedChangesTarget> dirtyTargets, OperationWithInput<UnsavedChangesDialog.Result> saveOperation, Command onCancelled) { getActive().showUnsavedChangesDialog(title, dirtyTargets, saveOperation, onCancelled); } public boolean insertSource(String code, boolean isBlock) { if (!hasActiveEditor()) return false; return getActive().insertCode(code, isBlock); } @Handler public void onMoveTabRight() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), 1); } @Handler public void onMoveTabLeft() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), -1); } @Handler public void onMoveTabToFirst() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), activeColumn_.getPhysicalTabIndex() * -1); } @Handler public void onMoveTabToLast() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), (activeColumn_.getTabCount() - activeColumn_.getPhysicalTabIndex()) - 1); } @Handler public void onSwitchToTab() { if (getActive().getTabCount() == 0) return; showOverflowPopout(); } @Handler public void onFirstTab() { if (getActive().getTabCount() == 0) return; ensureVisible(false); if (getActive().getTabCount() > 0) getActive().setPhysicalTabIndex(0); } @Handler public void onPreviousTab() { switchToTab(-1, userPrefs_.wrapTabNavigation().getValue()); } @Handler public void onNextTab() { switchToTab(1, userPrefs_.wrapTabNavigation().getValue()); } @Handler public void onLastTab() { if (getActive().getTabCount() == 0) return; activeColumn_.ensureVisible(false); if (activeColumn_.getTabCount() > 0) activeColumn_.setPhysicalTabIndex(activeColumn_.getTabCount() - 1); } @Handler public void onCloseSourceDoc() { closeSourceDoc(true); } @Handler public void onFindInFiles() { String searchPattern = ""; if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget textEditor = (TextEditingTarget) activeColumn_.getActiveEditor(); String selection = textEditor.getSelectedText(); boolean multiLineSelection = selection.indexOf('\n') != -1; if ((selection.length() != 0) && !multiLineSelection) searchPattern = selection; } events_.fireEvent(new FindInFilesEvent(searchPattern)); } @Override public void onDebugModeChanged(DebugModeChangedEvent evt) { // when debugging ends, always disengage any active debug highlights if (!evt.debugging() && hasActiveEditor()) { activeColumn_.getActiveEditor().endDebugHighlighting(); } } @Override public void onSourceExtendedTypeDetected(SourceExtendedTypeDetectedEvent e) { // set the extended type of the specified source file EditingTarget target = findEditor(e.getDocId()); if (target != null) target.adaptToExtendedFileType(e.getExtendedType()); } public void nextTabWithWrap() { switchToTab(1, true); } public void prevTabWithWrap() { switchToTab(-1, true); } private void switchToTab(int delta, boolean wrap) { if (getActive().getTabCount() == 0) return; activeColumn_.ensureVisible(false); int targetIndex = activeColumn_.getPhysicalTabIndex() + delta; if (targetIndex > (activeColumn_.getTabCount() - 1)) { if (wrap) targetIndex = 0; else return; } else if (targetIndex < 0) { if (wrap) targetIndex = activeColumn_.getTabCount() - 1; else return; } activeColumn_.setPhysicalTabIndex(targetIndex); } private void doActivateSource(final Command afterActivation) { getActive().ensureVisible(false); if (hasActiveEditor()) { activeColumn_.getActiveEditor().focus(); activeColumn_.getActiveEditor().ensureCursorVisible(); } if (afterActivation != null) afterActivation.execute(); } // new doc functions public void newRMarkdownV1Doc() { newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "v1.Rmd", Position.create(3, 0)); } public void newRMarkdownV2Doc() { rmarkdown_.showNewRMarkdownDialog( new OperationWithInput<NewRMarkdownDialog.Result>() { @Override public void execute(final NewRMarkdownDialog.Result result) { if (result == null) { // No document chosen, just create an empty one newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "default.Rmd"); } else if (result.isNewDocument()) { NewRMarkdownDialog.RmdNewDocument doc = result.getNewDocument(); String author = doc.getAuthor(); if (author.length() > 0) { userPrefs_.documentAuthor().setGlobalValue(author); userPrefs_.writeUserPrefs(); } newRMarkdownV2Doc(doc); } else { newDocFromRmdTemplate(result); } } }); } private void newDocFromRmdTemplate(final NewRMarkdownDialog.Result result) { final RmdChosenTemplate template = result.getFromTemplate(); if (template.createDir()) { rmarkdown_.createDraftFromTemplate(template); return; } rmarkdown_.getTemplateContent(template, new OperationWithInput<String>() { @Override public void execute(final String content) { if (content.length() == 0) globalDisplay_.showErrorMessage("Template Content Missing", "The template at " + template.getTemplatePath() + " is missing."); newDoc(FileTypeRegistry.RMARKDOWN, content, null); } }); } private void newRMarkdownV2Doc( final NewRMarkdownDialog.RmdNewDocument doc) { rmarkdown_.frontMatterToYAML((RmdFrontMatter) doc.getJSOResult().cast(), null, new CommandWithArg<String>() { @Override public void execute(final String yaml) { String template = ""; // select a template appropriate to the document type we're creating if (doc.getTemplate().equals(RmdTemplateData.PRESENTATION_TEMPLATE)) template = "presentation.Rmd"; else if (doc.isShiny()) { if (doc.getFormat().endsWith( RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX)) template = "shiny_presentation.Rmd"; else template = "shiny.Rmd"; } else template = "document.Rmd"; newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", template, Position.create(1, 0), null, new TransformerCommand<String>() { @Override public String transform(String input) { return RmdFrontMatter.FRONTMATTER_SEPARATOR + yaml + RmdFrontMatter.FRONTMATTER_SEPARATOR + "\n" + input; } }); } }); } public void newSourceDocWithTemplate(final TextFileType fileType, String name, String template) { newSourceDocWithTemplate(fileType, name, template, null); } public void newSourceDocWithTemplate(final TextFileType fileType, String name, String template, final Position cursorPosition) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, null); } public void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, onSuccess, null); } public void startDebug() { getActive().setPendingDebugSelection(); } private EditingTarget selectTabWithDocPath(String path) { for (SourceColumn column : columnList_) { EditingTarget editor = column.getEditorWithPath(path); if (editor != null) { column.selectTab(editor.asWidget()); return editor; } } return null; } private void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess, final TransformerCommand<String> contentTransformer) { final ProgressIndicator indicator = new GlobalProgressDelayer( globalDisplay_, 500, "Creating new document...").getIndicator(); server_.getSourceTemplate(name, template, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String templateContents) { indicator.onCompleted(); if (contentTransformer != null) templateContents = contentTransformer.transform(templateContents); newDoc(fileType, templateContents, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { if (cursorPosition != null) target.setCursorPosition(cursorPosition); if (onSuccess != null) onSuccess.execute(target); } }); } @Override public void onError(ServerError error) { indicator.onError(error.getUserMessage()); } }); } public void newDoc(EditableFileType fileType, ResultCallback<EditingTarget, ServerError> callback) { getActive().newDoc(fileType, callback); } public void newDoc(EditableFileType fileType, final String contents, final ResultCallback<EditingTarget, ServerError> resultCallback) { getActive().newDoc(fileType, contents, resultCallback); } public void disownDoc(String docId) { SourceColumn column = findByDocument(docId); column.closeDoc(docId); } // When dragging between columns/windows, we need to be specific about which column we're // removing the document from as it may exist in more than one column. If the column is null, // it is assumed that we are a satellite window and do not have multiple displays. public void disownDocOnDrag(String docId, SourceColumn column) { if (column == null) { if (getSize() > 1) Debug.logWarning("Warning: No column was provided to remove the doc from."); column = getActive(); } column.closeDoc(docId); column.cancelTabDrag(); } public void selectTab(EditingTarget target) { SourceColumn column = findByDocument(target.getId()); column.ensureVisible(false); column.selectTab(target.asWidget()); } public void closeTabs(JsArrayString ids) { if (ids != null) columnList_.forEach((column) -> column.closeTabs(ids)); } public void closeTabWithPath(String path, boolean interactive) { EditingTarget target = findEditorByPath(path); closeTab(target, interactive); } public void closeTab(boolean interactive) { if (hasActiveEditor()) closeTab(activeColumn_.getActiveEditor(), interactive); } public void closeTab(EditingTarget target, boolean interactive) { findByDocument(target.getId()).closeTab(target.asWidget(), interactive, null); } public void closeTab(EditingTarget target, boolean interactive, Command onClosed) { findByDocument(target.getId()).closeTab( target.asWidget(), interactive, onClosed); } public void closeAllTabs(boolean excludeActive, boolean excludeMain) { columnList_.forEach((column) -> closeAllTabs(column, excludeActive, excludeMain)); } public void closeAllTabs(SourceColumn column, boolean excludeActive, boolean excludeMain) { if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) { cpsExecuteForEachEditor(column.getEditors(), new CPSEditingTargetCommand() { @Override public void execute(EditingTarget target, Command continuation) { if (excludeActive && (hasActiveEditor() && target == activeColumn_.getActiveEditor())) { continuation.execute(); return; } else { column.closeTab(target.asWidget(), false, continuation); } } }); } } void closeSourceDoc(boolean interactive) { if (activeColumn_.getTabCount() == 0) return; closeTab(interactive); } public void saveAllSourceDocs() { columnList_.forEach((column) -> cpsExecuteForEachEditor( column.getEditors(), (editingTarget, continuation) -> { if (editingTarget.dirtyState().getValue()) { editingTarget.save(continuation); } else { continuation.execute(); } })); } public void revertUnsavedTargets(Command onCompleted) { ArrayList<EditingTarget> unsavedTargets = new ArrayList<>(); columnList_.forEach((column) -> unsavedTargets.addAll( column.getUnsavedEditors(Source.TYPE_FILE_BACKED, null))); // revert all of them cpsExecuteForEachEditor( // targets the user chose not to save unsavedTargets, // save each editor (saveTarget, continuation) -> { if (saveTarget.getPath() != null) { // file backed document -- revert it saveTarget.revertChanges(continuation); } else { // untitled document -- just close the tab non-interactively closeTab(saveTarget, false, continuation); } }, // onCompleted at the end onCompleted ); } public void closeAllLocalSourceDocs(String caption, SourceColumn sourceColumn, Command onCompleted, final boolean excludeActive) { // save active editor for exclusion (it changes as we close tabs) final EditingTarget excludeEditor = (excludeActive) ? activeColumn_.getActiveEditor() : null; // collect up a list of dirty documents ArrayList<EditingTarget> dirtyTargets = new ArrayList<>(); // if sourceColumn is not provided, assume we are closing editors for every column if (sourceColumn == null) columnList_.forEach((column) -> dirtyTargets.addAll(column.getDirtyEditors(excludeEditor))); else dirtyTargets.addAll(sourceColumn.getDirtyEditors(excludeEditor)); // create a command used to close all tabs final Command closeAllTabsCommand = sourceColumn == null ? () -> closeAllTabs(excludeActive, false) : () -> closeAllTabs(sourceColumn, excludeActive, false); saveEditingTargetsWithPrompt(caption, dirtyTargets, CommandUtil.join(closeAllTabsCommand, onCompleted), null); } public ArrayList<String> consolidateColumns(int num) { ArrayList<String> removedColumns = new ArrayList<>(); if (num >= columnList_.size() || num < 1) return removedColumns; for (SourceColumn column : columnList_) { if (!column.hasDoc() && column.getName() != MAIN_SOURCE_NAME) { removedColumns.add(column.getName()); closeColumn(column.getName()); if (num >= columnList_.size() || num == 1) break; } } // if we could not remove empty columns to get to the desired amount, consolidate editors SourceColumn mainColumn = getByName(MAIN_SOURCE_NAME); if (num < columnList_.size()) { ArrayList<SourceColumn> moveColumns = new ArrayList<>(columnList_); moveColumns.remove(mainColumn); // remove columns from the end of the list first int additionalColumnCount = num - 1; if (num > 1 && moveColumns.size() != additionalColumnCount) moveColumns = new ArrayList<>( moveColumns.subList(additionalColumnCount - 1, moveColumns.size() - 1)); for (SourceColumn column : moveColumns) { ArrayList<EditingTarget> editors = column.getEditors(); for (EditingTarget target : editors) { if (!target.dirtyState().getValue()) { column.closeTab(target.asWidget(), false); continue; } server_.getSourceDocument(target.getId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(final SourceDocument doc) { mainColumn.addTab(doc, Source.OPEN_INTERACTIVE); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Document Tab Move Failed", "Couldn't move the tab to this window: \n" + error.getMessage()); } }); } removedColumns.add(column.getName()); closeColumn(column, true); } } columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); return removedColumns; } public void closeColumn(String name) { SourceColumn column = getByName(name); if (column.getTabCount() > 0) return; if (column == activeColumn_) setActive(MAIN_SOURCE_NAME); columnList_.remove(column); columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); } public void closeColumn(SourceColumn column, boolean force) { if (column.getTabCount() > 0) { if (!force) return; else { for (EditingTarget target : column.getEditors()) column.closeDoc(target.getId()); } } if (column == activeColumn_) setActive(MAIN_SOURCE_NAME); columnList_.remove(column); columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); } public void ensureVisible(boolean newTabPending) { if (getActive() == null) return; getActive().ensureVisible(newTabPending); } public void openFile(FileSystemItem file) { openFile(file, fileTypeRegistry_.getTextTypeForFile(file)); } public void openFile(FileSystemItem file, TextFileType fileType) { openFile(file, fileType, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { } }); } public void openFile(final FileSystemItem file, final TextFileType fileType, final CommandWithArg<EditingTarget> executeOnSuccess) { // add this work to the queue openFileQueue_.add(new OpenFileEntry(file, fileType, executeOnSuccess)); // begin queue processing if it's the only work in the queue if (openFileQueue_.size() == 1) processOpenFileQueue(); } private void editFile(final String path) { server_.ensureFileExists( path, new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean success) { if (success) { FileSystemItem file = FileSystemItem.createFile(path); openFile(file); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } public void openProjectDocs(final Session session, boolean mainColumn) { if (mainColumn && activeColumn_ != getByName(MAIN_SOURCE_NAME)) setActive(MAIN_SOURCE_NAME); JsArrayString openDocs = session.getSessionInfo().getProjectOpenDocs(); if (openDocs.length() > 0) { // set new tab pending for the duration of the continuation activeColumn_.incrementNewTabPending(); // create a continuation for opening the source docs SerializedCommandQueue openCommands = new SerializedCommandQueue(); for (int i = 0; i < openDocs.length(); i++) { String doc = openDocs.get(i); final FileSystemItem fsi = FileSystemItem.createFile(doc); openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(final Command continuation) { openFile(fsi, fileTypeRegistry_.getTextTypeForFile(fsi), new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { continuation.execute(); } }); } }); } // decrement newTabPending and select first tab when done openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { activeColumn_.decrementNewTabPending(); onFirstTab(); continuation.execute(); } }); // execute the continuation openCommands.run(); } } public void fireDocTabsChanged() { activeColumn_.fireDocTabsChanged(); } public void scrollToPosition(FilePosition position, boolean moveCursor) { // ensure we have an active source column getActive(); if (hasActiveEditor()) { SourcePosition srcPosition = SourcePosition.create( position.getLine() - 1, position.getColumn() - 1); activeColumn_.getActiveEditor().navigateToPosition( srcPosition, false, false, moveCursor, null); } } private boolean hasDoc() { for (SourceColumn column : columnList_) { if (column.hasDoc()) return true; } return false; } private void vimSetTabIndex(int index) { int tabCount = activeColumn_.getTabCount(); if (index >= tabCount) return; activeColumn_.setPhysicalTabIndex(index); } private void processOpenFileQueue() { // no work to do if (openFileQueue_.isEmpty()) return; // find the first work unit final OpenFileEntry entry = openFileQueue_.peek(); // define command to advance queue final Command processNextEntry = new Command() { @Override public void execute() { openFileQueue_.remove(); if (!openFileQueue_.isEmpty()) processOpenFileQueue(); } }; openFile( entry.file, entry.fileType, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { processNextEntry.execute(); if (entry.executeOnSuccess != null) entry.executeOnSuccess.execute(target); } @Override public void onCancelled() { super.onCancelled(); processNextEntry.execute(); } @Override public void onFailure(ServerError error) { String message = error.getUserMessage(); // see if a special message was provided JSONValue errValue = error.getClientInfo(); if (errValue != null) { JSONString errMsg = errValue.isString(); if (errMsg != null) message = errMsg.stringValue(); } globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening file", message); processNextEntry.execute(); } }); } public void openFile(FileSystemItem file, final ResultCallback<EditingTarget, ServerError> resultCallback) { openFile(file, fileTypeRegistry_.getTextTypeForFile(file), resultCallback); } // top-level wrapper for opening files. takes care of: // - making sure the view is visible // - checking whether it is already open and re-selecting its tab // - prohibit opening very large files (>500KB) // - confirmation of opening large files (>100KB) // - finally, actually opening the file from the server // via the call to the lower level openFile method public void openFile(final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { activeColumn_.ensureVisible(true); if (fileType.isRNotebook()) { openNotebook(file, resultCallback); return; } if (file == null) { newDoc(fileType, resultCallback); return; } if (openFileAlreadyOpen(file, resultCallback)) return; EditingTarget target = editingTargetSource_.getEditingTarget(fileType); if (file.getLength() > target.getFileSizeLimit()) { if (resultCallback != null) resultCallback.onCancelled(); showFileTooLargeWarning(file, target.getFileSizeLimit()); } else if (file.getLength() > target.getLargeFileSize()) { confirmOpenLargeFile(file, new Operation() { public void execute() { openFileFromServer(file, fileType, resultCallback); } }, new Operation() { public void execute() { // user (wisely) cancelled if (resultCallback != null) resultCallback.onCancelled(); } }); } else { openFileFromServer(file, fileType, resultCallback); } } public void openNotebook( final FileSystemItem rmdFile, final SourceDocumentResult doc, final ResultCallback<EditingTarget, ServerError> resultCallback) { if (!StringUtil.isNullOrEmpty(doc.getDocPath())) { // this happens if we created the R Markdown file, or if the R Markdown // file on disk matched the one inside the notebook openFileFromServer(rmdFile, FileTypeRegistry.RMARKDOWN, resultCallback); } else if (!StringUtil.isNullOrEmpty(doc.getDocId())) { // this happens when we have to open an untitled buffer for the the // notebook (usually because the of a conflict between the Rmd on disk // and the one in the .nb.html file) server_.getSourceDocument(doc.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(SourceDocument doc) { // create the editor EditingTarget target = getActive().addTab(doc, Source.OPEN_INTERACTIVE); // show a warning bar if (target instanceof TextEditingTarget) { ((TextEditingTarget) target).showWarningMessage( "This notebook has the same name as an R Markdown " + "file, but doesn't match it."); } resultCallback.onSuccess(target); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage( "Notebook Open Failed", "This notebook could not be opened. " + "If the error persists, try removing the " + "accompanying R Markdown file. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } } public void beforeShow(boolean excludeMain) { for (SourceColumn column : columnList_) { if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) column.onBeforeShow(); } } public void beforeShow(String name) { SourceColumn column = getByName(name); if (column == null) { Debug.logWarning("WARNING: Unknown column " + name); return; } column.onBeforeShow(); } public void inEditorForId(String id, OperationWithInput<EditingTarget> onEditorLocated) { EditingTarget editor = findEditor(id); if (editor != null) onEditorLocated.execute(editor); } public void inEditorForPath(String path, OperationWithInput<EditingTarget> onEditorLocated) { EditingTarget editor = findEditorByPath(path); if (editor != null) onEditorLocated.execute(editor); } public void withTarget(String id, CommandWithArg<TextEditingTarget> command) { withTarget(id, command, null); } public void withTarget(String id, CommandWithArg<TextEditingTarget> command, Command onFailure) { EditingTarget target = StringUtil.isNullOrEmpty(id) ? activeColumn_.getActiveEditor() : findEditor(id); if (target == null) { if (onFailure != null) onFailure.execute(); return; } if (!(target instanceof TextEditingTarget)) { if (onFailure != null) onFailure.execute(); return; } command.execute((TextEditingTarget) target); } public HashSet<AppCommand> getDynamicCommands() { return dynamicCommands_; } private void getEditorContext(String id, String path, DocDisplay docDisplay) { getEditorContext(id, path, docDisplay, server_); } public static void getEditorContext(String id, String path, DocDisplay docDisplay, SourceServerOperations server) { AceEditor editor = (AceEditor) docDisplay; Selection selection = editor.getNativeSelection(); Range[] ranges = selection.getAllRanges(); // clamp ranges to document boundaries for (Range range : ranges) { Position start = range.getStart(); start.setRow(MathUtil.clamp(start.getRow(), 0, editor.getRowCount())); start.setColumn(MathUtil.clamp(start.getColumn(), 0, editor.getLine(start.getRow()).length())); Position end = range.getEnd(); end.setRow(MathUtil.clamp(end.getRow(), 0, editor.getRowCount())); end.setColumn(MathUtil.clamp(end.getColumn(), 0, editor.getLine(end.getRow()).length())); } JsArray<GetEditorContextEvent.DocumentSelection> docSelections = JavaScriptObject.createArray().cast(); for (Range range : ranges) { docSelections.push(GetEditorContextEvent.DocumentSelection.create( range, editor.getTextForRange(range))); } id = StringUtil.notNull(id); path = StringUtil.notNull(path); GetEditorContextEvent.SelectionData data = GetEditorContextEvent.SelectionData.create(id, path, editor.getCode(), docSelections); server.getEditorContextCompleted(data, new VoidServerRequestCallback()); } private void initDynamicCommands() { dynamicCommands_ = new HashSet<>(); dynamicCommands_.add(commands_.saveSourceDoc()); dynamicCommands_.add(commands_.reopenSourceDocWithEncoding()); dynamicCommands_.add(commands_.saveSourceDocAs()); dynamicCommands_.add(commands_.saveSourceDocWithEncoding()); dynamicCommands_.add(commands_.printSourceDoc()); dynamicCommands_.add(commands_.vcsFileLog()); dynamicCommands_.add(commands_.vcsFileDiff()); dynamicCommands_.add(commands_.vcsFileRevert()); dynamicCommands_.add(commands_.executeCode()); dynamicCommands_.add(commands_.executeCodeWithoutFocus()); dynamicCommands_.add(commands_.executeAllCode()); dynamicCommands_.add(commands_.executeToCurrentLine()); dynamicCommands_.add(commands_.executeFromCurrentLine()); dynamicCommands_.add(commands_.executeCurrentFunction()); dynamicCommands_.add(commands_.executeCurrentSection()); dynamicCommands_.add(commands_.executeLastCode()); dynamicCommands_.add(commands_.insertChunk()); dynamicCommands_.add(commands_.insertSection()); dynamicCommands_.add(commands_.executeSetupChunk()); dynamicCommands_.add(commands_.executePreviousChunks()); dynamicCommands_.add(commands_.executeSubsequentChunks()); dynamicCommands_.add(commands_.executeCurrentChunk()); dynamicCommands_.add(commands_.executeNextChunk()); dynamicCommands_.add(commands_.previewJS()); dynamicCommands_.add(commands_.previewSql()); dynamicCommands_.add(commands_.sourceActiveDocument()); dynamicCommands_.add(commands_.sourceActiveDocumentWithEcho()); dynamicCommands_.add(commands_.knitDocument()); dynamicCommands_.add(commands_.toggleRmdVisualMode()); dynamicCommands_.add(commands_.enableProsemirrorDevTools()); dynamicCommands_.add(commands_.previewHTML()); dynamicCommands_.add(commands_.compilePDF()); dynamicCommands_.add(commands_.compileNotebook()); dynamicCommands_.add(commands_.synctexSearch()); dynamicCommands_.add(commands_.popoutDoc()); dynamicCommands_.add(commands_.returnDocToMain()); dynamicCommands_.add(commands_.findReplace()); dynamicCommands_.add(commands_.findNext()); dynamicCommands_.add(commands_.findPrevious()); dynamicCommands_.add(commands_.findFromSelection()); dynamicCommands_.add(commands_.replaceAndFind()); dynamicCommands_.add(commands_.extractFunction()); dynamicCommands_.add(commands_.extractLocalVariable()); dynamicCommands_.add(commands_.commentUncomment()); dynamicCommands_.add(commands_.reindent()); dynamicCommands_.add(commands_.reflowComment()); dynamicCommands_.add(commands_.jumpTo()); dynamicCommands_.add(commands_.jumpToMatching()); dynamicCommands_.add(commands_.goToHelp()); dynamicCommands_.add(commands_.goToDefinition()); dynamicCommands_.add(commands_.setWorkingDirToActiveDoc()); dynamicCommands_.add(commands_.debugDumpContents()); dynamicCommands_.add(commands_.debugImportDump()); dynamicCommands_.add(commands_.goToLine()); dynamicCommands_.add(commands_.checkSpelling()); dynamicCommands_.add(commands_.wordCount()); dynamicCommands_.add(commands_.codeCompletion()); dynamicCommands_.add(commands_.findUsages()); dynamicCommands_.add(commands_.debugBreakpoint()); dynamicCommands_.add(commands_.vcsViewOnGitHub()); dynamicCommands_.add(commands_.vcsBlameOnGitHub()); dynamicCommands_.add(commands_.editRmdFormatOptions()); dynamicCommands_.add(commands_.reformatCode()); dynamicCommands_.add(commands_.showDiagnosticsActiveDocument()); dynamicCommands_.add(commands_.renameInScope()); dynamicCommands_.add(commands_.insertRoxygenSkeleton()); dynamicCommands_.add(commands_.expandSelection()); dynamicCommands_.add(commands_.shrinkSelection()); dynamicCommands_.add(commands_.toggleDocumentOutline()); dynamicCommands_.add(commands_.knitWithParameters()); dynamicCommands_.add(commands_.clearKnitrCache()); dynamicCommands_.add(commands_.goToNextSection()); dynamicCommands_.add(commands_.goToPrevSection()); dynamicCommands_.add(commands_.goToNextChunk()); dynamicCommands_.add(commands_.goToPrevChunk()); dynamicCommands_.add(commands_.profileCode()); dynamicCommands_.add(commands_.profileCodeWithoutFocus()); dynamicCommands_.add(commands_.saveProfileAs()); dynamicCommands_.add(commands_.restartRClearOutput()); dynamicCommands_.add(commands_.restartRRunAllChunks()); dynamicCommands_.add(commands_.notebookCollapseAllOutput()); dynamicCommands_.add(commands_.notebookExpandAllOutput()); dynamicCommands_.add(commands_.notebookClearOutput()); dynamicCommands_.add(commands_.notebookClearAllOutput()); dynamicCommands_.add(commands_.notebookToggleExpansion()); dynamicCommands_.add(commands_.sendToTerminal()); dynamicCommands_.add(commands_.openNewTerminalAtEditorLocation()); dynamicCommands_.add(commands_.sendFilenameToTerminal()); dynamicCommands_.add(commands_.renameSourceDoc()); dynamicCommands_.add(commands_.sourceAsLauncherJob()); dynamicCommands_.add(commands_.sourceAsJob()); dynamicCommands_.add(commands_.runSelectionAsJob()); dynamicCommands_.add(commands_.runSelectionAsLauncherJob()); dynamicCommands_.add(commands_.toggleSoftWrapMode()); for (AppCommand command : dynamicCommands_) { command.setVisible(false); command.setEnabled(false); } } public void initVimCommands() { vimCommands_.save(this); vimCommands_.selectTabIndex(this); vimCommands_.selectNextTab(this); vimCommands_.selectPreviousTab(this); vimCommands_.closeActiveTab(this); vimCommands_.closeAllTabs(this); vimCommands_.createNewDocument(this); vimCommands_.saveAndCloseActiveTab(this); vimCommands_.readFile(this, userPrefs_.defaultEncoding().getValue()); vimCommands_.runRScript(this); vimCommands_.reflowText(this); vimCommands_.showVimHelp( RStudioGinjector.INSTANCE.getShortcutViewer()); vimCommands_.showHelpAtCursor(this); vimCommands_.reindent(this); vimCommands_.expandShrinkSelection(this); vimCommands_.openNextFile(this); vimCommands_.openPreviousFile(this); vimCommands_.addStarRegister(); } public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command String key = command.getId() + column.getName(); if (sourceAppCommands_.get(key) != null) return sourceAppCommands_.get(key); // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.put(key, sourceCommand); return sourceCommand; } private void openNotebook(final FileSystemItem rnbFile, final ResultCallback<EditingTarget, ServerError> resultCallback) { // construct path to .Rmd final String rnbPath = rnbFile.getPath(); final String rmdPath = FilePathUtils.filePathSansExtension(rnbPath) + ".Rmd"; final FileSystemItem rmdFile = FileSystemItem.createFile(rmdPath); // if we already have associated .Rmd file open, then just edit it // TODO: should we perform conflict resolution here as well? if (openFileAlreadyOpen(rmdFile, resultCallback)) return; // ask the server to extract the .Rmd, then open that Command extractRmdCommand = new Command() { @Override public void execute() { server_.extractRmdFromNotebook( rnbPath, new ServerRequestCallback<SourceDocumentResult>() { @Override public void onResponseReceived(SourceDocumentResult doc) { openNotebook(rmdFile, doc, resultCallback); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Notebook Open Failed", "This notebook could not be opened. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } }; dependencyManager_.withRMarkdown("R Notebook", "Using R Notebooks", extractRmdCommand); } private void openFileFromServer( final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { final Command dismissProgress = globalDisplay_.showProgress( "Opening file..."); server_.openDocument( file.getPath(), fileType.getTypeId(), userPrefs_.defaultEncoding().getValue(), new ServerRequestCallback<SourceDocument>() { @Override public void onError(ServerError error) { dismissProgress.execute(); pMruList_.get().remove(file.getPath()); Debug.logError(error); if (resultCallback != null) resultCallback.onFailure(error); } @Override public void onResponseReceived(SourceDocument document) { // apply (dynamic) doc property defaults SourceColumn.applyDocPropertyDefaults(document, false, userPrefs_); // if we are opening for a source navigation then we // need to force Rmds into source mode if (openingForSourceNavigation_) { document.getProperties().setString( TextEditingTarget.RMD_VISUAL_MODE, DocUpdateSentinel.PROPERTY_FALSE ); } dismissProgress.execute(); pMruList_.get().add(document.getPath()); EditingTarget target = getActive().addTab(document, Source.OPEN_INTERACTIVE); if (resultCallback != null) resultCallback.onSuccess(target); } }); } private boolean openFileAlreadyOpen(final FileSystemItem file, final ResultCallback<EditingTarget, ServerError> resultCallback) { for (SourceColumn column : columnList_) { // check to see if any local editors have the file open for (int i = 0; i < column.getEditors().size(); i++) { EditingTarget target = column.getEditors().get(i); String thisPath = target.getPath(); if (thisPath != null && thisPath.equalsIgnoreCase(file.getPath())) { column.selectTab(target.asWidget()); pMruList_.get().add(thisPath); if (resultCallback != null) resultCallback.onSuccess(target); return true; } } } return false; } private void showFileTooLargeWarning(FileSystemItem file, long sizeLimit) { StringBuilder msg = new StringBuilder(); msg.append("The file '" + file.getName() + "' is too "); msg.append("large to open in the source editor (the file is "); msg.append(StringUtil.formatFileSize(file.getLength()) + " and the "); msg.append("maximum file size is "); msg.append(StringUtil.formatFileSize(sizeLimit) + ")"); globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING, "Selected File Too Large", msg.toString()); } private void confirmOpenLargeFile(FileSystemItem file, Operation openOperation, Operation noOperation) { StringBuilder msg = new StringBuilder(); msg.append("The source file '" + file.getName() + "' is large ("); msg.append(StringUtil.formatFileSize(file.getLength()) + ") "); msg.append("and may take some time to open. "); msg.append("Are you sure you want to continue opening it?"); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Confirm Open", msg.toString(), false, // Don't include cancel openOperation, noOperation, false); // 'No' is default } private void saveEditingTargetsWithPrompt( String title, ArrayList<EditingTarget> editingTargets, final Command onCompleted, final Command onCancelled) { // execute on completed right away if the list is empty if (editingTargets.size() == 0) { onCompleted.execute(); } // if there is just one thing dirty then go straight to the save dialog else if (editingTargets.size() == 1) { editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled); } // otherwise use the multi save changes dialog else { // convert to UnsavedChangesTarget collection ArrayList<UnsavedChangesTarget> unsavedTargets = new ArrayList<>(editingTargets); // show dialog showUnsavedChangesDialog( title, unsavedTargets, new OperationWithInput<UnsavedChangesDialog.Result>() { @Override public void execute(UnsavedChangesDialog.Result result) { saveChanges(result.getSaveTargets(), onCompleted); } }, onCancelled); } } public ArrayList<UnsavedChangesTarget> getUnsavedChanges(int type, Set<String> ids) { ArrayList<UnsavedChangesTarget> targets = new ArrayList<>(); columnList_.forEach((column) -> targets.addAll(column.getUnsavedEditors(type, ids))); return targets; } public void saveChanges(ArrayList<UnsavedChangesTarget> targets, Command onCompleted) { // convert back to editing targets ArrayList<EditingTarget> saveTargets = new ArrayList<>(); for (UnsavedChangesTarget target: targets) { EditingTarget saveTarget = findEditor(target.getId()); if (saveTarget != null) saveTargets.add(saveTarget); } CPSEditingTargetCommand saveCommand = new CPSEditingTargetCommand() { @Override public void execute(EditingTarget saveTarget, Command continuation) { saveTarget.save(continuation); } }; // execute the save cpsExecuteForEachEditor( // targets the user chose to save saveTargets, // save each editor saveCommand, // onCompleted at the end onCompleted ); } private void pasteFileContentsAtCursor(final String path, final String encoding) { if (activeColumn_ == null) return; EditingTarget activeEditor = activeColumn_.getActiveEditor(); if (activeEditor instanceof TextEditingTarget) { final TextEditingTarget target = (TextEditingTarget) activeEditor; server_.getFileContents(path, encoding, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String content) { target.insertCode(content, false); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } } private void pasteRCodeExecutionResult(final String code) { server_.executeRCode(code, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String output) { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.insertCode(output, false); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void reflowText() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.reflowText(); } } private void reindent() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.getDocDisplay().reindent(); } } private void saveActiveSourceDoc() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeColumn_.getActiveEditor(); target.save(); } } private void saveAndCloseActiveSourceDoc() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeColumn_.getActiveEditor(); target.save(new Command() { @Override public void execute() { onCloseSourceDoc(); } }); } } private void revertActiveDocument() { if (!hasActiveEditor()) return; if (activeColumn_.getActiveEditor().getPath() != null) activeColumn_.getActiveEditor().revertChanges(null); // Ensure that the document is in view activeColumn_.getActiveEditor().ensureCursorVisible(); } private void showHelpAtCursor() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.showHelpAtCursor(); } } /** * Execute the given command for each editor, using continuation-passing * style. When executed, the CPSEditingTargetCommand needs to execute its * own Command parameter to continue the iteration. * @param command The command to run on each EditingTarget */ private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command, final Command completedCommand) { SerializedCommandQueue queue = new SerializedCommandQueue(); // Clone editors_, since the original may be mutated during iteration for (final EditingTarget editor : new ArrayList<>(editors)) { queue.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { command.execute(editor, continuation); } }); } if (completedCommand != null) { queue.addCommand(new SerializedCommand() { public void onExecute(Command continuation) { completedCommand.execute(); continuation.execute(); } }); } } public SourceColumn getByName(String name) { for (SourceColumn column : columnList_) { if (StringUtil.equals(column.getName(), name)) return column; } return null; } private boolean contains(String name) { for (SourceColumn column : columnList_) { if (StringUtil.equals(column.getName(), name)) return true; } return false; } private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command) { cpsExecuteForEachEditor(editors, command, null); } private static class OpenFileEntry { public OpenFileEntry(FileSystemItem fileIn, TextFileType fileTypeIn, CommandWithArg<EditingTarget> executeIn) { file = fileIn; fileType = fileTypeIn; executeOnSuccess = executeIn; } public final FileSystemItem file; public final TextFileType fileType; public final CommandWithArg<EditingTarget> executeOnSuccess; } private State columnState_; private SourceColumn activeColumn_; private boolean openingForSourceNavigation_ = false; private boolean docsRestored_ = false; private final Queue<OpenFileEntry> openFileQueue_ = new LinkedList<>(); private final ArrayList<SourceColumn> columnList_ = new ArrayList<>(); private HashSet<AppCommand> dynamicCommands_ = new HashSet<>(); private HashMap<String, SourceAppCommand> sourceAppCommands_ = new HashMap<>(); private SourceVimCommands vimCommands_; private Commands commands_; private EventBus events_; private Provider<FileMRUList> pMruList_; private SourceWindowManager windowManager_; private Session session_; private Synctex synctex_; private UserPrefs userPrefs_; private UserState userState_; private GlobalDisplay globalDisplay_; private TextEditingTargetRMarkdownHelper rmarkdown_; private EditingTargetSource editingTargetSource_; private FileTypeRegistry fileTypeRegistry_; private SourceServerOperations server_; private DependencyManager dependencyManager_; private final SourceNavigationHistory sourceNavigationHistory_ = new SourceNavigationHistory(30); public final static String COLUMN_PREFIX = "Source"; public final static String MAIN_SOURCE_NAME = COLUMN_PREFIX; }
src/gwt/src/org/rstudio/studio/client/workbench/views/source/SourceColumnManager.java
/* * SourceColumnManager.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.dom.client.Element; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import org.rstudio.core.client.*; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.js.JsUtil; import org.rstudio.core.client.widget.ModalDialogBase; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.OperationWithInput; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.FilePathUtils; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.dependencies.DependencyManager; import org.rstudio.studio.client.common.filetypes.*; import org.rstudio.studio.client.common.synctex.Synctex; import org.rstudio.studio.client.events.GetEditorContextEvent; import org.rstudio.studio.client.palette.model.CommandPaletteEntrySource; import org.rstudio.studio.client.palette.model.CommandPaletteItem; import org.rstudio.studio.client.rmarkdown.model.RmdChosenTemplate; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter; import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat; import org.rstudio.studio.client.rmarkdown.model.RmdTemplateData; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.FileMRUList; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.ClientState; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.UnsavedChangesTarget; import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue; import org.rstudio.studio.client.workbench.prefs.model.UserPrefs; import org.rstudio.studio.client.workbench.prefs.model.UserState; import org.rstudio.studio.client.workbench.ui.PaneConfig; import org.rstudio.studio.client.workbench.ui.unsaved.UnsavedChangesDialog; import org.rstudio.studio.client.workbench.views.environment.events.DebugModeChangedEvent; import org.rstudio.studio.client.workbench.views.output.find.events.FindInFilesEvent; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource; import org.rstudio.studio.client.workbench.views.source.editors.codebrowser.CodeBrowserEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.ObjectExplorerEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.explorer.model.ObjectExplorerHandle; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Selection; import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditingTargetSelectedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRMarkdownDialog; import org.rstudio.studio.client.workbench.views.source.events.*; import org.rstudio.studio.client.workbench.views.source.model.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @Singleton public class SourceColumnManager implements CommandPaletteEntrySource, SourceExtendedTypeDetectedEvent.Handler, DebugModeChangedEvent.Handler { public interface CPSEditingTargetCommand { void execute(EditingTarget editingTarget, Command continuation); } public static class State extends JavaScriptObject { public static native State createState(JsArrayString names, String activeColumn) /*-{ return { names: names, activeColumn: activeColumn } }-*/; protected State() {} public final String[] getNames() { return JsUtil.toStringArray(getNamesNative()); } public final native String getActiveColumn() /*-{ return this.activeColumn || ""; }-*/; private native JsArrayString getNamesNative() /*-{ return this.names; }-*/; } interface Binder extends CommandBinder<Commands, SourceColumnManager> { } SourceColumnManager() { RStudioGinjector.INSTANCE.injectMembers(this);} @Inject public SourceColumnManager(Binder binder, Source.Display display, SourceServerOperations server, GlobalDisplay globalDisplay, Commands commands, EditingTargetSource editingTargetSource, FileTypeRegistry fileTypeRegistry, EventBus events, DependencyManager dependencyManager, final Session session, Synctex synctex, UserPrefs userPrefs, UserState userState, Provider<FileMRUList> pMruList, SourceWindowManager windowManager) { commands_ = commands; binder.bind(commands_, this); server_ = server; globalDisplay_ = globalDisplay; editingTargetSource_ = editingTargetSource; fileTypeRegistry_ = fileTypeRegistry; events_ = events; dependencyManager_ = dependencyManager; session_ = session; synctex_ = synctex; userPrefs_ = userPrefs; userState_ = userState; pMruList_ = pMruList; windowManager_ = windowManager; rmarkdown_ = new TextEditingTargetRMarkdownHelper(); vimCommands_ = new SourceVimCommands(); columnState_ = null; initDynamicCommands(); events_.addHandler(SourceExtendedTypeDetectedEvent.TYPE, this); events_.addHandler(DebugModeChangedEvent.TYPE, this); events_.addHandler(EditingTargetSelectedEvent.TYPE, new EditingTargetSelectedEvent.Handler() { @Override public void onEditingTargetSelected(EditingTargetSelectedEvent event) { setActive(event.getTarget()); } }); events_.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler() { public void onSourceFileSaved(SourceFileSavedEvent event) { pMruList_.get().add(event.getPath()); } }); events_.addHandler(DocTabActivatedEvent.TYPE, new DocTabActivatedEvent.Handler() { public void onDocTabActivated(DocTabActivatedEvent event) { setActiveDocId(event.getId()); } }); events_.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler() { public void onSwitchToDoc(SwitchToDocEvent event) { ensureVisible(false); activeColumn_.setPhysicalTabIndex(event.getSelectedIndex()); // Fire an activation event just to ensure the activated // tab gets focus commands_.activateSource().execute(); } }); sourceNavigationHistory_.addChangeHandler(event -> manageSourceNavigationCommands()); SourceColumn column = GWT.create(SourceColumn.class); column.loadDisplay(MAIN_SOURCE_NAME, display, this); columnList_.add(column); new JSObjectStateValue("source-column-manager", "column-info", ClientState.PERSISTENT, session_.getSessionInfo().getClientState(), false) { @Override protected void onInit(JsObject value) { if (!userPrefs_.allowSourceColumns().getGlobalValue()) { if (columnList_.size() > 1) { PaneConfig paneConfig = userPrefs_.panes().getValue().cast(); userPrefs_.panes().setGlobalValue(PaneConfig.create( JsArrayUtil.copy(paneConfig.getQuadrants()), paneConfig.getTabSet1(), paneConfig.getTabSet2(), paneConfig.getHiddenTabSet(), paneConfig.getConsoleLeftOnTop(), paneConfig.getConsoleRightOnTop(), 0).cast()); consolidateColumns(1); } return; } if (value == null) { // default to main column name here because we haven't loaded any columns yet columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), MAIN_SOURCE_NAME); return; } State state = value.cast(); for (int i = 0; i < state.getNames().length; i++) { String name = state.getNames()[i]; if (!StringUtil.equals(name, MAIN_SOURCE_NAME)) add(name, false); } } @Override protected JsObject getValue() { return columnState_.cast(); } }; setActive(column.getName()); // register custom focus handler for case where ProseMirror // instance (or element within) had focus ModalDialogBase.registerReturnFocusHandler((Element el) -> { final String sourceClass = ClassIds.getClassId(ClassIds.SOURCE_PANEL); Element sourceEl = DomUtils.findParentElement(el, (Element parent) -> { return parent.hasClassName(sourceClass); }); if (sourceEl != null) { commands_.activateSource().execute(); return true; } return false; }); } public String add() { Source.Display display = GWT.create(SourcePane.class); return add(display, false); } public String add(Source.Display display) { return add(display, false); } public String add(String name, boolean updateState) { return add(name, false, updateState); } public String add (String name, boolean activate, boolean updateState) { Source.Display display = GWT.create(SourcePane.class); return add(name, display, activate, updateState); } public String add(Source.Display display, boolean activate) { return add(display, activate, true); } public String add(Source.Display display, boolean activate, boolean updateState) { return add(COLUMN_PREFIX + StringUtil.makeRandomId(12), display, activate, updateState); } public String add(String name, Source.Display display, boolean activate, boolean updateState) { if (contains(name)) return ""; SourceColumn column = GWT.create(SourceColumn.class); column.loadDisplay(name, display, this); columnList_.add(column); if (activate || activeColumn_ == null) setActive(column); if (updateState) columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); return column.getName(); } public void initialSelect(int index) { SourceColumn lastActive = getByName(columnState_.getActiveColumn()); if (lastActive != null) setActive(getByName(columnState_.getActiveColumn())); getActive().initialSelect(index); } public void setActive(int xpos) { SourceColumn column = findByPosition(xpos); if (column == null) return; setActive(column); } public void setActive(String name) { if (StringUtil.isNullOrEmpty(name) && activeColumn_ != null) { if (hasActiveEditor()) activeColumn_.setActiveEditor(""); activeColumn_ = null; return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); } private void setActive(EditingTarget target) { setActive(findByDocument(target.getId())); activeColumn_.setActiveEditor(target); } public void setActive(SourceColumn column) { SourceColumn prevColumn = activeColumn_; activeColumn_ = column; // If the active column changed, we need to update the active editor if (prevColumn != null && prevColumn != activeColumn_) { prevColumn.setActiveEditor(""); if (!hasActiveEditor()) activeColumn_.setActiveEditor(); manageCommands(true); } columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), activeColumn_ == null ? "" : activeColumn_.getName()); } private void setActiveDocId(String docId) { if (StringUtil.isNullOrEmpty(docId)) return; for (SourceColumn column : columnList_) { EditingTarget target = column.setActiveEditor(docId); if (target != null) { setActive(target); return; } } } public void setDocsRestored() { docsRestored_ = true; } public void setOpeningForSourceNavigation(boolean value) { openingForSourceNavigation_ = value; } public void activateColumn(String name, final Command afterActivation) { if (!StringUtil.isNullOrEmpty(name)) setActive(getByName(name)); if (!hasActiveEditor()) { if (activeColumn_ == null) setActive(MAIN_SOURCE_NAME); newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { setActive(target); doActivateSource(afterActivation); } }); } else { doActivateSource(afterActivation); } } public String getLeftColumnName() { return columnList_.get(columnList_.size() - 1).getName(); } public String getNextColumnName() { int index = columnList_.indexOf(getActive()); if (index < 1) return ""; else return columnList_.get(index - 1).getName(); } public String getPreviousColumnName() { int index = columnList_.indexOf(getActive()); if (index == getSize() - 1) return ""; else return columnList_.get(index + 1).getName(); } // This method sets activeColumn_ to the main column if it is null. It should be used in cases // where it is better for the column to be the main column than null. public SourceColumn getActive() { if (activeColumn_ != null && (!columnList_.get(0).asWidget().isAttached() || activeColumn_.asWidget().isAttached() && activeColumn_.asWidget().getOffsetWidth() > 0)) return activeColumn_; setActive(MAIN_SOURCE_NAME); return activeColumn_; } public String getActiveDocId() { if (hasActiveEditor()) return activeColumn_.getActiveEditor().getId(); return null; } public String getActiveDocPath() { if (hasActiveEditor()) return activeColumn_.getActiveEditor().getPath(); return null; } public boolean hasActiveEditor() { return activeColumn_ != null && activeColumn_.getActiveEditor() != null; } public boolean isActiveEditor(EditingTarget editingTarget) { return hasActiveEditor() && activeColumn_.getActiveEditor() == editingTarget; } public boolean getDocsRestored() { return docsRestored_; } // see if there are additional command palette items made available // by the active editor public List<CommandPaletteItem> getCommandPaletteItems() { if (!hasActiveEditor()) return null; return activeColumn_.getActiveEditor().getCommandPaletteItems(); } public int getTabCount() { return getActive().getTabCount(); } public int getPhysicalTabIndex() { if (getActive() != null) return getActive().getPhysicalTabIndex(); else return -1; } public ArrayList<String> getNames(boolean excludeMain) { ArrayList<String> result = new ArrayList<>(); columnList_.forEach((column) ->{ if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) result.add(column.getName()); }); return result; } public ArrayList<Widget> getWidgets(boolean excludeMain) { ArrayList<Widget> result = new ArrayList<>(); for (SourceColumn column : columnList_) { if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) result.add(column.asWidget()); } return result; } public ArrayList<SourceColumn> getColumnList() { return columnList_; } public Element getActiveElement() { if (activeColumn_ == null) return null; return activeColumn_.asWidget().getElement(); } public Widget getWidget(String name) { return getByName(name) == null ? null : getByName(name).asWidget(); } public Session getSession() { return session_; } public SourceNavigationHistory getSourceNavigationHistory() { return sourceNavigationHistory_; } public void recordCurrentNavigationHistoryPosition() { if (hasActiveEditor()) activeColumn_.getActiveEditor().recordCurrentNavigationPosition(); } public String getEditorPositionString() { if (hasActiveEditor()) return activeColumn_.getActiveEditor().getCurrentStatus(); return "No document tabs open"; } public Synctex getSynctex() { return synctex_; } public UserState getUserState() { return userState_; } public int getSize() { return columnList_.size(); } public SourceColumn get(int index) { if (index >= columnList_.size()) return null; return columnList_.get(index); } public int getUntitledNum(String prefix) { AtomicInteger max = new AtomicInteger(); columnList_.forEach((column) -> max.set(Math.max(max.get(), column.getUntitledNum(prefix)))); return max.intValue(); } public native final int getUntitledNum(String name, String prefix) /*-{ var match = (new RegExp("^" + prefix + "([0-9]{1,5})$")).exec(name); if (!match) return 0; return parseInt(match[1]); }-*/; public void clearSourceNavigationHistory() { if (!hasDoc()) sourceNavigationHistory_.clear(); } public void manageCommands(boolean forceSync) { boolean saveAllEnabled = false; for (SourceColumn column : columnList_) { if (column.isInitialized() && !StringUtil.equals(getActive().getName(), column.getName())) column.manageCommands(forceSync, activeColumn_); // if one document is dirty then we are enabled if (!saveAllEnabled && column.isSaveCommandActive()) saveAllEnabled = true; } // the active column is always managed last because any column can disable a command, but // only the active one can enable a command if (activeColumn_.isInitialized()) activeColumn_.manageCommands(forceSync, activeColumn_); if (!session_.getSessionInfo().getAllowShell()) commands_.sendToTerminal().setVisible(false); // if source windows are open, managing state of the command becomes // complicated, so leave it enabled if (windowManager_.areSourceWindowsOpen()) commands_.saveAllSourceDocs().setEnabled(saveAllEnabled); if (activeColumn_ != null && !StringUtil.equals(activeColumn_.getName(), MAIN_SOURCE_NAME)) commands_.focusSourceColumnSeparator().setEnabled(true); else commands_.focusSourceColumnSeparator().setEnabled(false); manageSourceNavigationCommands(); } private void manageSourceNavigationCommands() { commands_.sourceNavigateBack().setEnabled( sourceNavigationHistory_.isBackEnabled()); commands_.sourceNavigateForward().setEnabled( sourceNavigationHistory_.isForwardEnabled()); } public EditingTarget addTab(SourceDocument doc, int mode, SourceColumn column) { if (column == null) column = getActive(); return column.addTab(doc, mode); } public EditingTarget addTab(SourceDocument doc, boolean atEnd, int mode, SourceColumn column) { if (column == null || getByName(column.getName()) == null) column = getActive(); return column.addTab(doc, atEnd, mode); } public EditingTarget findEditor(String docId) { for (SourceColumn column : columnList_) { EditingTarget target = column.getDoc(docId); if (target != null) return target; } return null; } public EditingTarget findEditorByPath(String path) { if (StringUtil.isNullOrEmpty(path)) return null; for (SourceColumn column : columnList_) { EditingTarget target = column.getEditorWithPath(path); if (target != null) return target; } return null; } public SourceColumn findByDocument(String docId) { for (SourceColumn column : columnList_) { if (column.hasDoc(docId)) return column; } return null; } public SourceColumn findByPosition(int x) { for (SourceColumn column : columnList_) { Widget w = column.asWidget(); int left = w.getAbsoluteLeft(); int right = w.getAbsoluteLeft() + w.getOffsetWidth(); if (x >= left && x <= right) return column; } return null; } public boolean isEmpty(String name) { return getByName(name) == null || getByName(name).getTabCount() == 0; } public boolean attemptTextEditorActivate() { if (!(hasActiveEditor() || activeColumn_.getActiveEditor() instanceof TextEditingTarget)) return false; TextEditingTarget editingTarget = (TextEditingTarget) activeColumn_.getActiveEditor(); editingTarget.ensureTextEditorActive(() -> { getEditorContext( editingTarget.getId(), editingTarget.getPath(), editingTarget.getDocDisplay() ); }); return true; } public void activateCodeBrowser( final String codeBrowserPath, boolean replaceIfActive, final ResultCallback<CodeBrowserEditingTarget, ServerError> callback) { // first check to see if this request can be fulfilled with an existing // code browser tab EditingTarget target = selectTabWithDocPath(codeBrowserPath); if (target != null) { callback.onSuccess((CodeBrowserEditingTarget) target); return; } // then check to see if the active editor is a code browser -- if it is, // we'll use it as is, replacing its contents if (replaceIfActive && hasActiveEditor() && activeColumn_.getActiveEditor() instanceof CodeBrowserEditingTarget) { events_.fireEvent(new CodeBrowserCreatedEvent(activeColumn_.getActiveEditor().getId(), codeBrowserPath)); callback.onSuccess((CodeBrowserEditingTarget) activeColumn_.getActiveEditor()); return; } // create a new one newDoc(FileTypeRegistry.CODEBROWSER, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget arg) { events_.fireEvent(new CodeBrowserCreatedEvent( arg.getId(), codeBrowserPath)); callback.onSuccess((CodeBrowserEditingTarget) arg); } @Override public void onFailure(ServerError error) { callback.onFailure(error); } @Override public void onCancelled() { callback.onCancelled(); } }); } public void activateObjectExplorer(ObjectExplorerHandle handle) { columnList_.forEach((column) -> { for (EditingTarget target : column.getEditors()) { // bail if this isn't an object explorer filetype FileType fileType = target.getFileType(); if (!(fileType instanceof ObjectExplorerFileType)) continue; // check for identical titles if (handle.getTitle() == target.getTitle()) { ((ObjectExplorerEditingTarget) target).update(handle); ensureVisible(false); column.selectTab(target.asWidget()); return; } } }); ensureVisible(true); server_.newDocument( FileTypeRegistry.OBJECT_EXPLORER.getTypeId(), null, (JsObject) handle.cast(), new SimpleRequestCallback<SourceDocument>("Show Object Explorer") { @Override public void onResponseReceived(SourceDocument response) { getActive().addTab(response, Source.OPEN_INTERACTIVE); } }); } public void showOverflowPopout() { ensureVisible(false); getActive().showOverflowPopout(); } public void showDataItem(DataItem data) { columnList_.forEach((column) -> { for (EditingTarget target : column.getEditors()) { String path = target.getPath(); if (path != null && path.equals(data.getURI())) { ((DataEditingTarget) target).updateData(data); ensureVisible(false); column.selectTab(target.asWidget()); return; } } }); ensureVisible(true); server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), null, (JsObject) data.cast(), new SimpleRequestCallback<SourceDocument>("Show Data Frame") { @Override public void onResponseReceived(SourceDocument response) { getActive().addTab(response, Source.OPEN_INTERACTIVE); } }); } public void showUnsavedChangesDialog( String title, ArrayList<UnsavedChangesTarget> dirtyTargets, OperationWithInput<UnsavedChangesDialog.Result> saveOperation, Command onCancelled) { getActive().showUnsavedChangesDialog(title, dirtyTargets, saveOperation, onCancelled); } public boolean insertSource(String code, boolean isBlock) { if (!hasActiveEditor()) return false; return getActive().insertCode(code, isBlock); } @Handler public void onMoveTabRight() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), 1); } @Handler public void onMoveTabLeft() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), -1); } @Handler public void onMoveTabToFirst() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), activeColumn_.getPhysicalTabIndex() * -1); } @Handler public void onMoveTabToLast() { getActive().moveTab(activeColumn_.getPhysicalTabIndex(), (activeColumn_.getTabCount() - activeColumn_.getPhysicalTabIndex()) - 1); } @Handler public void onSwitchToTab() { if (getActive().getTabCount() == 0) return; showOverflowPopout(); } @Handler public void onFirstTab() { if (getActive().getTabCount() == 0) return; ensureVisible(false); if (getActive().getTabCount() > 0) getActive().setPhysicalTabIndex(0); } @Handler public void onPreviousTab() { switchToTab(-1, userPrefs_.wrapTabNavigation().getValue()); } @Handler public void onNextTab() { switchToTab(1, userPrefs_.wrapTabNavigation().getValue()); } @Handler public void onLastTab() { if (getActive().getTabCount() == 0) return; activeColumn_.ensureVisible(false); if (activeColumn_.getTabCount() > 0) activeColumn_.setPhysicalTabIndex(activeColumn_.getTabCount() - 1); } @Handler public void onCloseSourceDoc() { closeSourceDoc(true); } @Handler public void onFindInFiles() { String searchPattern = ""; if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget textEditor = (TextEditingTarget) activeColumn_.getActiveEditor(); String selection = textEditor.getSelectedText(); boolean multiLineSelection = selection.indexOf('\n') != -1; if ((selection.length() != 0) && !multiLineSelection) searchPattern = selection; } events_.fireEvent(new FindInFilesEvent(searchPattern)); } @Override public void onDebugModeChanged(DebugModeChangedEvent evt) { // when debugging ends, always disengage any active debug highlights if (!evt.debugging() && hasActiveEditor()) { activeColumn_.getActiveEditor().endDebugHighlighting(); } } @Override public void onSourceExtendedTypeDetected(SourceExtendedTypeDetectedEvent e) { // set the extended type of the specified source file EditingTarget target = findEditor(e.getDocId()); if (target != null) target.adaptToExtendedFileType(e.getExtendedType()); } public void nextTabWithWrap() { switchToTab(1, true); } public void prevTabWithWrap() { switchToTab(-1, true); } private void switchToTab(int delta, boolean wrap) { if (getActive().getTabCount() == 0) return; activeColumn_.ensureVisible(false); int targetIndex = activeColumn_.getPhysicalTabIndex() + delta; if (targetIndex > (activeColumn_.getTabCount() - 1)) { if (wrap) targetIndex = 0; else return; } else if (targetIndex < 0) { if (wrap) targetIndex = activeColumn_.getTabCount() - 1; else return; } activeColumn_.setPhysicalTabIndex(targetIndex); } private void doActivateSource(final Command afterActivation) { getActive().ensureVisible(false); if (hasActiveEditor()) { activeColumn_.getActiveEditor().focus(); activeColumn_.getActiveEditor().ensureCursorVisible(); } if (afterActivation != null) afterActivation.execute(); } // new doc functions public void newRMarkdownV1Doc() { newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "v1.Rmd", Position.create(3, 0)); } public void newRMarkdownV2Doc() { rmarkdown_.showNewRMarkdownDialog( new OperationWithInput<NewRMarkdownDialog.Result>() { @Override public void execute(final NewRMarkdownDialog.Result result) { if (result == null) { // No document chosen, just create an empty one newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "default.Rmd"); } else if (result.isNewDocument()) { NewRMarkdownDialog.RmdNewDocument doc = result.getNewDocument(); String author = doc.getAuthor(); if (author.length() > 0) { userPrefs_.documentAuthor().setGlobalValue(author); userPrefs_.writeUserPrefs(); } newRMarkdownV2Doc(doc); } else { newDocFromRmdTemplate(result); } } }); } private void newDocFromRmdTemplate(final NewRMarkdownDialog.Result result) { final RmdChosenTemplate template = result.getFromTemplate(); if (template.createDir()) { rmarkdown_.createDraftFromTemplate(template); return; } rmarkdown_.getTemplateContent(template, new OperationWithInput<String>() { @Override public void execute(final String content) { if (content.length() == 0) globalDisplay_.showErrorMessage("Template Content Missing", "The template at " + template.getTemplatePath() + " is missing."); newDoc(FileTypeRegistry.RMARKDOWN, content, null); } }); } private void newRMarkdownV2Doc( final NewRMarkdownDialog.RmdNewDocument doc) { rmarkdown_.frontMatterToYAML((RmdFrontMatter) doc.getJSOResult().cast(), null, new CommandWithArg<String>() { @Override public void execute(final String yaml) { String template = ""; // select a template appropriate to the document type we're creating if (doc.getTemplate().equals(RmdTemplateData.PRESENTATION_TEMPLATE)) template = "presentation.Rmd"; else if (doc.isShiny()) { if (doc.getFormat().endsWith( RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX)) template = "shiny_presentation.Rmd"; else template = "shiny.Rmd"; } else template = "document.Rmd"; newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", template, Position.create(1, 0), null, new TransformerCommand<String>() { @Override public String transform(String input) { return RmdFrontMatter.FRONTMATTER_SEPARATOR + yaml + RmdFrontMatter.FRONTMATTER_SEPARATOR + "\n" + input; } }); } }); } public void newSourceDocWithTemplate(final TextFileType fileType, String name, String template) { newSourceDocWithTemplate(fileType, name, template, null); } public void newSourceDocWithTemplate(final TextFileType fileType, String name, String template, final Position cursorPosition) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, null); } public void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess) { newSourceDocWithTemplate(fileType, name, template, cursorPosition, onSuccess, null); } public void startDebug() { getActive().setPendingDebugSelection(); } private EditingTarget selectTabWithDocPath(String path) { for (SourceColumn column : columnList_) { EditingTarget editor = column.getEditorWithPath(path); if (editor != null) { column.selectTab(editor.asWidget()); return editor; } } return null; } private void newSourceDocWithTemplate( final TextFileType fileType, String name, String template, final Position cursorPosition, final CommandWithArg<EditingTarget> onSuccess, final TransformerCommand<String> contentTransformer) { final ProgressIndicator indicator = new GlobalProgressDelayer( globalDisplay_, 500, "Creating new document...").getIndicator(); server_.getSourceTemplate(name, template, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String templateContents) { indicator.onCompleted(); if (contentTransformer != null) templateContents = contentTransformer.transform(templateContents); newDoc(fileType, templateContents, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { if (cursorPosition != null) target.setCursorPosition(cursorPosition); if (onSuccess != null) onSuccess.execute(target); } }); } @Override public void onError(ServerError error) { indicator.onError(error.getUserMessage()); } }); } public void newDoc(EditableFileType fileType, ResultCallback<EditingTarget, ServerError> callback) { getActive().newDoc(fileType, callback); } public void newDoc(EditableFileType fileType, final String contents, final ResultCallback<EditingTarget, ServerError> resultCallback) { getActive().newDoc(fileType, contents, resultCallback); } public void disownDoc(String docId) { SourceColumn column = findByDocument(docId); column.closeDoc(docId); } // When dragging between columns/windows, we need to be specific about which column we're // removing the document from as it may exist in more than one column. If the column is null, // it is assumed that we are a satellite window and do not have multiple displays. public void disownDocOnDrag(String docId, SourceColumn column) { if (column == null) { if (getSize() > 1) Debug.logWarning("Warning: No column was provided to remove the doc from."); column = getActive(); } column.closeDoc(docId); column.cancelTabDrag(); } public void selectTab(EditingTarget target) { SourceColumn column = findByDocument(target.getId()); column.ensureVisible(false); column.selectTab(target.asWidget()); } public void closeTabs(JsArrayString ids) { if (ids != null) columnList_.forEach((column) -> column.closeTabs(ids)); } public void closeTabWithPath(String path, boolean interactive) { EditingTarget target = findEditorByPath(path); closeTab(target, interactive); } public void closeTab(boolean interactive) { if (hasActiveEditor()) closeTab(activeColumn_.getActiveEditor(), interactive); } public void closeTab(EditingTarget target, boolean interactive) { findByDocument(target.getId()).closeTab(target.asWidget(), interactive, null); } public void closeTab(EditingTarget target, boolean interactive, Command onClosed) { findByDocument(target.getId()).closeTab( target.asWidget(), interactive, onClosed); } public void closeAllTabs(boolean excludeActive, boolean excludeMain) { columnList_.forEach((column) -> closeAllTabs(column, excludeActive, excludeMain)); } public void closeAllTabs(SourceColumn column, boolean excludeActive, boolean excludeMain) { if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) { cpsExecuteForEachEditor(column.getEditors(), new CPSEditingTargetCommand() { @Override public void execute(EditingTarget target, Command continuation) { if (excludeActive && (hasActiveEditor() && target == activeColumn_.getActiveEditor())) { continuation.execute(); return; } else { column.closeTab(target.asWidget(), false, continuation); } } }); } } void closeSourceDoc(boolean interactive) { if (activeColumn_.getTabCount() == 0) return; closeTab(interactive); } public void saveAllSourceDocs() { columnList_.forEach((column) -> cpsExecuteForEachEditor( column.getEditors(), (editingTarget, continuation) -> { if (editingTarget.dirtyState().getValue()) { editingTarget.save(continuation); } else { continuation.execute(); } })); } public void revertUnsavedTargets(Command onCompleted) { ArrayList<EditingTarget> unsavedTargets = new ArrayList<>(); columnList_.forEach((column) -> unsavedTargets.addAll( column.getUnsavedEditors(Source.TYPE_FILE_BACKED, null))); // revert all of them cpsExecuteForEachEditor( // targets the user chose not to save unsavedTargets, // save each editor (saveTarget, continuation) -> { if (saveTarget.getPath() != null) { // file backed document -- revert it saveTarget.revertChanges(continuation); } else { // untitled document -- just close the tab non-interactively closeTab(saveTarget, false, continuation); } }, // onCompleted at the end onCompleted ); } public void closeAllLocalSourceDocs(String caption, SourceColumn sourceColumn, Command onCompleted, final boolean excludeActive) { // save active editor for exclusion (it changes as we close tabs) final EditingTarget excludeEditor = (excludeActive) ? activeColumn_.getActiveEditor() : null; // collect up a list of dirty documents ArrayList<EditingTarget> dirtyTargets = new ArrayList<>(); // if sourceColumn is not provided, assume we are closing editors for every column if (sourceColumn == null) columnList_.forEach((column) -> dirtyTargets.addAll(column.getDirtyEditors(excludeEditor))); else dirtyTargets.addAll(sourceColumn.getDirtyEditors(excludeEditor)); // create a command used to close all tabs final Command closeAllTabsCommand = sourceColumn == null ? () -> closeAllTabs(excludeActive, false) : () -> closeAllTabs(sourceColumn, excludeActive, false); saveEditingTargetsWithPrompt(caption, dirtyTargets, CommandUtil.join(closeAllTabsCommand, onCompleted), null); } public ArrayList<String> consolidateColumns(int num) { ArrayList<String> removedColumns = new ArrayList<>(); if (num >= columnList_.size() || num < 1) return removedColumns; for (SourceColumn column : columnList_) { if (!column.hasDoc() && column.getName() != MAIN_SOURCE_NAME) { removedColumns.add(column.getName()); closeColumn(column.getName()); if (num >= columnList_.size() || num == 1) break; } } // if we could not remove empty columns to get to the desired amount, consolidate editors SourceColumn mainColumn = getByName(MAIN_SOURCE_NAME); if (num < columnList_.size()) { ArrayList<SourceColumn> moveColumns = new ArrayList<>(columnList_); moveColumns.remove(mainColumn); // remove columns from the end of the list first int additionalColumnCount = num - 1; if (num > 1 && moveColumns.size() != additionalColumnCount) moveColumns = new ArrayList<>( moveColumns.subList(additionalColumnCount - 1, moveColumns.size() - 1)); for (SourceColumn column : moveColumns) { ArrayList<EditingTarget> editors = column.getEditors(); for (EditingTarget target : editors) { if (!target.dirtyState().getValue()) { column.closeTab(target.asWidget(), false); continue; } server_.getSourceDocument(target.getId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(final SourceDocument doc) { mainColumn.addTab(doc, Source.OPEN_INTERACTIVE); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Document Tab Move Failed", "Couldn't move the tab to this window: \n" + error.getMessage()); } }); } removedColumns.add(column.getName()); closeColumn(column, true); } } columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); return removedColumns; } public void closeColumn(String name) { SourceColumn column = getByName(name); if (column.getTabCount() > 0) return; if (column == activeColumn_) setActive(MAIN_SOURCE_NAME); columnList_.remove(column); columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); } public void closeColumn(SourceColumn column, boolean force) { if (column.getTabCount() > 0) { if (!force) return; else { for (EditingTarget target : column.getEditors()) column.closeDoc(target.getId()); } } if (column == activeColumn_) setActive(MAIN_SOURCE_NAME); columnList_.remove(column); columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)), getActive().getName()); } public void ensureVisible(boolean newTabPending) { if (getActive() == null) return; getActive().ensureVisible(newTabPending); } public void openFile(FileSystemItem file) { openFile(file, fileTypeRegistry_.getTextTypeForFile(file)); } public void openFile(FileSystemItem file, TextFileType fileType) { openFile(file, fileType, new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { } }); } public void openFile(final FileSystemItem file, final TextFileType fileType, final CommandWithArg<EditingTarget> executeOnSuccess) { // add this work to the queue openFileQueue_.add(new OpenFileEntry(file, fileType, executeOnSuccess)); // begin queue processing if it's the only work in the queue if (openFileQueue_.size() == 1) processOpenFileQueue(); } private void editFile(final String path) { server_.ensureFileExists( path, new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean success) { if (success) { FileSystemItem file = FileSystemItem.createFile(path); openFile(file); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } public void openProjectDocs(final Session session, boolean mainColumn) { if (mainColumn && activeColumn_ != getByName(MAIN_SOURCE_NAME)) setActive(MAIN_SOURCE_NAME); JsArrayString openDocs = session.getSessionInfo().getProjectOpenDocs(); if (openDocs.length() > 0) { // set new tab pending for the duration of the continuation activeColumn_.incrementNewTabPending(); // create a continuation for opening the source docs SerializedCommandQueue openCommands = new SerializedCommandQueue(); for (int i = 0; i < openDocs.length(); i++) { String doc = openDocs.get(i); final FileSystemItem fsi = FileSystemItem.createFile(doc); openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(final Command continuation) { openFile(fsi, fileTypeRegistry_.getTextTypeForFile(fsi), new CommandWithArg<EditingTarget>() { @Override public void execute(EditingTarget arg) { continuation.execute(); } }); } }); } // decrement newTabPending and select first tab when done openCommands.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { activeColumn_.decrementNewTabPending(); onFirstTab(); continuation.execute(); } }); // execute the continuation openCommands.run(); } } public void fireDocTabsChanged() { activeColumn_.fireDocTabsChanged(); } public void scrollToPosition(FilePosition position, boolean moveCursor) { // ensure we have an active source column getActive(); if (hasActiveEditor()) { SourcePosition srcPosition = SourcePosition.create( position.getLine() - 1, position.getColumn() - 1); activeColumn_.getActiveEditor().navigateToPosition( srcPosition, false, false, moveCursor, null); } } private boolean hasDoc() { for (SourceColumn column : columnList_) { if (column.hasDoc()) return true; } return false; } private void vimSetTabIndex(int index) { int tabCount = activeColumn_.getTabCount(); if (index >= tabCount) return; activeColumn_.setPhysicalTabIndex(index); } private void processOpenFileQueue() { // no work to do if (openFileQueue_.isEmpty()) return; // find the first work unit final OpenFileEntry entry = openFileQueue_.peek(); // define command to advance queue final Command processNextEntry = new Command() { @Override public void execute() { openFileQueue_.remove(); if (!openFileQueue_.isEmpty()) processOpenFileQueue(); } }; openFile( entry.file, entry.fileType, new ResultCallback<EditingTarget, ServerError>() { @Override public void onSuccess(EditingTarget target) { processNextEntry.execute(); if (entry.executeOnSuccess != null) entry.executeOnSuccess.execute(target); } @Override public void onCancelled() { super.onCancelled(); processNextEntry.execute(); } @Override public void onFailure(ServerError error) { String message = error.getUserMessage(); // see if a special message was provided JSONValue errValue = error.getClientInfo(); if (errValue != null) { JSONString errMsg = errValue.isString(); if (errMsg != null) message = errMsg.stringValue(); } globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening file", message); processNextEntry.execute(); } }); } public void openFile(FileSystemItem file, final ResultCallback<EditingTarget, ServerError> resultCallback) { openFile(file, fileTypeRegistry_.getTextTypeForFile(file), resultCallback); } // top-level wrapper for opening files. takes care of: // - making sure the view is visible // - checking whether it is already open and re-selecting its tab // - prohibit opening very large files (>500KB) // - confirmation of opening large files (>100KB) // - finally, actually opening the file from the server // via the call to the lower level openFile method public void openFile(final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { activeColumn_.ensureVisible(true); if (fileType.isRNotebook()) { openNotebook(file, resultCallback); return; } if (file == null) { newDoc(fileType, resultCallback); return; } if (openFileAlreadyOpen(file, resultCallback)) return; EditingTarget target = editingTargetSource_.getEditingTarget(fileType); if (file.getLength() > target.getFileSizeLimit()) { if (resultCallback != null) resultCallback.onCancelled(); showFileTooLargeWarning(file, target.getFileSizeLimit()); } else if (file.getLength() > target.getLargeFileSize()) { confirmOpenLargeFile(file, new Operation() { public void execute() { openFileFromServer(file, fileType, resultCallback); } }, new Operation() { public void execute() { // user (wisely) cancelled if (resultCallback != null) resultCallback.onCancelled(); } }); } else { openFileFromServer(file, fileType, resultCallback); } } public void openNotebook( final FileSystemItem rmdFile, final SourceDocumentResult doc, final ResultCallback<EditingTarget, ServerError> resultCallback) { if (!StringUtil.isNullOrEmpty(doc.getDocPath())) { // this happens if we created the R Markdown file, or if the R Markdown // file on disk matched the one inside the notebook openFileFromServer(rmdFile, FileTypeRegistry.RMARKDOWN, resultCallback); } else if (!StringUtil.isNullOrEmpty(doc.getDocId())) { // this happens when we have to open an untitled buffer for the the // notebook (usually because the of a conflict between the Rmd on disk // and the one in the .nb.html file) server_.getSourceDocument(doc.getDocId(), new ServerRequestCallback<SourceDocument>() { @Override public void onResponseReceived(SourceDocument doc) { // create the editor EditingTarget target = getActive().addTab(doc, Source.OPEN_INTERACTIVE); // show a warning bar if (target instanceof TextEditingTarget) { ((TextEditingTarget) target).showWarningMessage( "This notebook has the same name as an R Markdown " + "file, but doesn't match it."); } resultCallback.onSuccess(target); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage( "Notebook Open Failed", "This notebook could not be opened. " + "If the error persists, try removing the " + "accompanying R Markdown file. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } } public void beforeShow(boolean excludeMain) { for (SourceColumn column : columnList_) { if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME)) column.onBeforeShow(); } } public void beforeShow(String name) { SourceColumn column = getByName(name); if (column == null) { Debug.logWarning("WARNING: Unknown column " + name); return; } column.onBeforeShow(); } public void inEditorForId(String id, OperationWithInput<EditingTarget> onEditorLocated) { EditingTarget editor = findEditor(id); if (editor != null) onEditorLocated.execute(editor); } public void inEditorForPath(String path, OperationWithInput<EditingTarget> onEditorLocated) { EditingTarget editor = findEditorByPath(path); if (editor != null) onEditorLocated.execute(editor); } public void withTarget(String id, CommandWithArg<TextEditingTarget> command) { withTarget(id, command, null); } public void withTarget(String id, CommandWithArg<TextEditingTarget> command, Command onFailure) { EditingTarget target = StringUtil.isNullOrEmpty(id) ? activeColumn_.getActiveEditor() : findEditor(id); if (target == null) { if (onFailure != null) onFailure.execute(); return; } if (!(target instanceof TextEditingTarget)) { if (onFailure != null) onFailure.execute(); return; } command.execute((TextEditingTarget) target); } public HashSet<AppCommand> getDynamicCommands() { return dynamicCommands_; } private void getEditorContext(String id, String path, DocDisplay docDisplay) { getEditorContext(id, path, docDisplay, server_); } public static void getEditorContext(String id, String path, DocDisplay docDisplay, SourceServerOperations server) { AceEditor editor = (AceEditor) docDisplay; Selection selection = editor.getNativeSelection(); Range[] ranges = selection.getAllRanges(); // clamp ranges to document boundaries for (Range range : ranges) { Position start = range.getStart(); start.setRow(MathUtil.clamp(start.getRow(), 0, editor.getRowCount())); start.setColumn(MathUtil.clamp(start.getColumn(), 0, editor.getLine(start.getRow()).length())); Position end = range.getEnd(); end.setRow(MathUtil.clamp(end.getRow(), 0, editor.getRowCount())); end.setColumn(MathUtil.clamp(end.getColumn(), 0, editor.getLine(end.getRow()).length())); } JsArray<GetEditorContextEvent.DocumentSelection> docSelections = JavaScriptObject.createArray().cast(); for (Range range : ranges) { docSelections.push(GetEditorContextEvent.DocumentSelection.create( range, editor.getTextForRange(range))); } id = StringUtil.notNull(id); path = StringUtil.notNull(path); GetEditorContextEvent.SelectionData data = GetEditorContextEvent.SelectionData.create(id, path, editor.getCode(), docSelections); server.getEditorContextCompleted(data, new VoidServerRequestCallback()); } private void initDynamicCommands() { dynamicCommands_ = new HashSet<>(); dynamicCommands_.add(commands_.saveSourceDoc()); dynamicCommands_.add(commands_.reopenSourceDocWithEncoding()); dynamicCommands_.add(commands_.saveSourceDocAs()); dynamicCommands_.add(commands_.saveSourceDocWithEncoding()); dynamicCommands_.add(commands_.printSourceDoc()); dynamicCommands_.add(commands_.vcsFileLog()); dynamicCommands_.add(commands_.vcsFileDiff()); dynamicCommands_.add(commands_.vcsFileRevert()); dynamicCommands_.add(commands_.executeCode()); dynamicCommands_.add(commands_.executeCodeWithoutFocus()); dynamicCommands_.add(commands_.executeAllCode()); dynamicCommands_.add(commands_.executeToCurrentLine()); dynamicCommands_.add(commands_.executeFromCurrentLine()); dynamicCommands_.add(commands_.executeCurrentFunction()); dynamicCommands_.add(commands_.executeCurrentSection()); dynamicCommands_.add(commands_.executeLastCode()); dynamicCommands_.add(commands_.insertChunk()); dynamicCommands_.add(commands_.insertSection()); dynamicCommands_.add(commands_.executeSetupChunk()); dynamicCommands_.add(commands_.executePreviousChunks()); dynamicCommands_.add(commands_.executeSubsequentChunks()); dynamicCommands_.add(commands_.executeCurrentChunk()); dynamicCommands_.add(commands_.executeNextChunk()); dynamicCommands_.add(commands_.previewJS()); dynamicCommands_.add(commands_.previewSql()); dynamicCommands_.add(commands_.sourceActiveDocument()); dynamicCommands_.add(commands_.sourceActiveDocumentWithEcho()); dynamicCommands_.add(commands_.knitDocument()); dynamicCommands_.add(commands_.toggleRmdVisualMode()); dynamicCommands_.add(commands_.enableProsemirrorDevTools()); dynamicCommands_.add(commands_.previewHTML()); dynamicCommands_.add(commands_.compilePDF()); dynamicCommands_.add(commands_.compileNotebook()); dynamicCommands_.add(commands_.synctexSearch()); dynamicCommands_.add(commands_.popoutDoc()); dynamicCommands_.add(commands_.returnDocToMain()); dynamicCommands_.add(commands_.findReplace()); dynamicCommands_.add(commands_.findNext()); dynamicCommands_.add(commands_.findPrevious()); dynamicCommands_.add(commands_.findFromSelection()); dynamicCommands_.add(commands_.replaceAndFind()); dynamicCommands_.add(commands_.extractFunction()); dynamicCommands_.add(commands_.extractLocalVariable()); dynamicCommands_.add(commands_.commentUncomment()); dynamicCommands_.add(commands_.reindent()); dynamicCommands_.add(commands_.reflowComment()); dynamicCommands_.add(commands_.jumpTo()); dynamicCommands_.add(commands_.jumpToMatching()); dynamicCommands_.add(commands_.goToHelp()); dynamicCommands_.add(commands_.goToDefinition()); dynamicCommands_.add(commands_.setWorkingDirToActiveDoc()); dynamicCommands_.add(commands_.debugDumpContents()); dynamicCommands_.add(commands_.debugImportDump()); dynamicCommands_.add(commands_.goToLine()); dynamicCommands_.add(commands_.checkSpelling()); dynamicCommands_.add(commands_.wordCount()); dynamicCommands_.add(commands_.codeCompletion()); dynamicCommands_.add(commands_.findUsages()); dynamicCommands_.add(commands_.debugBreakpoint()); dynamicCommands_.add(commands_.vcsViewOnGitHub()); dynamicCommands_.add(commands_.vcsBlameOnGitHub()); dynamicCommands_.add(commands_.editRmdFormatOptions()); dynamicCommands_.add(commands_.reformatCode()); dynamicCommands_.add(commands_.showDiagnosticsActiveDocument()); dynamicCommands_.add(commands_.renameInScope()); dynamicCommands_.add(commands_.insertRoxygenSkeleton()); dynamicCommands_.add(commands_.expandSelection()); dynamicCommands_.add(commands_.shrinkSelection()); dynamicCommands_.add(commands_.toggleDocumentOutline()); dynamicCommands_.add(commands_.knitWithParameters()); dynamicCommands_.add(commands_.clearKnitrCache()); dynamicCommands_.add(commands_.goToNextSection()); dynamicCommands_.add(commands_.goToPrevSection()); dynamicCommands_.add(commands_.goToNextChunk()); dynamicCommands_.add(commands_.goToPrevChunk()); dynamicCommands_.add(commands_.profileCode()); dynamicCommands_.add(commands_.profileCodeWithoutFocus()); dynamicCommands_.add(commands_.saveProfileAs()); dynamicCommands_.add(commands_.restartRClearOutput()); dynamicCommands_.add(commands_.restartRRunAllChunks()); dynamicCommands_.add(commands_.notebookCollapseAllOutput()); dynamicCommands_.add(commands_.notebookExpandAllOutput()); dynamicCommands_.add(commands_.notebookClearOutput()); dynamicCommands_.add(commands_.notebookClearAllOutput()); dynamicCommands_.add(commands_.notebookToggleExpansion()); dynamicCommands_.add(commands_.sendToTerminal()); dynamicCommands_.add(commands_.openNewTerminalAtEditorLocation()); dynamicCommands_.add(commands_.sendFilenameToTerminal()); dynamicCommands_.add(commands_.renameSourceDoc()); dynamicCommands_.add(commands_.sourceAsLauncherJob()); dynamicCommands_.add(commands_.sourceAsJob()); dynamicCommands_.add(commands_.runSelectionAsJob()); dynamicCommands_.add(commands_.runSelectionAsLauncherJob()); dynamicCommands_.add(commands_.toggleSoftWrapMode()); for (AppCommand command : dynamicCommands_) { command.setVisible(false); command.setEnabled(false); } } public void initVimCommands() { vimCommands_.save(this); vimCommands_.selectTabIndex(this); vimCommands_.selectNextTab(this); vimCommands_.selectPreviousTab(this); vimCommands_.closeActiveTab(this); vimCommands_.closeAllTabs(this); vimCommands_.createNewDocument(this); vimCommands_.saveAndCloseActiveTab(this); vimCommands_.readFile(this, userPrefs_.defaultEncoding().getValue()); vimCommands_.runRScript(this); vimCommands_.reflowText(this); vimCommands_.showVimHelp( RStudioGinjector.INSTANCE.getShortcutViewer()); vimCommands_.showHelpAtCursor(this); vimCommands_.reindent(this); vimCommands_.expandShrinkSelection(this); vimCommands_.openNextFile(this); vimCommands_.openPreviousFile(this); vimCommands_.addStarRegister(); } public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command String key = command.getId() + column.getName(); if (sourceAppCommands_.get(key) != null) return sourceAppCommands_.get(key); // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.put(key, sourceCommand); return sourceCommand; } private void openNotebook(final FileSystemItem rnbFile, final ResultCallback<EditingTarget, ServerError> resultCallback) { // construct path to .Rmd final String rnbPath = rnbFile.getPath(); final String rmdPath = FilePathUtils.filePathSansExtension(rnbPath) + ".Rmd"; final FileSystemItem rmdFile = FileSystemItem.createFile(rmdPath); // if we already have associated .Rmd file open, then just edit it // TODO: should we perform conflict resolution here as well? if (openFileAlreadyOpen(rmdFile, resultCallback)) return; // ask the server to extract the .Rmd, then open that Command extractRmdCommand = new Command() { @Override public void execute() { server_.extractRmdFromNotebook( rnbPath, new ServerRequestCallback<SourceDocumentResult>() { @Override public void onResponseReceived(SourceDocumentResult doc) { openNotebook(rmdFile, doc, resultCallback); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Notebook Open Failed", "This notebook could not be opened. \n\n" + error.getMessage()); resultCallback.onFailure(error); } }); } }; dependencyManager_.withRMarkdown("R Notebook", "Using R Notebooks", extractRmdCommand); } private void openFileFromServer( final FileSystemItem file, final TextFileType fileType, final ResultCallback<EditingTarget, ServerError> resultCallback) { final Command dismissProgress = globalDisplay_.showProgress( "Opening file..."); server_.openDocument( file.getPath(), fileType.getTypeId(), userPrefs_.defaultEncoding().getValue(), new ServerRequestCallback<SourceDocument>() { @Override public void onError(ServerError error) { dismissProgress.execute(); pMruList_.get().remove(file.getPath()); Debug.logError(error); if (resultCallback != null) resultCallback.onFailure(error); } @Override public void onResponseReceived(SourceDocument document) { // apply (dynamic) doc property defaults SourceColumn.applyDocPropertyDefaults(document, false, userPrefs_); // if we are opening for a source navigation then we // need to force Rmds into source mode if (openingForSourceNavigation_) { document.getProperties().setString( TextEditingTarget.RMD_VISUAL_MODE, DocUpdateSentinel.PROPERTY_FALSE ); } dismissProgress.execute(); pMruList_.get().add(document.getPath()); EditingTarget target = getActive().addTab(document, Source.OPEN_INTERACTIVE); if (resultCallback != null) resultCallback.onSuccess(target); } }); } private boolean openFileAlreadyOpen(final FileSystemItem file, final ResultCallback<EditingTarget, ServerError> resultCallback) { for (SourceColumn column : columnList_) { // check to see if any local editors have the file open for (int i = 0; i < column.getEditors().size(); i++) { EditingTarget target = column.getEditors().get(i); String thisPath = target.getPath(); if (thisPath != null && thisPath.equalsIgnoreCase(file.getPath())) { column.selectTab(target.asWidget()); pMruList_.get().add(thisPath); if (resultCallback != null) resultCallback.onSuccess(target); return true; } } } return false; } private void showFileTooLargeWarning(FileSystemItem file, long sizeLimit) { StringBuilder msg = new StringBuilder(); msg.append("The file '" + file.getName() + "' is too "); msg.append("large to open in the source editor (the file is "); msg.append(StringUtil.formatFileSize(file.getLength()) + " and the "); msg.append("maximum file size is "); msg.append(StringUtil.formatFileSize(sizeLimit) + ")"); globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING, "Selected File Too Large", msg.toString()); } private void confirmOpenLargeFile(FileSystemItem file, Operation openOperation, Operation noOperation) { StringBuilder msg = new StringBuilder(); msg.append("The source file '" + file.getName() + "' is large ("); msg.append(StringUtil.formatFileSize(file.getLength()) + ") "); msg.append("and may take some time to open. "); msg.append("Are you sure you want to continue opening it?"); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Confirm Open", msg.toString(), false, // Don't include cancel openOperation, noOperation, false); // 'No' is default } private void saveEditingTargetsWithPrompt( String title, ArrayList<EditingTarget> editingTargets, final Command onCompleted, final Command onCancelled) { // execute on completed right away if the list is empty if (editingTargets.size() == 0) { onCompleted.execute(); } // if there is just one thing dirty then go straight to the save dialog else if (editingTargets.size() == 1) { editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled); } // otherwise use the multi save changes dialog else { // convert to UnsavedChangesTarget collection ArrayList<UnsavedChangesTarget> unsavedTargets = new ArrayList<>(editingTargets); // show dialog showUnsavedChangesDialog( title, unsavedTargets, new OperationWithInput<UnsavedChangesDialog.Result>() { @Override public void execute(UnsavedChangesDialog.Result result) { saveChanges(result.getSaveTargets(), onCompleted); } }, onCancelled); } } public ArrayList<UnsavedChangesTarget> getUnsavedChanges(int type, Set<String> ids) { ArrayList<UnsavedChangesTarget> targets = new ArrayList<>(); columnList_.forEach((column) -> targets.addAll(column.getUnsavedEditors(type, ids))); return targets; } public void saveChanges(ArrayList<UnsavedChangesTarget> targets, Command onCompleted) { // convert back to editing targets ArrayList<EditingTarget> saveTargets = new ArrayList<>(); for (UnsavedChangesTarget target: targets) { EditingTarget saveTarget = findEditor(target.getId()); if (saveTarget != null) saveTargets.add(saveTarget); } CPSEditingTargetCommand saveCommand = new CPSEditingTargetCommand() { @Override public void execute(EditingTarget saveTarget, Command continuation) { saveTarget.save(continuation); } }; // execute the save cpsExecuteForEachEditor( // targets the user chose to save saveTargets, // save each editor saveCommand, // onCompleted at the end onCompleted ); } private void pasteFileContentsAtCursor(final String path, final String encoding) { if (activeColumn_ == null) return; EditingTarget activeEditor = activeColumn_.getActiveEditor(); if (activeEditor instanceof TextEditingTarget) { final TextEditingTarget target = (TextEditingTarget) activeEditor; server_.getFileContents(path, encoding, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String content) { target.insertCode(content, false); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } } private void pasteRCodeExecutionResult(final String code) { server_.executeRCode(code, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String output) { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.insertCode(output, false); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private void reflowText() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.reflowText(); } } private void reindent() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.getDocDisplay().reindent(); } } private void saveActiveSourceDoc() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeColumn_.getActiveEditor(); target.save(); } } private void saveAndCloseActiveSourceDoc() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget target = (TextEditingTarget) activeColumn_.getActiveEditor(); target.save(new Command() { @Override public void execute() { onCloseSourceDoc(); } }); } } private void revertActiveDocument() { if (!hasActiveEditor()) return; if (activeColumn_.getActiveEditor().getPath() != null) activeColumn_.getActiveEditor().revertChanges(null); // Ensure that the document is in view activeColumn_.getActiveEditor().ensureCursorVisible(); } private void showHelpAtCursor() { if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget) { TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor(); editor.showHelpAtCursor(); } } /** * Execute the given command for each editor, using continuation-passing * style. When executed, the CPSEditingTargetCommand needs to execute its * own Command parameter to continue the iteration. * @param command The command to run on each EditingTarget */ private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command, final Command completedCommand) { SerializedCommandQueue queue = new SerializedCommandQueue(); // Clone editors_, since the original may be mutated during iteration for (final EditingTarget editor : new ArrayList<>(editors)) { queue.addCommand(new SerializedCommand() { @Override public void onExecute(Command continuation) { command.execute(editor, continuation); } }); } if (completedCommand != null) { queue.addCommand(new SerializedCommand() { public void onExecute(Command continuation) { completedCommand.execute(); continuation.execute(); } }); } } public SourceColumn getByName(String name) { for (SourceColumn column : columnList_) { if (StringUtil.equals(column.getName(), name)) return column; } return null; } private boolean contains(String name) { for (SourceColumn column : columnList_) { if (StringUtil.equals(column.getName(), name)) return true; } return false; } private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors, final CPSEditingTargetCommand command) { cpsExecuteForEachEditor(editors, command, null); } private static class OpenFileEntry { public OpenFileEntry(FileSystemItem fileIn, TextFileType fileTypeIn, CommandWithArg<EditingTarget> executeIn) { file = fileIn; fileType = fileTypeIn; executeOnSuccess = executeIn; } public final FileSystemItem file; public final TextFileType fileType; public final CommandWithArg<EditingTarget> executeOnSuccess; } private State columnState_; private SourceColumn activeColumn_; private boolean openingForSourceNavigation_ = false; private boolean docsRestored_ = false; private final Queue<OpenFileEntry> openFileQueue_ = new LinkedList<>(); private final ArrayList<SourceColumn> columnList_ = new ArrayList<>(); private HashSet<AppCommand> dynamicCommands_ = new HashSet<>(); private HashMap<String, SourceAppCommand> sourceAppCommands_ = new HashMap<>(); private SourceVimCommands vimCommands_; private Commands commands_; private EventBus events_; private Provider<FileMRUList> pMruList_; private SourceWindowManager windowManager_; private Session session_; private Synctex synctex_; private UserPrefs userPrefs_; private UserState userState_; private GlobalDisplay globalDisplay_; private TextEditingTargetRMarkdownHelper rmarkdown_; private EditingTargetSource editingTargetSource_; private FileTypeRegistry fileTypeRegistry_; private SourceServerOperations server_; private DependencyManager dependencyManager_; private final SourceNavigationHistory sourceNavigationHistory_ = new SourceNavigationHistory(30); public final static String COLUMN_PREFIX = "Source"; public final static String MAIN_SOURCE_NAME = COLUMN_PREFIX; }
process columns one-by-one
src/gwt/src/org/rstudio/studio/client/workbench/views/source/SourceColumnManager.java
process columns one-by-one
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/source/SourceColumnManager.java <ide> <ide> public void showDataItem(DataItem data) <ide> { <del> columnList_.forEach((column) -> { <add> for (SourceColumn column : columnList_) <add> { <ide> for (EditingTarget target : column.getEditors()) <ide> { <ide> String path = target.getPath(); <ide> return; <ide> } <ide> } <del> }); <add> } <ide> <ide> ensureVisible(true); <ide> server_.newDocument(
JavaScript
apache-2.0
f40a3641ee6fd050ee58b69b4fe46ad6a22fda9d
0
appbaseio/reactivesearch,appbaseio/reactivesearch,appbaseio/reactivesearch,appbaseio/reactivesearch
packages/web/examples/ssr/components/MeetupList.js
import React from 'react'; const MeetupList = ({ data }) => ({ title: ( <div className="meetup-title"> {data.member ? data.member.member_name : ''} is going to ${data.event ? data.event.event_name : ''} </div> ), image: data.member.photo, image_size: 'small', description: ( <div className="flex column"> <div className="meetup-location"> <span className="location"><i className="fas fa-map-marker-alt" /></span> {data.group ? data.group.group_city : ''} </div> <div className="flex wrap meetup-topics"> { data.group.group_topics.slice(0, 4).map(tag => ( <div className="meetup-topic" key={tag.topic_name}>{tag.topic_name}</div> )) } </div> </div> ), url: data.event.event_url, }); export default MeetupList;
cleanup
packages/web/examples/ssr/components/MeetupList.js
cleanup
<ide><path>ackages/web/examples/ssr/components/MeetupList.js <del>import React from 'react'; <del> <del>const MeetupList = ({ data }) => ({ <del> title: ( <del> <div className="meetup-title"> <del> {data.member ? data.member.member_name : ''} is going to ${data.event ? data.event.event_name : ''} <del> </div> <del> ), <del> image: data.member.photo, <del> image_size: 'small', <del> description: ( <del> <div className="flex column"> <del> <div className="meetup-location"> <del> <span className="location"><i className="fas fa-map-marker-alt" /></span> <del> {data.group ? data.group.group_city : ''} <del> </div> <del> <div className="flex wrap meetup-topics"> <del> { <del> data.group.group_topics.slice(0, 4).map(tag => ( <del> <div className="meetup-topic" key={tag.topic_name}>{tag.topic_name}</div> <del> )) <del> } <del> </div> <del> </div> <del> ), <del> url: data.event.event_url, <del>}); <del> <del>export default MeetupList;
Java
apache-2.0
e46cd66e991bed2e4f5c16ae323bbfd2afe960f5
0
noemus/kotlin-eclipse,noemus/kotlin-eclipse
package org.jetbrains.kotlin.core.filesystem; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.filesystem.provider.FileInfo; import org.eclipse.core.internal.filesystem.local.LocalFile; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.compiler.util.Util; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.backend.common.output.OutputFile; import org.jetbrains.kotlin.codegen.state.GenerationState; import org.jetbrains.kotlin.core.asJava.KotlinLightClassGeneration; import org.jetbrains.kotlin.core.log.KotlinLogger; import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache; import org.jetbrains.kotlin.psi.JetFile; public class KotlinFileStore extends LocalFile { public KotlinFileStore(File file) { super(file); } @Override public InputStream openInputStream(int options, IProgressMonitor monitor) throws CoreException { IJavaProject javaProject = getJavaProject(); if (javaProject == null) { throw new CoreException(Status.CANCEL_STATUS); } List<JetFile> jetFiles = KotlinLightClassManager.getInstance(javaProject).getSourceFiles(file); if (!jetFiles.isEmpty()) { AnalysisResult analysisResult = KotlinAnalysisProjectCache.getInstance(javaProject).getAnalysisResult(); GenerationState state = KotlinLightClassGeneration.buildLightClasses(analysisResult, javaProject, jetFiles); String requestedClassName = new Path(file.getAbsolutePath()).lastSegment(); for (OutputFile outputFile : state.getFactory().asList()) { String generatedClassName = new Path(outputFile.getRelativePath()).lastSegment(); if (requestedClassName.equals(generatedClassName)) { return new ByteArrayInputStream(outputFile.asByteArray()); } } } throw new CoreException(Status.CANCEL_STATUS); } @Override public IFileInfo fetchInfo(int options, IProgressMonitor monitor) { FileInfo info = (FileInfo) super.fetchInfo(options, monitor); if (Util.isClassFileName(getName())) { IFile workspaceFile = findFileInWorkspace(); if (workspaceFile != null) { info.setExists(workspaceFile.exists()); } } else { IContainer workspaceContainer = findFolderInWorkspace(); if (workspaceContainer != null) { info.setExists(workspaceContainer.exists()); info.setDirectory(true); } } return info; } @Override public String[] childNames(int options, IProgressMonitor monitor) { List<String> children = new ArrayList<>(); try { IContainer folder = findFolderInWorkspace(); if (folder != null && folder.exists()) { for (IResource member : folder.members()) { children.add(member.getName()); } } } catch (CoreException e) { KotlinLogger.logAndThrow(e); } return children.toArray(new String[children.size()]); } @Override public IFileStore mkdir(int options, IProgressMonitor monitor) throws CoreException { return this; } @Override public OutputStream openOutputStream(int options, IProgressMonitor monitor) throws CoreException { return new ByteArrayOutputStream(); } @Override public IFileStore getChild(String name) { return new KotlinFileStore(new File(file, name)); } @Override public IFileStore getChild(IPath path) { return new KotlinFileStore(new File(file, path.toOSString())); } @Override public IFileStore getFileStore(IPath path) { return new KotlinFileStore(new Path(file.getPath()).append(path).toFile()); } @Override public IFileStore getParent() { File parent = file.getParentFile(); return parent != null ? new KotlinFileStore(parent) : null; } @Nullable private IFile findFileInWorkspace() { IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI()); if (files != null && files.length > 0) { assert files.length == 1 : "By " + file.toURI() + "found more than one file"; return files[0]; } return null; } @Nullable private IContainer findFolderInWorkspace() { IContainer[] containers = ResourcesPlugin.getWorkspace().getRoot().findContainersForLocationURI(file.toURI()); if (containers != null && containers.length > 0) { assert containers.length == 1 : "By " + file.toURI() + "found more than one file"; return containers[0]; } return null; } @Nullable private IJavaProject getJavaProject() { IFile file = findFileInWorkspace(); return file != null ? JavaCore.create(file.getProject()) : null; } }
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/filesystem/KotlinFileStore.java
package org.jetbrains.kotlin.core.filesystem; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.internal.filesystem.local.LocalFile; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.backend.common.output.OutputFile; import org.jetbrains.kotlin.codegen.state.GenerationState; import org.jetbrains.kotlin.core.asJava.KotlinLightClassGeneration; import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache; import org.jetbrains.kotlin.psi.JetFile; public class KotlinFileStore extends LocalFile { public KotlinFileStore(File file) { super(file); } @Override public InputStream openInputStream(int options, IProgressMonitor monitor) throws CoreException { IJavaProject javaProject = getJavaProject(); if (javaProject == null) { throw new CoreException(Status.CANCEL_STATUS); } List<JetFile> jetFiles = KotlinLightClassManager.getInstance(javaProject).getSourceFiles(file); if (!jetFiles.isEmpty()) { AnalysisResult analysisResult = KotlinAnalysisProjectCache.getInstance(javaProject).getAnalysisResult(); GenerationState state = KotlinLightClassGeneration.buildLightClasses(analysisResult, javaProject, jetFiles); String requestedClassName = new Path(file.getAbsolutePath()).lastSegment(); for (OutputFile outputFile : state.getFactory().asList()) { String generatedClassName = new Path(outputFile.getRelativePath()).lastSegment(); if (requestedClassName.equals(generatedClassName)) { return new ByteArrayInputStream(outputFile.asByteArray()); } } } throw new CoreException(Status.CANCEL_STATUS); } @Override public IFileStore mkdir(int options, IProgressMonitor monitor) throws CoreException { return this; } @Override public OutputStream openOutputStream(int options, IProgressMonitor monitor) throws CoreException { return new ByteArrayOutputStream(); } @Override public IFileStore getChild(String name) { return new KotlinFileStore(new File(file, name)); } @Override public IFileStore getChild(IPath path) { return new KotlinFileStore(new File(file, path.toOSString())); } @Override public IFileStore getFileStore(IPath path) { return new KotlinFileStore(new Path(file.getPath()).append(path).toFile()); } @Override public IFileStore getParent() { File parent = file.getParentFile(); return parent != null ? new KotlinFileStore(parent) : null; } @Nullable private IJavaProject getJavaProject() { IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI()); if (files != null && files.length > 0) { return JavaCore.create(files[0].getProject()); } return null; } }
Make Kotlin light classes synchronized with workspace Now light classes are not removed after refreshing workspace
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/filesystem/KotlinFileStore.java
Make Kotlin light classes synchronized with workspace
<ide><path>otlin-eclipse-core/src/org/jetbrains/kotlin/core/filesystem/KotlinFileStore.java <ide> import java.io.File; <ide> import java.io.InputStream; <ide> import java.io.OutputStream; <add>import java.util.ArrayList; <ide> import java.util.List; <ide> <add>import org.eclipse.core.filesystem.IFileInfo; <ide> import org.eclipse.core.filesystem.IFileStore; <add>import org.eclipse.core.filesystem.provider.FileInfo; <ide> import org.eclipse.core.internal.filesystem.local.LocalFile; <add>import org.eclipse.core.resources.IContainer; <ide> import org.eclipse.core.resources.IFile; <add>import org.eclipse.core.resources.IResource; <ide> import org.eclipse.core.resources.ResourcesPlugin; <ide> import org.eclipse.core.runtime.CoreException; <ide> import org.eclipse.core.runtime.IPath; <ide> import org.eclipse.core.runtime.Status; <ide> import org.eclipse.jdt.core.IJavaProject; <ide> import org.eclipse.jdt.core.JavaCore; <add>import org.eclipse.jdt.internal.compiler.util.Util; <ide> import org.jetbrains.annotations.Nullable; <ide> import org.jetbrains.kotlin.analyzer.AnalysisResult; <ide> import org.jetbrains.kotlin.backend.common.output.OutputFile; <ide> import org.jetbrains.kotlin.codegen.state.GenerationState; <ide> import org.jetbrains.kotlin.core.asJava.KotlinLightClassGeneration; <add>import org.jetbrains.kotlin.core.log.KotlinLogger; <ide> import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache; <ide> import org.jetbrains.kotlin.psi.JetFile; <ide> <ide> } <ide> <ide> @Override <add> public IFileInfo fetchInfo(int options, IProgressMonitor monitor) { <add> FileInfo info = (FileInfo) super.fetchInfo(options, monitor); <add> if (Util.isClassFileName(getName())) { <add> IFile workspaceFile = findFileInWorkspace(); <add> if (workspaceFile != null) { <add> info.setExists(workspaceFile.exists()); <add> } <add> } else { <add> IContainer workspaceContainer = findFolderInWorkspace(); <add> if (workspaceContainer != null) { <add> info.setExists(workspaceContainer.exists()); <add> info.setDirectory(true); <add> } <add> } <add> <add> return info; <add> } <add> <add> @Override <add> public String[] childNames(int options, IProgressMonitor monitor) { <add> List<String> children = new ArrayList<>(); <add> try { <add> IContainer folder = findFolderInWorkspace(); <add> if (folder != null && folder.exists()) { <add> for (IResource member : folder.members()) { <add> children.add(member.getName()); <add> } <add> } <add> } catch (CoreException e) { <add> KotlinLogger.logAndThrow(e); <add> } <add> <add> return children.toArray(new String[children.size()]); <add> } <add> <add> @Override <ide> public IFileStore mkdir(int options, IProgressMonitor monitor) throws CoreException { <ide> return this; <ide> } <ide> } <ide> <ide> @Nullable <del> private IJavaProject getJavaProject() { <add> private IFile findFileInWorkspace() { <ide> IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI()); <ide> if (files != null && files.length > 0) { <del> return JavaCore.create(files[0].getProject()); <add> assert files.length == 1 : "By " + file.toURI() + "found more than one file"; <add> <add> return files[0]; <ide> } <ide> <ide> return null; <ide> } <add> <add> @Nullable <add> private IContainer findFolderInWorkspace() { <add> IContainer[] containers = ResourcesPlugin.getWorkspace().getRoot().findContainersForLocationURI(file.toURI()); <add> if (containers != null && containers.length > 0) { <add> assert containers.length == 1 : "By " + file.toURI() + "found more than one file"; <add> return containers[0]; <add> } <add> <add> return null; <add> } <add> <add> @Nullable <add> private IJavaProject getJavaProject() { <add> IFile file = findFileInWorkspace(); <add> return file != null ? JavaCore.create(file.getProject()) : null; <add> } <ide> }
Java
mit
28284994d43f9766c6dc54587a99520a49f84f61
0
sammuelyee/validator,tripu/validator,YOTOV-LIMITED/validator,tripu/validator,validator/validator,YOTOV-LIMITED/validator,tripu/validator,validator/validator,takenspc/validator,sammuelyee/validator,tripu/validator,takenspc/validator,sammuelyee/validator,YOTOV-LIMITED/validator,validator/validator,YOTOV-LIMITED/validator,YOTOV-LIMITED/validator,validator/validator,takenspc/validator,sammuelyee/validator,takenspc/validator,validator/validator,tripu/validator,sammuelyee/validator,takenspc/validator
/* * Copyright (c) 2012 Mozilla Foundation * * 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.whattf.checker; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class RdfaLiteChecker extends Checker { private String GUIDANCE = " Consider checking against the HTML5 + RDFa 1.1 schema instead."; private void warnNonRDFaLite(String localName, String att) throws SAXException { warn("RDFa Core attribute \u201C" + att + "\u201D is only allowed on the \u201C" + localName + "\u201D element in HTML5 + RDFa 1.1 documents," + " not in HTML5 + RDFa 1.1 Lite documents." + GUIDANCE); } /** * @see org.whattf.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if ("http://www.w3.org/1999/xhtml" != uri) { return; } int len = atts.getLength(); for (int i = 0; i < len; i++) { String att = atts.getLocalName(i); if ("datatype" == att || "resource" == att || "inlist" == att) { warn("RDFa Core attribute \u201C" + att + "\u201D is only allowed in HTML + RDFa 1.1 documents," + " not in HTML + RDFa 1.1 Lite documents." + GUIDANCE); } else if ("content" == att && "meta" != localName) { warnNonRDFaLite(localName, att); } else if ("href" == att && "a" != localName && "area" != localName && "link" != localName && "base" != localName) { warnNonRDFaLite(localName, att); } else if (("rel" == att || "rev" == att) && "a" != localName && "area" != localName && "link" != localName) { warnNonRDFaLite(localName, att); } else if ("src" == att && "audio" != localName && "embed" != localName && "iframe" != localName && "img" != localName && "input" != localName && "script" != localName && "source" != localName && "track" != localName && "video" != localName) { warnNonRDFaLite(localName, att); } } } }
non-schema/java/src/org/whattf/checker/RdfaLiteChecker.java
/* * Copyright (c) 2012 Mozilla Foundation * * 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.whattf.checker; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class RdfaLiteChecker extends Checker { private String guidance = " Consider checking against the HTML5 + RDFa 1.1 schema instead."; private void warnNonRDFaLite(String localName, String att) throws SAXException { warn("RDFa Core attribute \u201C" + att + "\u201D is only allowed on the \u201C" + localName + "\u201D element in HTML5 + RDFa 1.1 documents," + " not in HTML5 + RDFa 1.1 Lite documents." + guidance); } /** * @see org.whattf.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if ("http://www.w3.org/1999/xhtml" != uri) { return; } int len = atts.getLength(); for (int i = 0; i < len; i++) { String att = atts.getLocalName(i); if ("datatype" == att || "resource" == att || "inlist" == att) { warn("RDFa Core attribute \u201C" + att + "\u201D is only allowed in HTML + RDFa 1.1 documents," + " not in HTML + RDFa 1.1 Lite documents." + guidance); } else if ("content" == att && "meta" != localName) { warnNonRDFaLite(localName, att); } else if ("href" == att && "a" != localName && "area" != localName && "link" != localName && "base" != localName) { warnNonRDFaLite(localName, att); } else if (("rel" == att || "rev" == att) && "a" != localName && "area" != localName && "link" != localName) { warnNonRDFaLite(localName, att); } else if ("src" == att && "audio" != localName && "embed" != localName && "iframe" != localName && "img" != localName && "input" != localName && "script" != localName && "source" != localName && "track" != localName && "video" != localName) { warnNonRDFaLite(localName, att); } } } }
Use proper case for private string in class. r=hsivonen.
non-schema/java/src/org/whattf/checker/RdfaLiteChecker.java
Use proper case for private string in class. r=hsivonen.
<ide><path>on-schema/java/src/org/whattf/checker/RdfaLiteChecker.java <ide> <ide> public class RdfaLiteChecker extends Checker { <ide> <del> private String guidance = " Consider checking against the HTML5 + RDFa 1.1 schema instead."; <add> private String GUIDANCE = " Consider checking against the HTML5 + RDFa 1.1 schema instead."; <ide> <ide> private void warnNonRDFaLite(String localName, String att) <ide> throws SAXException { <ide> warn("RDFa Core attribute \u201C" + att <ide> + "\u201D is only allowed on the \u201C" + localName <ide> + "\u201D element in HTML5 + RDFa 1.1 documents," <del> + " not in HTML5 + RDFa 1.1 Lite documents." + guidance); <add> + " not in HTML5 + RDFa 1.1 Lite documents." + GUIDANCE); <ide> } <ide> <ide> /** <ide> warn("RDFa Core attribute \u201C" <ide> + att <ide> + "\u201D is only allowed in HTML + RDFa 1.1 documents," <del> + " not in HTML + RDFa 1.1 Lite documents." + guidance); <add> + " not in HTML + RDFa 1.1 Lite documents." + GUIDANCE); <ide> } else if ("content" == att && "meta" != localName) { <ide> warnNonRDFaLite(localName, att); <ide> } else if ("href" == att && "a" != localName && "area" != localName
Java
agpl-3.0
b04eaca989008e759ed9f43a5a21d77de5295083
0
roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Modifications: // // 2003 Jan 31: Cleaned up some unused imports. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // // Tab Size = 8 // package org.opennms.netmgt.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.netmgt.ConfigFileConstants; public class GroupFactory extends GroupManager { /** * The static singleton instance object */ private static GroupFactory s_instance; /** * Boolean indicating if the init() method has been called */ private static boolean s_initialized = false; /** * */ private File m_groupsConfFile; /** * */ private long m_lastModified; /** * Constructor which parses the file */ public GroupFactory() { } public static synchronized void init() throws IOException, FileNotFoundException, MarshalException, ValidationException { if (!s_initialized) { getInstance().reload(); s_initialized = true; } } /** * Singleton static call to get the only instance that should exist for the * GroupFactory * * @return the single group factory instance */ public static synchronized GroupFactory getInstance() { if (s_instance == null || !s_initialized) { s_instance = new GroupFactory(); } return s_instance; } /** * Parses the groups.xml via the Castor classes */ public synchronized void reload() throws IOException, FileNotFoundException, MarshalException, ValidationException { File confFile = ConfigFileConstants.getFile(ConfigFileConstants.GROUPS_CONF_FILE_NAME); reloadFromFile(confFile); } /** * @param confFile * @throws FileNotFoundException * @throws MarshalException * @throws ValidationException */ private void reloadFromFile(File confFile) throws FileNotFoundException, MarshalException, ValidationException { m_groupsConfFile = confFile; InputStream configIn = new FileInputStream(m_groupsConfFile); m_lastModified = m_groupsConfFile.lastModified(); Reader reader = new InputStreamReader(configIn); parseXml(reader); } /** * @param data * @throws IOException */ protected void saveXml(String data) throws IOException { if (data != null) { FileWriter fileWriter = new FileWriter(m_groupsConfFile); fileWriter.write(data); fileWriter.flush(); fileWriter.close(); } } /** * */ protected void updateFromFile() throws IOException, MarshalException, ValidationException { if (m_lastModified != m_groupsConfFile.lastModified()) { reload(); } } }
src/services/org/opennms/netmgt/config/GroupFactory.java
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Modifications: // // 2003 Jan 31: Cleaned up some unused imports. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // // Tab Size = 8 // package org.opennms.netmgt.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.netmgt.ConfigFileConstants; public class GroupFactory extends GroupManager { /** * The static singleton instance object */ private static GroupFactory s_instance; /** * Boolean indicating if the init() method has been called */ private static boolean s_initialized = false; /** * */ private File m_groupsConfFile; /** * */ private long m_lastModified; /** * Constructor which parses the file */ public GroupFactory() { } public static synchronized void init() throws IOException, FileNotFoundException, MarshalException, ValidationException { if (!s_initialized) { getInstance().reload(); s_initialized = true; } } /** * Singleton static call to get the only instance that should exist for the * GroupFactory * * @return the single group factory instance */ public static synchronized GroupFactory getInstance() { if (s_instance == null || !s_initialized) { s_instance = new GroupFactory(); } return s_instance; } /** * Parses the groups.xml via the Castor classes */ public synchronized void reload() throws IOException, FileNotFoundException, MarshalException, ValidationException { File confFile = ConfigFileConstants.getFile(ConfigFileConstants.GROUPS_CONF_FILE_NAME); getInstance().reloadFromFile(confFile); } /** * @param confFile * @throws FileNotFoundException * @throws MarshalException * @throws ValidationException */ private void reloadFromFile(File confFile) throws FileNotFoundException, MarshalException, ValidationException { m_groupsConfFile = confFile; InputStream configIn = new FileInputStream(m_groupsConfFile); m_lastModified = m_groupsConfFile.lastModified(); Reader reader = new InputStreamReader(configIn); getInstance().parseXml(reader); } /** * @param data * @throws IOException */ protected void saveXml(String data) throws IOException { if (data != null) { FileWriter fileWriter = new FileWriter(m_groupsConfFile); fileWriter.write(data); fileWriter.flush(); fileWriter.close(); } } /** * */ protected void updateFromFile() throws IOException, MarshalException, ValidationException { if (m_lastModified != m_groupsConfFile.lastModified()) { reload(); } } }
Fixed group factory not not make getInstance call from non-static methods.
src/services/org/opennms/netmgt/config/GroupFactory.java
Fixed group factory not not make getInstance call from non-static methods.
<ide><path>rc/services/org/opennms/netmgt/config/GroupFactory.java <ide> public synchronized void reload() throws IOException, FileNotFoundException, MarshalException, ValidationException { <ide> File confFile = ConfigFileConstants.getFile(ConfigFileConstants.GROUPS_CONF_FILE_NAME); <ide> <del> getInstance().reloadFromFile(confFile); <add> reloadFromFile(confFile); <ide> } <ide> <ide> /** <ide> <ide> Reader reader = new InputStreamReader(configIn); <ide> <del> getInstance().parseXml(reader); <add> parseXml(reader); <ide> } <ide> <ide> /**
Java
apache-2.0
3da4c147a882b417f29441b0d1df1985d5131f8d
0
anomaly/closure-compiler,MatrixFrog/closure-compiler,google/closure-compiler,monetate/closure-compiler,google/closure-compiler,Pimm/closure-compiler,tiobe/closure-compiler,MatrixFrog/closure-compiler,Yannic/closure-compiler,vobruba-martin/closure-compiler,MatrixFrog/closure-compiler,shantanusharma/closure-compiler,vobruba-martin/closure-compiler,google/closure-compiler,mprobst/closure-compiler,GerHobbelt/closure-compiler,tdelmas/closure-compiler,Dominator008/closure-compiler,Dominator008/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,ChadKillingsworth/closure-compiler,vobruba-martin/closure-compiler,MatrixFrog/closure-compiler,shantanusharma/closure-compiler,Yannic/closure-compiler,anomaly/closure-compiler,shantanusharma/closure-compiler,Yannic/closure-compiler,mprobst/closure-compiler,tiobe/closure-compiler,anomaly/closure-compiler,ChadKillingsworth/closure-compiler,tdelmas/closure-compiler,nawawi/closure-compiler,anomaly/closure-compiler,tdelmas/closure-compiler,GerHobbelt/closure-compiler,Dominator008/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,google/closure-compiler,tiobe/closure-compiler,brad4d/closure-compiler,tdelmas/closure-compiler,mprobst/closure-compiler,shantanusharma/closure-compiler,brad4d/closure-compiler,Pimm/closure-compiler,Pimm/closure-compiler,GerHobbelt/closure-compiler,mprobst/closure-compiler,nawawi/closure-compiler,vobruba-martin/closure-compiler,brad4d/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,tiobe/closure-compiler,GerHobbelt/closure-compiler
/* * Copyright 2004 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.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping; import com.google.javascript.jscomp.CompilerOptions.DevMode; import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection; import com.google.javascript.jscomp.TypeValidator.TypeMismatch; import com.google.javascript.jscomp.WarningsGuard.DiagnosticGroupState; import com.google.javascript.jscomp.deps.ModuleLoader; import com.google.javascript.jscomp.deps.SortedDependencies.MissingProvideException; import com.google.javascript.jscomp.parsing.Config; import com.google.javascript.jscomp.parsing.ParserRunner; import com.google.javascript.jscomp.parsing.parser.trees.Comment; import com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.ReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfoBuilder; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TypeIRegistry; import com.google.javascript.rhino.jstype.JSTypeRegistry; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.FileSystems; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; /** * Compiler (and the other classes in this package) does the following: * <ul> * <li>parses JS code * <li>checks for undefined variables * <li>performs optimizations such as constant folding and constants inlining * <li>renames variables (to short names) * <li>outputs compact JavaScript code * </ul> * * External variables are declared in 'externs' files. For instance, the file * may include definitions for global javascript/browser objects such as * window, document. * */ public class Compiler extends AbstractCompiler implements ErrorHandler, SourceFileMapping { static final String SINGLETON_MODULE_NAME = "$singleton$"; static final DiagnosticType MODULE_DEPENDENCY_ERROR = DiagnosticType.error("JSC_MODULE_DEPENDENCY_ERROR", "Bad dependency: {0} -> {1}. " + "Modules must be listed in dependency order."); static final DiagnosticType MISSING_ENTRY_ERROR = DiagnosticType.error( "JSC_MISSING_ENTRY_ERROR", "required entry point \"{0}\" never provided"); static final DiagnosticType MISSING_MODULE_ERROR = DiagnosticType.error( "JSC_MISSING_ENTRY_ERROR", "unknown module \"{0}\" specified in entry point spec"); // Used in PerformanceTracker static final String READING_PASS_NAME = "readInputs"; static final String PARSING_PASS_NAME = "parseInputs"; static final String CROSS_MODULE_CODE_MOTION_NAME = "crossModuleCodeMotion"; static final String CROSS_MODULE_METHOD_MOTION_NAME = "crossModuleMethodMotion"; private static final String CONFIG_RESOURCE = "com.google.javascript.jscomp.parsing.ParserConfig"; CompilerOptions options = null; private PassConfig passes = null; // The externs inputs private List<CompilerInput> externs; // The JS source modules private List<JSModule> modules; // The graph of the JS source modules. Must be null if there are less than // 2 modules, because we use this as a signal for which passes to run. private JSModuleGraph moduleGraph; // The module loader for resolving paths into module URIs. private ModuleLoader moduleLoader; // The JS source inputs private List<CompilerInput> inputs; // error manager to which error management is delegated private ErrorManager errorManager; // Warnings guard for filtering warnings. private WarningsGuard warningsGuard; // Compile-time injected libraries. The node points to the last node of // the library, so code can be inserted after. private final Map<String, Node> injectedLibraries = new LinkedHashMap<>(); // Node of the final injected library. Future libraries will be injected // after this node. private Node lastInjectedLibrary; // Parse tree root nodes Node externsRoot; Node jsRoot; Node externAndJsRoot; // Used for debugging; to see the compiled code between passes private String lastJsSource = null; /** @see #getLanguageMode() */ private CompilerOptions.LanguageMode languageMode = CompilerOptions.LanguageMode.ECMASCRIPT3; private Map<InputId, CompilerInput> inputsById; // Function to load source files from disk or memory. private Function<String, SourceFile> originalSourcesLoader = new Function<String, SourceFile>() { @Override public SourceFile apply(String filename) { return SourceFile.fromFile(filename); } }; // Original sources referenced by the source maps. private ConcurrentHashMap<String, SourceFile> sourceMapOriginalSources = new ConcurrentHashMap<>(); /** Configured {@link SourceMapInput}s, plus any source maps discovered in source files. */ private final ConcurrentHashMap<String, SourceMapInput> inputSourceMaps = new ConcurrentHashMap<>(); // Map from filenames to lists of all the comments in each file. private Map<String, List<Comment>> commentsPerFile = new HashMap<>(); /** The source code map */ private SourceMap sourceMap; /** The externs created from the exports. */ private String externExports = null; /** * Ids for function inlining so that each declared name remains * unique. */ private int uniqueNameId = 0; /** * Whether to assume there are references to the RegExp Global object * properties. */ private boolean hasRegExpGlobalReferences = true; /** The function information map */ private FunctionInformationMap functionInformationMap; /** Debugging information */ private final StringBuilder debugLog = new StringBuilder(); /** Detects Google-specific coding conventions. */ CodingConvention defaultCodingConvention = new ClosureCodingConvention(); private JSTypeRegistry typeRegistry; private Config parserConfig = null; private Config externsParserConfig = null; private ReverseAbstractInterpreter abstractInterpreter; private TypeValidator typeValidator; // The compiler can ask phaseOptimizer for things like which pass is currently // running, or which functions have been changed by optimizations private PhaseOptimizer phaseOptimizer = null; public PerformanceTracker tracker; // Used by optimize-returns, optimize-parameters and remove-unused-variables private DefinitionUseSiteFinder defFinder = null; // Types that have been forward declared private final Set<String> forwardDeclaredTypes = new HashSet<>(); // For use by the new type inference private GlobalTypeInfo symbolTable; private MostRecentTypechecker mostRecentTypechecker = MostRecentTypechecker.NONE; // This error reporter gets the messages from the current Rhino parser or TypeRegistry. private final ErrorReporter oldErrorReporter = RhinoErrorReporter.forOldRhino(this); /** Error strings used for reporting JSErrors */ public static final DiagnosticType OPTIMIZE_LOOP_ERROR = DiagnosticType.error( "JSC_OPTIMIZE_LOOP_ERROR", "Exceeded max number of optimization iterations: {0}"); public static final DiagnosticType MOTION_ITERATIONS_ERROR = DiagnosticType.error("JSC_OPTIMIZE_LOOP_ERROR", "Exceeded max number of code motion iterations: {0}"); private final CompilerExecutor compilerExecutor = new CompilerExecutor(); /** * Logger for the whole com.google.javascript.jscomp domain - * setting configuration for this logger affects all loggers * in other classes within the compiler. */ public static final Logger logger = Logger.getLogger("com.google.javascript.jscomp"); private final PrintStream outStream; private GlobalVarReferenceMap globalRefMap = null; private volatile double progress = 0.0; private String lastPassName; private Set<String> externProperties = null; private static final Joiner pathJoiner = Joiner.on(File.separator); /** * Creates a Compiler that reports errors and warnings to its logger. */ public Compiler() { this((PrintStream) null); } /** * Creates a Compiler that reports errors and warnings to an output stream. */ public Compiler(PrintStream stream) { addChangeHandler(recentChange); this.outStream = stream; } /** * Creates a Compiler that uses a custom error manager. */ public Compiler(ErrorManager errorManager) { this(); setErrorManager(errorManager); } /** * Sets the error manager. * * @param errorManager the error manager, it cannot be {@code null} */ public void setErrorManager(ErrorManager errorManager) { Preconditions.checkNotNull( errorManager, "the error manager cannot be null"); this.errorManager = errorManager; } /** * Creates a message formatter instance corresponding to the value of * {@link CompilerOptions}. */ private MessageFormatter createMessageFormatter() { boolean colorize = options.shouldColorizeErrorOutput(); return options.errorFormat.toFormatter(this, colorize); } @VisibleForTesting void setOriginalSourcesLoader( Function<String, SourceFile> originalSourcesLoader) { this.originalSourcesLoader = originalSourcesLoader; } /** * Initializes the compiler options. It's called as part of a normal compile() job. * Public for the callers that are not doing a normal compile() job. */ public void initOptions(CompilerOptions options) { this.options = options; this.languageMode = options.getLanguageIn(); if (errorManager == null) { if (this.outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), this.outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } reconcileOptionsWithGuards(); // TODO(johnlenz): generally, the compiler should not be changing the options object // provided by the user. This should be handled a different way. // Turn off type-based optimizations when type checking is off if (!options.checkTypes) { options.setDisambiguateProperties(false); options.setAmbiguateProperties(false); options.setInlineProperties(false); options.setUseTypesForLocalOptimization(false); options.setUseTypesForOptimization(false); } if (options.legacyCodeCompile) { options.setDisambiguateProperties(false); options.setAmbiguateProperties(false); options.useNonStrictWarningsGuard(); } initWarningsGuard(options.getWarningsGuard()); } public void printConfig(PrintStream printStream) { printStream.println("==== CompilerOptions ===="); printStream.println(options.toString()); printStream.println("==== WarningsGuard ===="); printStream.println(warningsGuard.toString()); } void initWarningsGuard(WarningsGuard warningsGuard) { this.warningsGuard = new ComposeWarningsGuard( new SuppressDocWarningsGuard(getDiagnosticGroups().getRegisteredGroups()), warningsGuard); } /** * When the CompilerOptions and its WarningsGuard overlap, reconcile * any discrepencies. */ protected void reconcileOptionsWithGuards() { // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { // If DiagnosticGroups did not override the plain checkTypes // option, and checkTypes is enabled, then turn off the // parser type warnings. options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } DiagnosticGroupState ntiState = options.getWarningsGuard().enablesExplicitly(DiagnosticGroups.NEW_CHECK_TYPES); if (ntiState == DiagnosticGroupState.ON) { options.setNewTypeInference(true); } else if (ntiState == DiagnosticGroupState.OFF) { options.setNewTypeInference(false); } // With NTI, we still need OTI to run because the later passes that use // types only understand OTI types at the moment. // But we do not want to see the warnings from OTI. if (options.getNewTypeInference()) { options.checkTypes = true; // Suppress warnings from the const checks of CheckAccessControls so as to avoid // duplication. options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS_CONST, CheckLevel.OFF); if (!options.reportOTIErrorsUnderNTI) { options.setWarningLevel( DiagnosticGroups.OLD_CHECK_TYPES, CheckLevel.OFF); options.setWarningLevel( DiagnosticGroups.OLD_REPORT_UNKNOWN_TYPES, CheckLevel.OFF); options.setWarningLevel( FunctionTypeBuilder.ALL_DIAGNOSTICS, CheckLevel.OFF); } options.setWarningLevel( DiagnosticGroup.forType(RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.WARNING); } if (options.checkGlobalThisLevel.isOn() && !options.disables(DiagnosticGroups.GLOBAL_THIS)) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } if (expectStrictModeInput()) { options.setWarningLevel( DiagnosticGroups.ES5_STRICT, CheckLevel.ERROR); } // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. if (!options.checkSymbols && !options.enables(DiagnosticGroups.CHECK_VARIABLES)) { options.setWarningLevel( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF); } } private boolean expectStrictModeInput() { switch (options.getLanguageIn()) { case ECMASCRIPT3: case ECMASCRIPT5: case ECMASCRIPT6: return false; case ECMASCRIPT5_STRICT: case ECMASCRIPT6_STRICT: case ECMASCRIPT6_TYPED: return true; default: return options.isStrictModeInput(); } } /** * Initializes the instance state needed for a compile job. */ public <T1 extends SourceFile, T2 extends SourceFile> void init( List<T1> externs, List<T2> inputs, CompilerOptions options) { JSModule module = new JSModule(SINGLETON_MODULE_NAME); for (SourceFile input : inputs) { module.add(input); } List<JSModule> modules = new ArrayList<>(1); modules.add(module); initModules(externs, modules, options); addFilesToSourceMap(inputs); if (options.printConfig) { printConfig(System.err); } } /** * Initializes the instance state needed for a compile job if the sources * are in modules. */ public <T extends SourceFile> void initModules( List<T> externs, List<JSModule> modules, CompilerOptions options) { initOptions(options); checkFirstModule(modules); fillEmptyModules(modules); this.externs = makeCompilerInput(externs, true); // Generate the module graph, and report any errors in the module // specification as errors. this.modules = modules; if (modules.size() > 1) { try { this.moduleGraph = new JSModuleGraph(modules); } catch (JSModuleGraph.ModuleDependenceException e) { // problems with the module format. Report as an error. The // message gives all details. report(JSError.make(MODULE_DEPENDENCY_ERROR, e.getModule().getName(), e.getDependentModule().getName())); return; } } else { this.moduleGraph = null; } this.inputs = getAllInputsFromModules(modules); initBasedOnOptions(); initInputsByIdMap(); initAST(); } /** * Do any initialization that is dependent on the compiler options. */ private void initBasedOnOptions() { inputSourceMaps.putAll(options.inputSourceMaps); // Create the source map if necessary. if (options.sourceMapOutputPath != null) { sourceMap = options.sourceMapFormat.getInstance(); sourceMap.setPrefixMappings(options.sourceMapLocationMappings); if (options.applyInputSourceMaps) { sourceMap.setSourceFileMapping(this); } } } private <T extends SourceFile> List<CompilerInput> makeCompilerInput( List<T> files, boolean isExtern) { List<CompilerInput> inputs = new ArrayList<>(files.size()); for (T file : files) { inputs.add(new CompilerInput(file, isExtern)); } return inputs; } private static final DiagnosticType EMPTY_MODULE_LIST_ERROR = DiagnosticType.error("JSC_EMPTY_MODULE_LIST_ERROR", "At least one module must be provided"); private static final DiagnosticType EMPTY_ROOT_MODULE_ERROR = DiagnosticType.error("JSC_EMPTY_ROOT_MODULE_ERROR", "Root module ''{0}'' must contain at least one source code input"); /** * Verifies that at least one module has been provided and that the first one * has at least one source code input. */ private void checkFirstModule(List<JSModule> modules) { if (modules.isEmpty()) { report(JSError.make(EMPTY_MODULE_LIST_ERROR)); } else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) { // The root module may only be empty if there is exactly 1 module. report(JSError.make(EMPTY_ROOT_MODULE_ERROR, modules.get(0).getName())); } } /** * Empty modules get an empty "fill" file, so that we can move code into * an empty module. */ static String createFillFileName(String moduleName) { return moduleName + "$fillFile"; } /** * Creates an OS specific path string from parts */ public static String joinPathParts(String... pathParts) { return pathJoiner.join(pathParts); } /** * Fill any empty modules with a place holder file. It makes any cross module * motion easier. */ private static void fillEmptyModules(List<JSModule> modules) { for (JSModule module : modules) { if (module.getInputs().isEmpty()) { module.add(SourceFile.fromCode( createFillFileName(module.getName()), "")); } } } /** * Rebuilds the internal list of inputs by iterating over all modules. * This is necessary if inputs have been added to or removed from a module * after the {@link #init(List, List, CompilerOptions)} call. */ public void rebuildInputsFromModules() { inputs = getAllInputsFromModules(modules); initInputsByIdMap(); } /** * Builds a single list of all module inputs. Verifies that it contains no * duplicates. */ private static List<CompilerInput> getAllInputsFromModules( List<JSModule> modules) { List<CompilerInput> inputs = new ArrayList<>(); Map<String, JSModule> inputMap = new HashMap<>(); for (JSModule module : modules) { for (CompilerInput input : module.getInputs()) { String inputName = input.getName(); // NOTE(nicksantos): If an input is in more than one module, // it will show up twice in the inputs list, and then we // will get an error down the line. inputs.add(input); inputMap.put(inputName, module); } } return inputs; } static final DiagnosticType DUPLICATE_INPUT = DiagnosticType.error("JSC_DUPLICATE_INPUT", "Duplicate input: {0}"); static final DiagnosticType DUPLICATE_EXTERN_INPUT = DiagnosticType.error("JSC_DUPLICATE_EXTERN_INPUT", "Duplicate extern input: {0}"); /** * Returns the relative path, resolved relative to the base path, where the * base path is interpreted as a filename rather than a directory. E.g.: * getRelativeTo("../foo/bar.js", "baz/bam/qux.js") --> "baz/foo/bar.js" */ private static String getRelativeTo(String relative, String base) { return FileSystems.getDefault().getPath(base) .resolveSibling(relative) .normalize() .toString() .replace(File.separator, "/"); } /** * Creates a map to make looking up an input by name fast. Also checks for * duplicate inputs. */ void initInputsByIdMap() { inputsById = new HashMap<>(); for (CompilerInput input : externs) { InputId id = input.getInputId(); CompilerInput previous = putCompilerInput(id, input); if (previous != null) { report(JSError.make(DUPLICATE_EXTERN_INPUT, input.getName())); } } for (CompilerInput input : inputs) { InputId id = input.getInputId(); CompilerInput previous = putCompilerInput(id, input); if (previous != null) { report(JSError.make(DUPLICATE_INPUT, input.getName())); } } } /** * Sets up the skeleton of the AST (the externs and root). */ private void initAST() { jsRoot = IR.root(); externsRoot = IR.root(); externAndJsRoot = IR.root(externsRoot, jsRoot); } public Result compile( SourceFile extern, SourceFile input, CompilerOptions options) { return compile(ImmutableList.of(extern), ImmutableList.of(input), options); } /** * Compiles a list of inputs. */ public <T1 extends SourceFile, T2 extends SourceFile> Result compile( List<T1> externs, List<T2> inputs, CompilerOptions options) { // The compile method should only be called once. Preconditions.checkState(jsRoot == null); try { init(externs, inputs, options); if (hasErrors()) { return getResult(); } return compile(); } finally { Tracer t = newTracer("generateReport"); errorManager.generateReport(); stopTracer(t, "generateReport"); } } /** * Compiles a list of modules. */ public <T extends SourceFile> Result compileModules(List<T> externs, List<JSModule> modules, CompilerOptions options) { // The compile method should only be called once. Preconditions.checkState(jsRoot == null); try { initModules(externs, modules, options); if (hasErrors()) { return getResult(); } return compile(); } finally { Tracer t = newTracer("generateReport"); errorManager.generateReport(); stopTracer(t, "generateReport"); } } private Result compile() { return runInCompilerThread(new Callable<Result>() { @Override public Result call() throws Exception { compileInternal(); return getResult(); } }); } /** * Disable threads. This is for clients that run on AppEngine and * don't have threads. */ public void disableThreads() { compilerExecutor.disableThreads(); } /** * Sets the timeout when Compiler is run in a thread * @param timeout seconds to wait before timeout */ public void setTimeout(int timeout) { compilerExecutor.setTimeout(timeout); } /** * The primary purpose of this method is to run the provided code with a larger than standard * stack. */ <T> T runInCompilerThread(Callable<T> callable) { return compilerExecutor.runInCompilerThread( callable, options != null && options.getTracerMode().isOn()); } private void compileInternal() { setProgress(0.0, null); CompilerOptionsPreprocessor.preprocess(options); read(); // Guesstimate. setProgress(0.02, "read"); parse(); // Guesstimate. setProgress(0.15, "parse"); if (hasErrors()) { return; } if (!precheck()) { return; } if (options.skipNonTranspilationPasses) { // i.e. whitespace-only mode, which will not work with goog.module without: whitespaceOnlyPasses(); if (options.lowerFromEs6()) { transpileAndDontCheck(); } } else { check(); // check() also includes transpilation if (hasErrors()) { return; } if (!options.checksOnly && !options.shouldGenerateTypedExterns()) { optimize(); } } if (options.recordFunctionInformation) { recordFunctionInformation(); } if (options.devMode == DevMode.START_AND_END) { runSanityCheck(); } setProgress(1.0, "recordFunctionInformation"); if (tracker != null) { tracker.outputTracerReport(); } } public void read() { readInputs(); } public void parse() { parseInputs(); } PassConfig getPassConfig() { if (passes == null) { passes = createPassConfigInternal(); } return passes; } /** * Create the passes object. Clients should use setPassConfig instead of * overriding this. */ PassConfig createPassConfigInternal() { return new DefaultPassConfig(options); } /** * @param passes The PassConfig to use with this Compiler. * @throws NullPointerException if passes is null * @throws IllegalStateException if this.passes has already been assigned */ public void setPassConfig(PassConfig passes) { // Important to check for null because if setPassConfig(null) is // called before this.passes is set, getPassConfig() will create a // new PassConfig object and use that, which is probably not what // the client wanted since they probably meant to use their // own PassConfig object. Preconditions.checkNotNull(passes); Preconditions.checkState(this.passes == null, "setPassConfig was already called"); this.passes = passes; } /** * Carry out any special checks or procedures that need to be done before * proceeding with rest of the compilation process. * * @return true, to continue with compilation */ boolean precheck() { return true; } public void whitespaceOnlyPasses() { runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS); Tracer t = newTracer("runWhitespaceOnlyPasses"); try { for (PassFactory pf : getPassConfig().getWhitespaceOnlyPasses()) { pf.create(this).process(externsRoot, jsRoot); } } finally { stopTracer(t, "runWhitespaceOnlyPasses"); } } public void transpileAndDontCheck() { Tracer t = newTracer("runTranspileOnlyPasses"); try { for (PassFactory pf : getPassConfig().getTranspileOnlyPasses()) { pf.create(this).process(externsRoot, jsRoot); } } finally { stopTracer(t, "runTranspileOnlyPasses"); } } public void check() { runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS); // We are currently only interested in check-passes for progress reporting // as it is used for IDEs, that's why the maximum progress is set to 1.0. phaseOptimizer = new PhaseOptimizer(this, tracker, new PhaseOptimizer.ProgressRange(getProgress(), 1.0)); if (options.devMode == DevMode.EVERY_PASS) { phaseOptimizer.setSanityCheck(sanityCheck); } if (options.getCheckDeterminism()) { phaseOptimizer.setPrintAstHashcodes(true); } phaseOptimizer.consume(getPassConfig().getChecks()); phaseOptimizer.process(externsRoot, jsRoot); if (hasErrors()) { return; } if (options.getTweakProcessing().shouldStrip() || !options.stripTypes.isEmpty() || !options.stripNameSuffixes.isEmpty() || !options.stripTypePrefixes.isEmpty() || !options.stripNamePrefixes.isEmpty()) { stripCode(options.stripTypes, options.stripNameSuffixes, options.stripTypePrefixes, options.stripNamePrefixes); } runCustomPasses(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS); phaseOptimizer = null; } private void externExports() { logger.fine("Creating extern file for exports"); startPass("externExports"); ExternExportsPass pass = new ExternExportsPass(this); process(pass); externExports = pass.getGeneratedExterns(); endPass("externExports"); } @Override void process(CompilerPass p) { p.process(externsRoot, jsRoot); } private final PassFactory sanityCheck = new PassFactory("sanityCheck", false) { @Override protected CompilerPass create(AbstractCompiler compiler) { return new SanityCheck(compiler); } }; private void maybeSanityCheck() { if (options.devMode == DevMode.EVERY_PASS) { runSanityCheck(); } } private void runSanityCheck() { sanityCheck.create(this).process(externsRoot, jsRoot); } /** * Strips code for smaller compiled code. This is useful for removing debug * statements to prevent leaking them publicly. */ void stripCode(Set<String> stripTypes, Set<String> stripNameSuffixes, Set<String> stripTypePrefixes, Set<String> stripNamePrefixes) { logger.fine("Strip code"); startPass("stripCode"); StripCode r = new StripCode(this, stripTypes, stripNameSuffixes, stripTypePrefixes, stripNamePrefixes); if (options.getTweakProcessing().shouldStrip()) { r.enableTweakStripping(); } process(r); endPass("stripCode"); } /** * Runs custom passes that are designated to run at a particular time. */ private void runCustomPasses(CustomPassExecutionTime executionTime) { if (options.customPasses != null) { Tracer t = newTracer("runCustomPasses"); try { for (CompilerPass p : options.customPasses.get(executionTime)) { process(p); } } finally { stopTracer(t, "runCustomPasses"); } } } private Tracer currentTracer = null; private String currentPassName = null; /** * Marks the beginning of a pass. */ void startPass(String passName) { Preconditions.checkState(currentTracer == null); currentPassName = passName; currentTracer = newTracer(passName); beforePass(passName); } /** * Marks the end of a pass. */ void endPass(String passName) { Preconditions.checkState(currentTracer != null, "Tracer should not be null at the end of a pass."); stopTracer(currentTracer, currentPassName); afterPass(passName); currentPassName = null; currentTracer = null; maybeSanityCheck(); } @Override final void beforePass(String passName) { // does nothing for now } @Override final void afterPass(String passName) { if (options.printSourceAfterEachPass) { String currentJsSource = getCurrentJsSource(); if (!currentJsSource.equals(this.lastJsSource)) { System.out.println(); System.out.println("// " + passName + " yields:"); System.out.println("// ************************************"); System.out.println(currentJsSource); lastJsSource = currentJsSource; } } } final String getCurrentJsSource() { List<String> filenames = options.filesToPrintAfterEachPass; if (filenames.isEmpty()) { return toSource(); } else { StringBuilder builder = new StringBuilder(); for (String filename : filenames) { Node script = getScriptNode(filename); String source = script != null ? "// " + script.getSourceFileName() + "\n" + toSource(script) : "File '" + filename + "' not found"; builder.append(source); } return builder.toString(); } } final Node getScriptNode(String filename) { for (Node file : jsRoot.children()) { if (file.getSourceFileName() != null && file.getSourceFileName().endsWith(filename)) { return file; } } return null; } /** * Returns a new tracer for the given pass name. */ Tracer newTracer(String passName) { String comment = passName + (recentChange.hasCodeChanged() ? " on recently changed AST" : ""); if (options.getTracerMode().isOn() && tracker != null) { tracker.recordPassStart(passName, true); } return new Tracer("Compiler", comment); } void stopTracer(Tracer t, String passName) { long result = t.stop(); if (options.getTracerMode().isOn() && tracker != null) { tracker.recordPassStop(passName, result); } } /** * Returns the result of the compilation. */ public Result getResult() { PassConfig.State state = getPassConfig().getIntermediateState(); Set<SourceFile> transpiledFiles = new HashSet<>(); if (jsRoot != null) { for (Node scriptNode : jsRoot.children()) { if (scriptNode.getBooleanProp(Node.TRANSPILED)) { transpiledFiles.add(getSourceFileByName(scriptNode.getSourceFileName())); } } } return new Result(getErrors(), getWarnings(), debugLog.toString(), state.variableMap, state.propertyMap, state.anonymousFunctionNameMap, state.stringMap, functionInformationMap, sourceMap, externExports, state.cssNames, state.idGeneratorMap, transpiledFiles); } /** * Returns the array of errors (never null). */ public JSError[] getErrors() { if (errorManager == null) { return new JSError[] {}; } return errorManager.getErrors(); } /** * Returns the array of warnings (never null). */ public JSError[] getWarnings() { if (errorManager == null) { return new JSError[] {}; } return errorManager.getWarnings(); } @Override public Node getRoot() { return externAndJsRoot; } @Override CompilerOptions.LanguageMode getLanguageMode() { return languageMode; } @Override void setLanguageMode(CompilerOptions.LanguageMode mode) { languageMode = mode; } /** * Creates a new id for making unique names. */ private int nextUniqueNameId() { return uniqueNameId++; } /** * Resets the unique name id counter */ @VisibleForTesting void resetUniqueNameId() { uniqueNameId = 0; } @Override Supplier<String> getUniqueNameIdSupplier() { final Compiler self = this; return new Supplier<String>() { @Override public String get() { return String.valueOf(self.nextUniqueNameId()); } }; } @Override boolean areNodesEqualForInlining(Node n1, Node n2) { if (options.shouldAmbiguateProperties() || options.shouldDisambiguateProperties()) { // The type based optimizations require that type information is preserved // during other optimizations. return n1.isEquivalentToTyped(n2); } else { return n1.isEquivalentTo(n2); } } //------------------------------------------------------------------------ // Inputs //------------------------------------------------------------------------ // TODO(nicksantos): Decide which parts of these belong in an AbstractCompiler // interface, and which ones should always be injected. @Override public CompilerInput getInput(InputId id) { return inputsById.get(id); } /** * Removes an input file from AST. * @param id The id of the input to be removed. */ protected void removeExternInput(InputId id) { CompilerInput input = getInput(id); if (input == null) { return; } Preconditions.checkState(input.isExtern(), "Not an extern input: %s", input.getName()); inputsById.remove(id); externs.remove(input); Node root = input.getAstRoot(this); if (root != null) { root.detach(); } } // Where to put a new synthetic externs file. private static enum SyntheticExternsPosition { START, END } CompilerInput newExternInput(String name, SyntheticExternsPosition pos) { SourceAst ast = new SyntheticAst(name); if (inputsById.containsKey(ast.getInputId())) { throw new IllegalArgumentException("Conflicting externs name: " + name); } CompilerInput input = new CompilerInput(ast, true); putCompilerInput(input.getInputId(), input); if (pos == SyntheticExternsPosition.START) { externsRoot.addChildToFront(ast.getAstRoot(this)); externs.add(0, input); } else { externsRoot.addChildToBack(ast.getAstRoot(this)); externs.add(input); } return input; } CompilerInput putCompilerInput(InputId id, CompilerInput input) { if (inputsById == null) { inputsById = new HashMap<>(); } input.setCompiler(this); return inputsById.put(id, input); } /** * Replace a source input dynamically. Intended for incremental * re-compilation. * * If the new source input doesn't parse, then keep the old input * in the AST and return false. * * @return Whether the new AST was attached successfully. */ boolean replaceIncrementalSourceAst(JsAst ast) { CompilerInput oldInput = getInput(ast.getInputId()); Preconditions.checkNotNull(oldInput, "No input to replace: %s", ast.getInputId().getIdName()); Node newRoot = ast.getAstRoot(this); if (newRoot == null) { return false; } Node oldRoot = oldInput.getAstRoot(this); if (oldRoot != null) { oldRoot.replaceWith(newRoot); } else { getRoot().getLastChild().addChildToBack(newRoot); } CompilerInput newInput = new CompilerInput(ast); putCompilerInput(ast.getInputId(), newInput); JSModule module = oldInput.getModule(); if (module != null) { module.addAfter(newInput, oldInput); module.remove(oldInput); } // Verify the input id is set properly. Preconditions.checkState( newInput.getInputId().equals(oldInput.getInputId())); InputId inputIdOnAst = newInput.getAstRoot(this).getInputId(); Preconditions.checkState(newInput.getInputId().equals(inputIdOnAst)); inputs.remove(oldInput); return true; } /** * Add a new source input dynamically. Intended for incremental compilation. * <p> * If the new source input doesn't parse, it will not be added, and a false * will be returned. * * @param ast the JS Source to add. * @return true if the source was added successfully, false otherwise. * @throws IllegalStateException if an input for this ast already exists. */ boolean addNewSourceAst(JsAst ast) { CompilerInput oldInput = getInput(ast.getInputId()); if (oldInput != null) { throw new IllegalStateException( "Input already exists: " + ast.getInputId().getIdName()); } Node newRoot = ast.getAstRoot(this); if (newRoot == null) { return false; } getRoot().getLastChild().addChildToBack(newRoot); CompilerInput newInput = new CompilerInput(ast); // TODO(tylerg): handle this for multiple modules at some point. if (moduleGraph == null && !modules.isEmpty()) { // singleton module modules.get(0).add(newInput); } putCompilerInput(ast.getInputId(), newInput); return true; } @Override JSModuleGraph getModuleGraph() { return moduleGraph; } /** * Gets a module graph. This will always return a module graph, even * in the degenerate case when there's only one module. */ JSModuleGraph getDegenerateModuleGraph() { return moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph; } @Override public TypeIRegistry getTypeIRegistry() { switch (mostRecentTypechecker) { case NONE: // Even in compiles where typechecking is not enabled, some passes ask for the // type registry, eg, GatherExternProperties does. Also, in CheckAccessControls, // the constructor asks for a type registry, and this may happen before type checking // runs. So, in the NONE case, if NTI is enabled, return a new registry, since NTI is // the relevant type checker. If NTI is not enabled, return an old registry. return options.getNewTypeInference() ? getSymbolTable() : getTypeRegistry(); case OTI: return getTypeRegistry(); case NTI: return getSymbolTable(); default: throw new RuntimeException("Unhandled typechecker " + mostRecentTypechecker); } } @Override public JSTypeRegistry getTypeRegistry() { if (typeRegistry == null) { typeRegistry = new JSTypeRegistry(oldErrorReporter, forwardDeclaredTypes); } return typeRegistry; } @Override void forwardDeclareType(String typeName) { if (options.allowUnfulfilledForwardDeclarations()) { forwardDeclaredTypes.add(typeName); } } @Override void setMostRecentTypechecker(MostRecentTypechecker lastRun) { this.mostRecentTypechecker = lastRun; } @Override // Only used by jsdev public MemoizedScopeCreator getTypedScopeCreator() { return getPassConfig().getTypedScopeCreator(); } @SuppressWarnings("unchecked") DefaultPassConfig ensureDefaultPassConfig() { PassConfig passes = getPassConfig().getBasePassConfig(); Preconditions.checkState(passes instanceof DefaultPassConfig, "PassConfigs must eventually delegate to the DefaultPassConfig"); return (DefaultPassConfig) passes; } public SymbolTable buildKnownSymbolTable() { SymbolTable symbolTable = new SymbolTable(this, getTypeRegistry()); MemoizedScopeCreator typedScopeCreator = getTypedScopeCreator(); if (typedScopeCreator != null) { symbolTable.addScopes(typedScopeCreator.getAllMemoizedScopes()); symbolTable.addSymbolsFrom(typedScopeCreator); } else { symbolTable.findScopes(externsRoot, jsRoot); } GlobalNamespace globalNamespace = ensureDefaultPassConfig().getGlobalNamespace(); if (globalNamespace != null) { symbolTable.addSymbolsFrom(globalNamespace); } ReferenceCollectingCallback refCollector = new ReferenceCollectingCallback( this, ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR, SyntacticScopeCreator.makeUntyped(this)); refCollector.process(getRoot()); symbolTable.addSymbolsFrom(refCollector); PreprocessorSymbolTable preprocessorSymbolTable = ensureDefaultPassConfig().getPreprocessorSymbolTable(); if (preprocessorSymbolTable != null) { symbolTable.addSymbolsFrom(preprocessorSymbolTable); } symbolTable.fillNamespaceReferences(); symbolTable.fillPropertyScopes(); symbolTable.fillThisReferences(externsRoot, jsRoot); symbolTable.fillPropertySymbols(externsRoot, jsRoot); symbolTable.fillJSDocInfo(externsRoot, jsRoot); symbolTable.fillSymbolVisibility(externsRoot, jsRoot); return symbolTable; } @Override public TypedScope getTopScope() { return getPassConfig().getTopScope(); } @Override public ReverseAbstractInterpreter getReverseAbstractInterpreter() { if (abstractInterpreter == null) { ChainableReverseAbstractInterpreter interpreter = new SemanticReverseAbstractInterpreter(getTypeRegistry()); if (options.closurePass) { interpreter = new ClosureReverseAbstractInterpreter(getTypeRegistry()) .append(interpreter).getFirst(); } abstractInterpreter = interpreter; } return abstractInterpreter; } @Override // Only used by passes in the old type checker. TypeValidator getTypeValidator() { if (typeValidator == null) { typeValidator = new TypeValidator(this); } return typeValidator; } @Override Iterable<TypeMismatch> getTypeMismatches() { return getTypeValidator().getMismatches(); } @Override Iterable<TypeMismatch> getImplicitInterfaceUses() { return getTypeValidator().getImplicitInterfaceUses(); } @Override GlobalTypeInfo getSymbolTable() { if (this.symbolTable == null) { this.symbolTable = new GlobalTypeInfo(this, forwardDeclaredTypes); } return this.symbolTable; } @Override DefinitionUseSiteFinder getDefinitionFinder() { return this.defFinder; } @Override void setDefinitionFinder(DefinitionUseSiteFinder defFinder) { this.defFinder = defFinder; } //------------------------------------------------------------------------ // Reading //------------------------------------------------------------------------ /** * Performs all externs and main inputs IO. * * <p>Allows for easy measurement of IO cost separately from parse cost. */ void readInputs() { if (options.getTracerMode().isOn()) { tracker = new PerformanceTracker(externsRoot, jsRoot, options.getTracerMode(), this.outStream); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer(READING_PASS_NAME); beforePass(READING_PASS_NAME); try { for (CompilerInput input : Iterables.concat(externs, inputs)) { try { input.getCode(); } catch (IOException e) { report(JSError.make(AbstractCompiler.READ_ERROR, input.getName())); } } } finally { afterPass(READING_PASS_NAME); stopTracer(tracer, READING_PASS_NAME); } } //------------------------------------------------------------------------ // Parsing //------------------------------------------------------------------------ /** * Parses the externs and main inputs. * * @return A synthetic root node whose two children are the externs root * and the main root */ Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; // If old roots exist (we are parsing a second time), detach each of the // individual file parse trees. externsRoot.detachChildren(); jsRoot.detachChildren(); Tracer tracer = newTracer(PARSING_PASS_NAME); beforePass(PARSING_PASS_NAME); try { // Parse externs sources. for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } if (options.lowerFromEs6() || options.transformAMDToCJSModules || options.processCommonJSModules) { this.moduleLoader = new ModuleLoader( this, options.moduleRoots, inputs, ModuleLoader.PathResolver.RELATIVE, options.moduleResolutionMode); if (options.moduleResolutionMode == ModuleLoader.ResolutionMode.NODE) { this.moduleLoader.setPackageJsonMainEntries(processJsonInputs(inputs)); } if (options.lowerFromEs6()) { processEs6Modules(); } // Modules inferred in ProcessCommonJS pass. if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } // Build a map of module identifiers for any input which provides no namespace. // These files could be imported modules which have no exports, but do have side effects. Map<String, CompilerInput> inputModuleIdentifiers = new HashMap<>(); for (CompilerInput input : inputs) { if (input.getKnownProvides().isEmpty()) { ModuleIdentifier modInfo = ModuleIdentifier.forFile(input.getSourceFile().getOriginalPath()); inputModuleIdentifiers.put(modInfo.getClosureNamespace(), input); } } // Find out if any input attempted to import a module that had no exports. // In this case we must force module rewriting to occur on the imported file Map<String, CompilerInput> inputsToRewrite = new HashMap<>(); for (CompilerInput input : inputs) { for (String require : input.getKnownRequires()) { if (inputModuleIdentifiers.containsKey(require) && !inputsToRewrite.containsKey(require)) { inputsToRewrite.put(require, inputModuleIdentifiers.get(require)); } } } if (!inputsToRewrite.isEmpty()) { processEs6Modules(new ArrayList<>(inputsToRewrite.values()), true); } } else { // Use an empty module loader if we're not actually dealing with modules. this.moduleLoader = ModuleLoader.EMPTY; } orderInputs(); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } // Build the AST. for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } // TODO(johnlenz): we shouldn't need to check both isExternExportsEnabled and // externExportsPath. if (options.sourceMapOutputPath != null || options.isExternExportsEnabled() || options.externExportsPath != null || !options.replaceStringsFunctionDescriptions.isEmpty()) { // Annotate the nodes in the tree with information from the // input file. This information is used to construct the SourceMap. SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverseEs6(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { afterPass(PARSING_PASS_NAME); stopTracer(tracer, PARSING_PASS_NAME); } } void orderInputsWithLargeStack() { runInCompilerThread(new Callable<Void>() { @Override public Void call() throws Exception { Tracer tracer = newTracer("orderInputsWithLargeStack"); try { orderInputs(); } finally { stopTracer(tracer, "orderInputsWithLargeStack"); } return null; } }); } void orderInputs() { hoistUnorderedExterns(); // Check if the sources need to be re-ordered. boolean staleInputs = false; if (options.dependencyOptions.needsManagement()) { for (CompilerInput input : inputs) { // Forward-declare all the provided types, so that they // are not flagged even if they are dropped from the process. for (String provide : input.getProvides()) { forwardDeclareType(provide); } } try { inputs = getDegenerateModuleGraph().manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); } catch (JSModuleGraph.MissingModuleException e) { report(JSError.make( MISSING_MODULE_ERROR, e.getMessage())); } } if (options.dependencyOptions.needsManagement() && options.allowGoogProvideInExterns()) { hoistAllExterns(); } hoistNoCompileFiles(); if (staleInputs) { repartitionInputs(); } } /** * Hoists inputs with the @externs annotation and no provides or requires into the externs list. */ void hoistUnorderedExterns() { boolean staleInputs = false; for (CompilerInput input : inputs) { if (options.dependencyOptions.needsManagement()) { // If we're doing scanning dependency info anyway, use that // information to skip sources that obviously aren't externs. if (!input.getProvides().isEmpty() || !input.getRequires().isEmpty()) { continue; } } if (hoistIfExtern(input)) { staleInputs = true; } } if (staleInputs) { repartitionInputs(); } } /** * Hoists inputs with the @externs annotation into the externs list. */ void hoistAllExterns() { boolean staleInputs = false; for (CompilerInput input : inputs) { if (hoistIfExtern(input)) { staleInputs = true; } } if (staleInputs) { repartitionInputs(); } } /** * Hoists a compiler input to externs if it contains the @externs annotation. * Return whether or not the given input was hoisted. */ private boolean hoistIfExtern(CompilerInput input) { Node n = input.getAstRoot(this); // Inputs can have a null AST on a parse error. if (n == null) { return false; } JSDocInfo info = n.getJSDocInfo(); if (info != null && info.isExterns()) { // If the input file is explicitly marked as an externs file, then // assume the programmer made a mistake and throw it into // the externs pile anyways. externsRoot.addChildToBack(n); input.setIsExtern(true); input.getModule().remove(input); externs.add(input); return true; } return false; } /** * Hoists inputs with the @nocompile annotation out of the inputs. */ void hoistNoCompileFiles() { boolean staleInputs = false; for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); // Inputs can have a null AST on a parse error. if (n == null) { continue; } JSDocInfo info = n.getJSDocInfo(); if (info != null && info.isNoCompile()) { input.getModule().remove(input); staleInputs = true; } } if (staleInputs) { repartitionInputs(); } } private void repartitionInputs() { fillEmptyModules(modules); rebuildInputsFromModules(); } /** * Transforms JSON files to a module export that closure compiler can process and keeps track of * any "main" entries in package.json files. */ Map<String, String> processJsonInputs(List<CompilerInput> inputsToProcess) { RewriteJsonToModule rewriteJson = new RewriteJsonToModule(this); for (CompilerInput input : inputsToProcess) { if (!input.getSourceFile().getOriginalPath().endsWith(".json")) { continue; } input.setCompiler(this); try { // JSON objects need wrapped in parens to parse properly input.getSourceFile().setCode("(" + input.getSourceFile().getCode() + ")"); } catch (IOException e) { continue; } Node root = input.getAstRoot(this); if (root == null) { continue; } rewriteJson.process(null, root); } return rewriteJson.getPackageJsonMainEntries(); } void processEs6Modules() { processEs6Modules(inputs, false); } void processEs6Modules(List<CompilerInput> inputsToProcess, boolean forceRewrite) { for (CompilerInput input : inputsToProcess) { input.setCompiler(this); Node root = input.getAstRoot(this); if (root == null) { continue; } new ProcessEs6Modules(this).processFile(root, forceRewrite); } } /** * Transforms AMD and CJS modules to something closure compiler can * process and creates JSModules and the corresponding dependency tree * on the way. */ void processAMDAndCommonJSModules() { for (CompilerInput input : inputs) { input.setCompiler(this); Node root = input.getAstRoot(this); if (root == null) { continue; } if (options.transformAMDToCJSModules) { new TransformAMDToCJSModule(this).process(null, root); } if (options.processCommonJSModules) { ProcessCommonJSModules cjs = new ProcessCommonJSModules(this, true); cjs.process(null, root); } } } public Node parse(SourceFile file) { initCompilerOptionsIfTesting(); addToDebugLog("Parsing: " + file.getName()); return new JsAst(file).getAstRoot(this); } private int syntheticCodeId = 0; @Override Node parseSyntheticCode(String js) { SourceFile source = SourceFile.fromCode(" [synthetic:" + (++syntheticCodeId) + "] ", js); addFilesToSourceMap(ImmutableList.of(source)); CompilerInput input = new CompilerInput(source); putCompilerInput(input.getInputId(), input); return input.getAstRoot(this); } /** * Allow subclasses to override the default CompileOptions object. */ protected CompilerOptions newCompilerOptions() { return new CompilerOptions(); } void initCompilerOptionsIfTesting() { if (options == null) { // initialization for tests that don't initialize the compiler // by the normal mechanisms. initOptions(newCompilerOptions()); } } @Override Node parseSyntheticCode(String fileName, String js) { initCompilerOptionsIfTesting(); addFileToSourceMap(fileName, js); CompilerInput input = new CompilerInput(SourceFile.fromCode(fileName, js)); putCompilerInput(input.getInputId(), input); return input.getAstRoot(this); } @Override Node parseTestCode(String js) { initCompilerOptionsIfTesting(); initBasedOnOptions(); CompilerInput input = new CompilerInput( SourceFile.fromCode("[testcode]", js)); if (inputsById == null) { inputsById = new HashMap<>(); } putCompilerInput(input.getInputId(), input); return input.getAstRoot(this); } @Override ErrorReporter getDefaultErrorReporter() { return oldErrorReporter; } //------------------------------------------------------------------------ // Convert back to source code //------------------------------------------------------------------------ /** * Converts the main parse tree back to JS code. */ @Override public String toSource() { return runInCompilerThread(new Callable<String>() { @Override public String call() throws Exception { Tracer tracer = newTracer("toSource"); try { CodeBuilder cb = new CodeBuilder(); if (jsRoot != null) { int i = 0; for (Node scriptNode = jsRoot.getFirstChild(); scriptNode != null; scriptNode = scriptNode.getNext()) { toSource(cb, i++, scriptNode); } } return cb.toString(); } finally { stopTracer(tracer, "toSource"); } } }); } /** * Converts the parse tree for each input back to JS code. */ public String[] toSourceArray() { return runInCompilerThread(new Callable<String[]>() { @Override public String[] call() throws Exception { Tracer tracer = newTracer("toSourceArray"); try { int numInputs = inputs.size(); String[] sources = new String[numInputs]; CodeBuilder cb = new CodeBuilder(); for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); cb.reset(); toSource(cb, i, scriptNode); sources[i] = cb.toString(); } return sources; } finally { stopTracer(tracer, "toSourceArray"); } } }); } /** * Converts the parse tree for a module back to JS code. */ public String toSource(final JSModule module) { return runInCompilerThread(new Callable<String>() { @Override public String call() throws Exception { List<CompilerInput> inputs = module.getInputs(); int numInputs = inputs.size(); if (numInputs == 0) { return ""; } CodeBuilder cb = new CodeBuilder(); for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); if (scriptNode == null) { throw new IllegalArgumentException( "Bad module: " + module.getName()); } toSource(cb, i, scriptNode); } return cb.toString(); } }); } /** * Converts the parse tree for each input in a module back to JS code. */ public String[] toSourceArray(final JSModule module) { return runInCompilerThread(new Callable<String[]>() { @Override public String[] call() throws Exception { List<CompilerInput> inputs = module.getInputs(); int numInputs = inputs.size(); if (numInputs == 0) { return new String[0]; } String[] sources = new String[numInputs]; CodeBuilder cb = new CodeBuilder(); for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); if (scriptNode == null) { throw new IllegalArgumentException( "Bad module input: " + inputs.get(i).getName()); } cb.reset(); toSource(cb, i, scriptNode); sources[i] = cb.toString(); } return sources; } }); } /** * Writes out JS code from a root node. If printing input delimiters, this * method will attach a comment to the start of the text indicating which * input the output derived from. If there were any preserve annotations * within the root's source, they will also be printed in a block comment * at the beginning of the output. */ public void toSource(final CodeBuilder cb, final int inputSeqNum, final Node root) { runInCompilerThread(new Callable<Void>() { @Override public Void call() throws Exception { if (options.printInputDelimiter) { if ((cb.getLength() > 0) && !cb.endsWith("\n")) { cb.append("\n"); // Make sure that the label starts on a new line } Preconditions.checkState(root.isScript()); String delimiter = options.inputDelimiter; String inputName = root.getInputId().getIdName(); String sourceName = root.getSourceFileName(); Preconditions.checkState(sourceName != null); Preconditions.checkState(!sourceName.isEmpty()); delimiter = delimiter .replaceAll("%name%", Matcher.quoteReplacement(inputName)) .replaceAll("%num%", String.valueOf(inputSeqNum)); cb.append(delimiter) .append("\n"); } if (root.getJSDocInfo() != null) { String license = root.getJSDocInfo().getLicense(); if (license != null && cb.addLicense(license)) { cb.append("/*\n") .append(license) .append("*/\n"); } } // If there is a valid source map, then indicate to it that the current // root node's mappings are offset by the given string builder buffer. if (options.sourceMapOutputPath != null) { sourceMap.setStartingPosition( cb.getLineIndex(), cb.getColumnIndex()); } // if LanguageMode is strict, only print 'use strict' // for the first input file String code = toSource(root, sourceMap, inputSeqNum == 0); if (!code.isEmpty()) { cb.append(code); // In order to avoid parse ambiguity when files are concatenated // together, all files should end in a semi-colon. Do a quick // heuristic check if there's an obvious semi-colon already there. int length = code.length(); char lastChar = code.charAt(length - 1); char secondLastChar = length >= 2 ? code.charAt(length - 2) : '\0'; boolean hasSemiColon = lastChar == ';' || (lastChar == '\n' && secondLastChar == ';'); if (!hasSemiColon) { cb.append(";"); } } return null; } }); } /** * Generates JavaScript source code for an AST, doesn't generate source * map info. */ @Override public String toSource(Node n) { initCompilerOptionsIfTesting(); return toSource(n, null, true); } /** * Generates JavaScript source code for an AST. */ private String toSource(Node n, SourceMap sourceMap, boolean firstOutput) { CodePrinter.Builder builder = new CodePrinter.Builder(n); builder.setTypeRegistry(this.typeRegistry); builder.setCompilerOptions(options); builder.setSourceMap(sourceMap); builder.setTagAsExterns(firstOutput && options.shouldGenerateTypedExterns()); builder.setTagAsStrict(firstOutput && shouldEmitUseStrict()); return builder.build(); } private boolean shouldEmitUseStrict() { switch (options.getLanguageOut()) { case ECMASCRIPT3: case ECMASCRIPT5: case ECMASCRIPT6: return false; default: return options.isEmitUseStrict(); } } /** * Stores a buffer of text to which more can be appended. This is just like a * StringBuilder except that we also track the number of lines. */ public static class CodeBuilder { private final StringBuilder sb = new StringBuilder(); private int lineCount = 0; private int colCount = 0; private final Set<String> uniqueLicenses = new HashSet<>(); /** Removes all text, but leaves the line count unchanged. */ void reset() { sb.setLength(0); } /** Appends the given string to the text buffer. */ CodeBuilder append(String str) { sb.append(str); // Adjust the line and column information for the new text. int index = -1; int lastIndex = index; while ((index = str.indexOf('\n', index + 1)) >= 0) { ++lineCount; lastIndex = index; } if (lastIndex == -1) { // No new lines, append the new characters added. colCount += str.length(); } else { colCount = str.length() - (lastIndex + 1); } return this; } /** Returns all text in the text buffer. */ @Override public String toString() { return sb.toString(); } /** Returns the length of the text buffer. */ public int getLength() { return sb.length(); } /** Returns the (zero-based) index of the last line in the text buffer. */ int getLineIndex() { return lineCount; } /** Returns the (zero-based) index of the last column in the text buffer. */ int getColumnIndex() { return colCount; } /** Determines whether the text ends with the given suffix. */ boolean endsWith(String suffix) { return (sb.length() > suffix.length()) && suffix.equals(sb.substring(sb.length() - suffix.length())); } /** Adds a license and returns whether it is unique (has yet to be encountered). */ boolean addLicense(String license) { return uniqueLicenses.add(license); } } //------------------------------------------------------------------------ // Optimizations //------------------------------------------------------------------------ public void optimize() { List<PassFactory> optimizations = getPassConfig().getOptimizations(); if (optimizations.isEmpty()) { return; } // Ideally, this pass should be the first pass run, however: // 1) VariableReferenceCheck reports unexpected warnings if Normalize // is done first. // 2) ReplaceMessages, stripCode, and potentially custom passes rely on // unmodified local names. normalize(); // Create extern exports after the normalize because externExports depends on unique names. if (options.isExternExportsEnabled() || options.externExportsPath != null) { externExports(); } phaseOptimizer = new PhaseOptimizer(this, tracker, null); if (options.devMode == DevMode.EVERY_PASS) { phaseOptimizer.setSanityCheck(sanityCheck); } if (options.getCheckDeterminism()) { phaseOptimizer.setPrintAstHashcodes(true); } phaseOptimizer.consume(optimizations); phaseOptimizer.process(externsRoot, jsRoot); phaseOptimizer = null; } @Override void setCssRenamingMap(CssRenamingMap map) { options.cssRenamingMap = map; } @Override CssRenamingMap getCssRenamingMap() { return options.cssRenamingMap; } /** Control Flow Analysis. */ ControlFlowGraph<Node> computeCFG() { logger.fine("Computing Control Flow Graph"); Tracer tracer = newTracer("computeCFG"); ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false); process(cfa); stopTracer(tracer, "computeCFG"); return cfa.getCfg(); } public void normalize() { logger.fine("Normalizing"); startPass("normalize"); process(new Normalize(this, false)); endPass("normalize"); } @Override void prepareAst(Node root) { CompilerPass pass = new PrepareAst(this); pass.process(null, root); } void recordFunctionInformation() { logger.fine("Recording function information"); startPass("recordFunctionInformation"); RecordFunctionInformation recordFunctionInfoPass = new RecordFunctionInformation( this, getPassConfig().getIntermediateState().functionNames); process(recordFunctionInfoPass); functionInformationMap = recordFunctionInfoPass.getMap(); endPass("recordFunctionInformation"); } protected final RecentChange recentChange = new RecentChange(); private final List<CodeChangeHandler> codeChangeHandlers = new ArrayList<>(); /** Name of the synthetic input that holds synthesized externs. */ static final String SYNTHETIC_EXTERNS = "{SyntheticVarsDeclar}"; /** * Name of the synthetic input that holds synthesized externs which * must be at the end of the externs AST. */ static final String SYNTHETIC_EXTERNS_AT_END = "{SyntheticVarsAtEnd}"; private CompilerInput synthesizedExternsInput = null; private CompilerInput synthesizedExternsInputAtEnd = null; private ImmutableMap<String, Node> defaultDefineValues = ImmutableMap.of(); @Override void addChangeHandler(CodeChangeHandler handler) { codeChangeHandlers.add(handler); } @Override void removeChangeHandler(CodeChangeHandler handler) { codeChangeHandlers.remove(handler); } @Override void setScope(Node n) { if (phaseOptimizer != null) { phaseOptimizer.setScope(n); } } @Override Node getJsRoot() { return jsRoot; } @Override boolean hasScopeChanged(Node n) { if (phaseOptimizer == null) { return true; } return phaseOptimizer.hasScopeChanged(n); } @Override void reportChangeToEnclosingScope(Node n) { if (phaseOptimizer != null) { phaseOptimizer.reportChangeToEnclosingScope(n); phaseOptimizer.startCrossScopeReporting(); reportCodeChange(); phaseOptimizer.endCrossScopeReporting(); } else { reportCodeChange(); } } /** * Some tests don't want to call the compiler "wholesale," they may not want * to call check and/or optimize. With this method, tests can execute custom * optimization loops. */ @VisibleForTesting void setPhaseOptimizer(PhaseOptimizer po) { this.phaseOptimizer = po; } @Override public void reportCodeChange() { for (CodeChangeHandler handler : codeChangeHandlers) { handler.reportChange(); } } @Override public CodingConvention getCodingConvention() { CodingConvention convention = options.getCodingConvention(); convention = convention != null ? convention : defaultCodingConvention; return convention; } private Config.LanguageMode getParserConfigLanguageMode( CompilerOptions.LanguageMode languageMode) { switch (languageMode) { case ECMASCRIPT3: return Config.LanguageMode.ECMASCRIPT3; case ECMASCRIPT5: case ECMASCRIPT5_STRICT: return Config.LanguageMode.ECMASCRIPT5; case ECMASCRIPT6: case ECMASCRIPT6_STRICT: case ECMASCRIPT_2015: return Config.LanguageMode.ECMASCRIPT6; case ECMASCRIPT6_TYPED: return Config.LanguageMode.TYPESCRIPT; case ECMASCRIPT7: case ECMASCRIPT_2016: return Config.LanguageMode.ECMASCRIPT7; case ECMASCRIPT8: case ECMASCRIPT_NEXT: return Config.LanguageMode.ECMASCRIPT8; default: throw new IllegalStateException("unexpected language mode: " + options.getLanguageIn()); } } @Override Config getParserConfig(ConfigContext context) { if (parserConfig == null) { Config.LanguageMode configLanguageMode = getParserConfigLanguageMode(options.getLanguageIn()); Config.StrictMode strictMode = expectStrictModeInput() ? Config.StrictMode.STRICT : Config.StrictMode.SLOPPY; parserConfig = createConfig(configLanguageMode, strictMode); // Externs must always be parsed with at least ES5 language mode. externsParserConfig = configLanguageMode.equals(Config.LanguageMode.ECMASCRIPT3) ? createConfig(Config.LanguageMode.ECMASCRIPT5, strictMode) : parserConfig; } switch (context) { case EXTERNS: return externsParserConfig; default: return parserConfig; } } protected Config createConfig(Config.LanguageMode mode, Config.StrictMode strictMode) { Config config = ParserRunner.createConfig( mode, options.isParseJsDocDocumentation(), options.canContinueAfterErrors() ? Config.RunMode.KEEP_GOING : Config.RunMode.STOP_AFTER_ERROR, options.extraAnnotationNames, options.parseInlineSourceMaps, strictMode); return config; } //------------------------------------------------------------------------ // Error reporting //------------------------------------------------------------------------ /** * The warning classes that are available from the command-line, and * are suppressible by the {@code @suppress} annotation. */ protected DiagnosticGroups getDiagnosticGroups() { return new DiagnosticGroups(); } @Override public void report(JSError error) { CheckLevel level = error.getDefaultLevel(); if (warningsGuard != null) { CheckLevel newLevel = warningsGuard.level(error); if (newLevel != null) { level = newLevel; } } if (level.isOn()) { initCompilerOptionsIfTesting(); if (getOptions().errorHandler != null) { getOptions().errorHandler.report(level, error); } errorManager.report(level, error); } } @Override public void report(CheckLevel ignoredLevel, JSError error) { report(error); } @Override public CheckLevel getErrorLevel(JSError error) { Preconditions.checkNotNull(options); return warningsGuard.level(error); } /** * Report an internal error. */ @Override void throwInternalError(String message, Exception cause) { String finalMessage = "INTERNAL COMPILER ERROR.\n" + "Please report this problem.\n\n" + message; RuntimeException e = new RuntimeException(finalMessage, cause); if (cause != null) { e.setStackTrace(cause.getStackTrace()); } throw e; } /** * Gets the number of errors. */ public int getErrorCount() { return errorManager.getErrorCount(); } /** * Gets the number of warnings. */ public int getWarningCount() { return errorManager.getWarningCount(); } @Override boolean hasHaltingErrors() { return !getOptions().canContinueAfterErrors() && getErrorCount() > 0; } /** * Consults the {@link ErrorManager} to see if we've encountered errors * that should halt compilation. <p> * * If {@link CompilerOptions#canContinueAfterErrors} is {@code true}, this function * always returns {@code false} without consulting the error manager. The * error manager will continue to be told about new errors and warnings, but * the compiler will complete compilation of all inputs.<p> */ public boolean hasErrors() { return hasHaltingErrors(); } /** Called from the compiler passes, adds debug info */ @Override void addToDebugLog(String str) { if (options.useDebugLog) { debugLog.append(str); debugLog.append('\n'); logger.fine(str); } } @Override public SourceFile getSourceFileByName(String sourceName) { // Here we assume that the source name is the input name, this // is try of JavaScript parsed from source. if (sourceName != null) { CompilerInput input = inputsById.get(new InputId(sourceName)); if (input != null) { return input.getSourceFile(); } // Alternatively, the sourceName might have been reverse-mapped by // an input source-map, so let's look in our sourcemap original sources. return sourceMapOriginalSources.get(sourceName); } return null; } @Override public void addInputSourceMap(String sourceFileName, SourceMapInput inputSourceMap) { inputSourceMaps.put(sourceFileName, inputSourceMap); } @Override public OriginalMapping getSourceMapping(String sourceName, int lineNumber, int columnNumber) { if (sourceName == null) { return null; } SourceMapInput sourceMap = inputSourceMaps.get(sourceName); if (sourceMap == null) { return null; } // JSCompiler uses 1-indexing for lineNumber and 0-indexing for // columnNumber. // SourceMap uses 1-indexing for both. OriginalMapping result = sourceMap.getSourceMap() .getMappingForLine(lineNumber, columnNumber + 1); if (result == null) { return null; } // The sourcemap will return a path relative to the sourcemap's file. // Translate it to one relative to our base directory. String path = getRelativeTo(result.getOriginalFile(), sourceMap.getOriginalPath()); sourceMapOriginalSources.putIfAbsent( path, originalSourcesLoader.apply(path)); return result.toBuilder() .setOriginalFile(path) .setColumnPosition(result.getColumnPosition() - 1) .build(); } @Override public String getSourceLine(String sourceName, int lineNumber) { if (lineNumber < 1) { return null; } SourceFile input = getSourceFileByName(sourceName); if (input != null) { return input.getLine(lineNumber); } return null; } @Override public Region getSourceRegion(String sourceName, int lineNumber) { if (lineNumber < 1) { return null; } SourceFile input = getSourceFileByName(sourceName); if (input != null) { return input.getRegion(lineNumber); } return null; } //------------------------------------------------------------------------ // Package-private helpers //------------------------------------------------------------------------ @Override Node getNodeForCodeInsertion(JSModule module) { if (module == null) { if (inputs.isEmpty()) { throw new IllegalStateException("No inputs"); } return inputs.get(0).getAstRoot(this); } List<CompilerInput> moduleInputs = module.getInputs(); if (!moduleInputs.isEmpty()) { return moduleInputs.get(0).getAstRoot(this); } throw new IllegalStateException("Root module has no inputs"); } public SourceMap getSourceMap() { return sourceMap; } VariableMap getVariableMap() { return getPassConfig().getIntermediateState().variableMap; } VariableMap getPropertyMap() { return getPassConfig().getIntermediateState().propertyMap; } VariableMap getStringMap() { return getPassConfig().getIntermediateState().stringMap; } @Override CompilerOptions getOptions() { return options; } FunctionInformationMap getFunctionalInformationMap() { return functionInformationMap; } /** * Sets the logging level for the com.google.javascript.jscomp package. */ public static void setLoggingLevel(Level level) { logger.setLevel(level); } /** Gets the DOT graph of the AST generated at the end of compilation. */ public String getAstDotGraph() throws IOException { if (jsRoot != null) { ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false); cfa.process(null, jsRoot); return DotFormatter.toDot(jsRoot, cfa.getCfg()); } else { return ""; } } @Override public ErrorManager getErrorManager() { if (options == null) { initOptions(newCompilerOptions()); } return errorManager; } @Override List<CompilerInput> getInputsInOrder() { return Collections.unmodifiableList(inputs); } /** * Returns an unmodifiable view of the compiler inputs indexed by id. */ public Map<InputId, CompilerInput> getInputsById() { return Collections.unmodifiableMap(inputsById); } /** * Gets the externs in the order in which they are being processed. */ List<CompilerInput> getExternsInOrder() { return Collections.unmodifiableList(externs); } @VisibleForTesting List<CompilerInput> getInputsForTesting() { return inputs; } @VisibleForTesting List<CompilerInput> getExternsForTesting() { return externs; } @Override boolean hasRegExpGlobalReferences() { return hasRegExpGlobalReferences; } @Override void setHasRegExpGlobalReferences(boolean references) { hasRegExpGlobalReferences = references; } @Override void updateGlobalVarReferences(Map<Var, ReferenceCollection> refMapPatch, Node collectionRoot) { Preconditions.checkState(collectionRoot.isScript() || collectionRoot.isRoot()); if (globalRefMap == null) { globalRefMap = new GlobalVarReferenceMap(getInputsInOrder(), getExternsInOrder()); } globalRefMap.updateGlobalVarReferences(refMapPatch, collectionRoot); } @Override GlobalVarReferenceMap getGlobalVarReferences() { return globalRefMap; } @Override CompilerInput getSynthesizedExternsInput() { if (synthesizedExternsInput == null) { synthesizedExternsInput = newExternInput(SYNTHETIC_EXTERNS, SyntheticExternsPosition.START); } return synthesizedExternsInput; } @Override CompilerInput getSynthesizedExternsInputAtEnd() { if (synthesizedExternsInputAtEnd == null) { synthesizedExternsInputAtEnd = newExternInput( SYNTHETIC_EXTERNS_AT_END, SyntheticExternsPosition.END); } return synthesizedExternsInputAtEnd; } @Override public double getProgress() { return progress; } @Override String getLastPassName() { return lastPassName; } @Override void setProgress(double newProgress, String passName) { this.lastPassName = passName; if (newProgress > 1.0) { progress = 1.0; } else { progress = newProgress; } } @Override void setExternProperties(Set<String> externProperties) { this.externProperties = externProperties; } @Override Set<String> getExternProperties() { return externProperties; } /** * Replaces one file in a hot-swap mode. The given JsAst should be made * from a new version of a file that already was present in the last compile * call. If the file is new, this will silently ignored. * * @param ast the ast of the file that is being replaced */ public void replaceScript(JsAst ast) { CompilerInput input = this.getInput(ast.getInputId()); if (!replaceIncrementalSourceAst(ast)) { return; } Node originalRoot = input.getAstRoot(this); processNewScript(ast, originalRoot); } /** * Adds a new Script AST to the compile state. If a script for the same file * already exists the script will not be added, instead a call to * #replaceScript should be used. * * @param ast the ast of the new file */ public void addNewScript(JsAst ast) { if (!addNewSourceAst(ast)) { return; } Node emptyScript = new Node(Token.SCRIPT); InputId inputId = ast.getInputId(); emptyScript.setInputId(inputId); emptyScript.setStaticSourceFile( SourceFile.fromCode(inputId.getIdName(), "")); processNewScript(ast, emptyScript); } private void processNewScript(JsAst ast, Node originalRoot) { languageMode = options.getLanguageIn(); Node js = ast.getAstRoot(this); Preconditions.checkNotNull(js); runHotSwap(originalRoot, js, this.getCleanupPassConfig()); // NOTE: If hot swap passes that use GlobalNamespace are added, we will need // to revisit this approach to clearing GlobalNamespaces runHotSwapPass(null, null, ensureDefaultPassConfig().garbageCollectChecks); this.getTypeRegistry().clearNamedTypes(); this.removeSyntheticVarsInput(); runHotSwap(originalRoot, js, this.ensureDefaultPassConfig()); } /** * Execute the passes from a PassConfig instance over a single replaced file. */ private void runHotSwap( Node originalRoot, Node js, PassConfig passConfig) { for (PassFactory passFactory : passConfig.getChecks()) { runHotSwapPass(originalRoot, js, passFactory); } } private void runHotSwapPass( Node originalRoot, Node js, PassFactory passFactory) { HotSwapCompilerPass pass = passFactory.getHotSwapPass(this); if (pass != null) { if (logger.isLoggable(Level.INFO)) { logger.info("Performing HotSwap for pass " + passFactory.getName()); } pass.hotSwapScript(js, originalRoot); } } private PassConfig getCleanupPassConfig() { return new CleanupPasses(getOptions()); } private void removeSyntheticVarsInput() { String sourceName = Compiler.SYNTHETIC_EXTERNS; removeExternInput(new InputId(sourceName)); } @Override Node ensureLibraryInjected(String resourceName, boolean force) { boolean doNotInject = !force && (options.skipNonTranspilationPasses || options.preventLibraryInjection); if (injectedLibraries.containsKey(resourceName) || doNotInject) { return lastInjectedLibrary; } // Load/parse the code. String originalCode = ResourceLoader.loadTextResource( Compiler.class, "js/" + resourceName + ".js"); Node ast = parseSyntheticCode(" [synthetic:" + resourceName + "] ", originalCode); // Look for string literals of the form 'require foo bar' or 'externs baz' or 'normalize'. // As we process each one, remove it from its parent. for (Node node = ast.getFirstChild(); node != null && node.isExprResult() && node.getFirstChild().isString(); node = ast.getFirstChild()) { String directive = node.getFirstChild().getString(); List<String> words = Splitter.on(' ').limit(2).splitToList(directive); switch (words.get(0)) { case "use": // 'use strict' is ignored (and deleted). break; case "require": // 'require lib'; pulls in the named library before this one. ensureLibraryInjected(words.get(1), force); break; case "declare": // 'declare name'; adds the name to the externs (with no type information). // Note that we could simply add the entire externs library, but that leads to // potentially-surprising behavior when the externs that are present depend on // whether or not a polyfill is used. Node var = IR.var(IR.name(words.get(1))); JSDocInfoBuilder jsdoc = new JSDocInfoBuilder(false); // Suppress duplicate-var warning in case this name is already defined in the externs. jsdoc.addSuppression("duplicate"); var.setJSDocInfo(jsdoc.build()); getSynthesizedExternsInputAtEnd() .getAstRoot(this) .addChildToBack(var); break; default: throw new RuntimeException("Bad directive: " + directive); } ast.removeChild(node); } // If we've already started optimizations, then we need to normalize this. if (getLifeCycleStage().isNormalized()) { Normalize.normalizeSyntheticCode(this, ast, "jscomp_" + resourceName + "_"); } // Insert the code immediately after the last-inserted runtime library. Node lastChild = ast.getLastChild(); Node firstChild = ast.removeChildren(); if (firstChild == null) { // Handle require-only libraries. return lastInjectedLibrary; } Node parent = getNodeForCodeInsertion(null); if (lastInjectedLibrary == null) { parent.addChildrenToFront(firstChild); } else { parent.addChildrenAfter(firstChild, lastInjectedLibrary); } lastInjectedLibrary = lastChild; injectedLibraries.put(resourceName, lastChild); reportCodeChange(); return lastChild; } /** Returns the compiler version baked into the jar. */ @GwtIncompatible("java.util.ResourceBundle") public static String getReleaseVersion() { ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE); return config.getString("compiler.version"); } /** Returns the compiler date baked into the jar. */ @GwtIncompatible("java.util.ResourceBundle") public static String getReleaseDate() { ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE); return config.getString("compiler.date"); } @Override void addComments(String filename, List<Comment> comments) { if (!getOptions().preservesDetailedSourceInfo()) { throw new UnsupportedOperationException( "addComments may only be called in IDE mode."); } commentsPerFile.put(filename, comments); } @Override public List<Comment> getComments(String filename) { if (!getOptions().preservesDetailedSourceInfo()) { throw new UnsupportedOperationException( "getComments may only be called in IDE mode."); } return commentsPerFile.get(filename); } @Override void setDefaultDefineValues(ImmutableMap<String, Node> values) { this.defaultDefineValues = values; } @Override ImmutableMap<String, Node> getDefaultDefineValues() { return this.defaultDefineValues; } @Override ModuleLoader getModuleLoader() { return moduleLoader; } private void addFilesToSourceMap(Iterable<? extends SourceFile> files) { if (getOptions().sourceMapIncludeSourcesContent && getSourceMap() != null) { for (SourceFile file : files) { getSourceMap().addSourceFile(file); } } } private void addFileToSourceMap(String filename, String contents) { if (getOptions().sourceMapIncludeSourcesContent && getSourceMap() != null) { getSourceMap().addSourceFile(SourceFile.fromCode(filename, contents)); } } }
src/com/google/javascript/jscomp/Compiler.java
/* * Copyright 2004 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.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping; import com.google.javascript.jscomp.CompilerOptions.DevMode; import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection; import com.google.javascript.jscomp.TypeValidator.TypeMismatch; import com.google.javascript.jscomp.WarningsGuard.DiagnosticGroupState; import com.google.javascript.jscomp.deps.ModuleLoader; import com.google.javascript.jscomp.deps.SortedDependencies.MissingProvideException; import com.google.javascript.jscomp.parsing.Config; import com.google.javascript.jscomp.parsing.ParserRunner; import com.google.javascript.jscomp.parsing.parser.trees.Comment; import com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.ReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfoBuilder; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TypeIRegistry; import com.google.javascript.rhino.jstype.JSTypeRegistry; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.FileSystems; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; /** * Compiler (and the other classes in this package) does the following: * <ul> * <li>parses JS code * <li>checks for undefined variables * <li>performs optimizations such as constant folding and constants inlining * <li>renames variables (to short names) * <li>outputs compact JavaScript code * </ul> * * External variables are declared in 'externs' files. For instance, the file * may include definitions for global javascript/browser objects such as * window, document. * */ public class Compiler extends AbstractCompiler implements ErrorHandler, SourceFileMapping { static final String SINGLETON_MODULE_NAME = "$singleton$"; static final DiagnosticType MODULE_DEPENDENCY_ERROR = DiagnosticType.error("JSC_MODULE_DEPENDENCY_ERROR", "Bad dependency: {0} -> {1}. " + "Modules must be listed in dependency order."); static final DiagnosticType MISSING_ENTRY_ERROR = DiagnosticType.error( "JSC_MISSING_ENTRY_ERROR", "required entry point \"{0}\" never provided"); static final DiagnosticType MISSING_MODULE_ERROR = DiagnosticType.error( "JSC_MISSING_ENTRY_ERROR", "unknown module \"{0}\" specified in entry point spec"); // Used in PerformanceTracker static final String PARSING_PASS_NAME = "parseInputs"; static final String CROSS_MODULE_CODE_MOTION_NAME = "crossModuleCodeMotion"; static final String CROSS_MODULE_METHOD_MOTION_NAME = "crossModuleMethodMotion"; private static final String CONFIG_RESOURCE = "com.google.javascript.jscomp.parsing.ParserConfig"; CompilerOptions options = null; private PassConfig passes = null; // The externs inputs private List<CompilerInput> externs; // The JS source modules private List<JSModule> modules; // The graph of the JS source modules. Must be null if there are less than // 2 modules, because we use this as a signal for which passes to run. private JSModuleGraph moduleGraph; // The module loader for resolving paths into module URIs. private ModuleLoader moduleLoader; // The JS source inputs private List<CompilerInput> inputs; // error manager to which error management is delegated private ErrorManager errorManager; // Warnings guard for filtering warnings. private WarningsGuard warningsGuard; // Compile-time injected libraries. The node points to the last node of // the library, so code can be inserted after. private final Map<String, Node> injectedLibraries = new LinkedHashMap<>(); // Node of the final injected library. Future libraries will be injected // after this node. private Node lastInjectedLibrary; // Parse tree root nodes Node externsRoot; Node jsRoot; Node externAndJsRoot; // Used for debugging; to see the compiled code between passes private String lastJsSource = null; /** @see #getLanguageMode() */ private CompilerOptions.LanguageMode languageMode = CompilerOptions.LanguageMode.ECMASCRIPT3; private Map<InputId, CompilerInput> inputsById; // Function to load source files from disk or memory. private Function<String, SourceFile> originalSourcesLoader = new Function<String, SourceFile>() { @Override public SourceFile apply(String filename) { return SourceFile.fromFile(filename); } }; // Original sources referenced by the source maps. private ConcurrentHashMap<String, SourceFile> sourceMapOriginalSources = new ConcurrentHashMap<>(); /** Configured {@link SourceMapInput}s, plus any source maps discovered in source files. */ private final ConcurrentHashMap<String, SourceMapInput> inputSourceMaps = new ConcurrentHashMap<>(); // Map from filenames to lists of all the comments in each file. private Map<String, List<Comment>> commentsPerFile = new HashMap<>(); /** The source code map */ private SourceMap sourceMap; /** The externs created from the exports. */ private String externExports = null; /** * Ids for function inlining so that each declared name remains * unique. */ private int uniqueNameId = 0; /** * Whether to assume there are references to the RegExp Global object * properties. */ private boolean hasRegExpGlobalReferences = true; /** The function information map */ private FunctionInformationMap functionInformationMap; /** Debugging information */ private final StringBuilder debugLog = new StringBuilder(); /** Detects Google-specific coding conventions. */ CodingConvention defaultCodingConvention = new ClosureCodingConvention(); private JSTypeRegistry typeRegistry; private Config parserConfig = null; private Config externsParserConfig = null; private ReverseAbstractInterpreter abstractInterpreter; private TypeValidator typeValidator; // The compiler can ask phaseOptimizer for things like which pass is currently // running, or which functions have been changed by optimizations private PhaseOptimizer phaseOptimizer = null; public PerformanceTracker tracker; // Used by optimize-returns, optimize-parameters and remove-unused-variables private DefinitionUseSiteFinder defFinder = null; // Types that have been forward declared private final Set<String> forwardDeclaredTypes = new HashSet<>(); // For use by the new type inference private GlobalTypeInfo symbolTable; private MostRecentTypechecker mostRecentTypechecker = MostRecentTypechecker.NONE; // This error reporter gets the messages from the current Rhino parser or TypeRegistry. private final ErrorReporter oldErrorReporter = RhinoErrorReporter.forOldRhino(this); /** Error strings used for reporting JSErrors */ public static final DiagnosticType OPTIMIZE_LOOP_ERROR = DiagnosticType.error( "JSC_OPTIMIZE_LOOP_ERROR", "Exceeded max number of optimization iterations: {0}"); public static final DiagnosticType MOTION_ITERATIONS_ERROR = DiagnosticType.error("JSC_OPTIMIZE_LOOP_ERROR", "Exceeded max number of code motion iterations: {0}"); private final CompilerExecutor compilerExecutor = new CompilerExecutor(); /** * Logger for the whole com.google.javascript.jscomp domain - * setting configuration for this logger affects all loggers * in other classes within the compiler. */ public static final Logger logger = Logger.getLogger("com.google.javascript.jscomp"); private final PrintStream outStream; private GlobalVarReferenceMap globalRefMap = null; private volatile double progress = 0.0; private String lastPassName; private Set<String> externProperties = null; private static final Joiner pathJoiner = Joiner.on(File.separator); /** * Creates a Compiler that reports errors and warnings to its logger. */ public Compiler() { this((PrintStream) null); } /** * Creates a Compiler that reports errors and warnings to an output stream. */ public Compiler(PrintStream stream) { addChangeHandler(recentChange); this.outStream = stream; } /** * Creates a Compiler that uses a custom error manager. */ public Compiler(ErrorManager errorManager) { this(); setErrorManager(errorManager); } /** * Sets the error manager. * * @param errorManager the error manager, it cannot be {@code null} */ public void setErrorManager(ErrorManager errorManager) { Preconditions.checkNotNull( errorManager, "the error manager cannot be null"); this.errorManager = errorManager; } /** * Creates a message formatter instance corresponding to the value of * {@link CompilerOptions}. */ private MessageFormatter createMessageFormatter() { boolean colorize = options.shouldColorizeErrorOutput(); return options.errorFormat.toFormatter(this, colorize); } @VisibleForTesting void setOriginalSourcesLoader( Function<String, SourceFile> originalSourcesLoader) { this.originalSourcesLoader = originalSourcesLoader; } /** * Initializes the compiler options. It's called as part of a normal compile() job. * Public for the callers that are not doing a normal compile() job. */ public void initOptions(CompilerOptions options) { this.options = options; this.languageMode = options.getLanguageIn(); if (errorManager == null) { if (this.outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), this.outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } reconcileOptionsWithGuards(); // TODO(johnlenz): generally, the compiler should not be changing the options object // provided by the user. This should be handled a different way. // Turn off type-based optimizations when type checking is off if (!options.checkTypes) { options.setDisambiguateProperties(false); options.setAmbiguateProperties(false); options.setInlineProperties(false); options.setUseTypesForLocalOptimization(false); options.setUseTypesForOptimization(false); } if (options.legacyCodeCompile) { options.setDisambiguateProperties(false); options.setAmbiguateProperties(false); options.useNonStrictWarningsGuard(); } initWarningsGuard(options.getWarningsGuard()); } public void printConfig(PrintStream printStream) { printStream.println("==== CompilerOptions ===="); printStream.println(options.toString()); printStream.println("==== WarningsGuard ===="); printStream.println(warningsGuard.toString()); } void initWarningsGuard(WarningsGuard warningsGuard) { this.warningsGuard = new ComposeWarningsGuard( new SuppressDocWarningsGuard(getDiagnosticGroups().getRegisteredGroups()), warningsGuard); } /** * When the CompilerOptions and its WarningsGuard overlap, reconcile * any discrepencies. */ protected void reconcileOptionsWithGuards() { // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { // If DiagnosticGroups did not override the plain checkTypes // option, and checkTypes is enabled, then turn off the // parser type warnings. options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } DiagnosticGroupState ntiState = options.getWarningsGuard().enablesExplicitly(DiagnosticGroups.NEW_CHECK_TYPES); if (ntiState == DiagnosticGroupState.ON) { options.setNewTypeInference(true); } else if (ntiState == DiagnosticGroupState.OFF) { options.setNewTypeInference(false); } // With NTI, we still need OTI to run because the later passes that use // types only understand OTI types at the moment. // But we do not want to see the warnings from OTI. if (options.getNewTypeInference()) { options.checkTypes = true; // Suppress warnings from the const checks of CheckAccessControls so as to avoid // duplication. options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS_CONST, CheckLevel.OFF); if (!options.reportOTIErrorsUnderNTI) { options.setWarningLevel( DiagnosticGroups.OLD_CHECK_TYPES, CheckLevel.OFF); options.setWarningLevel( DiagnosticGroups.OLD_REPORT_UNKNOWN_TYPES, CheckLevel.OFF); options.setWarningLevel( FunctionTypeBuilder.ALL_DIAGNOSTICS, CheckLevel.OFF); } options.setWarningLevel( DiagnosticGroup.forType(RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.WARNING); } if (options.checkGlobalThisLevel.isOn() && !options.disables(DiagnosticGroups.GLOBAL_THIS)) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } if (expectStrictModeInput()) { options.setWarningLevel( DiagnosticGroups.ES5_STRICT, CheckLevel.ERROR); } // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. if (!options.checkSymbols && !options.enables(DiagnosticGroups.CHECK_VARIABLES)) { options.setWarningLevel( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF); } } private boolean expectStrictModeInput() { switch (options.getLanguageIn()) { case ECMASCRIPT3: case ECMASCRIPT5: case ECMASCRIPT6: return false; case ECMASCRIPT5_STRICT: case ECMASCRIPT6_STRICT: case ECMASCRIPT6_TYPED: return true; default: return options.isStrictModeInput(); } } /** * Initializes the instance state needed for a compile job. */ public <T1 extends SourceFile, T2 extends SourceFile> void init( List<T1> externs, List<T2> inputs, CompilerOptions options) { JSModule module = new JSModule(SINGLETON_MODULE_NAME); for (SourceFile input : inputs) { module.add(input); } List<JSModule> modules = new ArrayList<>(1); modules.add(module); initModules(externs, modules, options); addFilesToSourceMap(inputs); if (options.printConfig) { printConfig(System.err); } } /** * Initializes the instance state needed for a compile job if the sources * are in modules. */ public <T extends SourceFile> void initModules( List<T> externs, List<JSModule> modules, CompilerOptions options) { initOptions(options); checkFirstModule(modules); fillEmptyModules(modules); this.externs = makeCompilerInput(externs, true); // Generate the module graph, and report any errors in the module // specification as errors. this.modules = modules; if (modules.size() > 1) { try { this.moduleGraph = new JSModuleGraph(modules); } catch (JSModuleGraph.ModuleDependenceException e) { // problems with the module format. Report as an error. The // message gives all details. report(JSError.make(MODULE_DEPENDENCY_ERROR, e.getModule().getName(), e.getDependentModule().getName())); return; } } else { this.moduleGraph = null; } this.inputs = getAllInputsFromModules(modules); initBasedOnOptions(); initInputsByIdMap(); initAST(); } /** * Do any initialization that is dependent on the compiler options. */ private void initBasedOnOptions() { inputSourceMaps.putAll(options.inputSourceMaps); // Create the source map if necessary. if (options.sourceMapOutputPath != null) { sourceMap = options.sourceMapFormat.getInstance(); sourceMap.setPrefixMappings(options.sourceMapLocationMappings); if (options.applyInputSourceMaps) { sourceMap.setSourceFileMapping(this); } } } private <T extends SourceFile> List<CompilerInput> makeCompilerInput( List<T> files, boolean isExtern) { List<CompilerInput> inputs = new ArrayList<>(files.size()); for (T file : files) { inputs.add(new CompilerInput(file, isExtern)); } return inputs; } private static final DiagnosticType EMPTY_MODULE_LIST_ERROR = DiagnosticType.error("JSC_EMPTY_MODULE_LIST_ERROR", "At least one module must be provided"); private static final DiagnosticType EMPTY_ROOT_MODULE_ERROR = DiagnosticType.error("JSC_EMPTY_ROOT_MODULE_ERROR", "Root module ''{0}'' must contain at least one source code input"); /** * Verifies that at least one module has been provided and that the first one * has at least one source code input. */ private void checkFirstModule(List<JSModule> modules) { if (modules.isEmpty()) { report(JSError.make(EMPTY_MODULE_LIST_ERROR)); } else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) { // The root module may only be empty if there is exactly 1 module. report(JSError.make(EMPTY_ROOT_MODULE_ERROR, modules.get(0).getName())); } } /** * Empty modules get an empty "fill" file, so that we can move code into * an empty module. */ static String createFillFileName(String moduleName) { return moduleName + "$fillFile"; } /** * Creates an OS specific path string from parts */ public static String joinPathParts(String... pathParts) { return pathJoiner.join(pathParts); } /** * Fill any empty modules with a place holder file. It makes any cross module * motion easier. */ private static void fillEmptyModules(List<JSModule> modules) { for (JSModule module : modules) { if (module.getInputs().isEmpty()) { module.add(SourceFile.fromCode( createFillFileName(module.getName()), "")); } } } /** * Rebuilds the internal list of inputs by iterating over all modules. * This is necessary if inputs have been added to or removed from a module * after the {@link #init(List, List, CompilerOptions)} call. */ public void rebuildInputsFromModules() { inputs = getAllInputsFromModules(modules); initInputsByIdMap(); } /** * Builds a single list of all module inputs. Verifies that it contains no * duplicates. */ private static List<CompilerInput> getAllInputsFromModules( List<JSModule> modules) { List<CompilerInput> inputs = new ArrayList<>(); Map<String, JSModule> inputMap = new HashMap<>(); for (JSModule module : modules) { for (CompilerInput input : module.getInputs()) { String inputName = input.getName(); // NOTE(nicksantos): If an input is in more than one module, // it will show up twice in the inputs list, and then we // will get an error down the line. inputs.add(input); inputMap.put(inputName, module); } } return inputs; } static final DiagnosticType DUPLICATE_INPUT = DiagnosticType.error("JSC_DUPLICATE_INPUT", "Duplicate input: {0}"); static final DiagnosticType DUPLICATE_EXTERN_INPUT = DiagnosticType.error("JSC_DUPLICATE_EXTERN_INPUT", "Duplicate extern input: {0}"); /** * Returns the relative path, resolved relative to the base path, where the * base path is interpreted as a filename rather than a directory. E.g.: * getRelativeTo("../foo/bar.js", "baz/bam/qux.js") --> "baz/foo/bar.js" */ private static String getRelativeTo(String relative, String base) { return FileSystems.getDefault().getPath(base) .resolveSibling(relative) .normalize() .toString() .replace(File.separator, "/"); } /** * Creates a map to make looking up an input by name fast. Also checks for * duplicate inputs. */ void initInputsByIdMap() { inputsById = new HashMap<>(); for (CompilerInput input : externs) { InputId id = input.getInputId(); CompilerInput previous = putCompilerInput(id, input); if (previous != null) { report(JSError.make(DUPLICATE_EXTERN_INPUT, input.getName())); } } for (CompilerInput input : inputs) { InputId id = input.getInputId(); CompilerInput previous = putCompilerInput(id, input); if (previous != null) { report(JSError.make(DUPLICATE_INPUT, input.getName())); } } } /** * Sets up the skeleton of the AST (the externs and root). */ private void initAST() { jsRoot = IR.root(); externsRoot = IR.root(); externAndJsRoot = IR.root(externsRoot, jsRoot); } public Result compile( SourceFile extern, SourceFile input, CompilerOptions options) { return compile(ImmutableList.of(extern), ImmutableList.of(input), options); } /** * Compiles a list of inputs. */ public <T1 extends SourceFile, T2 extends SourceFile> Result compile( List<T1> externs, List<T2> inputs, CompilerOptions options) { // The compile method should only be called once. Preconditions.checkState(jsRoot == null); try { init(externs, inputs, options); if (hasErrors()) { return getResult(); } return compile(); } finally { Tracer t = newTracer("generateReport"); errorManager.generateReport(); stopTracer(t, "generateReport"); } } /** * Compiles a list of modules. */ public <T extends SourceFile> Result compileModules(List<T> externs, List<JSModule> modules, CompilerOptions options) { // The compile method should only be called once. Preconditions.checkState(jsRoot == null); try { initModules(externs, modules, options); if (hasErrors()) { return getResult(); } return compile(); } finally { Tracer t = newTracer("generateReport"); errorManager.generateReport(); stopTracer(t, "generateReport"); } } private Result compile() { return runInCompilerThread(new Callable<Result>() { @Override public Result call() throws Exception { compileInternal(); return getResult(); } }); } /** * Disable threads. This is for clients that run on AppEngine and * don't have threads. */ public void disableThreads() { compilerExecutor.disableThreads(); } /** * Sets the timeout when Compiler is run in a thread * @param timeout seconds to wait before timeout */ public void setTimeout(int timeout) { compilerExecutor.setTimeout(timeout); } /** * The primary purpose of this method is to run the provided code with a larger than standard * stack. */ <T> T runInCompilerThread(Callable<T> callable) { return compilerExecutor.runInCompilerThread( callable, options != null && options.getTracerMode().isOn()); } private void compileInternal() { setProgress(0.0, null); CompilerOptionsPreprocessor.preprocess(options); parse(); // 15 percent of the work is assumed to be for parsing (based on some // minimal analysis on big JS projects, of course this depends on options) setProgress(0.15, "parse"); if (hasErrors()) { return; } if (!precheck()) { return; } if (options.skipNonTranspilationPasses) { // i.e. whitespace-only mode, which will not work with goog.module without: whitespaceOnlyPasses(); if (options.lowerFromEs6()) { transpileAndDontCheck(); } } else { check(); // check() also includes transpilation if (hasErrors()) { return; } if (!options.checksOnly && !options.shouldGenerateTypedExterns()) { optimize(); } } if (options.recordFunctionInformation) { recordFunctionInformation(); } if (options.devMode == DevMode.START_AND_END) { runSanityCheck(); } setProgress(1.0, "recordFunctionInformation"); if (tracker != null) { tracker.outputTracerReport(); } } public void parse() { parseInputs(); } PassConfig getPassConfig() { if (passes == null) { passes = createPassConfigInternal(); } return passes; } /** * Create the passes object. Clients should use setPassConfig instead of * overriding this. */ PassConfig createPassConfigInternal() { return new DefaultPassConfig(options); } /** * @param passes The PassConfig to use with this Compiler. * @throws NullPointerException if passes is null * @throws IllegalStateException if this.passes has already been assigned */ public void setPassConfig(PassConfig passes) { // Important to check for null because if setPassConfig(null) is // called before this.passes is set, getPassConfig() will create a // new PassConfig object and use that, which is probably not what // the client wanted since they probably meant to use their // own PassConfig object. Preconditions.checkNotNull(passes); Preconditions.checkState(this.passes == null, "setPassConfig was already called"); this.passes = passes; } /** * Carry out any special checks or procedures that need to be done before * proceeding with rest of the compilation process. * * @return true, to continue with compilation */ boolean precheck() { return true; } public void whitespaceOnlyPasses() { runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS); Tracer t = newTracer("runWhitespaceOnlyPasses"); try { for (PassFactory pf : getPassConfig().getWhitespaceOnlyPasses()) { pf.create(this).process(externsRoot, jsRoot); } } finally { stopTracer(t, "runWhitespaceOnlyPasses"); } } public void transpileAndDontCheck() { Tracer t = newTracer("runTranspileOnlyPasses"); try { for (PassFactory pf : getPassConfig().getTranspileOnlyPasses()) { pf.create(this).process(externsRoot, jsRoot); } } finally { stopTracer(t, "runTranspileOnlyPasses"); } } public void check() { runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS); // We are currently only interested in check-passes for progress reporting // as it is used for IDEs, that's why the maximum progress is set to 1.0. phaseOptimizer = new PhaseOptimizer(this, tracker, new PhaseOptimizer.ProgressRange(getProgress(), 1.0)); if (options.devMode == DevMode.EVERY_PASS) { phaseOptimizer.setSanityCheck(sanityCheck); } if (options.getCheckDeterminism()) { phaseOptimizer.setPrintAstHashcodes(true); } phaseOptimizer.consume(getPassConfig().getChecks()); phaseOptimizer.process(externsRoot, jsRoot); if (hasErrors()) { return; } if (options.getTweakProcessing().shouldStrip() || !options.stripTypes.isEmpty() || !options.stripNameSuffixes.isEmpty() || !options.stripTypePrefixes.isEmpty() || !options.stripNamePrefixes.isEmpty()) { stripCode(options.stripTypes, options.stripNameSuffixes, options.stripTypePrefixes, options.stripNamePrefixes); } runCustomPasses(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS); phaseOptimizer = null; } private void externExports() { logger.fine("Creating extern file for exports"); startPass("externExports"); ExternExportsPass pass = new ExternExportsPass(this); process(pass); externExports = pass.getGeneratedExterns(); endPass("externExports"); } @Override void process(CompilerPass p) { p.process(externsRoot, jsRoot); } private final PassFactory sanityCheck = new PassFactory("sanityCheck", false) { @Override protected CompilerPass create(AbstractCompiler compiler) { return new SanityCheck(compiler); } }; private void maybeSanityCheck() { if (options.devMode == DevMode.EVERY_PASS) { runSanityCheck(); } } private void runSanityCheck() { sanityCheck.create(this).process(externsRoot, jsRoot); } /** * Strips code for smaller compiled code. This is useful for removing debug * statements to prevent leaking them publicly. */ void stripCode(Set<String> stripTypes, Set<String> stripNameSuffixes, Set<String> stripTypePrefixes, Set<String> stripNamePrefixes) { logger.fine("Strip code"); startPass("stripCode"); StripCode r = new StripCode(this, stripTypes, stripNameSuffixes, stripTypePrefixes, stripNamePrefixes); if (options.getTweakProcessing().shouldStrip()) { r.enableTweakStripping(); } process(r); endPass("stripCode"); } /** * Runs custom passes that are designated to run at a particular time. */ private void runCustomPasses(CustomPassExecutionTime executionTime) { if (options.customPasses != null) { Tracer t = newTracer("runCustomPasses"); try { for (CompilerPass p : options.customPasses.get(executionTime)) { process(p); } } finally { stopTracer(t, "runCustomPasses"); } } } private Tracer currentTracer = null; private String currentPassName = null; /** * Marks the beginning of a pass. */ void startPass(String passName) { Preconditions.checkState(currentTracer == null); currentPassName = passName; currentTracer = newTracer(passName); beforePass(passName); } /** * Marks the end of a pass. */ void endPass(String passName) { Preconditions.checkState(currentTracer != null, "Tracer should not be null at the end of a pass."); stopTracer(currentTracer, currentPassName); afterPass(passName); currentPassName = null; currentTracer = null; maybeSanityCheck(); } @Override final void beforePass(String passName) { // does nothing for now } @Override final void afterPass(String passName) { if (options.printSourceAfterEachPass) { String currentJsSource = getCurrentJsSource(); if (!currentJsSource.equals(this.lastJsSource)) { System.out.println(); System.out.println("// " + passName + " yields:"); System.out.println("// ************************************"); System.out.println(currentJsSource); lastJsSource = currentJsSource; } } } final String getCurrentJsSource() { List<String> filenames = options.filesToPrintAfterEachPass; if (filenames.isEmpty()) { return toSource(); } else { StringBuilder builder = new StringBuilder(); for (String filename : filenames) { Node script = getScriptNode(filename); String source = script != null ? "// " + script.getSourceFileName() + "\n" + toSource(script) : "File '" + filename + "' not found"; builder.append(source); } return builder.toString(); } } final Node getScriptNode(String filename) { for (Node file : jsRoot.children()) { if (file.getSourceFileName() != null && file.getSourceFileName().endsWith(filename)) { return file; } } return null; } /** * Returns a new tracer for the given pass name. */ Tracer newTracer(String passName) { String comment = passName + (recentChange.hasCodeChanged() ? " on recently changed AST" : ""); if (options.getTracerMode().isOn() && tracker != null) { tracker.recordPassStart(passName, true); } return new Tracer("Compiler", comment); } void stopTracer(Tracer t, String passName) { long result = t.stop(); if (options.getTracerMode().isOn() && tracker != null) { tracker.recordPassStop(passName, result); } } /** * Returns the result of the compilation. */ public Result getResult() { PassConfig.State state = getPassConfig().getIntermediateState(); Set<SourceFile> transpiledFiles = new HashSet<>(); if (jsRoot != null) { for (Node scriptNode : jsRoot.children()) { if (scriptNode.getBooleanProp(Node.TRANSPILED)) { transpiledFiles.add(getSourceFileByName(scriptNode.getSourceFileName())); } } } return new Result(getErrors(), getWarnings(), debugLog.toString(), state.variableMap, state.propertyMap, state.anonymousFunctionNameMap, state.stringMap, functionInformationMap, sourceMap, externExports, state.cssNames, state.idGeneratorMap, transpiledFiles); } /** * Returns the array of errors (never null). */ public JSError[] getErrors() { if (errorManager == null) { return new JSError[] {}; } return errorManager.getErrors(); } /** * Returns the array of warnings (never null). */ public JSError[] getWarnings() { if (errorManager == null) { return new JSError[] {}; } return errorManager.getWarnings(); } @Override public Node getRoot() { return externAndJsRoot; } @Override CompilerOptions.LanguageMode getLanguageMode() { return languageMode; } @Override void setLanguageMode(CompilerOptions.LanguageMode mode) { languageMode = mode; } /** * Creates a new id for making unique names. */ private int nextUniqueNameId() { return uniqueNameId++; } /** * Resets the unique name id counter */ @VisibleForTesting void resetUniqueNameId() { uniqueNameId = 0; } @Override Supplier<String> getUniqueNameIdSupplier() { final Compiler self = this; return new Supplier<String>() { @Override public String get() { return String.valueOf(self.nextUniqueNameId()); } }; } @Override boolean areNodesEqualForInlining(Node n1, Node n2) { if (options.shouldAmbiguateProperties() || options.shouldDisambiguateProperties()) { // The type based optimizations require that type information is preserved // during other optimizations. return n1.isEquivalentToTyped(n2); } else { return n1.isEquivalentTo(n2); } } //------------------------------------------------------------------------ // Inputs //------------------------------------------------------------------------ // TODO(nicksantos): Decide which parts of these belong in an AbstractCompiler // interface, and which ones should always be injected. @Override public CompilerInput getInput(InputId id) { return inputsById.get(id); } /** * Removes an input file from AST. * @param id The id of the input to be removed. */ protected void removeExternInput(InputId id) { CompilerInput input = getInput(id); if (input == null) { return; } Preconditions.checkState(input.isExtern(), "Not an extern input: %s", input.getName()); inputsById.remove(id); externs.remove(input); Node root = input.getAstRoot(this); if (root != null) { root.detach(); } } // Where to put a new synthetic externs file. private static enum SyntheticExternsPosition { START, END } CompilerInput newExternInput(String name, SyntheticExternsPosition pos) { SourceAst ast = new SyntheticAst(name); if (inputsById.containsKey(ast.getInputId())) { throw new IllegalArgumentException("Conflicting externs name: " + name); } CompilerInput input = new CompilerInput(ast, true); putCompilerInput(input.getInputId(), input); if (pos == SyntheticExternsPosition.START) { externsRoot.addChildToFront(ast.getAstRoot(this)); externs.add(0, input); } else { externsRoot.addChildToBack(ast.getAstRoot(this)); externs.add(input); } return input; } CompilerInput putCompilerInput(InputId id, CompilerInput input) { if (inputsById == null) { inputsById = new HashMap<>(); } input.setCompiler(this); return inputsById.put(id, input); } /** * Replace a source input dynamically. Intended for incremental * re-compilation. * * If the new source input doesn't parse, then keep the old input * in the AST and return false. * * @return Whether the new AST was attached successfully. */ boolean replaceIncrementalSourceAst(JsAst ast) { CompilerInput oldInput = getInput(ast.getInputId()); Preconditions.checkNotNull(oldInput, "No input to replace: %s", ast.getInputId().getIdName()); Node newRoot = ast.getAstRoot(this); if (newRoot == null) { return false; } Node oldRoot = oldInput.getAstRoot(this); if (oldRoot != null) { oldRoot.replaceWith(newRoot); } else { getRoot().getLastChild().addChildToBack(newRoot); } CompilerInput newInput = new CompilerInput(ast); putCompilerInput(ast.getInputId(), newInput); JSModule module = oldInput.getModule(); if (module != null) { module.addAfter(newInput, oldInput); module.remove(oldInput); } // Verify the input id is set properly. Preconditions.checkState( newInput.getInputId().equals(oldInput.getInputId())); InputId inputIdOnAst = newInput.getAstRoot(this).getInputId(); Preconditions.checkState(newInput.getInputId().equals(inputIdOnAst)); inputs.remove(oldInput); return true; } /** * Add a new source input dynamically. Intended for incremental compilation. * <p> * If the new source input doesn't parse, it will not be added, and a false * will be returned. * * @param ast the JS Source to add. * @return true if the source was added successfully, false otherwise. * @throws IllegalStateException if an input for this ast already exists. */ boolean addNewSourceAst(JsAst ast) { CompilerInput oldInput = getInput(ast.getInputId()); if (oldInput != null) { throw new IllegalStateException( "Input already exists: " + ast.getInputId().getIdName()); } Node newRoot = ast.getAstRoot(this); if (newRoot == null) { return false; } getRoot().getLastChild().addChildToBack(newRoot); CompilerInput newInput = new CompilerInput(ast); // TODO(tylerg): handle this for multiple modules at some point. if (moduleGraph == null && !modules.isEmpty()) { // singleton module modules.get(0).add(newInput); } putCompilerInput(ast.getInputId(), newInput); return true; } @Override JSModuleGraph getModuleGraph() { return moduleGraph; } /** * Gets a module graph. This will always return a module graph, even * in the degenerate case when there's only one module. */ JSModuleGraph getDegenerateModuleGraph() { return moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph; } @Override public TypeIRegistry getTypeIRegistry() { switch (mostRecentTypechecker) { case NONE: // Even in compiles where typechecking is not enabled, some passes ask for the // type registry, eg, GatherExternProperties does. Also, in CheckAccessControls, // the constructor asks for a type registry, and this may happen before type checking // runs. So, in the NONE case, if NTI is enabled, return a new registry, since NTI is // the relevant type checker. If NTI is not enabled, return an old registry. return options.getNewTypeInference() ? getSymbolTable() : getTypeRegistry(); case OTI: return getTypeRegistry(); case NTI: return getSymbolTable(); default: throw new RuntimeException("Unhandled typechecker " + mostRecentTypechecker); } } @Override public JSTypeRegistry getTypeRegistry() { if (typeRegistry == null) { typeRegistry = new JSTypeRegistry(oldErrorReporter, forwardDeclaredTypes); } return typeRegistry; } @Override void forwardDeclareType(String typeName) { if (options.allowUnfulfilledForwardDeclarations()) { forwardDeclaredTypes.add(typeName); } } @Override void setMostRecentTypechecker(MostRecentTypechecker lastRun) { this.mostRecentTypechecker = lastRun; } @Override // Only used by jsdev public MemoizedScopeCreator getTypedScopeCreator() { return getPassConfig().getTypedScopeCreator(); } @SuppressWarnings("unchecked") DefaultPassConfig ensureDefaultPassConfig() { PassConfig passes = getPassConfig().getBasePassConfig(); Preconditions.checkState(passes instanceof DefaultPassConfig, "PassConfigs must eventually delegate to the DefaultPassConfig"); return (DefaultPassConfig) passes; } public SymbolTable buildKnownSymbolTable() { SymbolTable symbolTable = new SymbolTable(this, getTypeRegistry()); MemoizedScopeCreator typedScopeCreator = getTypedScopeCreator(); if (typedScopeCreator != null) { symbolTable.addScopes(typedScopeCreator.getAllMemoizedScopes()); symbolTable.addSymbolsFrom(typedScopeCreator); } else { symbolTable.findScopes(externsRoot, jsRoot); } GlobalNamespace globalNamespace = ensureDefaultPassConfig().getGlobalNamespace(); if (globalNamespace != null) { symbolTable.addSymbolsFrom(globalNamespace); } ReferenceCollectingCallback refCollector = new ReferenceCollectingCallback( this, ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR, SyntacticScopeCreator.makeUntyped(this)); refCollector.process(getRoot()); symbolTable.addSymbolsFrom(refCollector); PreprocessorSymbolTable preprocessorSymbolTable = ensureDefaultPassConfig().getPreprocessorSymbolTable(); if (preprocessorSymbolTable != null) { symbolTable.addSymbolsFrom(preprocessorSymbolTable); } symbolTable.fillNamespaceReferences(); symbolTable.fillPropertyScopes(); symbolTable.fillThisReferences(externsRoot, jsRoot); symbolTable.fillPropertySymbols(externsRoot, jsRoot); symbolTable.fillJSDocInfo(externsRoot, jsRoot); symbolTable.fillSymbolVisibility(externsRoot, jsRoot); return symbolTable; } @Override public TypedScope getTopScope() { return getPassConfig().getTopScope(); } @Override public ReverseAbstractInterpreter getReverseAbstractInterpreter() { if (abstractInterpreter == null) { ChainableReverseAbstractInterpreter interpreter = new SemanticReverseAbstractInterpreter(getTypeRegistry()); if (options.closurePass) { interpreter = new ClosureReverseAbstractInterpreter(getTypeRegistry()) .append(interpreter).getFirst(); } abstractInterpreter = interpreter; } return abstractInterpreter; } @Override // Only used by passes in the old type checker. TypeValidator getTypeValidator() { if (typeValidator == null) { typeValidator = new TypeValidator(this); } return typeValidator; } @Override Iterable<TypeMismatch> getTypeMismatches() { return getTypeValidator().getMismatches(); } @Override Iterable<TypeMismatch> getImplicitInterfaceUses() { return getTypeValidator().getImplicitInterfaceUses(); } @Override GlobalTypeInfo getSymbolTable() { if (this.symbolTable == null) { this.symbolTable = new GlobalTypeInfo(this, forwardDeclaredTypes); } return this.symbolTable; } @Override DefinitionUseSiteFinder getDefinitionFinder() { return this.defFinder; } @Override void setDefinitionFinder(DefinitionUseSiteFinder defFinder) { this.defFinder = defFinder; } //------------------------------------------------------------------------ // Parsing //------------------------------------------------------------------------ /** * Parses the externs and main inputs. * * @return A synthetic root node whose two children are the externs root * and the main root */ Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; // If old roots exist (we are parsing a second time), detach each of the // individual file parse trees. externsRoot.detachChildren(); jsRoot.detachChildren(); if (options.getTracerMode().isOn()) { tracker = new PerformanceTracker(externsRoot, jsRoot, options.getTracerMode(), this.outStream); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer(PARSING_PASS_NAME); beforePass(PARSING_PASS_NAME); try { // Parse externs sources. for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } if (options.lowerFromEs6() || options.transformAMDToCJSModules || options.processCommonJSModules) { this.moduleLoader = new ModuleLoader( this, options.moduleRoots, inputs, ModuleLoader.PathResolver.RELATIVE, options.moduleResolutionMode); if (options.moduleResolutionMode == ModuleLoader.ResolutionMode.NODE) { this.moduleLoader.setPackageJsonMainEntries(processJsonInputs(inputs)); } if (options.lowerFromEs6()) { processEs6Modules(); } // Modules inferred in ProcessCommonJS pass. if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } // Build a map of module identifiers for any input which provides no namespace. // These files could be imported modules which have no exports, but do have side effects. Map<String, CompilerInput> inputModuleIdentifiers = new HashMap<>(); for (CompilerInput input : inputs) { if (input.getKnownProvides().isEmpty()) { ModuleIdentifier modInfo = ModuleIdentifier.forFile(input.getSourceFile().getOriginalPath()); inputModuleIdentifiers.put(modInfo.getClosureNamespace(), input); } } // Find out if any input attempted to import a module that had no exports. // In this case we must force module rewriting to occur on the imported file Map<String, CompilerInput> inputsToRewrite = new HashMap<>(); for (CompilerInput input : inputs) { for (String require : input.getKnownRequires()) { if (inputModuleIdentifiers.containsKey(require) && !inputsToRewrite.containsKey(require)) { inputsToRewrite.put(require, inputModuleIdentifiers.get(require)); } } } if (!inputsToRewrite.isEmpty()) { processEs6Modules(new ArrayList<>(inputsToRewrite.values()), true); } } else { // Use an empty module loader if we're not actually dealing with modules. this.moduleLoader = ModuleLoader.EMPTY; } orderInputs(); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } // Build the AST. for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } // TODO(johnlenz): we shouldn't need to check both isExternExportsEnabled and // externExportsPath. if (options.sourceMapOutputPath != null || options.isExternExportsEnabled() || options.externExportsPath != null || !options.replaceStringsFunctionDescriptions.isEmpty()) { // Annotate the nodes in the tree with information from the // input file. This information is used to construct the SourceMap. SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverseEs6(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { afterPass(PARSING_PASS_NAME); stopTracer(tracer, PARSING_PASS_NAME); } } void orderInputsWithLargeStack() { runInCompilerThread(new Callable<Void>() { @Override public Void call() throws Exception { Tracer tracer = newTracer("orderInputsWithLargeStack"); try { orderInputs(); } finally { stopTracer(tracer, "orderInputsWithLargeStack"); } return null; } }); } void orderInputs() { hoistUnorderedExterns(); // Check if the sources need to be re-ordered. boolean staleInputs = false; if (options.dependencyOptions.needsManagement()) { for (CompilerInput input : inputs) { // Forward-declare all the provided types, so that they // are not flagged even if they are dropped from the process. for (String provide : input.getProvides()) { forwardDeclareType(provide); } } try { inputs = getDegenerateModuleGraph().manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); } catch (JSModuleGraph.MissingModuleException e) { report(JSError.make( MISSING_MODULE_ERROR, e.getMessage())); } } if (options.dependencyOptions.needsManagement() && options.allowGoogProvideInExterns()) { hoistAllExterns(); } hoistNoCompileFiles(); if (staleInputs) { repartitionInputs(); } } /** * Hoists inputs with the @externs annotation and no provides or requires into the externs list. */ void hoistUnorderedExterns() { boolean staleInputs = false; for (CompilerInput input : inputs) { if (options.dependencyOptions.needsManagement()) { // If we're doing scanning dependency info anyway, use that // information to skip sources that obviously aren't externs. if (!input.getProvides().isEmpty() || !input.getRequires().isEmpty()) { continue; } } if (hoistIfExtern(input)) { staleInputs = true; } } if (staleInputs) { repartitionInputs(); } } /** * Hoists inputs with the @externs annotation into the externs list. */ void hoistAllExterns() { boolean staleInputs = false; for (CompilerInput input : inputs) { if (hoistIfExtern(input)) { staleInputs = true; } } if (staleInputs) { repartitionInputs(); } } /** * Hoists a compiler input to externs if it contains the @externs annotation. * Return whether or not the given input was hoisted. */ private boolean hoistIfExtern(CompilerInput input) { Node n = input.getAstRoot(this); // Inputs can have a null AST on a parse error. if (n == null) { return false; } JSDocInfo info = n.getJSDocInfo(); if (info != null && info.isExterns()) { // If the input file is explicitly marked as an externs file, then // assume the programmer made a mistake and throw it into // the externs pile anyways. externsRoot.addChildToBack(n); input.setIsExtern(true); input.getModule().remove(input); externs.add(input); return true; } return false; } /** * Hoists inputs with the @nocompile annotation out of the inputs. */ void hoistNoCompileFiles() { boolean staleInputs = false; for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); // Inputs can have a null AST on a parse error. if (n == null) { continue; } JSDocInfo info = n.getJSDocInfo(); if (info != null && info.isNoCompile()) { input.getModule().remove(input); staleInputs = true; } } if (staleInputs) { repartitionInputs(); } } private void repartitionInputs() { fillEmptyModules(modules); rebuildInputsFromModules(); } /** * Transforms JSON files to a module export that closure compiler can process and keeps track of * any "main" entries in package.json files. */ Map<String, String> processJsonInputs(List<CompilerInput> inputsToProcess) { RewriteJsonToModule rewriteJson = new RewriteJsonToModule(this); for (CompilerInput input : inputsToProcess) { if (!input.getSourceFile().getOriginalPath().endsWith(".json")) { continue; } input.setCompiler(this); try { // JSON objects need wrapped in parens to parse properly input.getSourceFile().setCode("(" + input.getSourceFile().getCode() + ")"); } catch (IOException e) { continue; } Node root = input.getAstRoot(this); if (root == null) { continue; } rewriteJson.process(null, root); } return rewriteJson.getPackageJsonMainEntries(); } void processEs6Modules() { processEs6Modules(inputs, false); } void processEs6Modules(List<CompilerInput> inputsToProcess, boolean forceRewrite) { for (CompilerInput input : inputsToProcess) { input.setCompiler(this); Node root = input.getAstRoot(this); if (root == null) { continue; } new ProcessEs6Modules(this).processFile(root, forceRewrite); } } /** * Transforms AMD and CJS modules to something closure compiler can * process and creates JSModules and the corresponding dependency tree * on the way. */ void processAMDAndCommonJSModules() { for (CompilerInput input : inputs) { input.setCompiler(this); Node root = input.getAstRoot(this); if (root == null) { continue; } if (options.transformAMDToCJSModules) { new TransformAMDToCJSModule(this).process(null, root); } if (options.processCommonJSModules) { ProcessCommonJSModules cjs = new ProcessCommonJSModules(this, true); cjs.process(null, root); } } } public Node parse(SourceFile file) { initCompilerOptionsIfTesting(); addToDebugLog("Parsing: " + file.getName()); return new JsAst(file).getAstRoot(this); } private int syntheticCodeId = 0; @Override Node parseSyntheticCode(String js) { SourceFile source = SourceFile.fromCode(" [synthetic:" + (++syntheticCodeId) + "] ", js); addFilesToSourceMap(ImmutableList.of(source)); CompilerInput input = new CompilerInput(source); putCompilerInput(input.getInputId(), input); return input.getAstRoot(this); } /** * Allow subclasses to override the default CompileOptions object. */ protected CompilerOptions newCompilerOptions() { return new CompilerOptions(); } void initCompilerOptionsIfTesting() { if (options == null) { // initialization for tests that don't initialize the compiler // by the normal mechanisms. initOptions(newCompilerOptions()); } } @Override Node parseSyntheticCode(String fileName, String js) { initCompilerOptionsIfTesting(); addFileToSourceMap(fileName, js); CompilerInput input = new CompilerInput(SourceFile.fromCode(fileName, js)); putCompilerInput(input.getInputId(), input); return input.getAstRoot(this); } @Override Node parseTestCode(String js) { initCompilerOptionsIfTesting(); initBasedOnOptions(); CompilerInput input = new CompilerInput( SourceFile.fromCode("[testcode]", js)); if (inputsById == null) { inputsById = new HashMap<>(); } putCompilerInput(input.getInputId(), input); return input.getAstRoot(this); } @Override ErrorReporter getDefaultErrorReporter() { return oldErrorReporter; } //------------------------------------------------------------------------ // Convert back to source code //------------------------------------------------------------------------ /** * Converts the main parse tree back to JS code. */ @Override public String toSource() { return runInCompilerThread(new Callable<String>() { @Override public String call() throws Exception { Tracer tracer = newTracer("toSource"); try { CodeBuilder cb = new CodeBuilder(); if (jsRoot != null) { int i = 0; for (Node scriptNode = jsRoot.getFirstChild(); scriptNode != null; scriptNode = scriptNode.getNext()) { toSource(cb, i++, scriptNode); } } return cb.toString(); } finally { stopTracer(tracer, "toSource"); } } }); } /** * Converts the parse tree for each input back to JS code. */ public String[] toSourceArray() { return runInCompilerThread(new Callable<String[]>() { @Override public String[] call() throws Exception { Tracer tracer = newTracer("toSourceArray"); try { int numInputs = inputs.size(); String[] sources = new String[numInputs]; CodeBuilder cb = new CodeBuilder(); for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); cb.reset(); toSource(cb, i, scriptNode); sources[i] = cb.toString(); } return sources; } finally { stopTracer(tracer, "toSourceArray"); } } }); } /** * Converts the parse tree for a module back to JS code. */ public String toSource(final JSModule module) { return runInCompilerThread(new Callable<String>() { @Override public String call() throws Exception { List<CompilerInput> inputs = module.getInputs(); int numInputs = inputs.size(); if (numInputs == 0) { return ""; } CodeBuilder cb = new CodeBuilder(); for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); if (scriptNode == null) { throw new IllegalArgumentException( "Bad module: " + module.getName()); } toSource(cb, i, scriptNode); } return cb.toString(); } }); } /** * Converts the parse tree for each input in a module back to JS code. */ public String[] toSourceArray(final JSModule module) { return runInCompilerThread(new Callable<String[]>() { @Override public String[] call() throws Exception { List<CompilerInput> inputs = module.getInputs(); int numInputs = inputs.size(); if (numInputs == 0) { return new String[0]; } String[] sources = new String[numInputs]; CodeBuilder cb = new CodeBuilder(); for (int i = 0; i < numInputs; i++) { Node scriptNode = inputs.get(i).getAstRoot(Compiler.this); if (scriptNode == null) { throw new IllegalArgumentException( "Bad module input: " + inputs.get(i).getName()); } cb.reset(); toSource(cb, i, scriptNode); sources[i] = cb.toString(); } return sources; } }); } /** * Writes out JS code from a root node. If printing input delimiters, this * method will attach a comment to the start of the text indicating which * input the output derived from. If there were any preserve annotations * within the root's source, they will also be printed in a block comment * at the beginning of the output. */ public void toSource(final CodeBuilder cb, final int inputSeqNum, final Node root) { runInCompilerThread(new Callable<Void>() { @Override public Void call() throws Exception { if (options.printInputDelimiter) { if ((cb.getLength() > 0) && !cb.endsWith("\n")) { cb.append("\n"); // Make sure that the label starts on a new line } Preconditions.checkState(root.isScript()); String delimiter = options.inputDelimiter; String inputName = root.getInputId().getIdName(); String sourceName = root.getSourceFileName(); Preconditions.checkState(sourceName != null); Preconditions.checkState(!sourceName.isEmpty()); delimiter = delimiter .replaceAll("%name%", Matcher.quoteReplacement(inputName)) .replaceAll("%num%", String.valueOf(inputSeqNum)); cb.append(delimiter) .append("\n"); } if (root.getJSDocInfo() != null) { String license = root.getJSDocInfo().getLicense(); if (license != null && cb.addLicense(license)) { cb.append("/*\n") .append(license) .append("*/\n"); } } // If there is a valid source map, then indicate to it that the current // root node's mappings are offset by the given string builder buffer. if (options.sourceMapOutputPath != null) { sourceMap.setStartingPosition( cb.getLineIndex(), cb.getColumnIndex()); } // if LanguageMode is strict, only print 'use strict' // for the first input file String code = toSource(root, sourceMap, inputSeqNum == 0); if (!code.isEmpty()) { cb.append(code); // In order to avoid parse ambiguity when files are concatenated // together, all files should end in a semi-colon. Do a quick // heuristic check if there's an obvious semi-colon already there. int length = code.length(); char lastChar = code.charAt(length - 1); char secondLastChar = length >= 2 ? code.charAt(length - 2) : '\0'; boolean hasSemiColon = lastChar == ';' || (lastChar == '\n' && secondLastChar == ';'); if (!hasSemiColon) { cb.append(";"); } } return null; } }); } /** * Generates JavaScript source code for an AST, doesn't generate source * map info. */ @Override public String toSource(Node n) { initCompilerOptionsIfTesting(); return toSource(n, null, true); } /** * Generates JavaScript source code for an AST. */ private String toSource(Node n, SourceMap sourceMap, boolean firstOutput) { CodePrinter.Builder builder = new CodePrinter.Builder(n); builder.setTypeRegistry(this.typeRegistry); builder.setCompilerOptions(options); builder.setSourceMap(sourceMap); builder.setTagAsExterns(firstOutput && options.shouldGenerateTypedExterns()); builder.setTagAsStrict(firstOutput && shouldEmitUseStrict()); return builder.build(); } private boolean shouldEmitUseStrict() { switch (options.getLanguageOut()) { case ECMASCRIPT3: case ECMASCRIPT5: case ECMASCRIPT6: return false; default: return options.isEmitUseStrict(); } } /** * Stores a buffer of text to which more can be appended. This is just like a * StringBuilder except that we also track the number of lines. */ public static class CodeBuilder { private final StringBuilder sb = new StringBuilder(); private int lineCount = 0; private int colCount = 0; private final Set<String> uniqueLicenses = new HashSet<>(); /** Removes all text, but leaves the line count unchanged. */ void reset() { sb.setLength(0); } /** Appends the given string to the text buffer. */ CodeBuilder append(String str) { sb.append(str); // Adjust the line and column information for the new text. int index = -1; int lastIndex = index; while ((index = str.indexOf('\n', index + 1)) >= 0) { ++lineCount; lastIndex = index; } if (lastIndex == -1) { // No new lines, append the new characters added. colCount += str.length(); } else { colCount = str.length() - (lastIndex + 1); } return this; } /** Returns all text in the text buffer. */ @Override public String toString() { return sb.toString(); } /** Returns the length of the text buffer. */ public int getLength() { return sb.length(); } /** Returns the (zero-based) index of the last line in the text buffer. */ int getLineIndex() { return lineCount; } /** Returns the (zero-based) index of the last column in the text buffer. */ int getColumnIndex() { return colCount; } /** Determines whether the text ends with the given suffix. */ boolean endsWith(String suffix) { return (sb.length() > suffix.length()) && suffix.equals(sb.substring(sb.length() - suffix.length())); } /** Adds a license and returns whether it is unique (has yet to be encountered). */ boolean addLicense(String license) { return uniqueLicenses.add(license); } } //------------------------------------------------------------------------ // Optimizations //------------------------------------------------------------------------ public void optimize() { List<PassFactory> optimizations = getPassConfig().getOptimizations(); if (optimizations.isEmpty()) { return; } // Ideally, this pass should be the first pass run, however: // 1) VariableReferenceCheck reports unexpected warnings if Normalize // is done first. // 2) ReplaceMessages, stripCode, and potentially custom passes rely on // unmodified local names. normalize(); // Create extern exports after the normalize because externExports depends on unique names. if (options.isExternExportsEnabled() || options.externExportsPath != null) { externExports(); } phaseOptimizer = new PhaseOptimizer(this, tracker, null); if (options.devMode == DevMode.EVERY_PASS) { phaseOptimizer.setSanityCheck(sanityCheck); } if (options.getCheckDeterminism()) { phaseOptimizer.setPrintAstHashcodes(true); } phaseOptimizer.consume(optimizations); phaseOptimizer.process(externsRoot, jsRoot); phaseOptimizer = null; } @Override void setCssRenamingMap(CssRenamingMap map) { options.cssRenamingMap = map; } @Override CssRenamingMap getCssRenamingMap() { return options.cssRenamingMap; } /** Control Flow Analysis. */ ControlFlowGraph<Node> computeCFG() { logger.fine("Computing Control Flow Graph"); Tracer tracer = newTracer("computeCFG"); ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false); process(cfa); stopTracer(tracer, "computeCFG"); return cfa.getCfg(); } public void normalize() { logger.fine("Normalizing"); startPass("normalize"); process(new Normalize(this, false)); endPass("normalize"); } @Override void prepareAst(Node root) { CompilerPass pass = new PrepareAst(this); pass.process(null, root); } void recordFunctionInformation() { logger.fine("Recording function information"); startPass("recordFunctionInformation"); RecordFunctionInformation recordFunctionInfoPass = new RecordFunctionInformation( this, getPassConfig().getIntermediateState().functionNames); process(recordFunctionInfoPass); functionInformationMap = recordFunctionInfoPass.getMap(); endPass("recordFunctionInformation"); } protected final RecentChange recentChange = new RecentChange(); private final List<CodeChangeHandler> codeChangeHandlers = new ArrayList<>(); /** Name of the synthetic input that holds synthesized externs. */ static final String SYNTHETIC_EXTERNS = "{SyntheticVarsDeclar}"; /** * Name of the synthetic input that holds synthesized externs which * must be at the end of the externs AST. */ static final String SYNTHETIC_EXTERNS_AT_END = "{SyntheticVarsAtEnd}"; private CompilerInput synthesizedExternsInput = null; private CompilerInput synthesizedExternsInputAtEnd = null; private ImmutableMap<String, Node> defaultDefineValues = ImmutableMap.of(); @Override void addChangeHandler(CodeChangeHandler handler) { codeChangeHandlers.add(handler); } @Override void removeChangeHandler(CodeChangeHandler handler) { codeChangeHandlers.remove(handler); } @Override void setScope(Node n) { if (phaseOptimizer != null) { phaseOptimizer.setScope(n); } } @Override Node getJsRoot() { return jsRoot; } @Override boolean hasScopeChanged(Node n) { if (phaseOptimizer == null) { return true; } return phaseOptimizer.hasScopeChanged(n); } @Override void reportChangeToEnclosingScope(Node n) { if (phaseOptimizer != null) { phaseOptimizer.reportChangeToEnclosingScope(n); phaseOptimizer.startCrossScopeReporting(); reportCodeChange(); phaseOptimizer.endCrossScopeReporting(); } else { reportCodeChange(); } } /** * Some tests don't want to call the compiler "wholesale," they may not want * to call check and/or optimize. With this method, tests can execute custom * optimization loops. */ @VisibleForTesting void setPhaseOptimizer(PhaseOptimizer po) { this.phaseOptimizer = po; } @Override public void reportCodeChange() { for (CodeChangeHandler handler : codeChangeHandlers) { handler.reportChange(); } } @Override public CodingConvention getCodingConvention() { CodingConvention convention = options.getCodingConvention(); convention = convention != null ? convention : defaultCodingConvention; return convention; } private Config.LanguageMode getParserConfigLanguageMode( CompilerOptions.LanguageMode languageMode) { switch (languageMode) { case ECMASCRIPT3: return Config.LanguageMode.ECMASCRIPT3; case ECMASCRIPT5: case ECMASCRIPT5_STRICT: return Config.LanguageMode.ECMASCRIPT5; case ECMASCRIPT6: case ECMASCRIPT6_STRICT: case ECMASCRIPT_2015: return Config.LanguageMode.ECMASCRIPT6; case ECMASCRIPT6_TYPED: return Config.LanguageMode.TYPESCRIPT; case ECMASCRIPT7: case ECMASCRIPT_2016: return Config.LanguageMode.ECMASCRIPT7; case ECMASCRIPT8: case ECMASCRIPT_NEXT: return Config.LanguageMode.ECMASCRIPT8; default: throw new IllegalStateException("unexpected language mode: " + options.getLanguageIn()); } } @Override Config getParserConfig(ConfigContext context) { if (parserConfig == null) { Config.LanguageMode configLanguageMode = getParserConfigLanguageMode(options.getLanguageIn()); Config.StrictMode strictMode = expectStrictModeInput() ? Config.StrictMode.STRICT : Config.StrictMode.SLOPPY; parserConfig = createConfig(configLanguageMode, strictMode); // Externs must always be parsed with at least ES5 language mode. externsParserConfig = configLanguageMode.equals(Config.LanguageMode.ECMASCRIPT3) ? createConfig(Config.LanguageMode.ECMASCRIPT5, strictMode) : parserConfig; } switch (context) { case EXTERNS: return externsParserConfig; default: return parserConfig; } } protected Config createConfig(Config.LanguageMode mode, Config.StrictMode strictMode) { Config config = ParserRunner.createConfig( mode, options.isParseJsDocDocumentation(), options.canContinueAfterErrors() ? Config.RunMode.KEEP_GOING : Config.RunMode.STOP_AFTER_ERROR, options.extraAnnotationNames, options.parseInlineSourceMaps, strictMode); return config; } //------------------------------------------------------------------------ // Error reporting //------------------------------------------------------------------------ /** * The warning classes that are available from the command-line, and * are suppressible by the {@code @suppress} annotation. */ protected DiagnosticGroups getDiagnosticGroups() { return new DiagnosticGroups(); } @Override public void report(JSError error) { CheckLevel level = error.getDefaultLevel(); if (warningsGuard != null) { CheckLevel newLevel = warningsGuard.level(error); if (newLevel != null) { level = newLevel; } } if (level.isOn()) { initCompilerOptionsIfTesting(); if (getOptions().errorHandler != null) { getOptions().errorHandler.report(level, error); } errorManager.report(level, error); } } @Override public void report(CheckLevel ignoredLevel, JSError error) { report(error); } @Override public CheckLevel getErrorLevel(JSError error) { Preconditions.checkNotNull(options); return warningsGuard.level(error); } /** * Report an internal error. */ @Override void throwInternalError(String message, Exception cause) { String finalMessage = "INTERNAL COMPILER ERROR.\n" + "Please report this problem.\n\n" + message; RuntimeException e = new RuntimeException(finalMessage, cause); if (cause != null) { e.setStackTrace(cause.getStackTrace()); } throw e; } /** * Gets the number of errors. */ public int getErrorCount() { return errorManager.getErrorCount(); } /** * Gets the number of warnings. */ public int getWarningCount() { return errorManager.getWarningCount(); } @Override boolean hasHaltingErrors() { return !getOptions().canContinueAfterErrors() && getErrorCount() > 0; } /** * Consults the {@link ErrorManager} to see if we've encountered errors * that should halt compilation. <p> * * If {@link CompilerOptions#canContinueAfterErrors} is {@code true}, this function * always returns {@code false} without consulting the error manager. The * error manager will continue to be told about new errors and warnings, but * the compiler will complete compilation of all inputs.<p> */ public boolean hasErrors() { return hasHaltingErrors(); } /** Called from the compiler passes, adds debug info */ @Override void addToDebugLog(String str) { if (options.useDebugLog) { debugLog.append(str); debugLog.append('\n'); logger.fine(str); } } @Override public SourceFile getSourceFileByName(String sourceName) { // Here we assume that the source name is the input name, this // is try of JavaScript parsed from source. if (sourceName != null) { CompilerInput input = inputsById.get(new InputId(sourceName)); if (input != null) { return input.getSourceFile(); } // Alternatively, the sourceName might have been reverse-mapped by // an input source-map, so let's look in our sourcemap original sources. return sourceMapOriginalSources.get(sourceName); } return null; } @Override public void addInputSourceMap(String sourceFileName, SourceMapInput inputSourceMap) { inputSourceMaps.put(sourceFileName, inputSourceMap); } @Override public OriginalMapping getSourceMapping(String sourceName, int lineNumber, int columnNumber) { if (sourceName == null) { return null; } SourceMapInput sourceMap = inputSourceMaps.get(sourceName); if (sourceMap == null) { return null; } // JSCompiler uses 1-indexing for lineNumber and 0-indexing for // columnNumber. // SourceMap uses 1-indexing for both. OriginalMapping result = sourceMap.getSourceMap() .getMappingForLine(lineNumber, columnNumber + 1); if (result == null) { return null; } // The sourcemap will return a path relative to the sourcemap's file. // Translate it to one relative to our base directory. String path = getRelativeTo(result.getOriginalFile(), sourceMap.getOriginalPath()); sourceMapOriginalSources.putIfAbsent( path, originalSourcesLoader.apply(path)); return result.toBuilder() .setOriginalFile(path) .setColumnPosition(result.getColumnPosition() - 1) .build(); } @Override public String getSourceLine(String sourceName, int lineNumber) { if (lineNumber < 1) { return null; } SourceFile input = getSourceFileByName(sourceName); if (input != null) { return input.getLine(lineNumber); } return null; } @Override public Region getSourceRegion(String sourceName, int lineNumber) { if (lineNumber < 1) { return null; } SourceFile input = getSourceFileByName(sourceName); if (input != null) { return input.getRegion(lineNumber); } return null; } //------------------------------------------------------------------------ // Package-private helpers //------------------------------------------------------------------------ @Override Node getNodeForCodeInsertion(JSModule module) { if (module == null) { if (inputs.isEmpty()) { throw new IllegalStateException("No inputs"); } return inputs.get(0).getAstRoot(this); } List<CompilerInput> moduleInputs = module.getInputs(); if (!moduleInputs.isEmpty()) { return moduleInputs.get(0).getAstRoot(this); } throw new IllegalStateException("Root module has no inputs"); } public SourceMap getSourceMap() { return sourceMap; } VariableMap getVariableMap() { return getPassConfig().getIntermediateState().variableMap; } VariableMap getPropertyMap() { return getPassConfig().getIntermediateState().propertyMap; } VariableMap getStringMap() { return getPassConfig().getIntermediateState().stringMap; } @Override CompilerOptions getOptions() { return options; } FunctionInformationMap getFunctionalInformationMap() { return functionInformationMap; } /** * Sets the logging level for the com.google.javascript.jscomp package. */ public static void setLoggingLevel(Level level) { logger.setLevel(level); } /** Gets the DOT graph of the AST generated at the end of compilation. */ public String getAstDotGraph() throws IOException { if (jsRoot != null) { ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false); cfa.process(null, jsRoot); return DotFormatter.toDot(jsRoot, cfa.getCfg()); } else { return ""; } } @Override public ErrorManager getErrorManager() { if (options == null) { initOptions(newCompilerOptions()); } return errorManager; } @Override List<CompilerInput> getInputsInOrder() { return Collections.unmodifiableList(inputs); } /** * Returns an unmodifiable view of the compiler inputs indexed by id. */ public Map<InputId, CompilerInput> getInputsById() { return Collections.unmodifiableMap(inputsById); } /** * Gets the externs in the order in which they are being processed. */ List<CompilerInput> getExternsInOrder() { return Collections.unmodifiableList(externs); } @VisibleForTesting List<CompilerInput> getInputsForTesting() { return inputs; } @VisibleForTesting List<CompilerInput> getExternsForTesting() { return externs; } @Override boolean hasRegExpGlobalReferences() { return hasRegExpGlobalReferences; } @Override void setHasRegExpGlobalReferences(boolean references) { hasRegExpGlobalReferences = references; } @Override void updateGlobalVarReferences(Map<Var, ReferenceCollection> refMapPatch, Node collectionRoot) { Preconditions.checkState(collectionRoot.isScript() || collectionRoot.isRoot()); if (globalRefMap == null) { globalRefMap = new GlobalVarReferenceMap(getInputsInOrder(), getExternsInOrder()); } globalRefMap.updateGlobalVarReferences(refMapPatch, collectionRoot); } @Override GlobalVarReferenceMap getGlobalVarReferences() { return globalRefMap; } @Override CompilerInput getSynthesizedExternsInput() { if (synthesizedExternsInput == null) { synthesizedExternsInput = newExternInput(SYNTHETIC_EXTERNS, SyntheticExternsPosition.START); } return synthesizedExternsInput; } @Override CompilerInput getSynthesizedExternsInputAtEnd() { if (synthesizedExternsInputAtEnd == null) { synthesizedExternsInputAtEnd = newExternInput( SYNTHETIC_EXTERNS_AT_END, SyntheticExternsPosition.END); } return synthesizedExternsInputAtEnd; } @Override public double getProgress() { return progress; } @Override String getLastPassName() { return lastPassName; } @Override void setProgress(double newProgress, String passName) { this.lastPassName = passName; if (newProgress > 1.0) { progress = 1.0; } else { progress = newProgress; } } @Override void setExternProperties(Set<String> externProperties) { this.externProperties = externProperties; } @Override Set<String> getExternProperties() { return externProperties; } /** * Replaces one file in a hot-swap mode. The given JsAst should be made * from a new version of a file that already was present in the last compile * call. If the file is new, this will silently ignored. * * @param ast the ast of the file that is being replaced */ public void replaceScript(JsAst ast) { CompilerInput input = this.getInput(ast.getInputId()); if (!replaceIncrementalSourceAst(ast)) { return; } Node originalRoot = input.getAstRoot(this); processNewScript(ast, originalRoot); } /** * Adds a new Script AST to the compile state. If a script for the same file * already exists the script will not be added, instead a call to * #replaceScript should be used. * * @param ast the ast of the new file */ public void addNewScript(JsAst ast) { if (!addNewSourceAst(ast)) { return; } Node emptyScript = new Node(Token.SCRIPT); InputId inputId = ast.getInputId(); emptyScript.setInputId(inputId); emptyScript.setStaticSourceFile( SourceFile.fromCode(inputId.getIdName(), "")); processNewScript(ast, emptyScript); } private void processNewScript(JsAst ast, Node originalRoot) { languageMode = options.getLanguageIn(); Node js = ast.getAstRoot(this); Preconditions.checkNotNull(js); runHotSwap(originalRoot, js, this.getCleanupPassConfig()); // NOTE: If hot swap passes that use GlobalNamespace are added, we will need // to revisit this approach to clearing GlobalNamespaces runHotSwapPass(null, null, ensureDefaultPassConfig().garbageCollectChecks); this.getTypeRegistry().clearNamedTypes(); this.removeSyntheticVarsInput(); runHotSwap(originalRoot, js, this.ensureDefaultPassConfig()); } /** * Execute the passes from a PassConfig instance over a single replaced file. */ private void runHotSwap( Node originalRoot, Node js, PassConfig passConfig) { for (PassFactory passFactory : passConfig.getChecks()) { runHotSwapPass(originalRoot, js, passFactory); } } private void runHotSwapPass( Node originalRoot, Node js, PassFactory passFactory) { HotSwapCompilerPass pass = passFactory.getHotSwapPass(this); if (pass != null) { if (logger.isLoggable(Level.INFO)) { logger.info("Performing HotSwap for pass " + passFactory.getName()); } pass.hotSwapScript(js, originalRoot); } } private PassConfig getCleanupPassConfig() { return new CleanupPasses(getOptions()); } private void removeSyntheticVarsInput() { String sourceName = Compiler.SYNTHETIC_EXTERNS; removeExternInput(new InputId(sourceName)); } @Override Node ensureLibraryInjected(String resourceName, boolean force) { boolean doNotInject = !force && (options.skipNonTranspilationPasses || options.preventLibraryInjection); if (injectedLibraries.containsKey(resourceName) || doNotInject) { return lastInjectedLibrary; } // Load/parse the code. String originalCode = ResourceLoader.loadTextResource( Compiler.class, "js/" + resourceName + ".js"); Node ast = parseSyntheticCode(" [synthetic:" + resourceName + "] ", originalCode); // Look for string literals of the form 'require foo bar' or 'externs baz' or 'normalize'. // As we process each one, remove it from its parent. for (Node node = ast.getFirstChild(); node != null && node.isExprResult() && node.getFirstChild().isString(); node = ast.getFirstChild()) { String directive = node.getFirstChild().getString(); List<String> words = Splitter.on(' ').limit(2).splitToList(directive); switch (words.get(0)) { case "use": // 'use strict' is ignored (and deleted). break; case "require": // 'require lib'; pulls in the named library before this one. ensureLibraryInjected(words.get(1), force); break; case "declare": // 'declare name'; adds the name to the externs (with no type information). // Note that we could simply add the entire externs library, but that leads to // potentially-surprising behavior when the externs that are present depend on // whether or not a polyfill is used. Node var = IR.var(IR.name(words.get(1))); JSDocInfoBuilder jsdoc = new JSDocInfoBuilder(false); // Suppress duplicate-var warning in case this name is already defined in the externs. jsdoc.addSuppression("duplicate"); var.setJSDocInfo(jsdoc.build()); getSynthesizedExternsInputAtEnd() .getAstRoot(this) .addChildToBack(var); break; default: throw new RuntimeException("Bad directive: " + directive); } ast.removeChild(node); } // If we've already started optimizations, then we need to normalize this. if (getLifeCycleStage().isNormalized()) { Normalize.normalizeSyntheticCode(this, ast, "jscomp_" + resourceName + "_"); } // Insert the code immediately after the last-inserted runtime library. Node lastChild = ast.getLastChild(); Node firstChild = ast.removeChildren(); if (firstChild == null) { // Handle require-only libraries. return lastInjectedLibrary; } Node parent = getNodeForCodeInsertion(null); if (lastInjectedLibrary == null) { parent.addChildrenToFront(firstChild); } else { parent.addChildrenAfter(firstChild, lastInjectedLibrary); } lastInjectedLibrary = lastChild; injectedLibraries.put(resourceName, lastChild); reportCodeChange(); return lastChild; } /** Returns the compiler version baked into the jar. */ @GwtIncompatible("java.util.ResourceBundle") public static String getReleaseVersion() { ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE); return config.getString("compiler.version"); } /** Returns the compiler date baked into the jar. */ @GwtIncompatible("java.util.ResourceBundle") public static String getReleaseDate() { ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE); return config.getString("compiler.date"); } @Override void addComments(String filename, List<Comment> comments) { if (!getOptions().preservesDetailedSourceInfo()) { throw new UnsupportedOperationException( "addComments may only be called in IDE mode."); } commentsPerFile.put(filename, comments); } @Override public List<Comment> getComments(String filename) { if (!getOptions().preservesDetailedSourceInfo()) { throw new UnsupportedOperationException( "getComments may only be called in IDE mode."); } return commentsPerFile.get(filename); } @Override void setDefaultDefineValues(ImmutableMap<String, Node> values) { this.defaultDefineValues = values; } @Override ImmutableMap<String, Node> getDefaultDefineValues() { return this.defaultDefineValues; } @Override ModuleLoader getModuleLoader() { return moduleLoader; } private void addFilesToSourceMap(Iterable<? extends SourceFile> files) { if (getOptions().sourceMapIncludeSourcesContent && getSourceMap() != null) { for (SourceFile file : files) { getSourceMap().addSourceFile(file); } } } private void addFileToSourceMap(String filename, String contents) { if (getOptions().sourceMapIncludeSourcesContent && getSourceMap() != null) { getSourceMap().addSourceFile(SourceFile.fromCode(filename, contents)); } } }
Moves all input IO into a dedicated pass for better time measurement. Previously IO and parsing occurred in the same pass which made it hard to know if performance fluctuation was caused by CPU contention or IO contention. After this change it should be possible to know if IO performance is the culprit. Tracer mode now looks like: Log: pass,runtime,allocMem,codeChanged,astReduction,reduction,gzReduction,astSize,size,gzSize readInputs,319,42,false,0,0,0,0,0,0 parseInputs,3851,88,false,0,0,0,0,0,0 beforeStandardChecks,1,119,false,0,0,0,0,0,0 checkJsDoc,307,119,false,0,0,0,0,0,0 ... ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=146417464
src/com/google/javascript/jscomp/Compiler.java
Moves all input IO into a dedicated pass for better time measurement.
<ide><path>rc/com/google/javascript/jscomp/Compiler.java <ide> import com.google.common.base.Supplier; <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableMap; <add>import com.google.common.collect.Iterables; <ide> import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping; <ide> import com.google.javascript.jscomp.CompilerOptions.DevMode; <ide> import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection; <ide> "unknown module \"{0}\" specified in entry point spec"); <ide> <ide> // Used in PerformanceTracker <add> static final String READING_PASS_NAME = "readInputs"; <ide> static final String PARSING_PASS_NAME = "parseInputs"; <ide> static final String CROSS_MODULE_CODE_MOTION_NAME = "crossModuleCodeMotion"; <ide> static final String CROSS_MODULE_METHOD_MOTION_NAME = <ide> private void compileInternal() { <ide> setProgress(0.0, null); <ide> CompilerOptionsPreprocessor.preprocess(options); <add> read(); <add> // Guesstimate. <add> setProgress(0.02, "read"); <ide> parse(); <del> // 15 percent of the work is assumed to be for parsing (based on some <del> // minimal analysis on big JS projects, of course this depends on options) <add> // Guesstimate. <ide> setProgress(0.15, "parse"); <ide> if (hasErrors()) { <ide> return; <ide> if (tracker != null) { <ide> tracker.outputTracerReport(); <ide> } <add> } <add> <add> public void read() { <add> readInputs(); <ide> } <ide> <ide> public void parse() { <ide> } <ide> <ide> //------------------------------------------------------------------------ <add> // Reading <add> //------------------------------------------------------------------------ <add> <add> /** <add> * Performs all externs and main inputs IO. <add> * <add> * <p>Allows for easy measurement of IO cost separately from parse cost. <add> */ <add> void readInputs() { <add> if (options.getTracerMode().isOn()) { <add> tracker = <add> new PerformanceTracker(externsRoot, jsRoot, options.getTracerMode(), this.outStream); <add> addChangeHandler(tracker.getCodeChangeHandler()); <add> } <add> <add> Tracer tracer = newTracer(READING_PASS_NAME); <add> beforePass(READING_PASS_NAME); <add> <add> try { <add> for (CompilerInput input : Iterables.concat(externs, inputs)) { <add> try { <add> input.getCode(); <add> } catch (IOException e) { <add> report(JSError.make(AbstractCompiler.READ_ERROR, input.getName())); <add> } <add> } <add> } finally { <add> afterPass(READING_PASS_NAME); <add> stopTracer(tracer, READING_PASS_NAME); <add> } <add> } <add> <add> //------------------------------------------------------------------------ <ide> // Parsing <ide> //------------------------------------------------------------------------ <ide> <ide> // individual file parse trees. <ide> externsRoot.detachChildren(); <ide> jsRoot.detachChildren(); <del> <del> if (options.getTracerMode().isOn()) { <del> tracker = <del> new PerformanceTracker(externsRoot, jsRoot, options.getTracerMode(), this.outStream); <del> addChangeHandler(tracker.getCodeChangeHandler()); <del> } <ide> <ide> Tracer tracer = newTracer(PARSING_PASS_NAME); <ide> beforePass(PARSING_PASS_NAME);
JavaScript
mit
ef028856137eea1e3a203cab379beb80fb841f6b
0
kzap/ScriptCraft,walterhiggins/ScriptCraft,TonyGravagno/ScriptCraft,kamem/ScriptCraft,EllieAdam/ScriptCraft,dighjd12/ScriptCraft,mverwijs/ScriptCraft,itrion/ScriptCraft,EllieAdam/ScriptCraft,bgon/BlocklyCraft,bgon/BlocklyCraft,kamem/ScriptCraft,ut7/ScriptCraft,dighjd12/ScriptCraft,itrion/ScriptCraft,carlrobert/ScriptCraft,vorburger/ScriptCraft,ut7/ScriptCraft,bgon/BlocklyCraft,carlrobert/ScriptCraft,TonyGravagno/ScriptCraft,achang6/ScriptCraft,vorburger/ScriptCraft,achang6/ScriptCraft,kzap/ScriptCraft,walterhiggins/ScriptCraft,mverwijs/ScriptCraft
var utils = require('utils'), blocks = require('blocks'), Location = org.bukkit.Location, Player = org.bukkit.entity.Player, Sign = org.bukkit.block.Sign, TreeType = org.bukkit.TreeType; /********************************************************************* ## Drone Plugin The Drone is a convenience class for building. It can be used for... 1. Building 2. Copying and Pasting It uses a fluent interface which means all of the Drone's methods return `this` and can be chained together like so... var theDrone = new Drone(); theDrone.up().left().box(blocks.oak).down().fwd(3).cylinder0(blocks.lava,8); ### TLDNR; (Just read this if you're impatient) At the in-game command prompt type... /js box( blocks.oak ) ... creates a single wooden block at the cross-hairs or player location /js box( blocks.oak ).right(2).box( blocks.wool.black, 4, 9, 1) ... creates a single wooden block and a 2001 black obelisk that is 4 wide x 9 tall x 1 long in size. If you want to see what else ScriptCraft's Drone can do, read on... ### Constructing a Drone Object Drones can be created in any of the following ways... 1. Calling any one of the methods listed below will return a Drone object. For example... var d = box( blocks.oak ) ... creates a 1x1x1 wooden block at the cross-hairs or player's location and returns a Drone object. This might look odd (if you're familiar with Java's Object-dot-method syntax) but all of the Drone class's methods are also global functions that return new Drone objects. This is short-hand for creating drones and is useful for playing around with Drones at the in-game command prompt. It's shorter than typing ... var d = new Drone().box( blocks.oak ) ... All of the Drone's methods return `this` so you can chain operations together like this... var d = box( blocks.oak ) .up() .box( blocks.oak ,3,1,3) .down() .fwd(2) .box( blocks.oak ) .turn() .fwd(2) .box( blocks.oak ) .turn() .fwd(2) .box( blocks.oak ); 2. Using the following form... d = new Drone() ...will create a new Drone. If the cross-hairs are pointing at a block at the time then, that block's location becomes the drone's starting point. If the cross-hairs are _not_ pointing at a block, then the drone's starting location will be 2 blocks directly in front of the player. TIP: Building always happens right and front of the drone's position... Plan View: ^ | | D----> For convenience you can use a _corner stone_ to begin building. The corner stone should be located just above ground level. If the cross-hair is point at or into ground level when you create a new Drone(), then building begins at that point. You can get around this by pointing at a 'corner stone' just above ground level or alternatively use the following statement... d = new Drone().up(); ... which will move the drone up one block as soon as it's created. ![corner stone](img/cornerstone1.png) 3. Or by using the following form... d = new Drone(x,y,z,direction,world); This will create a new Drone at the location you specified using x, y, z In minecraft, the X axis runs west to east and the Z axis runs north to south. The direction parameter says what direction you want the drone to face: 0 = east, 1 = south, 2 = west, 3 = north. If the direction parameter is omitted, the player's direction is used instead. Both the `direction` and `world` parameters are optional. 4. Create a new Drone based on a Bukkit Location object... d = new Drone(location); This is useful when you want to create a drone at a given `org.bukkit.Location` . The `Location` class is used throughout the bukkit API. For example, if you want to create a drone when a block is broken at the block's location you would do so like this... events.on('block.BlockBreakEvent',function( listener,event) { var location = event.block.location; var drone = new Drone(location); // do more stuff with the drone here... }); #### Parameters * location (optional) : *NB* If an `org.bukkit.Location` object is provided as a parameter, then it should be the only parameter. * x (optional) : The x coordinate of the Drone * y (optional) : The y coordinate of the Drone * z (optional) : The z coordinate of the Drone * direction (optional) : The direction in which the Drone is facing. Possible values are 0 (east), 1 (south), 2 (west) or 3 (north) * world (optional) : The world in which the drone is created. ### Drone.box() method the box() method is a convenience method for building things. (For the more performance-oriented method - see cuboid) #### parameters * b - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * w (optional - default 1) - the width of the structure * h (optional - default 1) - the height of the structure * d (optional - default 1) - the depth of the structure - NB this is not how deep underground the structure lies - this is how far away (depth of field) from the drone the structure will extend. #### Example To create a black structure 4 blocks wide, 9 blocks tall and 1 block long... box(blocks.wool.black, 4, 9, 1); ... or the following code does the same but creates a variable that can be used for further methods... var drone = new Drone(); drone.box(blocks.wool.black, 4, 9, 1); ![box example 1](img/boxex1.png) ### Drone.box0() method Another convenience method - this one creates 4 walls with no floor or ceiling. #### Parameters * block - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * width (optional - default 1) - the width of the structure * height (optional - default 1) - the height of the structure * length (optional - default 1) - the length of the structure - how far away (depth of field) from the drone the structure will extend. #### Example To create a stone building with the insided hollowed out 7 wide by 3 tall by 6 long... box0( blocks.stone, 7, 3, 6); ![example box0](img/box0ex1.png) ### Drone.boxa() method Construct a cuboid using an array of blocks. As the drone moves first along the width axis, then the height (y axis) then the length, each block is picked from the array and placed. #### Parameters * blocks - An array of blocks - each block in the array will be placed in turn. * width * height * length #### Example Construct a rainbow-colored road 100 blocks long... var rainbowColors = [blocks.wool.red, blocks.wool.orange, blocks.wool.yellow, blocks.wool.lime, blocks.wool.lightblue, blocks.wool.blue, blocks.wool.purple]; boxa(rainbowColors,7,1,30); ![boxa example](img/boxaex1.png) ### Drone Movement Drones can move freely in minecraft's 3-D world. You control the Drone's movement using any of the following methods.. * up() * down() * left() * right() * fwd() * back() * turn() ... Each of these methods takes a single optional parameter `numBlocks` - the number of blocks to move in the given direction. If no parameter is given, the default is 1. to change direction use the `turn()` method which also takes a single optional parameter (numTurns) - the number of 90 degree turns to make. Turns are always clock-wise. If the drone is facing north, then drone.turn() will make the turn face east. If the drone is facing east then drone.turn(2) will make the drone turn twice so that it is facing west. ### Drone Positional Info * getLocation() - Returns a Bukkit Location object for the drone ### Drone Markers Markers are useful when your Drone has to do a lot of work. You can set a check-point and return to the check-point using the move() method. If your drone is about to undertake a lot of work - e.g. building a road, skyscraper or forest you should set a check-point before doing so if you want your drone to return to its current location. A 'start' checkpoint is automatically created when the Drone is first created. Markers are created and returned to using the followng two methods... * chkpt - Saves the drone's current location so it can be returned to later. * move - moves the drone to a saved location. Alternatively you can provide an org.bukkit.Location object or x,y,z and direction parameters. #### Parameters * name - the name of the checkpoint to save or return to. #### Example drone.chkpt('town-square'); // // the drone can now go off on a long excursion // for ( i = 0; i< 100; i++) { drone.fwd(12).box(6); } // // return to the point before the excursion // drone.move('town-square'); ### Drone.prism() method Creates a prism. This is useful for roofs on houses. #### Parameters * block - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * width - the width of the prism * length - the length of the prism (will be 2 time its height) #### Example prism(blocks.oak,3,12); ![prism example](img/prismex1.png) ### Drone.prism0() method A variation on `prism` which hollows out the inside of the prism. It uses the same parameters as `prism`. ### Drone.cylinder() method A convenience method for building cylinders. Building begins radius blocks to the right and forward. #### Parameters * block - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * radius * height #### Example To create a cylinder of Iron 7 blocks in radius and 1 block high... cylinder(blocks.iron, 7 , 1); ![cylinder example](img/cylinderex1.png) ### Drone.cylinder0() method A version of cylinder that hollows out the middle. #### Example To create a hollow cylinder of Iron 7 blocks in radius and 1 block high... cylinder0(blocks.iron, 7, 1); ![cylinder0 example](img/cylinder0ex1.png) ### Drone.arc() method The arc() method can be used to create 1 or more 90 degree arcs in the horizontal or vertical planes. This method is called by cylinder() and cylinder0() and the sphere() and sphere0() methods. #### Parameters arc() takes a single parameter - an object with the following named properties... * radius - The radius of the arc. * blockType - The type of block to use - this is the block Id only (no meta). See [Data Values][dv]. * meta - The metadata value. See [Data Values][dv]. * orientation (default: 'horizontal' ) - the orientation of the arc - can be 'vertical' or 'horizontal'. * stack (default: 1 ) - the height or length of the arc (depending on the orientation - if orientation is horizontal then this parameter refers to the height, if vertical then it refers to the length ). * strokeWidth (default: 1 ) - the width of the stroke (how many blocks) - if drawing nested arcs it's usually a good idea to set strokeWidth to at least 2 so that there are no gaps between each arc. The arc method uses a [bresenham algorithm][bres] to plot points along the circumference. * fill - If true (or present) then the arc will be filled in. * quadrants (default: `{topleft:true,topright:true,bottomleft:true,bottomright:true}` - An object with 4 properties indicating which of the 4 quadrants of a circle to draw. If the quadrants property is absent then all 4 quadrants are drawn. #### Examples To draw a 1/4 circle (top right quadrant only) with a radius of 10 and stroke width of 2 blocks ... arc({blockType: blocks.iron, meta: 0, radius: 10, strokeWidth: 2, quadrants: { topright: true }, orientation: 'vertical', stack: 1, fill: false } ); ![arc example 1](img/arcex1.png) [bres]: http://en.wikipedia.org/wiki/Midpoint_circle_algorithm [dv]: http://www.minecraftwiki.net/wiki/Data_values ### Drone.door() method create a door - if a parameter is supplied an Iron door is created otherwise a wooden door is created. #### Parameters * doorType (optional - default wood) - If a parameter is provided then the door is Iron. #### Example To create a wooden door at the crosshairs/drone's location... var drone = new Drone(); drone.door(); To create an iron door... drone.door( blocks.door_iron ); ![iron door](img/doorex1.png) ### Drone.door2() method Create double doors (left and right side) #### Parameters * doorType (optional - default wood) - If a parameter is provided then the door is Iron. #### Example To create double-doors at the cross-hairs/drone's location... drone.door2(); ![double doors](img/door2ex1.png) ### Drone.sign() method Signs must use block 63 (stand-alone signs) or 68 (signs on walls) #### Parameters * message - can be a string or an array of strings. * block - can be 63 or 68 #### Example To create a free-standing sign... drone.sign(["Hello","World"],63); ![ground sign](img/signex1.png) ... to create a wall mounted sign... drone.sign(["Welcome","to","Scriptopia"], 68 ); ![wall sign](img/signex2.png) ### Drone Trees methods * oak() * spruce() * birch() * jungle() #### Example To create 4 trees in a row, point the cross-hairs at the ground then type `/js ` and ... up( ).oak( ).right(8 ).spruce( ).right(8 ).birch( ).right(8 ).jungle( ); Trees won't always generate unless the conditions are right. You should use the tree methods when the drone is directly above the ground. Trees will usually grow if the drone's current location is occupied by Air and is directly above an area of grass (That is why the `up( )` method is called first). ![tree example](img/treeex1.png) None of the tree methods require parameters. Tree methods will only be successful if the tree is placed on grass in a setting where trees can grow. ### Drone.garden() method places random flowers and long grass (similar to the effect of placing bonemeal on grass) #### Parameters * width - the width of the garden * length - how far from the drone the garden extends #### Example To create a garden 10 blocks wide by 5 blocks long... garden(10,5); ![garden example](img/gardenex1.png) ### Drone.rand() method rand takes either an array (if each blockid has the same chance of occurring) or an object where each property is a blockid and the value is it's weight (an integer) #### Example place random blocks stone, mossy stone and cracked stone (each block has the same chance of being picked) rand( [blocks.brick.stone, blocks.brick.mossy, blocks.brick.cracked ],w,d,h) to place random blocks stone has a 50% chance of being picked, rand({blocks.brick.stone: 5, blocks.brick.mossy: 3, blocks.brick.cracked: 2},w,d,h) regular stone has a 50% chance, mossy stone has a 30% chance and cracked stone has just a 20% chance of being picked. ### Copy & Paste using Drone A drone can be used to copy and paste areas of the game world. ### Drone.copy() method Copies an area so it can be pasted elsewhere. The name can be used for pasting the copied area elsewhere... #### Parameters * name - the name to be given to the copied area (used by `paste`) * width - the width of the area to copy * height - the height of the area to copy * length - the length of the area (extending away from the drone) to copy #### Example drone.copy('somethingCool',10,5,10 ).right(12 ).paste('somethingCool' ); ### Drone.paste() method Pastes a copied area to the current location. #### Example To copy a 10x5x10 area (using the drone's coordinates as the starting point) into memory. the copied area can be referenced using the name 'somethingCool'. The drone moves 12 blocks right then pastes the copy. drone.copy('somethingCool',10,5,10 ) .right(12 ) .paste('somethingCool' ); ### Chaining All of the Drone methods return a Drone object, which means methods can be 'chained' together so instead of writing this... drone = new Drone(); drone.fwd(3); drone.left(2); drone.box(2); // create a grass block drone.up(); drone.box(2); // create another grass block drone.down(); ...you could simply write ... var drone = new Drone().fwd(3).left(2).box(2).up().box(2).down(); ... since each Drone method is also a global function that constructs a drone if none is supplied, you can shorten even further to just... fwd(3).left(2).box(2).up().box(2).down() The Drone object uses a [Fluent Interface][fl] to make ScriptCraft scripts more concise and easier to write and read. Minecraft's in-game command prompt is limited to about 80 characters so chaining drone commands together means more can be done before hitting the command prompt limit. For complex building you should save your commands in a new script file and load it using /js load() [fl]: http://en.wikipedia.org/wiki/Fluent_interface ### Drone Properties * x - The Drone's position along the west-east axis (x increases as you move east) * y - The Drone's position along the vertical axis (y increses as you move up) * z - The Drone's position along the north-south axis (z increases as you move south) * dir - The Drone's direction 0 is east, 1 is south , 2 is west and 3 is north. ### Extending Drone The Drone object can be easily extended - new buidling recipes/blue-prints can be added and can become part of a Drone's chain using the *static* method `Drone.extend`. ### Drone.extend() static method Use this method to add new methods (which also become chainable global functions) to the Drone object. #### Parameters * name - The name of the new method e.g. 'pyramid' * function - The method body. #### Example // submitted by [edonaldson][edonaldson] Drone.extend('pyramid', function( block,height) { this.chkpt('pyramid'); for ( var i = height; i > 0; i -= 2) { this.box(block, i, 1, i).up().right().fwd(); } return this.move('pyramid'); }); Once the method is defined (it can be defined in a new pyramid.js file) it can be used like so... var d = new Drone(); d.pyramid(blocks.brick.stone, 12); ... or simply ... pyramid(blocks.brick.stone, 12); [edonaldson]: https://github.com/edonaldson ### Drone Constants #### Drone.PLAYER_STAIRS_FACING An array which can be used when constructing stairs facing in the Drone's direction... var d = new Drone(); d.box(blocks.stairs.oak + ':' + Drone.PLAYER_STAIRS_FACING[d.dir]); ... will construct a single oak stair block facing the drone. #### Drone.PLAYER_SIGN_FACING An array which can be used when placing signs so they face in a given direction. This is used internally by the Drone.sign() method. It should also be used for placing any of the following blocks... * chest * ladder * furnace * dispenser To place a chest facing the Drone ... drone.box( blocks.chest + ':' + Drone.PLAYER_SIGN_FACING[drone.dir]); #### Drone.PLAYER_TORCH_FACING Used when placing torches so that they face towards the drone. drone.box( blocks.torch + ':' + Drone.PLAYER_TORCH_FACING[drone.dir]); ***/ // // Implementation // ============== // // There is no need to read any further unless you want to understand how the Drone object works. // var putBlock = function( x, y, z, blockId, metadata, world ) { if ( typeof metadata == 'undefined' ) { metadata = 0; } var block = world.getBlockAt( x, y, z ); if ( block.typeId != blockId || block.data != metadata ) { block.setTypeIdAndData( blockId, metadata, false ); } }; var putSign = function( texts, x, y, z, blockId, meta, world ) { var i, block, state; if ( blockId != 63 && blockId != 68 ) { throw new Error( 'Invalid Parameter: blockId must be 63 or 68' ); } putBlock( x, y, z, blockId, meta, world ); block = world.getBlockAt( x, y, z ); state = block.state; if ( state instanceof Sign ) { for ( i = 0; i < texts.length; i++ ) { state.setLine( i % 4, texts[ i ] ); } state.update( true ); } }; var Drone = function( x, y, z, dir, world ) { this.record = false; var usePlayerCoords = false; var player = self; if ( x instanceof Player ) { player = x; } var playerPos = utils.getPlayerPos( player ); var that = this; var populateFromLocation = function( loc ) { that.x = loc.x; that.y = loc.y; that.z = loc.z; that.dir = _getDirFromRotation(loc.yaw); that.world = loc.world; }; var mp = utils.getMousePos( player ); if ( typeof x == 'undefined' || x instanceof Player ) { if ( mp ) { populateFromLocation( mp ); if ( playerPos ) { this.dir = _getDirFromRotation(playerPos.yaw); } } else { // base it on the player's current location usePlayerCoords = true; // // it's possible that drone.js could be loaded by a non-playing op // (from the server console) // if ( !playerPos ) { return null; } populateFromLocation( playerPos ); } } else { if ( arguments[0] instanceof Location ) { populateFromLocation( arguments[ 0 ] ); } else { this.x = x; this.y = y; this.z = z; if ( typeof dir == 'undefined' ) { this.dir = _getDirFromRotation( playerPos.yaw ); } else { this.dir = dir%4; } if ( typeof world == 'undefined' ) { this.world = playerPos.world; } else { this.world = world; } } } if ( usePlayerCoords ) { this.fwd( 3 ); } this.chkpt( 'start' ); this.record = true; this.history = []; return this; }; exports.Drone = Drone; /* because this is a plugin, any of its exports will be exported globally. Since 'blocks' is a module not a plugin it is convenient to export it via the Drone module. */ exports.blocks = blocks; Drone.queue = []; Drone.processingQueue = false; Drone.MAX_QUEUE_SIZE = 100000; Drone.tick = setInterval( function() { if ( Drone.processingQueue ) { return; } var maxOpsPerTick = Math.floor(Math.max(10,Math.sqrt(Drone.queue.length))) ; var op; Drone.processingQueue = true; while ( maxOpsPerTick > 0 ) { op = Drone.queue.shift(); if (!op){ Drone.processingQueue = false; return; } var block = op.world.getBlockAt( op.x, op.y, op.z ); block.setTypeIdAndData( op.typeid, op.meta, false ); // wph 20130210 - dont' know if this is a bug in bukkit but for chests, // the metadata is ignored (defaults to 2 - south facing) // only way to change data is to set it using property/bean. block.data = op.meta; maxOpsPerTick--; } Drone.processingQueue = false; return; }, 1); // // add custom methods to the Drone object using this function // Drone.extend = function( name, func ) { Drone.prototype[ '_' + name ] = func; Drone.prototype[ name ] = function( ) { if ( this.record ) { this.history.push( [ name, arguments ] ); } var oldVal = this.record; this.record = false; this[ '_' + name ].apply( this, arguments ); this.record = oldVal; return this; }; global[name] = function( ) { var result = new Drone( self ); result[name].apply( result, arguments ); return result; }; }; /************************************************************************** ### Drone.times() Method The times() method makes building multiple copies of buildings easy. It's possible to create rows or grids of buildings without resorting to `for` or `while` loops. #### Parameters * numTimes (optional - default 2) : The number of times you want to repeat the preceding statements. #### Example Say you want to do the same thing over and over. You have a couple of options... * You can use a for loop... d = new Drone(); for ( var i =0;i < 4; i++) { d.cottage().right(8); } While this will fit on the in-game prompt, it's awkward. You need to declare a new Drone object first, then write a for loop to create the 4 cottages. It's also error prone, even the `for` loop is too much syntax for what should really be simple. * You can use a while loop... d = new Drone(); var i=4; while (i--) { d.cottage().right(8); } ... which is slightly shorter but still too much syntax. Each of the above statements is fine for creating a 1-dimensional array of structures. But what if you want to create a 2-dimensional or 3-dimensional array of structures? Enter the `times()` method. The `times()` method lets you repeat commands in a chain any number of times. So to create 4 cottages in a row you would use the following statement... cottage().right(8).times(4); ...which will build a cottage, then move right 8 blocks, then do it again 4 times over so that at the end you will have 4 cottages in a row. What's more the `times()` method can be called more than once in a chain. So if you wanted to create a *grid* of 20 houses ( 4 x 5 ), you would do so using the following statement... cottage().right(8).times(4).fwd(8).left(32).times(5); ... breaking it down... 1. The first 3 calls in the chain ( `cottage()`, `right(8)`, `times(4)` ) build a single row of 4 cottages. 2. The last 3 calls in the chain ( `fwd(8)`, `left(32)`, `times(5)` ) move the drone forward 8 then left 32 blocks (4 x 8) to return to the original x coordinate, then everything in the chain is repeated again 5 times so that in the end, we have a grid of 20 cottages, 4 x 5. Normally this would require a nested loop but the `times()` method does away with the need for loops when repeating builds. Another example: This statement creates a row of trees 2 by 3 ... oak().right(10).times(2).left(20).fwd(10).times(3) ... You can see the results below. ![times example 1](img/times-trees.png) ***/ Drone.prototype.times = function( numTimes, commands ) { if ( typeof numTimes == 'undefined' ) { numTimes = 2; } if ( typeof commands == 'undefined' ) { commands = this.history.concat(); } this.history = [ [ 'times', [ numTimes + 1, commands ] ] ]; var oldVal = this.record; this.record = false; for ( var j = 1; j < numTimes; j++ ) { for ( var i = 0; i < commands.length; i++) { var command = commands[i]; var methodName = command[0]; var args = command[1]; print ('command=' + JSON.stringify(command ) + ',methodName=' + methodName ); this[ methodName ].apply( this, args ); } } this.record = oldVal; return this; }; Drone.prototype._checkpoints = {}; Drone.extend( 'chkpt', function( name ) { this._checkpoints[ name ] = { x:this.x, y:this.y, z:this.z, dir:this.dir }; } ); Drone.extend( 'move', function( ) { if ( arguments[0] instanceof Location ) { this.x = arguments[0].x; this.y = arguments[0].y; this.z = arguments[0].z; this.dir = _getDirFromRotation(arguments[0].yaw ); this.world = arguments[0].world; } else if ( typeof arguments[0] === 'string' ) { var coords = this._checkpoints[arguments[0]]; if ( coords ) { this.x = coords.x; this.y = coords.y; this.z = coords.z; this.dir = coords.dir%4; } } else { // expect x,y,z,dir switch( arguments.length ) { case 4: this.dir = arguments[3]; case 3: this.z = arguments[2]; case 2: this.y = arguments[1]; case 1: this.x = arguments[0]; } } } ); Drone.extend( 'turn', function ( n ) { if ( typeof n == 'undefined' ) { n = 1; } this.dir += n; this.dir %=4; } ); Drone.extend( 'right', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } _movements[ this.dir ].right( this, n ); }); Drone.extend( 'left', function( n ) { if ( typeof n == 'undefined') { n = 1; } _movements[ this.dir ].left( this, n ); }); Drone.extend( 'fwd', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } _movements[ this.dir ].fwd( this, n ); }); Drone.extend( 'back', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } _movements[ this.dir ].back( this, n ); }); Drone.extend( 'up', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } this.y+= n; }); Drone.extend( 'down', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } this.y-= n; }); // // position // Drone.prototype.getLocation = function( ) { return new Location( this.world, this.x, this.y, this.z ); }; // // building // Drone.extend( 'sign', function( message, block ) { if ( message.constructor != Array ) { message = [message]; } var bm = this._getBlockIdAndMeta( block ); block = bm[0]; var meta = bm[1]; if ( block != 63 && block != 68 ) { print('ERROR: Invalid block id for use in signs'); return; } if ( block == 68 ) { meta = Drone.PLAYER_SIGN_FACING[ this.dir % 4 ]; this.back(); } if ( block == 63 ) { meta = ( 12 + ( ( this.dir + 2 ) * 4 ) ) % 16; } putSign( message, this.x, this.y, this.z, block, meta, this.world ); if ( block == 68 ) { this.fwd(); } }); Drone.prototype.cuboida = function(/* Array */ blocks, w, h, d ) { var properBlocks = []; var len = blocks.length; for ( var i = 0; i < len; i++ ) { var bm = this._getBlockIdAndMeta( blocks[ i ] ); properBlocks.push( [ bm[0], bm[1] ] ); } if ( typeof h == 'undefined' ) { h = 1; } if ( typeof d == 'undefined' ) { d = 1; } if ( typeof w == 'undefined' ) { w = 1; } var that = this; var dir = this.dir; var bi = 0; /* */ _traverse[dir].depth( that, d, function( ) { _traverseHeight( that, h, function( ) { _traverse[dir].width( that, w, function( ) { var block = that.world.getBlockAt( that.x, that.y, that.z ); var properBlock = properBlocks[ bi % len ]; block.setTypeIdAndData( properBlock[0], properBlock[1], false ); bi++; }); }); }); return this; }; /* faster cuboid because blockid, meta and world must be provided use this method when you need to repeatedly place blocks */ Drone.prototype.cuboidX = function( blockType, meta, w, h, d ) { if ( typeof h == 'undefined' ) { h = 1; } if ( typeof d == 'undefined' ) { d = 1; } if ( typeof w == 'undefined' ) { w = 1; } var that = this; var dir = this.dir; var depthFunc = function( ) { var len = Drone.queue.length; if ( len < Drone.MAX_QUEUE_SIZE ) { Drone.queue.push({ world: that.world, x: that.x, y: that.y, z:that.z, typeid: blockType, meta: meta }); } else { throw new Error('Drone is too busy!'); } }; var heightFunc = function( ) { _traverse[dir].depth( that, d, depthFunc ); }; var widthFunc = function( ) { _traverseHeight( that, h, heightFunc ); }; _traverse[dir].width( that, w, widthFunc ); return this; }; Drone.prototype.cuboid = function( block, w, h, d ) { var bm = this._getBlockIdAndMeta( block ); return this.cuboidX( bm[0], bm[1], w, h, d ); }; Drone.prototype.cuboid0 = function( block, w, h, d ) { this.chkpt( 'start_point' ); // Front wall this.cuboid( block, w, h, 1 ); // Left wall this.cuboid( block, 1, h, d ); // Right wall this.right( w - 1 ).cuboid( block, 1, h, d ).left( w - 1 ); // Back wall this.fwd( d - 1 ).cuboid( block, w, h, 1 ); return this.move( 'start_point' ); }; Drone.extend( 'door', function( door ) { if ( typeof door == 'undefined' ) { door = 64; } else { door = 71; } this.cuboidX( door, this.dir ) .up( ) .cuboidX( door, 8 ) .down( ); } ); Drone.extend( 'door2' , function( door ) { if ( typeof door == 'undefined' ) { door = 64; } else { door = 71; } this .cuboidX( door, this.dir ).up( ) .cuboidX( door, 8 ).right( ) .cuboidX( door, 9 ).down( ) .cuboidX( door, this.dir ).left( ); } ); // player dirs: 0 = east, 1 = south, 2 = west, 3 = north // block dirs: 0 = east, 1 = west, 2 = south , 3 = north // sign dirs: 5 = east, 3 = south, 4 = west, 2 = north Drone.PLAYER_STAIRS_FACING = [ 0, 2, 1, 3 ]; // for blocks 68 (wall signs) 65 (ladders) 61,62 (furnaces) 23 (dispenser) and 54 (chest) Drone.PLAYER_SIGN_FACING = [ 4, 2, 5, 3 ]; Drone.PLAYER_TORCH_FACING = [ 2, 4, 1, 3 ]; var _STAIRBLOCKS = { 53: '5:0' // oak wood ,67: 4 // cobblestone ,108: 45 // brick ,109: 98 // stone brick ,114: 112 // nether brick ,128: 24 // sandstone ,134: '5:1' // spruce wood ,135: '5:2' // birch wood ,136: '5:3' // jungle wood }; // // prism private implementation // var _prism = function( block, w, d ) { var stairEquiv = _STAIRBLOCKS[block]; if ( stairEquiv ) { this.fwd( ).prism(stairEquiv,w,d-2 ).back( ); var d2 = 0; var middle = Math.floor( d/2 ); var uc = 0,dc = 0; while ( d2 < d ) { var di = (d2 < middle?this.dir:(this.dir+2 )%4 ); var bd = block + ':' + Drone.PLAYER_STAIRS_FACING[di]; var putStep = true; if ( d2 == middle ) { if ( d % 2 == 1 ) { putStep = false; } } if ( putStep ) { this.cuboid(bd,w ); } if ( d2 < middle-1 ) { this.up( ); uc++; } var modulo = d % 2; if ( modulo == 1 ) { if ( d2 > middle && d2<d-1) { this.down( ); dc++; } }else{ if ( d2 >= middle && d2<d-1 ) { this.down( ); dc++; } } this.fwd( ); d2++; } this.back(d ); }else{ var c = 0; var d2 = d; while ( d2 >= 1 ) { this.cuboid(block,w,1,d2 ); d2 -= 2; this.fwd( ).up( ); c++; } this.down(c ).back(c ); } return this; }; // // prism0 private implementation // var _prism0 = function( block,w,d ) { this.prism(block,w,d ) .fwd( ).right( ) .prism(0,w-2,d-2 ) .left( ).back( ); var se = _STAIRBLOCKS[block]; if ( d % 2 == 1 && se ) { // top of roof will be open - need repair var f = Math.floor(d/2 ); this.fwd(f ).up(f ).cuboid(se,w ).down(f ).back(f ); } }; Drone.extend('prism0',_prism0 ); Drone.extend('prism',_prism ); Drone.extend('box',Drone.prototype.cuboid ); Drone.extend('box0',Drone.prototype.cuboid0 ); Drone.extend('boxa',Drone.prototype.cuboida ); // // show the Drone's position and direction // Drone.prototype.toString = function( ) { var dirs = ['east','south','west','north']; return 'x: ' + this.x + ' y: '+this.y + ' z: ' + this.z + ' dir: ' + this.dir + ' '+dirs[this.dir]; }; Drone.prototype.debug = function( ) { print(this.toString( ) ); return this; }; /* do the bresenham thing */ var _bresenham = function( x0,y0,radius, setPixel, quadrants ) { // // credit: Following code is copied almost verbatim from // http://en.wikipedia.org/wiki/Midpoint_circle_algorithm // Bresenham's circle algorithm // var f = 1 - radius; var ddF_x = 1; var ddF_y = -2 * radius; var x = 0; var y = radius; var defaultQuadrants = {topleft: true, topright: true, bottomleft: true, bottomright: true}; quadrants = quadrants?quadrants:defaultQuadrants; /* II | I ------------ III | IV */ if ( quadrants.topleft || quadrants.topright ) setPixel(x0, y0 + radius ); // quadrant I/II topmost if ( quadrants.bottomleft || quadrants.bottomright ) setPixel(x0, y0 - radius ); // quadrant III/IV bottommost if ( quadrants.topright || quadrants.bottomright ) setPixel(x0 + radius, y0 ); // quadrant I/IV rightmost if ( quadrants.topleft || quadrants.bottomleft ) setPixel(x0 - radius, y0 ); // quadrant II/III leftmost while ( x < y ) { if(f >= 0 ) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if ( quadrants.topright ) { setPixel(x0 + x, y0 + y ); // quadrant I setPixel(x0 + y, y0 + x ); // quadrant I } if ( quadrants.topleft ) { setPixel(x0 - x, y0 + y ); // quadrant II setPixel(x0 - y, y0 + x ); // quadrant II } if ( quadrants.bottomleft ) { setPixel(x0 - x, y0 - y ); // quadrant III setPixel(x0 - y, y0 - x ); // quadrant III } if ( quadrants.bottomright ) { setPixel(x0 + x, y0 - y ); // quadrant IV setPixel(x0 + y, y0 - x ); // quadrant IV } } }; var _getStrokeDir = function( x,y ) { var absY = Math.abs(y ); var absX = Math.abs(x ); var strokeDir = 0; if ( y > 0 && absY >= absX ) strokeDir = 0 ; //down else if ( y < 0 && absY >= absX ) strokeDir = 1 ; // up else if ( x > 0 && absX >= absY ) strokeDir = 2 ; // left else if ( x < 0 && absX >= absY ) strokeDir = 3 ; // right return strokeDir; }; /* The daddy of all arc-related API calls - if you're drawing anything that bends it ends up here. */ var _arc2 = function( params ) { var drone = params.drone; var orientation = params.orientation?params.orientation:'horizontal'; var quadrants = params.quadrants?params.quadrants:{ topright:1, topleft:2, bottomleft:3, bottomright:4 }; var stack = params.stack?params.stack:1; var radius = params.radius; var strokeWidth = params.strokeWidth?params.strokeWidth:1; drone.chkpt('arc2' ); var x0, y0, gotoxy,setPixel; if ( orientation == 'horizontal' ) { gotoxy = function( x,y ) { return drone.right(x ).fwd(y );}; drone.right(radius ).fwd(radius ).chkpt('center' ); switch ( drone.dir ) { case 0: // east case 2: // west x0 = drone.z; y0 = drone.x; break; case 1: // south case 3: // north x0 = drone.x; y0 = drone.z; } setPixel = function( x,y ) { x = (x-x0 ); y = (y-y0 ); if ( params.fill ) { // wph 20130114 more efficient esp. for large cylinders/spheres if ( y < 0 ) { drone .fwd(y ).right(x ) .cuboidX(params.blockType,params.meta,1,stack,Math.abs(y*2 )+1 ) .back(y ).left(x ); } }else{ if ( strokeWidth == 1 ) { gotoxy(x,y ) .cuboidX(params.blockType, params.meta, 1, // width stack, // height strokeWidth // depth ) .move('center' ); } else { var strokeDir = _getStrokeDir(x,y ); var width = 1, depth = 1; switch ( strokeDir ) { case 0: // down y = y-(strokeWidth-1 ); depth = strokeWidth; break; case 1: // up depth = strokeWidth; break; case 2: // left width = strokeWidth; x = x-(strokeWidth-1 ); break; case 3: // right width = strokeWidth; break; } gotoxy(x,y ) .cuboidX(params.blockType, params.meta, width, stack, depth ) .move('center' ); } } }; }else{ // vertical gotoxy = function( x,y ) { return drone.right(x ).up(y );}; drone.right(radius ).up(radius ).chkpt('center' ); switch ( drone.dir ) { case 0: // east case 2: // west x0 = drone.z; y0 = drone.y; break; case 1: // south case 3: // north x0 = drone.x; y0 = drone.y; } setPixel = function( x,y ) { x = (x-x0 ); y = (y-y0 ); if ( params.fill ) { // wph 20130114 more efficient esp. for large cylinders/spheres if ( y < 0 ) { drone .up(y ).right(x ) .cuboidX(params.blockType,params.meta,1,Math.abs(y*2 )+1,stack ) .down(y ).left(x ); } }else{ if ( strokeWidth == 1 ) { gotoxy(x,y ) .cuboidX(params.blockType,params.meta,strokeWidth,1,stack ) .move('center' ); }else{ var strokeDir = _getStrokeDir(x,y ); var width = 1, height = 1; switch ( strokeDir ) { case 0: // down y = y-(strokeWidth-1 ); height = strokeWidth; break; case 1: // up height = strokeWidth; break; case 2: // left width = strokeWidth; x = x-(strokeWidth-1 ); break; case 3: // right width = strokeWidth; break; } gotoxy(x,y ) .cuboidX(params.blockType, params.meta, width, height, stack ) .move('center' ); } } }; } /* setPixel assumes a 2D plane - need to put a block along appropriate plane */ _bresenham(x0,y0,radius,setPixel,quadrants ); params.drone.move('arc2' ); }; Drone.extend('arc',function( params ) { params.drone = this; _arc2(params ); } ); var _cylinder0 = function( block,radius,height,exactParams ) { var arcParams = { radius: radius, fill: false, orientation: 'horizontal', stack: height, }; if ( exactParams ) { arcParams.blockType = exactParams.blockType; arcParams.meta = exactParams.meta; }else{ var md = this._getBlockIdAndMeta(block ); arcParams.blockType = md[0]; arcParams.meta = md[1]; } return this.arc(arcParams ); }; var _cylinder1 = function( block,radius,height,exactParams ) { var arcParams = { radius: radius, fill: true, orientation: 'horizontal', stack: height, }; if ( exactParams ) { arcParams.blockType = exactParams.blockType; arcParams.meta = exactParams.meta; }else{ var md = this._getBlockIdAndMeta(block ); arcParams.blockType = md[0]; arcParams.meta = md[1]; } return this.arc(arcParams ); }; var _paste = function( name ) { var ccContent = Drone.clipBoard[name]; var srcBlocks = ccContent.blocks; var srcDir = ccContent.dir; // direction player was facing when copied. var dirOffset = (4 + (this.dir - srcDir ) ) %4; var that = this; _traverse[this.dir].width(that,srcBlocks.length,function( ww ) { var h = srcBlocks[ww].length; _traverseHeight(that,h,function( hh ) { var d = srcBlocks[ww][hh].length; _traverse[that.dir].depth(that,d,function( dd ) { var b = srcBlocks[ww][hh][dd]; var bm = that._getBlockIdAndMeta(b ); var cb = bm[0]; var md = bm[1]; // // need to adjust blocks which face a direction // switch ( cb ) { // // doors // case 64: // wood case 71: // iron // top half of door doesn't need to change if ( md < 8 ) { md = (md + dirOffset ) % 4; } break; // // stairs // case 53: // oak case 67: // cobblestone case 108: // red brick case 109: // stone brick case 114: // nether brick case 128: // sandstone case 134: // spruce case 135: // birch case 136: // junglewood var dir = md & 0x3; var a = Drone.PLAYER_STAIRS_FACING; var len = a.length; for ( var c=0;c < len;c++ ) { if ( a[c] == dir ) { break; } } c = (c + dirOffset ) %4; var newDir = a[c]; md = (md >>2<<2 ) + newDir; break; // // signs , ladders etc // case 23: // dispenser case 54: // chest case 61: // furnace case 62: // burning furnace case 65: // ladder case 68: // wall sign var a = Drone.PLAYER_SIGN_FACING; var len = a.length; for ( var c=0;c < len;c++ ) { if ( a[c] == md ) { break; } } c = (c + dirOffset ) %4; var newDir = a[c]; md = newDir; break; } putBlock(that.x,that.y,that.z,cb,md,that.world ); } ); } ); } ); }; var _getDirFromRotation = function( r ) { // 0 = east, 1 = south, 2 = west, 3 = north // 46 to 135 = west // 136 to 225 = north // 226 to 315 = east // 316 to 45 = south r = (r + 360 ) % 360; // east could be 270 or -90 if ( r > 45 && r <= 135 ) return 2; // west if ( r > 135 && r <= 225 ) return 3; // north if ( r > 225 && r <= 315 ) return 0; // east if ( r > 315 || r < 45 ) return 1; // south }; var _getBlockIdAndMeta = function(b ) { var defaultMeta = 0; if ( typeof b == 'string' ) { var bs = b; var sp = bs.indexOf(':' ); if ( sp == -1 ) { b = parseInt(bs ); // wph 20130414 - use sensible defaults for certain blocks e.g. stairs // should face the drone. for ( var i in blocks.stairs ) { if ( blocks.stairs[i] === b ) { defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; break; } } return [b,defaultMeta]; } b = parseInt(bs.substring(0,sp ) ); var md = parseInt(bs.substring(sp+1,bs.length ) ); return [b,md]; }else{ // wph 20130414 - use sensible defaults for certain blocks e.g. stairs // should face the drone. for ( var i in blocks.stairs ) { if ( blocks.stairs[i] === b ) { defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; break; } } return [b,defaultMeta]; } }; // // movement // var _movements = [{},{},{},{}]; // east _movements[0].right = function( that,n ) { that.z +=n; return that;}; _movements[0].left = function( that,n ) { that.z -=n; return that;}; _movements[0].fwd = function( that,n ) { that.x +=n; return that;}; _movements[0].back = function( that,n ) { that.x -= n; return that;}; // south _movements[1].right = _movements[0].back; _movements[1].left = _movements[0].fwd; _movements[1].fwd = _movements[0].right; _movements[1].back = _movements[0].left; // west _movements[2].right = _movements[0].left; _movements[2].left = _movements[0].right; _movements[2].fwd = _movements[0].back; _movements[2].back = _movements[0].fwd; // north _movements[3].right = _movements[0].fwd; _movements[3].left = _movements[0].back; _movements[3].fwd = _movements[0].left; _movements[3].back = _movements[0].right; var _traverse = [{},{},{},{}]; // east _traverse[0].width = function( that,n,callback ) { var s = that.z, e = s + n; for ( ; that.z < e; that.z++ ) { callback(that.z-s ); } that.z = s; }; _traverse[0].depth = function( that,n,callback ) { var s = that.x, e = s+n; for ( ;that.x < e;that.x++ ) { callback(that.x-s ); } that.x = s; }; // south _traverse[1].width = function( that,n,callback ) { var s = that.x, e = s-n; for ( ;that.x > e;that.x-- ) { callback(s-that.x ); } that.x = s; }; _traverse[1].depth = _traverse[0].width; // west _traverse[2].width = function( that,n,callback ) { var s = that.z, e = s-n; for ( ;that.z > e;that.z-- ) { callback(s-that.z ); } that.z = s; }; _traverse[2].depth = _traverse[1].width; // north _traverse[3].width = _traverse[0].depth; _traverse[3].depth = _traverse[2].width; var _traverseHeight = function( that,n,callback ) { var s = that.y, e = s + n; for ( ; that.y < e; that.y++ ) { callback(that.y-s ); } that.y = s; }; // // standard fisher-yates shuffle algorithm // var _fisherYates = function( myArray ) { var i = myArray.length; if ( i == 0 ) return false; while ( --i ) { var j = Math.floor( Math.random( ) * ( i + 1 ) ); var tempi = myArray[i]; var tempj = myArray[j]; myArray[i] = tempj; myArray[j] = tempi; } }; var _copy = function( name, w, h, d ) { var that = this; var ccContent = []; _traverse[this.dir].width(that,w,function( ww ) { ccContent.push([] ); _traverseHeight(that,h,function( hh ) { ccContent[ww].push([] ); _traverse[that.dir].depth(that,d,function( dd ) { var b = that.world.getBlockAt(that.x,that.y,that.z ); ccContent[ww][hh][dd] = b; } ); } ); } ); Drone.clipBoard[name] = {dir: this.dir, blocks: ccContent}; }; var _garden = function( w,d ) { // make sure grass is present first this.down( ).box(2,w,1,d ).up( ); // make flowers more common than long grass var dist = {37: 3, // red flower 38: 3, // yellow flower '31:1': 2, // long grass 0: 1 }; return this.rand(dist,w,1,d ); }; var _rand = function( blockDistribution ) { if ( !(blockDistribution.constructor == Array ) ) { var a = []; for ( var p in blockDistribution ) { var n = blockDistribution[p]; for ( var i = 0;i < n;i++ ) { a.push(p ); } } blockDistribution = a; } while ( blockDistribution.length < 1000 ) { // make array bigger so that it's more random blockDistribution = blockDistribution.concat(blockDistribution ); } _fisherYates(blockDistribution ); return blockDistribution; }; Drone.extend('rand',function( dist,w,h,d ) { var randomized = _rand(dist ); this.boxa(randomized,w,h,d ); } ); var _trees = { oak: TreeType.BIG_TREE , birch: TreeType.BIRCH , jungle: TreeType.JUNGLE, spruce: TreeType.REDWOOD }; for ( var p in _trees ) { Drone.extend(p, function( v ) { return function( ) { var block = this.world.getBlockAt(this.x,this.y,this.z ); if ( block.typeId == 2 ) { this.up( ); } var treeLoc = new Location(this.world,this.x,this.y,this.z ); var successful = treeLoc.world.generateTree(treeLoc,v ); if ( block.typeId == 2 ) { this.down( ); } }; }(_trees[p] ) ); } // // Drone's clipboard // Drone.clipBoard = {}; Drone.extend('garden',_garden ); Drone.extend('copy', _copy ); Drone.extend('paste',_paste ); Drone.extend('cylinder0',_cylinder0 ); Drone.extend('cylinder', _cylinder1 ); // // wph 20130130 - make this a method - extensions can use it. // Drone.prototype._getBlockIdAndMeta = _getBlockIdAndMeta;
src/main/js/plugins/drone/drone.js
var utils = require('utils'), blocks = require('blocks'), Location = org.bukkit.Location, Player = org.bukkit.entity.Player, Sign = org.bukkit.block.Sign, TreeType = org.bukkit.TreeType; /********************************************************************* ## Drone Plugin The Drone is a convenience class for building. It can be used for... 1. Building 2. Copying and Pasting It uses a fluent interface which means all of the Drone's methods return `this` and can be chained together like so... var theDrone = new Drone(); theDrone.up().left().box(blocks.oak).down().fwd(3).cylinder0(blocks.lava,8); ### TLDNR; (Just read this if you're impatient) At the in-game command prompt type... /js box( blocks.oak ) ... creates a single wooden block at the cross-hairs or player location /js box( blocks.oak ).right(2).box( blocks.wool.black, 4, 9, 1) ... creates a single wooden block and a 2001 black obelisk that is 4 wide x 9 tall x 1 long in size. If you want to see what else ScriptCraft's Drone can do, read on... ### Constructing a Drone Object Drones can be created in any of the following ways... 1. Calling any one of the methods listed below will return a Drone object. For example... var d = box( blocks.oak ) ... creates a 1x1x1 wooden block at the cross-hairs or player's location and returns a Drone object. This might look odd (if you're familiar with Java's Object-dot-method syntax) but all of the Drone class's methods are also global functions that return new Drone objects. This is short-hand for creating drones and is useful for playing around with Drones at the in-game command prompt. It's shorter than typing ... var d = new Drone().box( blocks.oak ) ... All of the Drone's methods return `this` so you can chain operations together like this... var d = box( blocks.oak ) .up() .box( blocks.oak ,3,1,3) .down() .fwd(2) .box( blocks.oak ) .turn() .fwd(2) .box( blocks.oak ) .turn() .fwd(2) .box( blocks.oak ); 2. Using the following form... d = new Drone() ...will create a new Drone. If the cross-hairs are pointing at a block at the time then, that block's location becomes the drone's starting point. If the cross-hairs are _not_ pointing at a block, then the drone's starting location will be 2 blocks directly in front of the player. TIP: Building always happens right and front of the drone's position... Plan View: ^ | | D----> For convenience you can use a _corner stone_ to begin building. The corner stone should be located just above ground level. If the cross-hair is point at or into ground level when you create a new Drone(), then building begins at that point. You can get around this by pointing at a 'corner stone' just above ground level or alternatively use the following statement... d = new Drone().up(); ... which will move the drone up one block as soon as it's created. ![corner stone](img/cornerstone1.png) 3. Or by using the following form... d = new Drone(x,y,z,direction,world); This will create a new Drone at the location you specified using x, y, z In minecraft, the X axis runs west to east and the Z axis runs north to south. The direction parameter says what direction you want the drone to face: 0 = east, 1 = south, 2 = west, 3 = north. If the direction parameter is omitted, the player's direction is used instead. Both the `direction` and `world` parameters are optional. 4. Create a new Drone based on a Bukkit Location object... d = new Drone(location); This is useful when you want to create a drone at a given `org.bukkit.Location` . The `Location` class is used throughout the bukkit API. For example, if you want to create a drone when a block is broken at the block's location you would do so like this... events.on('block.BlockBreakEvent',function( listener,event) { var location = event.block.location; var drone = new Drone(location); // do more stuff with the drone here... }); #### Parameters * location (optional) : *NB* If an `org.bukkit.Location` object is provided as a parameter, then it should be the only parameter. * x (optional) : The x coordinate of the Drone * y (optional) : The y coordinate of the Drone * z (optional) : The z coordinate of the Drone * direction (optional) : The direction in which the Drone is facing. Possible values are 0 (east), 1 (south), 2 (west) or 3 (north) * world (optional) : The world in which the drone is created. ### Drone.box() method the box() method is a convenience method for building things. (For the more performance-oriented method - see cuboid) #### parameters * b - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * w (optional - default 1) - the width of the structure * h (optional - default 1) - the height of the structure * d (optional - default 1) - the depth of the structure - NB this is not how deep underground the structure lies - this is how far away (depth of field) from the drone the structure will extend. #### Example To create a black structure 4 blocks wide, 9 blocks tall and 1 block long... box(blocks.wool.black, 4, 9, 1); ... or the following code does the same but creates a variable that can be used for further methods... var drone = new Drone(); drone.box(blocks.wool.black, 4, 9, 1); ![box example 1](img/boxex1.png) ### Drone.box0() method Another convenience method - this one creates 4 walls with no floor or ceiling. #### Parameters * block - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * width (optional - default 1) - the width of the structure * height (optional - default 1) - the height of the structure * length (optional - default 1) - the length of the structure - how far away (depth of field) from the drone the structure will extend. #### Example To create a stone building with the insided hollowed out 7 wide by 3 tall by 6 long... box0( blocks.stone, 7, 3, 6); ![example box0](img/box0ex1.png) ### Drone.boxa() method Construct a cuboid using an array of blocks. As the drone moves first along the width axis, then the height (y axis) then the length, each block is picked from the array and placed. #### Parameters * blocks - An array of blocks - each block in the array will be placed in turn. * width * height * length #### Example Construct a rainbow-colored road 100 blocks long... var rainbowColors = [blocks.wool.red, blocks.wool.orange, blocks.wool.yellow, blocks.wool.lime, blocks.wool.lightblue, blocks.wool.blue, blocks.wool.purple]; boxa(rainbowColors,7,1,30); ![boxa example](img/boxaex1.png) ### Drone Movement Drones can move freely in minecraft's 3-D world. You control the Drone's movement using any of the following methods.. * up() * down() * left() * right() * fwd() * back() * turn() ... Each of these methods takes a single optional parameter `numBlocks` - the number of blocks to move in the given direction. If no parameter is given, the default is 1. to change direction use the `turn()` method which also takes a single optional parameter (numTurns) - the number of 90 degree turns to make. Turns are always clock-wise. If the drone is facing north, then drone.turn() will make the turn face east. If the drone is facing east then drone.turn(2) will make the drone turn twice so that it is facing west. ### Drone Positional Info * getLocation() - Returns a Bukkit Location object for the drone ### Drone Markers Markers are useful when your Drone has to do a lot of work. You can set a check-point and return to the check-point using the move() method. If your drone is about to undertake a lot of work - e.g. building a road, skyscraper or forest you should set a check-point before doing so if you want your drone to return to its current location. A 'start' checkpoint is automatically created when the Drone is first created. Markers are created and returned to using the followng two methods... * chkpt - Saves the drone's current location so it can be returned to later. * move - moves the drone to a saved location. Alternatively you can provide an org.bukkit.Location object or x,y,z and direction parameters. #### Parameters * name - the name of the checkpoint to save or return to. #### Example drone.chkpt('town-square'); // // the drone can now go off on a long excursion // for ( i = 0; i< 100; i++) { drone.fwd(12).box(6); } // // return to the point before the excursion // drone.move('town-square'); ### Drone.prism() method Creates a prism. This is useful for roofs on houses. #### Parameters * block - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * width - the width of the prism * length - the length of the prism (will be 2 time its height) #### Example prism(blocks.oak,3,12); ![prism example](img/prismex1.png) ### Drone.prism0() method A variation on `prism` which hollows out the inside of the prism. It uses the same parameters as `prism`. ### Drone.cylinder() method A convenience method for building cylinders. Building begins radius blocks to the right and forward. #### Parameters * block - the block id - e.g. 6 for an oak sapling or '6:2' for a birch sapling. Alternatively you can use any one of the `blocks` values e.g. `blocks.sapling.birch` * radius * height #### Example To create a cylinder of Iron 7 blocks in radius and 1 block high... cylinder(blocks.iron, 7 , 1); ![cylinder example](img/cylinderex1.png) ### Drone.cylinder0() method A version of cylinder that hollows out the middle. #### Example To create a hollow cylinder of Iron 7 blocks in radius and 1 block high... cylinder0(blocks.iron, 7, 1); ![cylinder0 example](img/cylinder0ex1.png) ### Drone.arc() method The arc() method can be used to create 1 or more 90 degree arcs in the horizontal or vertical planes. This method is called by cylinder() and cylinder0() and the sphere() and sphere0() methods. #### Parameters arc() takes a single parameter - an object with the following named properties... * radius - The radius of the arc. * blockType - The type of block to use - this is the block Id only (no meta). See [Data Values][dv]. * meta - The metadata value. See [Data Values][dv]. * orientation (default: 'horizontal' ) - the orientation of the arc - can be 'vertical' or 'horizontal'. * stack (default: 1 ) - the height or length of the arc (depending on the orientation - if orientation is horizontal then this parameter refers to the height, if vertical then it refers to the length ). * strokeWidth (default: 1 ) - the width of the stroke (how many blocks) - if drawing nested arcs it's usually a good idea to set strokeWidth to at least 2 so that there are no gaps between each arc. The arc method uses a [bresenham algorithm][bres] to plot points along the circumference. * fill - If true (or present) then the arc will be filled in. * quadrants (default: `{topleft:true,topright:true,bottomleft:true,bottomright:true}` - An object with 4 properties indicating which of the 4 quadrants of a circle to draw. If the quadrants property is absent then all 4 quadrants are drawn. #### Examples To draw a 1/4 circle (top right quadrant only) with a radius of 10 and stroke width of 2 blocks ... arc({blockType: blocks.iron, meta: 0, radius: 10, strokeWidth: 2, quadrants: { topright: true }, orientation: 'vertical', stack: 1, fill: false } ); ![arc example 1](img/arcex1.png) [bres]: http://en.wikipedia.org/wiki/Midpoint_circle_algorithm [dv]: http://www.minecraftwiki.net/wiki/Data_values ### Drone.door() method create a door - if a parameter is supplied an Iron door is created otherwise a wooden door is created. #### Parameters * doorType (optional - default wood) - If a parameter is provided then the door is Iron. #### Example To create a wooden door at the crosshairs/drone's location... var drone = new Drone(); drone.door(); To create an iron door... drone.door( blocks.door_iron ); ![iron door](img/doorex1.png) ### Drone.door2() method Create double doors (left and right side) #### Parameters * doorType (optional - default wood) - If a parameter is provided then the door is Iron. #### Example To create double-doors at the cross-hairs/drone's location... drone.door2(); ![double doors](img/door2ex1.png) ### Drone.sign() method Signs must use block 63 (stand-alone signs) or 68 (signs on walls) #### Parameters * message - can be a string or an array of strings. * block - can be 63 or 68 #### Example To create a free-standing sign... drone.sign(["Hello","World"],63); ![ground sign](img/signex1.png) ... to create a wall mounted sign... drone.sign(["Welcome","to","Scriptopia"], 68 ); ![wall sign](img/signex2.png) ### Drone Trees methods * oak() * spruce() * birch() * jungle() #### Example To create 4 trees in a row, point the cross-hairs at the ground then type `/js ` and ... up( ).oak( ).right(8 ).spruce( ).right(8 ).birch( ).right(8 ).jungle( ); Trees won't always generate unless the conditions are right. You should use the tree methods when the drone is directly above the ground. Trees will usually grow if the drone's current location is occupied by Air and is directly above an area of grass (That is why the `up( )` method is called first). ![tree example](img/treeex1.png) None of the tree methods require parameters. Tree methods will only be successful if the tree is placed on grass in a setting where trees can grow. ### Drone.garden() method places random flowers and long grass (similar to the effect of placing bonemeal on grass) #### Parameters * width - the width of the garden * length - how far from the drone the garden extends #### Example To create a garden 10 blocks wide by 5 blocks long... garden(10,5); ![garden example](img/gardenex1.png) ### Drone.rand() method rand takes either an array (if each blockid has the same chance of occurring) or an object where each property is a blockid and the value is it's weight (an integer) #### Example place random blocks stone, mossy stone and cracked stone (each block has the same chance of being picked) rand( [blocks.brick.stone, blocks.brick.mossy, blocks.brick.cracked ],w,d,h) to place random blocks stone has a 50% chance of being picked, rand({blocks.brick.stone: 5, blocks.brick.mossy: 3, blocks.brick.cracked: 2},w,d,h) regular stone has a 50% chance, mossy stone has a 30% chance and cracked stone has just a 20% chance of being picked. ### Copy & Paste using Drone A drone can be used to copy and paste areas of the game world. ### Drone.copy() method Copies an area so it can be pasted elsewhere. The name can be used for pasting the copied area elsewhere... #### Parameters * name - the name to be given to the copied area (used by `paste`) * width - the width of the area to copy * height - the height of the area to copy * length - the length of the area (extending away from the drone) to copy #### Example drone.copy('somethingCool',10,5,10 ).right(12 ).paste('somethingCool' ); ### Drone.paste() method Pastes a copied area to the current location. #### Example To copy a 10x5x10 area (using the drone's coordinates as the starting point) into memory. the copied area can be referenced using the name 'somethingCool'. The drone moves 12 blocks right then pastes the copy. drone.copy('somethingCool',10,5,10 ) .right(12 ) .paste('somethingCool' ); ### Chaining All of the Drone methods return a Drone object, which means methods can be 'chained' together so instead of writing this... drone = new Drone(); drone.fwd(3); drone.left(2); drone.box(2); // create a grass block drone.up(); drone.box(2); // create another grass block drone.down(); ...you could simply write ... var drone = new Drone().fwd(3).left(2).box(2).up().box(2).down(); ... since each Drone method is also a global function that constructs a drone if none is supplied, you can shorten even further to just... fwd(3).left(2).box(2).up().box(2).down() The Drone object uses a [Fluent Interface][fl] to make ScriptCraft scripts more concise and easier to write and read. Minecraft's in-game command prompt is limited to about 80 characters so chaining drone commands together means more can be done before hitting the command prompt limit. For complex building you should save your commands in a new script file and load it using /js load() [fl]: http://en.wikipedia.org/wiki/Fluent_interface ### Drone Properties * x - The Drone's position along the west-east axis (x increases as you move east) * y - The Drone's position along the vertical axis (y increses as you move up) * z - The Drone's position along the north-south axis (z increases as you move south) * dir - The Drone's direction 0 is east, 1 is south , 2 is west and 3 is north. ### Extending Drone The Drone object can be easily extended - new buidling recipes/blue-prints can be added and can become part of a Drone's chain using the *static* method `Drone.extend`. ### Drone.extend() static method Use this method to add new methods (which also become chainable global functions) to the Drone object. #### Parameters * name - The name of the new method e.g. 'pyramid' * function - The method body. #### Example // submitted by [edonaldson][edonaldson] Drone.extend('pyramid', function( block,height) { this.chkpt('pyramid'); for ( var i = height; i > 0; i -= 2) { this.box(block, i, 1, i).up().right().fwd(); } return this.move('pyramid'); }); Once the method is defined (it can be defined in a new pyramid.js file) it can be used like so... var d = new Drone(); d.pyramid(blocks.brick.stone, 12); ... or simply ... pyramid(blocks.brick.stone, 12); [edonaldson]: https://github.com/edonaldson ### Drone Constants #### Drone.PLAYER_STAIRS_FACING An array which can be used when constructing stairs facing in the Drone's direction... var d = new Drone(); d.box(blocks.stairs.oak + ':' + Drone.PLAYER_STAIRS_FACING[d.dir]); ... will construct a single oak stair block facing the drone. #### Drone.PLAYER_SIGN_FACING An array which can be used when placing signs so they face in a given direction. This is used internally by the Drone.sign() method. It should also be used for placing any of the following blocks... * chest * ladder * furnace * dispenser To place a chest facing the Drone ... drone.box( blocks.chest + ':' + Drone.PLAYER_SIGN_FACING[drone.dir]); #### Drone.PLAYER_TORCH_FACING Used when placing torches so that they face towards the drone. drone.box( blocks.torch + ':' + Drone.PLAYER_TORCH_FACING[drone.dir]); ***/ // // Implementation // ============== // // There is no need to read any further unless you want to understand how the Drone object works. // var putBlock = function( x, y, z, blockId, metadata, world ) { if ( typeof metadata == 'undefined' ) { metadata = 0; } var block = world.getBlockAt( x, y, z ); if ( block.typeId != blockId || block.data != metadata ) { block.setTypeIdAndData( blockId, metadata, false ); } }; var putSign = function( texts, x, y, z, blockId, meta, world ) { var i, block, state; if ( blockId != 63 && blockId != 68 ) { throw new Error( 'Invalid Parameter: blockId must be 63 or 68' ); } putBlock( x, y, z, blockId, meta, world ); block = world.getBlockAt( x, y, z ); state = block.state; if ( state instanceof Sign ) { for ( i = 0; i < texts.length; i++ ) { state.setLine( i % 4, texts[ i ] ); } state.update( true ); } }; var Drone = function( x, y, z, dir, world ) { this.record = false; var usePlayerCoords = false; var player = self; if ( x instanceof Player ) { player = x; } var playerPos = utils.getPlayerPos( player ); var that = this; var populateFromLocation = function( loc ) { that.x = loc.x; that.y = loc.y; that.z = loc.z; that.dir = _getDirFromRotation(loc.yaw); that.world = loc.world; }; var mp = utils.getMousePos( player ); if ( typeof x == 'undefined' || x instanceof Player ) { if ( mp ) { populateFromLocation( mp ); if ( playerPos ) { this.dir = _getDirFromRotation(playerPos.yaw); } } else { // base it on the player's current location usePlayerCoords = true; // // it's possible that drone.js could be loaded by a non-playing op // (from the server console) // if ( !playerPos ) { return null; } populateFromLocation( playerPos ); } } else { if ( arguments[0] instanceof Location ) { populateFromLocation( arguments[ 0 ] ); } else { this.x = x; this.y = y; this.z = z; if ( typeof dir == 'undefined' ) { this.dir = _getDirFromRotation( playerPos.yaw ); } else { this.dir = dir%4; } if ( typeof world == 'undefined' ) { this.world = playerPos.world; } else { this.world = world; } } } if ( usePlayerCoords ) { this.fwd( 3 ); } this.chkpt( 'start' ); this.record = true; this.history = []; return this; }; exports.Drone = Drone; /* because this is a plugin, any of its exports will be exported globally. Since 'blocks' is a module not a plugin it is convenient to export it via the Drone module. */ exports.blocks = blocks; // // add custom methods to the Drone object using this function // Drone.extend = function( name, func ) { Drone.prototype[ '_' + name ] = func; Drone.prototype[ name ] = function( ) { if ( this.record ) { this.history.push( [ name, arguments ] ); } var oldVal = this.record; this.record = false; this[ '_' + name ].apply( this, arguments ); this.record = oldVal; return this; }; global[name] = function( ) { var result = new Drone( self ); result[name].apply( result, arguments ); return result; }; }; /************************************************************************** ### Drone.times() Method The times() method makes building multiple copies of buildings easy. It's possible to create rows or grids of buildings without resorting to `for` or `while` loops. #### Parameters * numTimes (optional - default 2) : The number of times you want to repeat the preceding statements. #### Example Say you want to do the same thing over and over. You have a couple of options... * You can use a for loop... d = new Drone(); for ( var i =0;i < 4; i++) { d.cottage().right(8); } While this will fit on the in-game prompt, it's awkward. You need to declare a new Drone object first, then write a for loop to create the 4 cottages. It's also error prone, even the `for` loop is too much syntax for what should really be simple. * You can use a while loop... d = new Drone(); var i=4; while (i--) { d.cottage().right(8); } ... which is slightly shorter but still too much syntax. Each of the above statements is fine for creating a 1-dimensional array of structures. But what if you want to create a 2-dimensional or 3-dimensional array of structures? Enter the `times()` method. The `times()` method lets you repeat commands in a chain any number of times. So to create 4 cottages in a row you would use the following statement... cottage().right(8).times(4); ...which will build a cottage, then move right 8 blocks, then do it again 4 times over so that at the end you will have 4 cottages in a row. What's more the `times()` method can be called more than once in a chain. So if you wanted to create a *grid* of 20 houses ( 4 x 5 ), you would do so using the following statement... cottage().right(8).times(4).fwd(8).left(32).times(5); ... breaking it down... 1. The first 3 calls in the chain ( `cottage()`, `right(8)`, `times(4)` ) build a single row of 4 cottages. 2. The last 3 calls in the chain ( `fwd(8)`, `left(32)`, `times(5)` ) move the drone forward 8 then left 32 blocks (4 x 8) to return to the original x coordinate, then everything in the chain is repeated again 5 times so that in the end, we have a grid of 20 cottages, 4 x 5. Normally this would require a nested loop but the `times()` method does away with the need for loops when repeating builds. Another example: This statement creates a row of trees 2 by 3 ... oak().right(10).times(2).left(20).fwd(10).times(3) ... You can see the results below. ![times example 1](img/times-trees.png) ***/ Drone.prototype.times = function( numTimes, commands ) { if ( typeof numTimes == 'undefined' ) { numTimes = 2; } if ( typeof commands == 'undefined' ) { commands = this.history.concat(); } this.history = [ [ 'times', [ numTimes + 1, commands ] ] ]; var oldVal = this.record; this.record = false; for ( var j = 1; j < numTimes; j++ ) { for ( var i = 0; i < commands.length; i++) { var command = commands[i]; var methodName = command[0]; var args = command[1]; print ('command=' + JSON.stringify(command ) + ',methodName=' + methodName ); this[ methodName ].apply( this, args ); } } this.record = oldVal; return this; }; Drone.prototype._checkpoints = {}; Drone.extend( 'chkpt', function( name ) { this._checkpoints[ name ] = { x:this.x, y:this.y, z:this.z, dir:this.dir }; } ); Drone.extend( 'move', function( ) { if ( arguments[0] instanceof Location ) { this.x = arguments[0].x; this.y = arguments[0].y; this.z = arguments[0].z; this.dir = _getDirFromRotation(arguments[0].yaw ); this.world = arguments[0].world; } else if ( typeof arguments[0] === 'string' ) { var coords = this._checkpoints[arguments[0]]; if ( coords ) { this.x = coords.x; this.y = coords.y; this.z = coords.z; this.dir = coords.dir%4; } } else { // expect x,y,z,dir switch( arguments.length ) { case 4: this.dir = arguments[3]; case 3: this.z = arguments[2]; case 2: this.y = arguments[1]; case 1: this.x = arguments[0]; } } } ); Drone.extend( 'turn', function ( n ) { if ( typeof n == 'undefined' ) { n = 1; } this.dir += n; this.dir %=4; } ); Drone.extend( 'right', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } _movements[ this.dir ].right( this, n ); }); Drone.extend( 'left', function( n ) { if ( typeof n == 'undefined') { n = 1; } _movements[ this.dir ].left( this, n ); }); Drone.extend( 'fwd', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } _movements[ this.dir ].fwd( this, n ); }); Drone.extend( 'back', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } _movements[ this.dir ].back( this, n ); }); Drone.extend( 'up', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } this.y+= n; }); Drone.extend( 'down', function( n ) { if ( typeof n == 'undefined' ) { n = 1; } this.y-= n; }); // // position // Drone.prototype.getLocation = function( ) { return new Location( this.world, this.x, this.y, this.z ); }; // // building // Drone.extend( 'sign', function( message, block ) { if ( message.constructor != Array ) { message = [message]; } var bm = this._getBlockIdAndMeta( block ); block = bm[0]; var meta = bm[1]; if ( block != 63 && block != 68 ) { print('ERROR: Invalid block id for use in signs'); return; } if ( block == 68 ) { meta = Drone.PLAYER_SIGN_FACING[ this.dir % 4 ]; this.back(); } if ( block == 63 ) { meta = ( 12 + ( ( this.dir + 2 ) * 4 ) ) % 16; } putSign( message, this.x, this.y, this.z, block, meta, this.world ); if ( block == 68 ) { this.fwd(); } }); Drone.prototype.cuboida = function(/* Array */ blocks, w, h, d ) { var properBlocks = []; var len = blocks.length; for ( var i = 0; i < len; i++ ) { var bm = this._getBlockIdAndMeta( blocks[ i ] ); properBlocks.push( [ bm[0], bm[1] ] ); } if ( typeof h == 'undefined' ) { h = 1; } if ( typeof d == 'undefined' ) { d = 1; } if ( typeof w == 'undefined' ) { w = 1; } var that = this; var dir = this.dir; var bi = 0; /* */ _traverse[dir].depth( that, d, function( ) { _traverseHeight( that, h, function( ) { _traverse[dir].width( that, w, function( ) { var block = that.world.getBlockAt( that.x, that.y, that.z ); var properBlock = properBlocks[ bi % len ]; block.setTypeIdAndData( properBlock[0], properBlock[1], false ); bi++; }); }); }); return this; }; /* faster cuboid because blockid, meta and world must be provided use this method when you need to repeatedly place blocks */ Drone.prototype.cuboidX = function( blockType, meta, w, h, d ) { if ( typeof h == 'undefined' ) { h = 1; } if ( typeof d == 'undefined' ) { d = 1; } if ( typeof w == 'undefined' ) { w = 1; } var that = this; var dir = this.dir; var depthFunc = function( ) { var block = that.world.getBlockAt( that.x, that.y, that.z ); block.setTypeIdAndData( blockType, meta, false ); // wph 20130210 - dont' know if this is a bug in bukkit but for chests, // the metadata is ignored (defaults to 2 - south facing) // only way to change data is to set it using property/bean. block.data = meta; }; var heightFunc = function( ) { _traverse[dir].depth( that, d, depthFunc ); }; var widthFunc = function( ) { _traverseHeight( that, h, heightFunc ); }; _traverse[dir].width( that, w, widthFunc ); return this; }; Drone.prototype.cuboid = function( block, w, h, d ) { var bm = this._getBlockIdAndMeta( block ); return this.cuboidX( bm[0], bm[1], w, h, d ); }; Drone.prototype.cuboid0 = function( block, w, h, d ) { this.chkpt( 'start_point' ); // Front wall this.cuboid( block, w, h, 1 ); // Left wall this.cuboid( block, 1, h, d ); // Right wall this.right( w - 1 ).cuboid( block, 1, h, d ).left( w - 1 ); // Back wall this.fwd( d - 1 ).cuboid( block, w, h, 1 ); return this.move( 'start_point' ); }; Drone.extend( 'door', function( door ) { if ( typeof door == 'undefined' ) { door = 64; } else { door = 71; } this.cuboid( door+':' + this.dir ) .up( ) .cuboid( door+':8' ) .down( ); } ); Drone.extend( 'door2' , function( door ) { if ( typeof door == 'undefined' ) { door = 64; } else { door = 71; } this .box( door+':' + this.dir ).up( ) .box( door+':8' ).right( ) .box( door+':9' ).down( ) .box( door+':' + this.dir ).left( ); } ); // player dirs: 0 = east, 1 = south, 2 = west, 3 = north // block dirs: 0 = east, 1 = west, 2 = south , 3 = north // sign dirs: 5 = east, 3 = south, 4 = west, 2 = north Drone.PLAYER_STAIRS_FACING = [ 0, 2, 1, 3 ]; // for blocks 68 (wall signs) 65 (ladders) 61,62 (furnaces) 23 (dispenser) and 54 (chest) Drone.PLAYER_SIGN_FACING = [ 4, 2, 5, 3 ]; Drone.PLAYER_TORCH_FACING = [ 2, 4, 1, 3 ]; var _STAIRBLOCKS = { 53: '5:0' // oak wood ,67: 4 // cobblestone ,108: 45 // brick ,109: 98 // stone brick ,114: 112 // nether brick ,128: 24 // sandstone ,134: '5:1' // spruce wood ,135: '5:2' // birch wood ,136: '5:3' // jungle wood }; // // prism private implementation // var _prism = function( block, w, d ) { var stairEquiv = _STAIRBLOCKS[block]; if ( stairEquiv ) { this.fwd( ).prism(stairEquiv,w,d-2 ).back( ); var d2 = 0; var middle = Math.floor( d/2 ); var uc = 0,dc = 0; while ( d2 < d ) { var di = (d2 < middle?this.dir:(this.dir+2 )%4 ); var bd = block + ':' + Drone.PLAYER_STAIRS_FACING[di]; var putStep = true; if ( d2 == middle ) { if ( d % 2 == 1 ) { putStep = false; } } if ( putStep ) { this.cuboid(bd,w ); } if ( d2 < middle-1 ) { this.up( ); uc++; } var modulo = d % 2; if ( modulo == 1 ) { if ( d2 > middle && d2<d-1) { this.down( ); dc++; } }else{ if ( d2 >= middle && d2<d-1 ) { this.down( ); dc++; } } this.fwd( ); d2++; } this.back(d ); }else{ var c = 0; var d2 = d; while ( d2 >= 1 ) { this.cuboid(block,w,1,d2 ); d2 -= 2; this.fwd( ).up( ); c++; } this.down(c ).back(c ); } return this; }; // // prism0 private implementation // var _prism0 = function( block,w,d ) { this.prism(block,w,d ) .fwd( ).right( ) .prism(0,w-2,d-2 ) .left( ).back( ); var se = _STAIRBLOCKS[block]; if ( d % 2 == 1 && se ) { // top of roof will be open - need repair var f = Math.floor(d/2 ); this.fwd(f ).up(f ).cuboid(se,w ).down(f ).back(f ); } }; Drone.extend('prism0',_prism0 ); Drone.extend('prism',_prism ); Drone.extend('box',Drone.prototype.cuboid ); Drone.extend('box0',Drone.prototype.cuboid0 ); Drone.extend('boxa',Drone.prototype.cuboida ); // // show the Drone's position and direction // Drone.prototype.toString = function( ) { var dirs = ['east','south','west','north']; return 'x: ' + this.x + ' y: '+this.y + ' z: ' + this.z + ' dir: ' + this.dir + ' '+dirs[this.dir]; }; Drone.prototype.debug = function( ) { print(this.toString( ) ); return this; }; /* do the bresenham thing */ var _bresenham = function( x0,y0,radius, setPixel, quadrants ) { // // credit: Following code is copied almost verbatim from // http://en.wikipedia.org/wiki/Midpoint_circle_algorithm // Bresenham's circle algorithm // var f = 1 - radius; var ddF_x = 1; var ddF_y = -2 * radius; var x = 0; var y = radius; var defaultQuadrants = {topleft: true, topright: true, bottomleft: true, bottomright: true}; quadrants = quadrants?quadrants:defaultQuadrants; /* II | I ------------ III | IV */ if ( quadrants.topleft || quadrants.topright ) setPixel(x0, y0 + radius ); // quadrant I/II topmost if ( quadrants.bottomleft || quadrants.bottomright ) setPixel(x0, y0 - radius ); // quadrant III/IV bottommost if ( quadrants.topright || quadrants.bottomright ) setPixel(x0 + radius, y0 ); // quadrant I/IV rightmost if ( quadrants.topleft || quadrants.bottomleft ) setPixel(x0 - radius, y0 ); // quadrant II/III leftmost while ( x < y ) { if(f >= 0 ) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if ( quadrants.topright ) { setPixel(x0 + x, y0 + y ); // quadrant I setPixel(x0 + y, y0 + x ); // quadrant I } if ( quadrants.topleft ) { setPixel(x0 - x, y0 + y ); // quadrant II setPixel(x0 - y, y0 + x ); // quadrant II } if ( quadrants.bottomleft ) { setPixel(x0 - x, y0 - y ); // quadrant III setPixel(x0 - y, y0 - x ); // quadrant III } if ( quadrants.bottomright ) { setPixel(x0 + x, y0 - y ); // quadrant IV setPixel(x0 + y, y0 - x ); // quadrant IV } } }; var _getStrokeDir = function( x,y ) { var absY = Math.abs(y ); var absX = Math.abs(x ); var strokeDir = 0; if ( y > 0 && absY >= absX ) strokeDir = 0 ; //down else if ( y < 0 && absY >= absX ) strokeDir = 1 ; // up else if ( x > 0 && absX >= absY ) strokeDir = 2 ; // left else if ( x < 0 && absX >= absY ) strokeDir = 3 ; // right return strokeDir; }; /* The daddy of all arc-related API calls - if you're drawing anything that bends it ends up here. */ var _arc2 = function( params ) { var drone = params.drone; var orientation = params.orientation?params.orientation:'horizontal'; var quadrants = params.quadrants?params.quadrants:{ topright:1, topleft:2, bottomleft:3, bottomright:4 }; var stack = params.stack?params.stack:1; var radius = params.radius; var strokeWidth = params.strokeWidth?params.strokeWidth:1; drone.chkpt('arc2' ); var x0, y0, gotoxy,setPixel; if ( orientation == 'horizontal' ) { gotoxy = function( x,y ) { return drone.right(x ).fwd(y );}; drone.right(radius ).fwd(radius ).chkpt('center' ); switch ( drone.dir ) { case 0: // east case 2: // west x0 = drone.z; y0 = drone.x; break; case 1: // south case 3: // north x0 = drone.x; y0 = drone.z; } setPixel = function( x,y ) { x = (x-x0 ); y = (y-y0 ); if ( params.fill ) { // wph 20130114 more efficient esp. for large cylinders/spheres if ( y < 0 ) { drone .fwd(y ).right(x ) .cuboidX(params.blockType,params.meta,1,stack,Math.abs(y*2 )+1 ) .back(y ).left(x ); } }else{ if ( strokeWidth == 1 ) { gotoxy(x,y ) .cuboidX(params.blockType, params.meta, 1, // width stack, // height strokeWidth // depth ) .move('center' ); } else { var strokeDir = _getStrokeDir(x,y ); var width = 1, depth = 1; switch ( strokeDir ) { case 0: // down y = y-(strokeWidth-1 ); depth = strokeWidth; break; case 1: // up depth = strokeWidth; break; case 2: // left width = strokeWidth; x = x-(strokeWidth-1 ); break; case 3: // right width = strokeWidth; break; } gotoxy(x,y ) .cuboidX(params.blockType, params.meta, width, stack, depth ) .move('center' ); } } }; }else{ // vertical gotoxy = function( x,y ) { return drone.right(x ).up(y );}; drone.right(radius ).up(radius ).chkpt('center' ); switch ( drone.dir ) { case 0: // east case 2: // west x0 = drone.z; y0 = drone.y; break; case 1: // south case 3: // north x0 = drone.x; y0 = drone.y; } setPixel = function( x,y ) { x = (x-x0 ); y = (y-y0 ); if ( params.fill ) { // wph 20130114 more efficient esp. for large cylinders/spheres if ( y < 0 ) { drone .up(y ).right(x ) .cuboidX(params.blockType,params.meta,1,Math.abs(y*2 )+1,stack ) .down(y ).left(x ); } }else{ if ( strokeWidth == 1 ) { gotoxy(x,y ) .cuboidX(params.blockType,params.meta,strokeWidth,1,stack ) .move('center' ); }else{ var strokeDir = _getStrokeDir(x,y ); var width = 1, height = 1; switch ( strokeDir ) { case 0: // down y = y-(strokeWidth-1 ); height = strokeWidth; break; case 1: // up height = strokeWidth; break; case 2: // left width = strokeWidth; x = x-(strokeWidth-1 ); break; case 3: // right width = strokeWidth; break; } gotoxy(x,y ) .cuboidX(params.blockType, params.meta, width, height, stack ) .move('center' ); } } }; } /* setPixel assumes a 2D plane - need to put a block along appropriate plane */ _bresenham(x0,y0,radius,setPixel,quadrants ); params.drone.move('arc2' ); }; Drone.extend('arc',function( params ) { params.drone = this; _arc2(params ); } ); var _cylinder0 = function( block,radius,height,exactParams ) { var arcParams = { radius: radius, fill: false, orientation: 'horizontal', stack: height, }; if ( exactParams ) { arcParams.blockType = exactParams.blockType; arcParams.meta = exactParams.meta; }else{ var md = this._getBlockIdAndMeta(block ); arcParams.blockType = md[0]; arcParams.meta = md[1]; } return this.arc(arcParams ); }; var _cylinder1 = function( block,radius,height,exactParams ) { var arcParams = { radius: radius, fill: true, orientation: 'horizontal', stack: height, }; if ( exactParams ) { arcParams.blockType = exactParams.blockType; arcParams.meta = exactParams.meta; }else{ var md = this._getBlockIdAndMeta(block ); arcParams.blockType = md[0]; arcParams.meta = md[1]; } return this.arc(arcParams ); }; var _paste = function( name ) { var ccContent = Drone.clipBoard[name]; var srcBlocks = ccContent.blocks; var srcDir = ccContent.dir; // direction player was facing when copied. var dirOffset = (4 + (this.dir - srcDir ) ) %4; var that = this; _traverse[this.dir].width(that,srcBlocks.length,function( ww ) { var h = srcBlocks[ww].length; _traverseHeight(that,h,function( hh ) { var d = srcBlocks[ww][hh].length; _traverse[that.dir].depth(that,d,function( dd ) { var b = srcBlocks[ww][hh][dd]; var bm = that._getBlockIdAndMeta(b ); var cb = bm[0]; var md = bm[1]; // // need to adjust blocks which face a direction // switch ( cb ) { // // doors // case 64: // wood case 71: // iron // top half of door doesn't need to change if ( md < 8 ) { md = (md + dirOffset ) % 4; } break; // // stairs // case 53: // oak case 67: // cobblestone case 108: // red brick case 109: // stone brick case 114: // nether brick case 128: // sandstone case 134: // spruce case 135: // birch case 136: // junglewood var dir = md & 0x3; var a = Drone.PLAYER_STAIRS_FACING; var len = a.length; for ( var c=0;c < len;c++ ) { if ( a[c] == dir ) { break; } } c = (c + dirOffset ) %4; var newDir = a[c]; md = (md >>2<<2 ) + newDir; break; // // signs , ladders etc // case 23: // dispenser case 54: // chest case 61: // furnace case 62: // burning furnace case 65: // ladder case 68: // wall sign var a = Drone.PLAYER_SIGN_FACING; var len = a.length; for ( var c=0;c < len;c++ ) { if ( a[c] == md ) { break; } } c = (c + dirOffset ) %4; var newDir = a[c]; md = newDir; break; } putBlock(that.x,that.y,that.z,cb,md,that.world ); } ); } ); } ); }; var _getDirFromRotation = function( r ) { // 0 = east, 1 = south, 2 = west, 3 = north // 46 to 135 = west // 136 to 225 = north // 226 to 315 = east // 316 to 45 = south r = (r + 360 ) % 360; // east could be 270 or -90 if ( r > 45 && r <= 135 ) return 2; // west if ( r > 135 && r <= 225 ) return 3; // north if ( r > 225 && r <= 315 ) return 0; // east if ( r > 315 || r < 45 ) return 1; // south }; var _getBlockIdAndMeta = function(b ) { var defaultMeta = 0; if ( typeof b == 'string' ) { var bs = b; var sp = bs.indexOf(':' ); if ( sp == -1 ) { b = parseInt(bs ); // wph 20130414 - use sensible defaults for certain blocks e.g. stairs // should face the drone. for ( var i in blocks.stairs ) { if ( blocks.stairs[i] === b ) { defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; break; } } return [b,defaultMeta]; } b = parseInt(bs.substring(0,sp ) ); var md = parseInt(bs.substring(sp+1,bs.length ) ); return [b,md]; }else{ // wph 20130414 - use sensible defaults for certain blocks e.g. stairs // should face the drone. for ( var i in blocks.stairs ) { if ( blocks.stairs[i] === b ) { defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; break; } } return [b,defaultMeta]; } }; // // movement // var _movements = [{},{},{},{}]; // east _movements[0].right = function( that,n ) { that.z +=n; return that;}; _movements[0].left = function( that,n ) { that.z -=n; return that;}; _movements[0].fwd = function( that,n ) { that.x +=n; return that;}; _movements[0].back = function( that,n ) { that.x -= n; return that;}; // south _movements[1].right = _movements[0].back; _movements[1].left = _movements[0].fwd; _movements[1].fwd = _movements[0].right; _movements[1].back = _movements[0].left; // west _movements[2].right = _movements[0].left; _movements[2].left = _movements[0].right; _movements[2].fwd = _movements[0].back; _movements[2].back = _movements[0].fwd; // north _movements[3].right = _movements[0].fwd; _movements[3].left = _movements[0].back; _movements[3].fwd = _movements[0].left; _movements[3].back = _movements[0].right; var _traverse = [{},{},{},{}]; // east _traverse[0].width = function( that,n,callback ) { var s = that.z, e = s + n; for ( ; that.z < e; that.z++ ) { callback(that.z-s ); } that.z = s; }; _traverse[0].depth = function( that,n,callback ) { var s = that.x, e = s+n; for ( ;that.x < e;that.x++ ) { callback(that.x-s ); } that.x = s; }; // south _traverse[1].width = function( that,n,callback ) { var s = that.x, e = s-n; for ( ;that.x > e;that.x-- ) { callback(s-that.x ); } that.x = s; }; _traverse[1].depth = _traverse[0].width; // west _traverse[2].width = function( that,n,callback ) { var s = that.z, e = s-n; for ( ;that.z > e;that.z-- ) { callback(s-that.z ); } that.z = s; }; _traverse[2].depth = _traverse[1].width; // north _traverse[3].width = _traverse[0].depth; _traverse[3].depth = _traverse[2].width; var _traverseHeight = function( that,n,callback ) { var s = that.y, e = s + n; for ( ; that.y < e; that.y++ ) { callback(that.y-s ); } that.y = s; }; // // standard fisher-yates shuffle algorithm // var _fisherYates = function( myArray ) { var i = myArray.length; if ( i == 0 ) return false; while ( --i ) { var j = Math.floor( Math.random( ) * ( i + 1 ) ); var tempi = myArray[i]; var tempj = myArray[j]; myArray[i] = tempj; myArray[j] = tempi; } }; var _copy = function( name, w, h, d ) { var that = this; var ccContent = []; _traverse[this.dir].width(that,w,function( ww ) { ccContent.push([] ); _traverseHeight(that,h,function( hh ) { ccContent[ww].push([] ); _traverse[that.dir].depth(that,d,function( dd ) { var b = that.world.getBlockAt(that.x,that.y,that.z ); ccContent[ww][hh][dd] = b; } ); } ); } ); Drone.clipBoard[name] = {dir: this.dir, blocks: ccContent}; }; var _garden = function( w,d ) { // make sure grass is present first this.down( ).box(2,w,1,d ).up( ); // make flowers more common than long grass var dist = {37: 3, // red flower 38: 3, // yellow flower '31:1': 2, // long grass 0: 1 }; return this.rand(dist,w,1,d ); }; var _rand = function( blockDistribution ) { if ( !(blockDistribution.constructor == Array ) ) { var a = []; for ( var p in blockDistribution ) { var n = blockDistribution[p]; for ( var i = 0;i < n;i++ ) { a.push(p ); } } blockDistribution = a; } while ( blockDistribution.length < 1000 ) { // make array bigger so that it's more random blockDistribution = blockDistribution.concat(blockDistribution ); } _fisherYates(blockDistribution ); return blockDistribution; }; Drone.extend('rand',function( dist,w,h,d ) { var randomized = _rand(dist ); this.boxa(randomized,w,h,d ); } ); var _trees = { oak: TreeType.BIG_TREE , birch: TreeType.BIRCH , jungle: TreeType.JUNGLE, spruce: TreeType.REDWOOD }; for ( var p in _trees ) { Drone.extend(p, function( v ) { return function( ) { var block = this.world.getBlockAt(this.x,this.y,this.z ); if ( block.typeId == 2 ) { this.up( ); } var treeLoc = new Location(this.world,this.x,this.y,this.z ); var successful = treeLoc.world.generateTree(treeLoc,v ); if ( block.typeId == 2 ) { this.down( ); } }; }(_trees[p] ) ); } // // Drone's clipboard // Drone.clipBoard = {}; Drone.extend('garden',_garden ); Drone.extend('copy', _copy ); Drone.extend('paste',_paste ); Drone.extend('cylinder0',_cylinder0 ); Drone.extend('cylinder', _cylinder1 ); // // wph 20130130 - make this a method - extensions can use it. // Drone.prototype._getBlockIdAndMeta = _getBlockIdAndMeta;
Drone.cuboidX() - foundation of most Drone building is now async.
src/main/js/plugins/drone/drone.js
Drone.cuboidX() - foundation of most Drone building is now async.
<ide><path>rc/main/js/plugins/drone/drone.js <ide> */ <ide> exports.blocks = blocks; <ide> <add>Drone.queue = []; <add>Drone.processingQueue = false; <add>Drone.MAX_QUEUE_SIZE = 100000; <add>Drone.tick = setInterval( function() { <add> if ( Drone.processingQueue ) { <add> return; <add> } <add> var maxOpsPerTick = Math.floor(Math.max(10,Math.sqrt(Drone.queue.length))) ; <add> var op; <add> Drone.processingQueue = true; <add> while ( maxOpsPerTick > 0 ) { <add> op = Drone.queue.shift(); <add> if (!op){ <add> Drone.processingQueue = false; <add> return; <add> } <add> var block = op.world.getBlockAt( op.x, op.y, op.z ); <add> block.setTypeIdAndData( op.typeid, op.meta, false ); <add> // wph 20130210 - dont' know if this is a bug in bukkit but for chests, <add> // the metadata is ignored (defaults to 2 - south facing) <add> // only way to change data is to set it using property/bean. <add> block.data = op.meta; <add> maxOpsPerTick--; <add> } <add> Drone.processingQueue = false; <add> return; <add>}, 1); <add> <ide> // <ide> // add custom methods to the Drone object using this function <ide> // <ide> var dir = this.dir; <ide> <ide> var depthFunc = function( ) { <del> var block = that.world.getBlockAt( that.x, that.y, that.z ); <del> block.setTypeIdAndData( blockType, meta, false ); <del> // wph 20130210 - dont' know if this is a bug in bukkit but for chests, <del> // the metadata is ignored (defaults to 2 - south facing) <del> // only way to change data is to set it using property/bean. <del> block.data = meta; <add> var len = Drone.queue.length; <add> if ( len < Drone.MAX_QUEUE_SIZE ) { <add> Drone.queue.push({ <add> world: that.world, <add> x: that.x, <add> y: that.y, <add> z:that.z, <add> typeid: blockType, <add> meta: meta <add> }); <add> } else { <add> throw new Error('Drone is too busy!'); <add> } <ide> }; <ide> var heightFunc = function( ) { <ide> _traverse[dir].depth( that, d, depthFunc ); <ide> return this.move( 'start_point' ); <ide> }; <ide> <add> <ide> Drone.extend( 'door', function( door ) { <ide> if ( typeof door == 'undefined' ) { <ide> door = 64; <ide> } else { <ide> door = 71; <ide> } <del> this.cuboid( door+':' + this.dir ) <add> this.cuboidX( door, this.dir ) <ide> .up( ) <del> .cuboid( door+':8' ) <add> .cuboidX( door, 8 ) <ide> .down( ); <ide> } ); <ide> <ide> door = 71; <ide> } <ide> this <del> .box( door+':' + this.dir ).up( ) <del> .box( door+':8' ).right( ) <del> .box( door+':9' ).down( ) <del> .box( door+':' + this.dir ).left( ); <add> .cuboidX( door, this.dir ).up( ) <add> .cuboidX( door, 8 ).right( ) <add> .cuboidX( door, 9 ).down( ) <add> .cuboidX( door, this.dir ).left( ); <ide> } ); <ide> // player dirs: 0 = east, 1 = south, 2 = west, 3 = north <ide> // block dirs: 0 = east, 1 = west, 2 = south , 3 = north
JavaScript
mit
b178bebb32ae52f9cc424d5f60b55a65d6ccab4c
0
affectry-inc/zangyo-bot
"use strict"; var moment = require('moment-timezone'); var luid = require('./utils').luid; moment.tz.setDefault("Asia/Tokyo"); moment.locale('ja', { weekdays: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], weekdaysShort: ["日","月","火","水","木","金","土"] }); function ZangyoBot(controller) { var zangyo_bot = {}; zangyo_bot.ranges = { today: "今日", yesterday: "昨日", day_before_yesterday: "一昨日", this_week: "今週", last_week: "先週", past_one_week: "過去一週間" }; zangyo_bot.createApplication = function(err, convo) { askApprover(convo); }; function askApprover(convo) { convo.ask("プロマネは誰? [@xxx]", function(response, convo) { if (response.text.match(/(cancel|キャンセル)/)) { convo.say('キャンセルしたよ!'); convo.next(); } else if (!response.text.match(/^\<\@[a-zA-Z0-9]+\>/g)) { convo.say('@xxx の形式でユーザーを1人指定してね。'); convo.repeat(); convo.next(); } else { var zangyo = {} zangyo.id = "Z" + luid(); zangyo.date = moment().format("YYYY-MM-DD"); zangyo.applicant = response.user; zangyo.approver = response.text.match(/^\<\@[a-zA-Z0-9]+\>/g)[0].slice(2, -1); askEndTime(convo, zangyo); convo.next(); } }); }; function askEndTime(convo, zangyo) { convo.ask("何時に終わる? [HH:MM]", function(response, convo) { if (response.text.match(/(cancel|キャンセル)/)) { convo.say('キャンセルしたよ!'); convo.next(); } else if (!response.text.match(/^([0-2]?[0-9]):([0-5]?[0-9])$/)) { convo.say('HH:MM の形式で時間を指定してね。29:59まで指定できるよ。'); convo.repeat(); convo.next(); } else { zangyo.end_time = response.text; askReason(convo, zangyo); convo.next(); } }); }; function askReason(convo, zangyo) { convo.ask("残業する理由は?", function(response, convo) { zangyo.reason = response.text; var summary = { "text": "残業申請する?", "attachments": [ { "callback_id": "apply-" + zangyo.id, "fallback": "<@" + zangyo.approver + "> さんへの残業申請", "color": "#aaa", "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ], "actions": [ { "type": "button", "name": "apply", "text": "申請", "style": "primary" }, { "type": "button", "name": "redo", "text": "やり直し" }, { "type": "button", "name": "cancel", "text": "キャンセル" } ] } ] } controller.storage.teams.get(response.team, function(err, team) { if (!team.zangyos) { team.zangyos = []; } team.zangyos.push(zangyo); controller.storage.teams.save(team); }); convo.say(summary); convo.next(); }); }; zangyo_bot.apply = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos[idx].applied_at = moment().unix(); controller.storage.teams.save(team); var zangyo = team.zangyos[idx]; var summary = { "text": "残業申請したよ。", "attachments": [ { "fallback": "<@" + zangyo.approver + "> さんへの残業申請", "color": "#aaa", "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ] } ] } bot.replyInteractive(message, summary); bot.startPrivateConversation({user: zangyo.approver}, function(err,convo) { if (err) { console.log(err); } else { var application = { "text": "残業申請が来たよ。承認する?", "attachments": [ { "callback_id": "approve-" + zangyo.id, "fallback": "<@" + zangyo.applicant + "> さんからの残業申請", "color": "#aaa", "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ], "actions": [ { "type": "button", "name": "approve", "text": "承認", "style": "primary" }, { "type": "button", "name": "reject", "text": "却下", "style": "danger" } ] } ] } convo.say(application); convo.next(); } }); }); }; zangyo_bot.redoApply = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos.splice(idx, 1); controller.storage.teams.save(team); bot.replyInteractive(message, "最初からやり直し!"); bot.startConversation(message, zangyo_bot.createApplication); }); }; zangyo_bot.cancelApply = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos.splice(idx, 1); controller.storage.teams.save(team); bot.replyInteractive(message, "キャンセルしたよ。さっさと帰ろう!"); }); }; zangyo_bot.approve = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos[idx].approved = true; team.zangyos[idx].approved_at = moment().unix(); controller.storage.teams.save(team); var zangyo = team.zangyos[idx]; bot.replyInteractive(message, getSummary(zangyo, true, true)); bot.configureIncomingWebhook(team.incoming_webhook); bot.sendWebhook(getSummary(zangyo, true, false), function(err,res) { if (err) console.log(err); }); }); }; zangyo_bot.rejectApprove = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos[idx].approved = false; team.zangyos[idx].approved_at = moment().unix(); controller.storage.teams.save(team); var zangyo = team.zangyos[idx]; bot.replyInteractive(message, getSummary(zangyo, false, true)); bot.configureIncomingWebhook(team.incoming_webhook); bot.sendWebhook(getSummary(zangyo, false, false), function(err,res) { if (err) console.log(err); }); }); }; function getSummary(zangyo, is_approved, is_reply) { var result_word, color, text; if (is_approved) { result_word = "承認"; color = "good"; } else { result_word = "却下"; color = "danger"; } if (is_reply) { text = "残業申請を" + result_word + "したよ。"; } var summary = { "text": text, "attachments": [ { "fallback": "<@" + zangyo.applicant + "> さんの残業申請", "color": color, "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ], "footer": "<@" + zangyo.approver + "> が" + result_word + "しました。", "ts": zangyo.approved_at } ] } return summary; }; function getTeamZangyo(team_id, zangyo_id, cb) { controller.storage.teams.get(team_id, function(err, team) { for (var i = 0; i < team.zangyos.length; i++) { if (team.zangyos[i].id == zangyo_id) { cb(team, i); break; } } }); }; zangyo_bot.replyList = function(bot, message, range, is_detailed) { if (is_detailed) { buildDetailedMessage(bot, message, range); } else { buildSimplifiedMessage(bot, message, range); } }; function buildSimplifiedMessage(bot, message, range) { findTargetZangyo(message.team, range, function(zangyo){ var field = {}; if (zangyo.approved == true) { field.value = ":white_check_mark: <@" + zangyo.applicant + "> - " + zangyo.end_time; } else { field.value = ":x: <@" + zangyo.applicant + "> - " + zangyo.end_time; } field.short = false return field; }, function(fields){ var reply; if (fields.length == 0) { reply = range + "は残業申請1件もないっす。。。"; } else { reply = { "text": range + "の残業申請一覧", "attachments": [ { "color": "#aaa", "fields": fields } ] } } bot.reply(message, reply); }); }; function buildDetailedMessage(bot, message, range) { findTargetZangyo(message.team, range, function(zangyo){ var attachment = {}; if (zangyo.approved == true) { attachment.color = "good"; attachment.footer = "<@" + zangyo.approver + "> が承認しました。"; } else { attachment.color = "danger"; attachment.footer = "<@" + zangyo.approver + "> が却下しました。"; } attachment.title = "<@" + zangyo.applicant + "> - " + zangyo.end_time; attachment.text = zangyo.reason; attachment.ts = zangyo.approved_at; return attachment; }, function(attachments){ var reply; if (attachments.length == 0) { reply = range + "は残業申請1件もないっす。。。"; } else { reply = { "text": range + "の残業申請一覧", "attachments": attachments } } bot.reply(message, reply); }); }; function findTargetZangyo(team_id, range, getMessageItem, replyWholeMessage) { var begin_date, end_date; switch (range) { case zangyo_bot.ranges.today: var today = moment().format("YYYY-MM-DD"); begin_date = today; end_date = today break; case zangyo_bot.ranges.yesterday: var yesterday = moment().subtract(1, 'days').format("YYYY-MM-DD"); begin_date = yesterday; end_date = yesterday; break; case zangyo_bot.ranges.day_before_yesterday: var day_before_yesterday = moment().subtract(2, 'days').format("YYYY-MM-DD"); begin_date = day_before_yesterday; end_date = day_before_yesterday; break; case zangyo_bot.ranges.this_week: begin_date = moment().startOf('isoweek').format("YYYY-MM-DD"); end_date = moment().endOf('isoweek').format("YYYY-MM-DD"); break; case zangyo_bot.ranges.last_week: var lastweek = moment().subtract(1, 'weeks'); begin_date = lastweek.startOf('isoweek').format("YYYY-MM-DD"); end_date = lastweek.endOf('isoweek').format("YYYY-MM-DD"); break; case zangyo_bot.ranges.past_one_week: begin_date = moment().subtract(7, 'days').format("YYYY-MM-DD"); end_date = moment().subtract(1, 'days').format("YYYY-MM-DD"); break; default: var target = range.match(/\d{1,2}/g); begin_date = moment().format("YYYY-") + ('0' + target[0]).slice(-2) + '-' + ('0' + target[1]).slice(-2); end_date = moment().format("YYYY-") + ('0' + target[0]).slice(-2) + '-' + ('0' + target[1]).slice(-2); break; } controller.storage.teams.get(team_id, function(err, team) { var list = []; for (var i = 0; i < team.zangyos.length; i++) { var zangyo = team.zangyos[i]; if (begin_date <= zangyo.date && zangyo.date <= end_date) { list.push(getMessageItem(zangyo)); } } replyWholeMessage(list); }); }; return zangyo_bot; } module.exports = ZangyoBot;
lib/zangyo_bot.js
"use strict"; var moment = require('moment-timezone'); var luid = require('./utils').luid; moment.tz.setDefault("Asia/Tokyo"); moment.locale('ja', { weekdays: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], weekdaysShort: ["日","月","火","水","木","金","土"] }); function ZangyoBot(controller) { var zangyo_bot = {}; zangyo_bot.ranges = { today: "今日", yesterday: "昨日", day_before_yesterday: "一昨日", this_week: "今週", last_week: "先週", past_one_week: "過去一週間" }; zangyo_bot.createApplication = function(err, convo) { askApprover(convo); }; function askApprover(convo) { convo.ask("プロマネは誰? [@xxx]", function(response, convo) { if (response.text.match(/(cancel|キャンセル)/)) { convo.say('キャンセルしたよ!'); convo.next(); } else if (!response.text.match(/^\<\@[a-zA-Z0-9]+\>/g)) { convo.say('@xxx の形式でユーザーを1人指定してね。'); convo.repeat(); convo.next(); } else { var zangyo = {} zangyo.id = "Z" + luid(); zangyo.date = moment().format("YYYY-MM-DD"); zangyo.applicant = response.user; zangyo.approver = response.text.match(/^\<\@[a-zA-Z0-9]+\>/g)[0].slice(2, -1); askEndTime(convo, zangyo); convo.next(); } }); }; function askEndTime(convo, zangyo) { convo.ask("何時に終わる? [HH:MM]", function(response, convo) { if (response.text.match(/(cancel|キャンセル)/)) { convo.say('キャンセルしたよ!'); convo.next(); } else if (!response.text.match(/^([0-2]?[0-9]):([0-5]?[0-9])$/)) { convo.say('HH:MM の形式で時間を指定してね。29:59まで指定できるよ。'); convo.repeat(); convo.next(); } else { zangyo.end_time = response.text; askReason(convo, zangyo); convo.next(); } }); }; function askReason(convo, zangyo) { convo.ask("残業する理由は?", function(response, convo) { zangyo.reason = response.text; var summary = { "text": "残業申請する?", "attachments": [ { "callback_id": "apply-" + zangyo.id, "fallback": "<@" + zangyo.approver + "> さんへの残業申請", "color": "#aaa", "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ], "actions": [ { "type": "button", "name": "apply", "text": "申請", "style": "primary" }, { "type": "button", "name": "redo", "text": "やり直し" }, { "type": "button", "name": "cancel", "text": "キャンセル" } ] } ] } controller.storage.teams.get(response.team, function(err, team) { if (!team.zangyos) { team.zangyos = []; } team.zangyos.push(zangyo); controller.storage.teams.save(team); }); convo.say(summary); convo.next(); }); }; zangyo_bot.apply = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos[idx].applied_at = moment().unix(); controller.storage.teams.save(team); var zangyo = team.zangyos[idx]; var summary = { "text": "残業申請したよ。", "attachments": [ { "fallback": "<@" + zangyo.approver + "> さんへの残業申請", "color": "#aaa", "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ] } ] } bot.replyInteractive(message, summary); bot.startPrivateConversation({user: zangyo.approver}, function(err,convo) { if (err) { console.log(err); } else { var application = { "text": "残業申請が来たよ。承認する?", "attachments": [ { "callback_id": "approve-" + zangyo.id, "fallback": "<@" + zangyo.applicant + "> さんからの残業申請", "color": "#aaa", "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ], "actions": [ { "type": "button", "name": "approve", "text": "承認", "style": "primary" }, { "type": "button", "name": "reject", "text": "却下", "style": "danger" } ] } ] } convo.say(application); convo.next(); } }); }); }; zangyo_bot.redoApply = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos.splice(idx, 1); controller.storage.teams.save(team); bot.replyInteractive(message, "最初からやり直し!"); bot.startConversation(message, zangyo_bot.createApplication); }); }; zangyo_bot.cancelApply = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos.splice(idx, 1); controller.storage.teams.save(team); bot.replyInteractive(message, "キャンセルしたよ。さっさと帰ろう!"); }); }; zangyo_bot.approve = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos[idx].approved = true; team.zangyos[idx].approved_at = moment().unix(); controller.storage.teams.save(team); var zangyo = team.zangyos[idx]; bot.replyInteractive(message, getSummary(zangyo, true, true)); bot.configureIncomingWebhook(team.incoming_webhook); bot.sendWebhook(getSummary(zangyo, true, false), function(err,res) { if (err) console.log(err); }); }); }; zangyo_bot.rejectApprove = function(zangyo_id, bot, message) { getTeamZangyo(message.team.id, zangyo_id, function(team, idx) { team.zangyos[idx].approved = false; team.zangyos[idx].approved_at = moment().unix(); controller.storage.teams.save(team); var zangyo = team.zangyos[idx]; bot.replyInteractive(message, getSummary(zangyo, false, true)); bot.configureIncomingWebhook(team.incoming_webhook); bot.sendWebhook(getSummary(zangyo, false, false), function(err,res) { if (err) console.log(err); }); }); }; function getSummary(zangyo, is_approved, is_reply) { var result_word, color, text; if (is_approved) { result_word = "承認"; color = "good"; } else { result_word = "却下"; color = "danger"; } if (is_reply) { text = "残業申請を" + result_word + "したよ。"; } var summary = { "text": text, "attachments": [ { "fallback": "<@" + zangyo.applicant + "> さんの残業申請", "color": color, "title": "残業申請 - " + moment(zangyo.date).format("MM月DD日(ddd)"), "text": "<@" + zangyo.applicant + "> >>> <@" + zangyo.approver + ">", "fields": [ { "title": zangyo.end_time + "まで、以下の理由により残業します。", "value": zangyo.reason, "short": false } ], "footer": "<@" + zangyo.approver + "> が" + result_word + "しました。", "ts": zangyo.approved_at } ] } return summary; }; function getTeamZangyo(team_id, zangyo_id, cb) { controller.storage.teams.get(team_id, function(err, team) { for (var i = 0; i < team.zangyos.length; i++) { if (team.zangyos[i].id == zangyo_id) { cb(team, i); break; } } }); }; zangyo_bot.replyList = function(bot, message, range, is_detailed) { if (is_detailed) { buildDetailedMessage(bot, message, range); } else { buildSimplifiedMessage(bot, message, range); } }; function buildSimplifiedMessage(bot, message, range) { findTargetZangyo(message.team, range, function(zangyo){ var field = {}; if (zangyo.approved == true) { field.value = ":white_check_mark: <@" + zangyo.applicant + "> - " + zangyo.end_time; } else { field.value = ":x: <@" + zangyo.applicant + "> - " + zangyo.end_time; } field.short = false return field; }, function(fields){ var reply; if (fields.length == 0) { reply = range + "は残業申請1件もないっす。。。"; } else { reply = { "text": range + "の残業申請一覧", "attachments": [ { "color": "#aaa", "fields": fields } ] } } bot.reply(message, reply); }); }; function buildDetailedMessage(bot, message, range) { findTargetZangyo(message.team, range, function(zangyo){ var attachment = {}; if (zangyo.approved == true) { attachment.color = "good"; attachment.footer = "<@" + zangyo.approver + "> が承認しました。"; } else { attachment.color = "danger"; attachment.footer = "<@" + zangyo.approver + "> が却下しました。"; } attachment.title = "<@" + zangyo.applicant + "> - " + zangyo.end_time; attachment.text = zangyo.reason; attachment.ts = zangyo.approved_at; return attachment; }, function(attachments){ var reply; if (attachments.length == 0) { reply = range + "は残業申請1件もないっす。。。"; } else { reply = { "text": range + "の残業申請一覧", "attachments": attachments } } bot.reply(message, reply); }); }; function findTargetZangyo(team_id, range, getMessageItem, replyWholeMessage) { var begin_date, end_date; switch (range) { case zangyo_bot.ranges.today: var today = moment().format("YYYY-MM-DD"); begin_date = today; end_date = today break; case zangyo_bot.ranges.yesterday: var yesterday = moment().subtract(1, 'days').format("YYYY-MM-DD"); begin_date = yesterday; end_date = yesterday; break; case zangyo_bot.ranges.day_before_yesterday: var day_before_yesterday = moment().subtract(2, 'days').format("YYYY-MM-DD"); begin_date = day_before_yesterday; end_date = day_before_yesterday; break; case zangyo_bot.ranges.this_week: begin_date = moment().startOf('isoweek').format("YYYY-MM-DD"); end_date = moment().endOf('isoweek').format("YYYY-MM-DD"); break; case zangyo_bot.ranges.last_week: var lastweek = moment().subtract(1, 'weeks'); begin_date = lastweek.startOf('isoweek').format("YYYY-MM-DD"); end_date = lastweek.endOf('isoweek').format("YYYY-MM-DD"); break; case zangyo_bot.ranges.past_one_week: begin_date = moment().subtract(7, 'days').format("YYYY-MM-DD"); end_date = moment().subtract(1, 'days').format("YYYY-MM-DD"); break; default: var target = range.match(/\d{1,2}/g); begin_date = moment().format("YYYY-") + target[0] + '-' + target[1]; end_date = moment().format("YYYY-") + target[0] + '-' + target[1]; break; } controller.storage.teams.get(team_id, function(err, team) { var list = []; for (var i = 0; i < team.zangyos.length; i++) { var zangyo = team.zangyos[i]; if (begin_date <= zangyo.date && zangyo.date <= end_date) { list.push(getMessageItem(zangyo)); } } replyWholeMessage(list); }); }; return zangyo_bot; } module.exports = ZangyoBot;
compare dates
lib/zangyo_bot.js
compare dates
<ide><path>ib/zangyo_bot.js <ide> break; <ide> default: <ide> var target = range.match(/\d{1,2}/g); <del> begin_date = moment().format("YYYY-") + target[0] + '-' + target[1]; <del> end_date = moment().format("YYYY-") + target[0] + '-' + target[1]; <add> begin_date = moment().format("YYYY-") + ('0' + target[0]).slice(-2) + '-' + ('0' + target[1]).slice(-2); <add> end_date = moment().format("YYYY-") + ('0' + target[0]).slice(-2) + '-' + ('0' + target[1]).slice(-2); <ide> break; <ide> } <ide>
Java
apache-2.0
911315bb9d71d368a06f2cd7b5a9abfb0183af90
0
LogNet/grpc-spring-boot-starter,LogNet/grpc-spring-boot-starter
package org.lognet.springboot.grpc; import com.pszymczyk.consul.junit.ConsulResource; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.examples.GreeterGrpc; import io.grpc.examples.GreeterOuterClass; import org.junit.AfterClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.lognet.springboot.grpc.demo.DemoApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; import java.util.List; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest(classes = DemoApp.class, properties = {"spring.cloud.config.enabled:false"}) public class ConsulRegistrationTest { @ClassRule public static final ConsulResource consul(){ int port = SocketUtils.findAvailableTcpPort(); ConsulResource consulResource = new ConsulResource(port); System.setProperty("spring.cloud.consul.port",String.valueOf(port)); return consulResource; } @AfterClass public static void clear(){ System.clearProperty("spring.cloud.consul.port"); } @Autowired private DiscoveryClient discoveryClient; @Test public void contextLoads() throws ExecutionException, InterruptedException { List<ServiceInstance> instances = discoveryClient.getInstances("grpc-grpc-demo"); assertFalse(instances.isEmpty()); ServiceInstance serviceInstance = instances.get(0); ManagedChannel channel = ManagedChannelBuilder.forAddress(serviceInstance.getHost(), serviceInstance.getPort()) .usePlaintext() .build(); final GreeterGrpc.GreeterFutureStub greeterFutureStub = GreeterGrpc.newFutureStub(channel); final GreeterOuterClass.HelloRequest helloRequest =GreeterOuterClass.HelloRequest.newBuilder().setName("Bob").build(); final String reply = greeterFutureStub.sayHello(helloRequest).get().getMessage(); assertNotNull("Replay should not be null",reply); } }
grpc-spring-boot2-starter-demo/src/test/java/org/lognet/springboot/grpc/ConsulRegistrationTest.java
package org.lognet.springboot.grpc; import com.pszymczyk.consul.junit.ConsulResource; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.examples.GreeterGrpc; import io.grpc.examples.GreeterOuterClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.lognet.springboot.grpc.demo.DemoApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest(classes = DemoApp.class, properties = {"spring.cloud.config.enabled:false"}) public class ConsulRegistrationTest { @ClassRule public static final ConsulResource consul = new ConsulResource(8500); @Autowired private DiscoveryClient discoveryClient; @Test public void contextLoads() throws ExecutionException, InterruptedException { List<ServiceInstance> instances = discoveryClient.getInstances("grpc-grpc-demo"); assertFalse(instances.isEmpty()); ServiceInstance serviceInstance = instances.get(0); ManagedChannel channel = ManagedChannelBuilder.forAddress(serviceInstance.getHost(), serviceInstance.getPort()) .usePlaintext() .build(); final GreeterGrpc.GreeterFutureStub greeterFutureStub = GreeterGrpc.newFutureStub(channel); final GreeterOuterClass.HelloRequest helloRequest =GreeterOuterClass.HelloRequest.newBuilder().setName("Bob").build(); final String reply = greeterFutureStub.sayHello(helloRequest).get().getMessage(); assertNotNull("Replay should not be null",reply); } }
Consul use random port
grpc-spring-boot2-starter-demo/src/test/java/org/lognet/springboot/grpc/ConsulRegistrationTest.java
Consul use random port
<ide><path>rpc-spring-boot2-starter-demo/src/test/java/org/lognet/springboot/grpc/ConsulRegistrationTest.java <ide> import io.grpc.ManagedChannelBuilder; <ide> import io.grpc.examples.GreeterGrpc; <ide> import io.grpc.examples.GreeterOuterClass; <add>import org.junit.AfterClass; <ide> import org.junit.ClassRule; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.springframework.cloud.client.ServiceInstance; <ide> import org.springframework.cloud.client.discovery.DiscoveryClient; <ide> import org.springframework.test.context.junit4.SpringRunner; <add>import org.springframework.util.SocketUtils; <ide> <ide> import java.util.List; <ide> import java.util.concurrent.ExecutionException; <ide> public class ConsulRegistrationTest { <ide> <ide> @ClassRule <del> public static final ConsulResource consul = new ConsulResource(8500); <add> public static final ConsulResource consul(){ <add> int port = SocketUtils.findAvailableTcpPort(); <add> ConsulResource consulResource = new ConsulResource(port); <add> System.setProperty("spring.cloud.consul.port",String.valueOf(port)); <add> return consulResource; <add> } <add> @AfterClass <add> public static void clear(){ <add> System.clearProperty("spring.cloud.consul.port"); <add> } <ide> <ide> @Autowired <ide> private DiscoveryClient discoveryClient; <ide> final GreeterOuterClass.HelloRequest helloRequest =GreeterOuterClass.HelloRequest.newBuilder().setName("Bob").build(); <ide> final String reply = greeterFutureStub.sayHello(helloRequest).get().getMessage(); <ide> assertNotNull("Replay should not be null",reply); <del> <del> <ide> } <ide> }
Java
apache-2.0
d0eae1eaba7743a536784521ae985b8b9eed228c
0
apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena
/* * 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 /////////////// package jena; import static org.apache.jena.atlas.logging.LogCtl.setCmdLogging; import java.io.ByteArrayOutputStream ; import java.io.File ; import java.io.FileOutputStream ; import java.io.PrintStream ; import java.net.MalformedURLException ; import java.net.URL ; import java.text.SimpleDateFormat ; import java.util.* ; import java.util.regex.Pattern ; import java.util.regex.PatternSyntaxException ; import org.apache.jena.ext.xerces.util.XMLChar; import org.apache.jena.ontology.Individual ; import org.apache.jena.ontology.OntModel ; import org.apache.jena.ontology.OntModelSpec ; import org.apache.jena.rdf.model.* ; import org.apache.jena.shared.JenaException ; import org.apache.jena.util.FileManager ; import org.apache.jena.util.iterator.ExtendedIterator ; import org.apache.jena.util.iterator.WrappedIterator ; import org.apache.jena.vocabulary.OWL ; import org.apache.jena.vocabulary.RDF ; import org.apache.jena.vocabulary.RDFS ; import org.apache.jena.vocabulary.XSD ; /** * <p> * A vocabulary generator, that will consume an ontology or other vocabulary file, * and generate a Java file with the constants from the vocabulary compiled in. * Designed to be highly flexible and customisable. * </p> */ public class schemagen { static { setCmdLogging(); } // Constants ////////////////////////////////// /** The namespace for the configuration model is {@value} */ public static final String NS = "http://jena.hpl.hp.com/2003/04/schemagen#"; /** The default location of the configuration model is {@value} */ public static final String DEFAULT_CONFIG_URI = "file:schemagen.rdf"; /** The default marker string for denoting substitutions is {@value} */ public static final String DEFAULT_MARKER = "%"; /** Default template for writing out value declarations */ public static final String DEFAULT_TEMPLATE = "public static final %valclass% %valname% = M_MODEL.%valcreator%( \"%valuri%\" );"; /** Default template for writing out individual declarations */ public static final String DEFAULT_INDIVIDUAL_TEMPLATE = "public static final %valclass% %valname% = M_MODEL.%valcreator%( \"%valuri%\", %valtype% );"; /** Default template for writing out individual declarations for non-ontology vocabularies */ public static final String DEFAULT_RDFS_INDIVIDUAL_TEMPLATE = "public static final %valclass% %valname% = M_MODEL.%valcreator%( \"%valuri%\" );"; /** Default template for the file header */ public static final String DEFAULT_HEADER_TEMPLATE = "/* CVS $" + "Id: $ */%nl%%package% %nl%%imports% %nl%/**%nl% * Vocabulary definitions from %sourceURI% %nl% * @author Auto-generated by schemagen on %date% %nl% */"; /** Default line length for comments before wrap */ public static final int COMMENT_LENGTH_LIMIT = 80; /** List of Java reserved keywords, see <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html">this list</a>. */ public static final String[] JAVA_KEYWORDS = { "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while" }; // Static variables ////////////////////////////////// private static List<String> KEYWORD_LIST; static { KEYWORD_LIST = Arrays.asList( JAVA_KEYWORDS ); } // Instance variables ////////////////////////////////// /** Schemagen options interface */ protected SchemagenOptions m_options; /** The model that contains the input source */ protected OntModel m_source; /** The output stream we write to */ protected PrintStream m_output; /** Option definitions */ /** Stack of replacements to apply */ protected List<Replacement> m_replacements = new ArrayList<>(); /** Output file newline char - default is Unix, override with --dos */ protected String m_nl = "\n"; /** Size of indent step */ protected int m_indentStep = 4; /** Set of names used so far */ protected Set<String> m_usedNames = new HashSet<>(); /** Map from resources to java names */ protected Map<Resource,String> m_resourcesToNames = new HashMap<>(); /** List of allowed namespace URI strings for admissible values */ protected List<String> m_includeURI = new ArrayList<>(); // Constructors ////////////////////////////////// // External signature methods ////////////////////////////////// /* Main entry point. See Javadoc for details of the many command line arguments */ public static void main( String... args ) { try { new schemagen().go( args ); } catch (SchemagenException e) { System.err.println( "Schemagen failed to run:" ); System.err.println( e.getMessage() ); if (e.getCause() != null) { System.err.println( "Caused by: " + e.getCause().getMessage() ); } System.exit( 1 ); } } // Internal implementation methods ////////////////////////////////// /** Read the configuration parameters and do setup */ protected void go( String[] args ) { go( new SchemagenOptionsImpl( args ) ); } /** Handle initial configuration options, then initiate processing */ protected void go( SchemagenOptions options ) { m_options = options; // check for user requesting help if (m_options.hasHelpOption()) { usage(); } // got the configuration, now we can begin processing processInput(); } /** The sequence of steps to process an entire file */ protected void processInput() { addIncludes(); determineLanguage(); selectInput(); selectOutput(); setGlobalReplacements(); processHeader(); writeClassDeclaration(); writeInitialDeclarations(); writeProperties(); writeClasses(); writeIndividuals(); writeDatatypes(); writeClassClose(); processFooter(); closeOutput(); } /** Add the included files */ protected void addIncludes() { // add any extra uri's that are allowed in the filter m_includeURI.addAll( m_options.getIncludeOption() ); } /** Create the source model after determining which input language */ protected void determineLanguage() { OntModelSpec s = null; if (m_options.hasLangRdfsOption()) { // RDFS language specified if (m_options.hasUseInfOption()) { s = OntModelSpec.RDFS_MEM_RDFS_INF; } else { s = OntModelSpec.RDFS_MEM; } } else { // owl is the default // s = OntModelSpec.getDefaultSpec( ProfileRegistry.OWL_LANG ); if (m_options.hasUseInfOption()) { s = OntModelSpec.OWL_MEM_RULE_INF; } else { s = OntModelSpec.OWL_MEM; } } m_source = ModelFactory.createOntologyModel( s, null ); m_source.getDocumentManager().setProcessImports( false ); // turn off strict checking on request if (m_options.hasNoStrictOption()) { m_source.setStrictMode( false ); } } /** Identify the URL that is to be read in and translated to a vocabulary file, and load the source into the source model */ protected void selectInput() { if (!m_options.hasInputOption()) { usage(); } String input = SchemagenUtils.urlCheck( m_options.getInputOption().getURI() ); String syntax = m_options.getEncodingOption(); try { FileManager.get().readModel( m_source, input, syntax ); } catch (JenaException e) { abort( "Failed to read input source " + input, e ); } } /** Identify the file we are to write the output to */ protected void selectOutput() { String outFile = m_options.getOutputOption(); if (outFile == null) { m_output = System.out; } else { try { // check for package name String packageName = m_options.getPackagenameOption(); if (packageName != null) { String packagePath = ""; // build the package path (e.g. com.foo.bar -> /com/foo/bar) for (String p: packageName.split( "\\." )) { packagePath = packagePath + File.separator + p; } if (!outFile.endsWith( packagePath )) { outFile = outFile + packagePath; } } File out = new File( outFile ); if (!out.exists() && !outFile.endsWith( ".java" )) { // create the directory if needed out.mkdirs(); } if (out.isDirectory()) { // create a file in this directory named classname.java String fileName = outFile + File.separator + getClassName() + ".java"; out = new File( fileName ); } m_output = new PrintStream( new FileOutputStream( out ) ); } catch (Exception e) { abort( "I/O error while trying to open file for writing: " + outFile, e ); } } // check for DOS line endings if (m_options.hasDosOption()) { m_nl = "\r\n"; } } /** Process the header at the start of the file, if defined */ protected void processHeader() { String header = m_options.hasHeaderOption() ? m_options.getHeaderOption() : DEFAULT_HEADER_TEMPLATE; // user can turn of header processing, default is to have it on if (!m_options.hasNoheaderOption()) { writeln( 0, substitute( header ) ); } else { // we have to do the imports at least writeln( 0, "import org.apache.jena.rdf.model.*;" ); if (m_options.hasOntologyOption()) { writeln( 0, "import org.apache.jena.ontology.*;" ); } if (m_options.hasIncludeSourceOption()) { writeln( 0, "import java.io.ByteArrayInputStream;" ); } } } /** Process the footer at the end of the file, if defined */ protected void processFooter() { String footer = m_options.getFooterOption(); if (footer != null) { writeln( 0, substitute( footer ) ); } } /** The list of replacements that are always available */ protected void setGlobalReplacements() { addReplacementPattern( "date", new SimpleDateFormat( "dd MMM yyyy HH:mm").format( new Date() ) ); addReplacementPattern( "package", m_options.hasPackagenameOption() ? ("package " + m_options.getPackagenameOption() + ";") : "" ); addReplacementPattern( "imports", getImports() ); addReplacementPattern( "classname", getClassName() ); addReplacementPattern( "nl", m_nl ); // protect \ in Windows file pathnames // looks for file:.* or C:.* (or variants thereof) String source = m_options.getInputOption().getURI(); if (source.matches( "(file:|[A-Za-z]:).*$" )) { source = source.replace( "\\", "\\\\" ); } addReplacementPattern( "sourceURI", source ); } /** Add a pattern-value pair to the list of available patterns */ protected void addReplacementPattern( String key, String replacement ) { if (replacement != null && key != null) { String marker = m_options.getMarkerOption(); marker = (marker == null) ? DEFAULT_MARKER : marker; try { m_replacements.add( new Replacement( Pattern.compile( marker + key + marker ), replacement ) ); } catch (PatternSyntaxException e) { abort( "Malformed regexp pattern " + marker + key + marker, e ); } } } /** Pop n replacements off the stack */ protected void pop( int n ) { for (int i = 0; i < n; i++) { m_replacements.remove( m_replacements.size() - 1 ); } } /** Close the output file */ protected void closeOutput() { m_output.flush(); m_output.close(); } /** Abort due to exception */ protected void abort( String msg, Exception cause ) { throw new SchemagenException( msg, cause ); } /** Print usage message and abort */ protected void usage() { System.err.println( "Usage:" ); System.err.println( " java jena.schemagen [options ...]" ); System.err.println(); System.err.println( "Commonly used options include:" ); System.err.println( " -i <input> the source document as a file or URL." ); System.err.println( " -n <name> the name of the created Java class." ); System.err.println( " -a <uri> the namespace URI of the source document." ); System.err.println( " -o <file> the file to write the generated class into." ); System.err.println( " -o <dir> the directory in which the generated Java class is created." ); System.err.println( " By default, output goes to stdout." ); System.err.println( " -e <encoding> the encoding of the input document (N3, RDF/XML, etc)." ); System.err.println( " -c <config> a filename or URL for an RDF document containing " ); System.err.println( " configuration parameters." ); System.err.println(); System.err.println( "Many other options are available. See the schemagen HOWTO in the " ); System.err.println( "Jena documentation for full details." ); System.exit( 1 ); } /** Use the current replacements list to do the subs in the given string */ protected String substitute( String sIn ) { String s = sIn; for ( Replacement r : m_replacements ) { s = r.pattern.matcher( s ).replaceAll( r.sub ); } return s; } /** Add the appropriate indent to a buffer */ protected int indentTo( int i, StringBuilder buf ) { int indent = i * m_indentStep; for (int j = 0; j < indent; j++) { buf.append( ' ' ); } return indent; } /** Write a blank line, with indent and newline */ protected void writeln( int indent ) { writeln( indent, "" ); } /** Write out the given string with n spaces of indent, with newline */ protected void writeln( int indent, String s ) { write( indent, s ); m_output.print( m_nl ); } /** Write out the given string with n spaces of indent */ protected void write( int indentLevel, String s ) { for (int i = 0; i < (m_indentStep * indentLevel); i++) { m_output.print( " " ); } m_output.print( s ); } /** Determine the list of imports to include in the file */ protected String getImports() { StringBuilder buf = new StringBuilder(); buf.append( "import org.apache.jena.rdf.model.*;" ); buf.append( m_nl ); if (useOntology()) { buf.append( "import org.apache.jena.ontology.*;" ); buf.append( m_nl ); } if (includeSource()) { buf.append( "import java.io.ByteArrayInputStream;" ); buf.append( m_nl ); } return buf.toString(); } /** Determine the class name of the vocabulary from the URI */ protected String getClassName() { // if a class name is given, just use that if (m_options.hasClassnameOption()) { return m_options.getClassnameOption(); } // otherwise, we generate a name based on the URI String uri = m_options.getInputOption().getURI(); // remove any suffixes uri = (uri.endsWith( "#" )) ? uri.substring( 0, uri.length() - 1 ) : uri; uri = (uri.endsWith( ".daml" )) ? uri.substring( 0, uri.length() - 5 ) : uri; uri = (uri.endsWith( ".owl" )) ? uri.substring( 0, uri.length() - 4 ) : uri; uri = (uri.endsWith( ".rdf" )) ? uri.substring( 0, uri.length() - 4 ) : uri; uri = (uri.endsWith( ".rdfs" )) ? uri.substring( 0, uri.length() - 5 ) : uri; uri = (uri.endsWith( ".n3" )) ? uri.substring( 0, uri.length() - 3 ) : uri; uri = (uri.endsWith( ".xml" )) ? uri.substring( 0, uri.length() - 4 ) : uri; uri = (uri.endsWith( ".ttl" )) ? uri.substring( 0, uri.length() - 4 ) : uri; // now work back to the first non name character from the end int i = uri.length() - 1; for (; i > 0; i--) { if (!Character.isUnicodeIdentifierPart( uri.charAt( i ) ) && uri.charAt( i ) != '-') { i++; break; } } String name = uri.substring( i ); // optionally add name suffix if (m_options.hasClassnameSuffixOption()) { name = name + m_options.getClassnameSuffixOption(); } // now we make the name into a legal Java identifier return asLegalJavaID( name, true ); } /** Answer true if we are using ontology terms in this vocabulary */ protected boolean useOntology() { return m_options.hasOntologyOption(); } /** Answer true if all comments are suppressed */ protected boolean noComments() { return m_options.hasNoCommentsOption(); } /** Answer true if ontology source code is to be included */ protected boolean includeSource() { return m_options.hasIncludeSourceOption(); } /** Converts to a legal Java identifier; capitalise first char if cap is true */ protected String asLegalJavaID( String s, boolean cap ) { StringBuilder buf = new StringBuilder(); int i = 0; // treat the first character specially - must be able to start a Java ID, may have to up-case try { for (; !Character.isJavaIdentifierStart( s.charAt( i )); i++) { /**/ } } catch (StringIndexOutOfBoundsException e) { System.err.println( "Could not identify legal Java identifier start character in '" + s + "', replacing with __" ); return "__"; } buf.append( cap ? Character.toUpperCase( s.charAt( i ) ) : s.charAt( i ) ); // copy the remaining characters - replace non-legal chars with '_' for (++i; i < s.length(); i++) { char c = s.charAt( i ); buf.append( Character.isJavaIdentifierPart( c ) ? c : '_' ); } // check for illegal keyword if (KEYWORD_LIST.contains( buf.toString() )) { buf.append( '_' ); } return buf.toString(); } /** The opening class declaration */ protected void writeClassDeclaration() { write( 0, "public class " ); write( 0, getClassName() ); write( 0, " " ); if (m_options.hasClassdecOption()) { write( 0, m_options.getClassdecOption() ); } writeln( 0, "{" ); } /** The close of the class decoration */ protected void writeClassClose() { writeln( 0, "}" ); } /** Write the declarations at the head of the class */ protected void writeInitialDeclarations() { writeModelDeclaration(); writeSource(); writeNamespace(); writeOntologyVersionInfo(); if (m_options.hasDeclarationsOption()) { writeln( 0, m_options.getDeclarationsOption() ); } } /** Write the declaration of the model */ protected void writeModelDeclaration() { if (useOntology()) { String lang = "OWL"; if (m_options.hasLangRdfsOption()) { lang = "RDFS"; } writeln( 1, "/** <p>The ontology model that holds the vocabulary terms</p> */" ); writeln( 1, "private static final OntModel M_MODEL = ModelFactory.createOntologyModel( OntModelSpec." + lang + "_MEM, null );" ); } else { writeln( 1, "/** <p>The RDF model that holds the vocabulary terms</p> */" ); writeln( 1, "private static final Model M_MODEL = ModelFactory.createDefaultModel();" ); } writeln( 1 ); } /** Write the source code of the input model into the file itself */ protected void writeSource() { if (includeSource()) { // first save a copy of the source in compact form into a buffer ByteArrayOutputStream bos = new ByteArrayOutputStream(); RDFWriter rw = m_source.getWriter( "Turtle" ); rw.setProperty( "objectLists", Boolean.FALSE.toString() ); rw.write( m_source, bos, null ); String output = bos.toString(); // now we embed each line of the source in the output writeln( 1, "private static final String SOURCE = " ); boolean first = true; StringTokenizer st = new StringTokenizer( output, "\n" ); while (st.hasMoreTokens()) { String tok = st.nextToken(); if (tok.endsWith( "\r" )) { tok = tok.substring( 0, tok.length() - 1 ); } write( 2, first ? " " : " + " ); write( 0, "\"" ); write( 0, protectQuotes( tok ) ); writeln( 2, "\\n\"" ); first = false; } // then we reference the string constant when reading the source // note that we avoid StringReader due to charset encoding issues writeln( 1, ";" ); writeln( 0, "" ); writeln( 1, "/** Read the ontology definition into the source model */ " ); writeln( 1, "static { " ); writeln( 2, "M_MODEL.read( new ByteArrayInputStream( SOURCE.getBytes() ), null, \"N3\" );" ); writeln( 1, "}" ); writeln( 0, "" ); } } /** Protect any double quotes in the given string so that it's a legal Java String */ private String protectQuotes( String s ) { return s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\"", "\\\\\"" ); } /** Write owl:versionInfo string if it exists **/ protected void writeOntologyVersionInfo() { String versionInfo = getOntologyElementVersionInfo(); if (null != versionInfo) { writeln( 1, "/** <p>The ontology's owl:versionInfo as a string</p> */" ); writeln( 1, "public static final String VERSION_INFO = \"" + protectQuotes(versionInfo) + "\";" ); writeln( 1 ); } } /** Write the string and resource that represent the namespace */ protected void writeNamespace() { String nsURI = determineNamespaceURI(); writeln( 1, "/** <p>The namespace of the vocabulary as a string</p> */" ); writeln( 1, "public static final String NS = \"" + nsURI + "\";" ); writeln( 1 ); writeln( 1, "/** <p>The namespace of the vocabulary as a string</p>" ); writeln( 1, " * @return namespace as String" ); writeln( 1, " * @see #NS */" ); writeln( 1, "public static String getURI() {return NS;}" ); writeln( 1 ); writeln( 1, "/** <p>The namespace of the vocabulary as a resource</p> */" ); writeln( 1, "public static final Resource NAMESPACE = M_MODEL.createResource( NS );" ); writeln( 1 ); } /** Determine what the namespace URI for this vocabulary is */ protected String determineNamespaceURI() { // we have a sequence of strategies for determining the ontology namespace String ns = getOptionNamespace(); if (ns == null) { ns = getDefaultPrefixNamespace(); } if (ns == null) { ns = getOntologyElementNamespace(); } if (ns == null) { ns = guessNamespace(); } // did we get one? if (ns == null) { abort( "Could not determine the base URI for the input vocabulary", null ); } m_includeURI.add( ns ); return ns; } /** User has set namespace via a schemagen option */ protected String getOptionNamespace() { return m_options.hasNamespaceOption() ? m_options.getNamespaceOption().getURI() : null; } /** Document has set an empty prefix for the model */ protected String getDefaultPrefixNamespace() { // alternatively, the default namespace may be set in the prefix mapping read from the input document String defaultNS = m_source.getNsPrefixURI( "" ); if (defaultNS == null) { defaultNS = m_source.getBaseModel().getNsPrefixURI( "" ); } return defaultNS; } /** Document has an owl:Ontology or daml:Ontology element */ protected String getOntologyElementVersionInfo() { String versionInfo = null; Resource ontologyClass = m_source.getProfile().ONTOLOGY(); if (null != ontologyClass) { StmtIterator i = m_source.getBaseModel().listStatements( null, RDF.type, ontologyClass ); if (i.hasNext()) { Resource ont = i.nextStatement().getSubject(); StmtIterator j = m_source.getBaseModel().listStatements( ont, OWL.versionInfo, (RDFNode)null ); if (j.hasNext()) { versionInfo = j.nextStatement().getObject().asLiteral().getLexicalForm(); // check for ambiguous answers if (j.hasNext()) { System.err.println( "Warning: ambiguous owl:versionInfo - there are more than one owl:versionInfo statements." ); System.err.println( "Picking first choice: " + versionInfo + ". Other choices are:" ); while (j.hasNext()) { System.err.print( " " ); System.err.print( j.nextStatement().getObject().toString() ); } System.err.println(); } } // check for ambiguous answers if (i.hasNext()) { System.err.println( "Warning: ambiguous owl:versionInfo - there is more than one owl:Ontology element." ); System.err.println( "Picking first choice: " + ont.getURI() + ". Other choices are:" ); while (i.hasNext()) { System.err.print( " " ); System.err.print( i.nextStatement().getObject().toString() ); } System.err.println(); } } } return versionInfo; } /** Document has an owl:Ontology or daml:Ontology element */ protected String getOntologyElementNamespace() { // if we are using an ontology model, we can get the namespace URI from the ontology element String uri = null; StmtIterator i = m_source.getBaseModel() .listStatements( null, RDF.type, m_source.getProfile().ONTOLOGY() ); if (i.hasNext()) { Resource ont = i.nextStatement().getSubject(); uri = ont.getURI(); // ensure ends with namespace separator char char ch = uri.charAt( uri.length() - 1 ); boolean endsWithNCNameCh = XMLChar.isNCName( ch ); uri = endsWithNCNameCh ? uri + "#" : uri; // check for ambiguous answers if (i.hasNext()) { System.err.println( "Warning: ambiguous default namespace - there is more than one owl:Ontology element." ); System.err.println( "Picking first choice: " + uri + ". Other choices are:" ); while (i.hasNext()) { System.err.print( " " ); System.err.print( i.nextStatement().getString() ); } System.err.println(); System.err.println( "Use the -a option to specify a particular namespace if required." ); } } return uri; } /** Guess the URI from the most prevalent URI */ protected String guessNamespace() { Map<String,Integer> nsCount = new HashMap<>(); // count all of the namespaces used in the model for (StmtIterator i = m_source.listStatements(); i.hasNext(); ) { Statement s = i.next(); countNamespace( s.getSubject(), nsCount ); countNamespace( s.getPredicate(), nsCount ); if (s.getObject().isResource()) { countNamespace( s.getResource(), nsCount ); } } // now find the maximal element String ns = null; int max = 0; for ( String nsKey : nsCount.keySet() ) { // we ignore the usual suspects if ( !( OWL.getURI().equals( nsKey ) || RDF.getURI().equals( nsKey ) || RDFS.getURI().equals( nsKey ) || XSD.getURI().equals( nsKey ) ) ) { // not an ignorable namespace int count = nsCount.get( nsKey ).intValue(); if ( count > max ) { // highest count seen so far max = count; ns = nsKey; } } } return ns; } /** Record a use of the given namespace in the count map */ private void countNamespace( Resource r, Map<String,Integer> nsCount ) { if (!r.isAnon()) { String ns = r.getNameSpace(); // increment the count for this namespace Integer count = nsCount.containsKey( ns ) ? (Integer) nsCount.get( ns ) : new Integer( 0 ); Integer count1 = new Integer( count.intValue() + 1 ); nsCount.put( ns, count1 ); } } /** Write the list of properties */ protected void writeProperties() { if (m_options.hasNopropertiesOption()) { return; } if (m_options.hasPropertySectionOption()) { writeln( 0, m_options.getPropertySectionOption()); } if (useOntology()) { writeObjectProperties(); writeDatatypeProperties(); writeAnnotationProperties(); // we also write out the RDF properties, to mop up any props that are not stated as // object, datatype or annotation properties writeRDFProperties( true ); } else { writeRDFProperties( false ); } } /** Write any object properties in the vocabulary */ protected void writeObjectProperties() { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; if (!m_options.hasLangRdfsOption()) { for (Iterator<? extends RDFNode> i = sorted( m_source.listObjectProperties() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "ObjectProperty", "createObjectProperty", "_PROP" ); } } } /** Write any datatype properties in the vocabulary */ protected void writeDatatypeProperties() { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; if (!m_options.hasLangRdfsOption()) { for (Iterator<? extends RDFNode> i = sorted( m_source.listDatatypeProperties() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "DatatypeProperty", "createDatatypeProperty", "_PROP" ); } } } /** Write any annotation properties in the vocabulary */ protected void writeAnnotationProperties() { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; if (!m_options.hasLangRdfsOption()) { for (Iterator<? extends RDFNode> i = sorted( m_source.listAnnotationProperties() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "AnnotationProperty", "createAnnotationProperty", "_PROP" ); } } } /** Write any vanilla RDF properties in the vocabulary */ protected void writeRDFProperties( boolean useOntProperty ) { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; String propType = useOntProperty ? "OntProperty" : "Property"; // select the appropriate properties based on the language choice Resource[] props; if (m_options.hasLangOwlOption()) { props = new Resource[] {OWL.ObjectProperty, OWL.DatatypeProperty, RDF.Property}; } else { props = new Resource[] {RDF.Property}; } // collect the properties to be written List<Resource> propertyResources = new ArrayList<>(); for ( Resource prop : props ) { for ( StmtIterator i = m_source.listStatements( null, RDF.type, prop ); i.hasNext(); ) { propertyResources.add( i.nextStatement().getSubject() ); } } // now write the properties for (Iterator<? extends RDFNode> i = sorted( propertyResources ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, propType, "create" + propType, "_PROP" ); } } /** Write any classes in the vocabulary */ protected void writeClasses() { if (m_options.hasNoclassesOption()) { return; } if (m_options.hasClassSectionOption()) { writeln( 0, m_options.getClassSectionOption()); } if (useOntology()) { writeOntClasses(); } else { writeRDFClasses(); } } /** Write classes as ontology terms */ protected void writeOntClasses() { String template = m_options.hasClassTemplateOption() ? m_options.getClassTemplateOption() : DEFAULT_TEMPLATE; for (Iterator<? extends RDFNode> i = sorted( m_source.listClasses() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "OntClass", "createClass", "_CLASS" ); } } /** Write classes as vanilla RDF terms */ protected void writeRDFClasses() { String template = m_options.hasClassTemplateOption() ? m_options.getClassTemplateOption() : DEFAULT_TEMPLATE; // make sure we're looking for the appropriate type of class Resource cls = OWL.Class; if (m_options.hasLangRdfsOption()) { cls = RDFS.Class; } // collect the classes to list List<Resource> classes = m_source.listStatements( null, RDF.type, cls ).mapWith( s -> s.getSubject()).toList(); for (Iterator<? extends RDFNode> i = sorted( classes ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "Resource", "createResource", "_CLASS" ); } } /** Write any instances (individuals) in the vocabulary */ protected void writeIndividuals() { if (m_options.hasNoindividualsOption()) { return; } if (m_options.hasIndividualsSectionOption()) { writeln( 0, m_options.getIndividualsSectionOption() ); } if (useOntology()) { writeOntIndividuals(); } else { writeRDFIndividuals(); } } /** Write individuals as ontology terms */ protected void writeOntIndividuals() { String template = m_options.hasIndividualTemplateOption() ? m_options.getIndividualTemplateOption() : DEFAULT_INDIVIDUAL_TEMPLATE; for (Iterator<? extends RDFNode> i = selectIndividuals(); i.hasNext(); ) { Individual ind = ((Resource) i.next()).as( Individual.class ); // do we have a local class resource Resource cls = ind.getOntClass(); if (cls == null) { cls = OWL.Thing; } String varName = m_resourcesToNames.get( cls ); String valType = (varName != null) ? varName : "M_MODEL.createClass( \"" + cls.getURI() + "\" )"; // push the individuals type onto the stack addReplacementPattern( "valtype", valType ); writeValue( ind, template, "Individual", "createIndividual", "_INSTANCE" ); pop( 1 ); } } /** Write individuals as vanilla RDF terms */ protected void writeRDFIndividuals() { String template = m_options.hasIndividualTemplateOption() ? m_options.getIndividualTemplateOption() : DEFAULT_RDFS_INDIVIDUAL_TEMPLATE; for (Iterator<? extends RDFNode> i = selectIndividuals(); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "Resource", "createResource", "_INSTANCE" ); } } /** Answer an iterator over the individuals selected for output */ protected ExtendedIterator<? extends RDFNode> selectIndividuals() { List<Resource> candidates = new ArrayList<>(); for (StmtIterator i = m_source.listStatements( null, RDF.type, (RDFNode) null ); i.hasNext(); ) { Statement candidate = i.nextStatement(); if (candidate.getObject().isResource()) { Resource candObj = candidate.getResource(); Resource candSubj = candidate.getSubject(); // ignore RDFS and OWL builtins if (!candObj.isAnon()) { String candTypeURI = candObj.getURI(); if (candTypeURI.startsWith( RDF.getURI() ) || candTypeURI.startsWith( OWL.getURI() ) || candTypeURI.startsWith( RDFS.getURI() )) { continue; } } // note that whether candSubj is included is tested later on by {@link #filter} if (!candSubj.isAnon() && (isIncluded( candObj ) || isIncluded( candSubj )) && !candidates.contains( candSubj )) { candidates.add( candSubj ); } } } return sorted( candidates ); } /** * Answer true if the given resource is accepted for presentation in the output, which * is true iff it is a URI node, whose namespace is one of the accepted namespaces in * {@link #m_includeURI}. * @param r A resource to test * @return True if the resource is to be included in the generated output */ protected boolean isIncluded( Resource r ) { boolean accepted = false; if (!r.isAnon()) { String uri = r.getURI(); for (Iterator<String> j = m_includeURI.iterator(); !accepted && j.hasNext(); ) { accepted = uri.startsWith( j.next() ); } } return accepted; } /** Write any datatypes in the vocabulary */ protected void writeDatatypes() { if (m_options.hasNodatatypesOption()) { return; } if (m_options.hasDatatypesSectionOption()) { writeln( 0, m_options.getDatatypesSectionOption() ); } String template = m_options.hasDatatypeTemplateOption() ? m_options.getDatatypeTemplateOption() : DEFAULT_TEMPLATE; // Cannot create a full RDFDatatype object since we don't know how to parse these custom types, but we can at least specify a Resource for (Iterator<? extends RDFNode> i = selectDatatypes(); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "Resource", "createResource", "_DATATYPE" ); } } /** Answer an iterator over the datatypes selected for output */ protected ExtendedIterator<? extends RDFNode> selectDatatypes() { List<Resource> candidates = new ArrayList<>(); for (StmtIterator i = m_source.listStatements( null, RDF.type, RDFS.Datatype ); i.hasNext(); ) { Statement candidate = i.nextStatement(); if (candidate.getObject().isResource()) { Resource candSubj = candidate.getSubject(); // ignore XSD builtins if (!candSubj.isAnon()) { String candTypeURI = candSubj.getURI(); if (candTypeURI.startsWith( XSD.getURI() )) { continue; } } // note that whether candSubj is included is tested later on by {@link #filter} if (!candSubj.isAnon() && !candidates.contains( candSubj )) { candidates.add( candSubj ); } } } return sorted( candidates ); } /** Write the value declaration out using the given template, optionally creating comments */ protected void writeValue( Resource r, String template, String valueClass, String creator, String disambiguator ) { if (!filter( r )) { if (!noComments() && hasComment( r )) { writeln( 1, formatComment( getComment( r ) ) ); } // push the local bindings for the substitution onto the stack addReplacementPattern( "valuri", r.getURI() ); addReplacementPattern( "valname", getValueName( r, disambiguator )); addReplacementPattern( "valclass", valueClass ); addReplacementPattern( "valcreator", creator ); // write out the value writeln( 1, substitute( template ) ); writeln( 1 ); // pop the local replacements off the stack pop( 4 ); } } /** Answer true if the given resource has an rdf:comment */ protected boolean hasComment( Resource r ) { return r.hasProperty( RDFS.comment ) ; } /** Answer all of the commentary on the given resource, as a string */ protected String getComment( Resource r ) { StringBuilder comment = new StringBuilder(); // collect any RDFS or DAML comments attached to the node for (NodeIterator ni = m_source.listObjectsOfProperty( r, RDFS.comment ); ni.hasNext(); ) { RDFNode n = ni.nextNode(); if (n instanceof Literal) { comment.append( ((Literal) n).getLexicalForm().trim() ); } else { System.err.println( "Warning: Comment on resource <" + r.getURI() + "> is not a literal: " + n ); } } return comment.toString(); } /** Format the comment as Javadoc, and limit the line width */ protected String formatComment( String comment ) { StringBuilder buf = new StringBuilder(); buf.append( "/** <p>" ); boolean inSpace = false; int pos = buf.length(); boolean singleLine = true; // now format the comment by compacting whitespace and limiting the line length // add the prefix to the start of each line for (int i = 0; i < comment.length(); i++ ) { char c = comment.charAt( i ); // compress whitespace if (Character.isWhitespace( c )) { if (inSpace) { continue; // more than one space is ignored } else { c = ' '; // map all whitespace to 0x20 inSpace = true; } } else { inSpace = false; } // escapes? if (c == '\\') { c = comment.charAt( ++i ); switch (c) { case 'n': buf.append( m_nl ); pos = indentTo( 1, buf ); buf.append( " * " ); pos += 3; singleLine = false; break; default: // add other escape sequences above break; } } else if (c == '<') { buf.append( "&lt;" ); pos += 4; } else if (c == '>') { buf.append( "&gt;" ); pos += 4; } else if (c == '&') { buf.append( "&amp;" ); pos += 5; } else { // add the char buf.append( c ); pos++; } // wrap any very long lines at 120 chars if ((pos > COMMENT_LENGTH_LIMIT) && (inSpace)) { buf.append( m_nl ); pos = indentTo( 1, buf ); buf.append( " * " ); pos += 3; singleLine = false; } } buf.append( "</p>" ); buf.append( singleLine ? "" : m_nl ); indentTo( singleLine ? 0 : 1, buf ); buf.append( " */" ); return buf.toString(); } /** Answer true if resource r <b>does not</b> show in output */ protected boolean filter( Resource r ) { if (r.isAnon()) { return true; } // if we've already processed this resource once, ignore it next time if (m_resourcesToNames.containsKey( r )) { return true; } // search the allowed URI's for ( String uri : m_includeURI ) { if ( r.getURI().startsWith( uri ) ) { // in return false; } } // we allow individuals whose class is not in the included NS's, unless opt strict-individuals is true */ if (!m_options.hasStrictIndividualsOption()) { for (StmtIterator j = r.listProperties( RDF.type ); j.hasNext(); ) { // we search the rdf:types of this resource Resource typeRes = j.nextStatement().getResource(); if (!typeRes.isAnon()) { String typeURI = typeRes.getURI(); // for any type that is in a permitted NS for ( String uri : m_includeURI ) { if ( typeURI.startsWith( uri ) ) { // in return false; } } } } } // default is out return true; } /** Answer the Java value name for the URI */ protected String getValueName( Resource r, String disambiguator ) { // the id name is basically the local name of the resource, possibly in upper case String name = m_options.hasUcNamesOption() ? getUCValueName( r ) : r.getLocalName(); // must be legal java name = asLegalJavaID( name, false ); // must not clash with an existing name int attempt = 0; String baseName = name; while (m_usedNames.contains( name )) { name = (attempt == 0) ? (name + disambiguator) : (baseName + disambiguator + attempt); attempt++; } // record this name so that we don't use it again (which will stop the vocabulary from compiling) m_usedNames.add( name ); // record the mapping from resource to name m_resourcesToNames.put( r, name ); return name; } /** Answer the local name of resource r mapped to upper case */ protected String getUCValueName( Resource r ) { StringBuilder buf = new StringBuilder(); String localName = r.getLocalName(); char lastChar = 0; for (int i = 0; i < localName.length(); i++) { char c = localName.charAt(i); if (Character.isLowerCase(lastChar) && Character.isUpperCase(c)) { buf.append( '_' ); } buf.append( Character.toUpperCase(c) ); lastChar = c; } return buf.toString(); } /** Answer an iterator that contains the elements of the given list, but sorted by URI */ protected ExtendedIterator<? extends RDFNode> sorted( ExtendedIterator<? extends RDFNode> i ) { return sorted( i.toList() ); } /** Answer an iterator that contains the elements of the given iterator, but sorted by URI */ protected ExtendedIterator<? extends RDFNode> sorted( List<? extends RDFNode> members ) { Collections.sort( members, new Comparator<RDFNode>() { @Override public int compare( RDFNode n0, RDFNode n1 ) { if (n0.isLiteral() || n1.isLiteral()) { if (n0.isLiteral() && n1.isLiteral()) { // two literals Literal l0 = (Literal) n0; Literal l1 = (Literal) n1; return l0.getLexicalForm().compareTo( l1.getLexicalForm() ); } else { return n0.isLiteral() ? -1 : 1; } } else { Resource r0 = (Resource) n0; Resource r1 = (Resource) n1; if (r0.isAnon() && r1.isAnon()) { // two anonID's - the order is important as long as its consistent return r0.getId().toString().compareTo( r1.getId().toString() ); } else if (r0.isAnon()) { return -1; } else if (r1.isAnon()) { return 1; } else { // two named resources return r0.getURI().compareTo( r1.getURI() ); } } }} ); return WrappedIterator.create( members.iterator() ); } //============================================================================== // Inner class definitions //============================================================================== public interface SchemagenOptions { /* Constants for the various options we can set */ public enum OPT { /** Select an alternative config file; use <code>-c &lt;filename&gt;</code> on command line */ CONFIG_FILE, /** Turn off all comment output; use <code>--nocomments</code> on command line; use <code>sgen:noComments</code> in config file */ NO_COMMENTS, /** Nominate the URL of the input document; use <code>-i &lt;URL&gt;</code> on command line; use <code>sgen:input</code> in config file */ INPUT, /** Specify that the language of the source is DAML+OIL; use <code>--daml</code> on command line; use <code>sgen:daml</code> in config file */ LANG_DAML, /** Specify that the language of the source is OWL (the default); use <code>--owl</code> on command line; use <code>sgen:owl</code> in config file */ LANG_OWL, /** Specify that the language of the source is RDFS; use <code>--rdfs</code> on command line; use <code>sgen:rdfs</code> in config file */ LANG_RDFS, /** Specify that destination file; use <code>-o &lt;fileName&gt;</code> on command line; use <code>sgen:output</code> in config file */ OUTPUT, /** Specify the file header; use <code>--header "..."</code> on command line; use <code>sgen:header</code> in config file */ HEADER, /** Specify the file footer; use <code>--footer "..."</code> on command line; use <code>sgen:footer</code> in config file */ FOOTER, /** Specify the uri of the configuration root node; use <code>--root &lt;URL&gt;</code> on command line */ ROOT, /** Specify the marker string for substitutions, default is '%'; use <code>-m "..."</code> on command line; use <code>sgen:marker</code> in config file */ MARKER, /** Specify the packagename; use <code>--package &lt;packagename&gt;</code> on command line; use <code>sgen:package</code> in config file */ PACKAGENAME, /** Use ontology terms in preference to vanilla RDF; use <code>--ontology</code> on command line; use <code>sgen:ontology</code> in config file */ ONTOLOGY, /** The name of the generated class; use <code>-n &lt;classname&gt;</code> on command line; use <code>sgen:classname</code> in config file */ CLASSNAME, /** Additional decoration for class header (such as implements); use <code>--classdec &lt;classname&gt;</code> on command line; use <code>sgen:classdec</code> in config file */ CLASSDEC, /** The namespace URI for the vocabulary; use <code>-a &lt;uri&gt;</code> on command line; use <code>sgen:namespace</code> in config file */ NAMESPACE, /** Additional declarations to add at the top of the class; use <code>--declarations &lt;...&gt;</code> on command line; use <code>sgen:declarations</code> in config file */ DECLARATIONS, /** Section declaration for properties section; use <code>--propSection &lt;...&gt;</code> on command line; use <code>sgen:propSection</code> in config file */ PROPERTY_SECTION, /** Section declaration for class section; use <code>--classSection &lt;...&gt;</code> on command line; use <code>sgen:classSection</code> in config file */ CLASS_SECTION, /** Section declaration for individuals section; use <code>--individualsSection &lt;...&gt;</code> on command line; use <code>sgen:individualsSection</code> in config file */ INDIVIDUALS_SECTION, /** Section declaration for datatypes section; use <code>--datatypesSection &lt;...&gt;</code> on command line; use <code>sgen:datatypesSection</code> in config file */ DATATYPES_SECTION, /** Option to suppress properties in vocab file; use <code>--noproperties &lt;...&gt;</code> on command line; use <code>sgen:noproperties</code> in config file */ NOPROPERTIES, /** Option to suppress classes in vocab file; use <code>--noclasses &lt;...&gt;</code> on command line; use <code>sgen:noclasses</code> in config file */ NOCLASSES, /** Option to suppress individuals in vocab file; use <code>--noindividuals &lt;...&gt;</code> on command line; use <code>sgen:noindividuals</code> in config file */ NOINDIVIDUALS, /** Option to suppress datatypes in vocab file; use <code>--nodatatypes &lt;...&gt;</code> on command line; use <code>sgen:nodatatypes</code> in config file */ NODATATYPES, /** Option for no file header; use <code>--noheader &lt;...&gt;</code> on command line; use <code>sgen:noheader</code> in config file */ NOHEADER, /** Template for writing out property declarations; use <code>--propTemplate &lt;...&gt;</code> on command line; use <code>sgen:propTemplate</code> in config file */ PROP_TEMPLATE, /** Template for writing out class declarations; use <code>--classTemplate &lt;...&gt;</code> on command line; use <code>sgen:classTemplate</code> in config file */ CLASS_TEMPLATE, /** Template for writing out individual declarations; use <code>--individualTemplate &lt;...&gt;</code> on command line; use <code>sgen:individualTemplate</code> in config file */ INDIVIDUAL_TEMPLATE, /** Template for writing out datatype declarations; use <code>--datatypeTemplate &lt;...&gt;</code> on command line; use <code>sgen:datatypeTemplate</code> in config file */ DATATYPE_TEMPLATE, /** Option for mapping constant names to uppercase; use <code>--uppercase &lt;...&gt;</code> on command line; use <code>sgen:uppercase</code> in config file */ UC_NAMES, /** Option for including non-local URI's in vocabulary; use <code>--include &lt;uri&gt;</code> on command line; use <code>sgen:include</code> in config file */ INCLUDE, /** Option for adding a suffix to the generated class name; use <code>--classnamesuffix &lt;uri&gt;</code> on command line; use <code>sgen:classnamesuffix</code> in config file */ CLASSNAME_SUFFIX, /** Option for the presentation syntax (encoding) of the file; use <code>-e <i>encoding</i></code> on command line; use <code>sgen:encoding</code> in config file */ ENCODING, /** Option to show the usage message; use --help on command line */ HELP, /** Option to generate an output file with DOS (\r\n) line endings. Default is Unix line endings. */ DOS, /** Option to generate to force the model to perform inference, off by default. */ USE_INF, /** Option to exclude instances of classes in the allowed namespaces, where the individuals themselves are in other namespaces; use <code>--strictIndividuals</code> on command line; use <code>sgen:strictIndividuals</code> in config file */ STRICT_INDIVIDUALS, /** Option to include the ontology source code in the generated file */ INCLUDE_SOURCE, /** Option to turn off strict checking in .a() */ NO_STRICT } public static final Object[][] m_optionDefinitions = new Object[][] { {OPT.CONFIG_FILE, new OptionDefinition( "-c", "configFile" ) }, {OPT.ROOT, new OptionDefinition( "-r", "root" ) }, {OPT.NO_COMMENTS, new OptionDefinition( "--nocomments", "noComments" ) }, {OPT.INPUT, new OptionDefinition( "-i", "input" ) }, {OPT.LANG_DAML, new OptionDefinition( "--daml", "daml" ) }, {OPT.LANG_OWL, new OptionDefinition( "--owl", "owl" ) }, {OPT.LANG_RDFS, new OptionDefinition( "--rdfs", "rdfs" ) }, {OPT.OUTPUT, new OptionDefinition( "-o", "output" ) }, {OPT.HEADER, new OptionDefinition( "--header", "header" ) }, {OPT.FOOTER, new OptionDefinition( "--footer", "footer" ) }, {OPT.MARKER, new OptionDefinition( "--marker", "marker" ) }, {OPT.PACKAGENAME, new OptionDefinition( "--package", "package" ) }, {OPT.ONTOLOGY, new OptionDefinition( "--ontology", "ontology" ) }, {OPT.CLASSNAME, new OptionDefinition( "-n", "classname" ) }, {OPT.CLASSDEC, new OptionDefinition( "--classdec", "classdec" ) }, {OPT.NAMESPACE, new OptionDefinition( "-a", "namespace" ) }, {OPT.DECLARATIONS, new OptionDefinition( "--declarations", "declarations" ) }, {OPT.PROPERTY_SECTION, new OptionDefinition( "--propSection", "propSection" ) }, {OPT.CLASS_SECTION, new OptionDefinition( "--classSection", "classSection" ) }, {OPT.INDIVIDUALS_SECTION, new OptionDefinition( "--individualsSection", "individualsSection" ) }, {OPT.DATATYPES_SECTION, new OptionDefinition( "--datatypesSection", "datatypesSection" ) }, {OPT.NOPROPERTIES, new OptionDefinition( "--noproperties", "noproperties" ) }, {OPT.NOCLASSES, new OptionDefinition( "--noclasses", "noclasses" ) }, {OPT.NOINDIVIDUALS, new OptionDefinition( "--noindividuals", "noindividuals" ) }, {OPT.NODATATYPES, new OptionDefinition( "--nodatatypes", "nodatatypes" ) }, {OPT.PROP_TEMPLATE, new OptionDefinition( "--propTemplate", "propTemplate" ) }, {OPT.CLASS_TEMPLATE, new OptionDefinition( "--classTemplate", "classTemplate" ) }, {OPT.INDIVIDUAL_TEMPLATE, new OptionDefinition( "--individualTemplate", "individualTemplate" ) }, {OPT.DATATYPE_TEMPLATE, new OptionDefinition( "--datatypeTemplate", "datatypeTemplate" ) }, {OPT.UC_NAMES, new OptionDefinition( "--uppercase", "uppercase" ) }, {OPT.INCLUDE, new OptionDefinition( "--include", "include" ) }, {OPT.CLASSNAME_SUFFIX, new OptionDefinition( "--classnamesuffix", "classnamesuffix" )}, {OPT.NOHEADER, new OptionDefinition( "--noheader", "noheader" )}, {OPT.ENCODING, new OptionDefinition( "-e", "encoding" )}, {OPT.HELP, new OptionDefinition( "--help", "help" )}, {OPT.DOS, new OptionDefinition( "--dos", "dos" )}, {OPT.USE_INF, new OptionDefinition( "--inference", "inference" )}, {OPT.STRICT_INDIVIDUALS, new OptionDefinition( "--strictIndividuals", "strictIndividuals" )}, {OPT.INCLUDE_SOURCE, new OptionDefinition( "--includeSource", "includeSource" )}, {OPT.NO_STRICT, new OptionDefinition( "--nostrict", "noStrict")}, }; public boolean hasConfigFileOption(); public String getConfigFileOption(); public boolean hasRootOption(); public String getRootOption(); public boolean hasNoCommentsOption(); public String getNoCommentsOption(); public boolean hasInputOption(); public Resource getInputOption(); public boolean hasLangOwlOption(); public String getLangOwlOption(); public boolean hasLangRdfsOption(); public String getLangRdfsOption(); public boolean hasOutputOption(); public String getOutputOption(); public boolean hasHeaderOption(); public String getHeaderOption(); public boolean hasFooterOption(); public String getFooterOption(); public boolean hasMarkerOption(); public String getMarkerOption(); public boolean hasPackagenameOption(); public String getPackagenameOption(); public boolean hasOntologyOption(); public String getOntologyOption(); public boolean hasClassnameOption(); public String getClassnameOption(); public boolean hasClassdecOption(); public String getClassdecOption(); public boolean hasNamespaceOption(); public Resource getNamespaceOption(); public boolean hasDeclarationsOption(); public String getDeclarationsOption(); public boolean hasPropertySectionOption(); public String getPropertySectionOption(); public boolean hasClassSectionOption(); public String getClassSectionOption(); public boolean hasIndividualsSectionOption(); public String getIndividualsSectionOption(); public boolean hasDatatypesSectionOption(); public String getDatatypesSectionOption(); public boolean hasNopropertiesOption(); public boolean hasNoclassesOption(); public boolean hasNoindividualsOption(); public boolean hasNodatatypesOption(); public boolean hasPropTemplateOption(); public String getPropTemplateOption(); public boolean hasClassTemplateOption(); public String getClassTemplateOption(); public boolean hasIndividualTemplateOption(); public String getIndividualTemplateOption(); public boolean hasDatatypeTemplateOption(); public String getDatatypeTemplateOption(); public boolean hasUcNamesOption(); public boolean hasIncludeOption(); public List<String> getIncludeOption(); public boolean hasClassnameSuffixOption(); public String getClassnameSuffixOption(); public boolean hasNoheaderOption(); public boolean hasEncodingOption(); public String getEncodingOption(); public boolean hasHelpOption(); public String getHelpOption(); public boolean hasDosOption(); public boolean hasUseInfOption(); public boolean hasStrictIndividualsOption(); public boolean hasIncludeSourceOption(); public boolean hasNoStrictOption(); } public static class SchemagenOptionsImpl implements SchemagenOptions { // Instance variables /** The list of command line arguments */ private List<String> m_cmdLineArgs = new ArrayList<>(); /** The root of the options in the config file */ private Resource m_root; /** The model that contains the configuration information */ private Model m_config = ModelFactory.createDefaultModel(); // Constructor public SchemagenOptionsImpl( String[] args ) { m_cmdLineArgs = Arrays.asList( args ); // check to see if there's a specified config file String configURL = DEFAULT_CONFIG_URI; if (hasConfigFileOption()) { // check for protocol; add file: if not specified configURL = SchemagenUtils.urlCheck( getConfigFileOption() ); } // try to read the config URI try { FileManager.get().readModel( m_config, configURL ); } catch (Exception e) { // if the user left the default config URI in place, it's not an error to fail to read it if (!configURL.equals( DEFAULT_CONFIG_URI )) { throw new SchemagenException( "Failed to read configuration from URL: " + configURL, e ); } } // ensure we have a root URI for the configuration model determineConfigRoot(); } /** * Return the configuration model used to hold config information * @return Model */ protected Model getConfigModel() { return m_config; } /** * Return the root resource to which configuration information is attached * @return Resource */ protected Resource getConfigRoot() { if (m_root == null) { determineConfigRoot(); } return m_root; } // Internal implementation methods /** Determine the root resource in the configuration file */ protected void determineConfigRoot() { if (hasValue( OPT.ROOT )) { m_root = m_config.getResource( getStringValue( OPT.ROOT ) ); } else { // no specified root, we assume there is only one with type sgen:Config StmtIterator i = m_config.listStatements( null, RDF.type, m_config.getResource( NS + "Config" ) ); if (i.hasNext()) { m_root = i.nextStatement().getSubject(); } else { // no configuration root, so we invent one m_root = m_config.createResource(); } } } /** Answer true if the given option is set to true */ protected boolean isTrue( OPT option ) { return getOpt( option ).isTrue( m_cmdLineArgs, m_root ); } /** Answer true if the given option has value */ protected boolean hasValue( OPT option ) { return getOpt( option ).hasValue( m_cmdLineArgs, m_root ); } /** Answer the value of the option or null */ protected RDFNode getValue( OPT option ) { return getOpt( option ).getValue( m_cmdLineArgs, m_root ); } /** Answer the String value of the option or null */ protected String getStringValue( OPT option ) { return getOpt( option ).getStringValue( m_cmdLineArgs, m_root ); } /** Answer true if the given option has a resource value */ protected boolean hasResourceValue( OPT option ) { return getOpt( option ).hasResourceValue( m_cmdLineArgs, m_root ); } /** Answer the value of the option or null */ protected Resource getResource( OPT option ) { return getOpt( option ).getResource( m_cmdLineArgs, m_root ); } /** Answer all values for the given options as Strings */ protected List<String> getAllValues( OPT option ) { List<String> values = new ArrayList<>(); OptionDefinition opt = getOpt( option ); // look in the command line arguments for (Iterator<String> i = m_cmdLineArgs.iterator(); i.hasNext(); ) { String s = i.next(); if (s.equals( opt.m_cmdLineForm )) { // next iterator value is the arg value values.add( i.next() ); } } // now look in the config file for (StmtIterator i = m_root.listProperties( opt.m_prop ); i.hasNext(); ) { Statement s = i.nextStatement(); if (s.getObject() instanceof Literal) { values.add( s.getString() ); } else { values.add( s.getResource().getURI() ); } } return values; } /** Answer the option object for the given option */ protected OptionDefinition getOpt( OPT option ) { for ( Object[] m_optionDefinition : m_optionDefinitions ) { if ( m_optionDefinition[0] == option ) { return (OptionDefinition) m_optionDefinition[1]; } } return null; } // External interface methods @Override public boolean hasConfigFileOption() { return hasValue( OPT.CONFIG_FILE ); } @Override public String getConfigFileOption() { return getStringValue( OPT.CONFIG_FILE ); } @Override public boolean hasRootOption() { return hasValue( OPT.ROOT ); } @Override public String getRootOption() { return getStringValue( OPT.ROOT ); } @Override public boolean hasNoCommentsOption() { return isTrue( OPT.NO_COMMENTS ); } @Override public String getNoCommentsOption() { return getStringValue( OPT.NO_COMMENTS ); } @Override public boolean hasInputOption() { return hasValue( OPT.INPUT ); } @Override public Resource getInputOption() { return getResource( OPT.INPUT ); } @Override public boolean hasLangOwlOption() { return isTrue( OPT.LANG_OWL ); } @Override public String getLangOwlOption() { return getStringValue( OPT.LANG_OWL ); } @Override public boolean hasLangRdfsOption() { return isTrue( OPT.LANG_RDFS ); } @Override public String getLangRdfsOption() { return getStringValue( OPT.LANG_RDFS ); } @Override public boolean hasOutputOption() { return hasValue( OPT.OUTPUT ); } @Override public String getOutputOption() { return getStringValue( OPT.OUTPUT ); } @Override public boolean hasHeaderOption() { return hasValue( OPT.HEADER ); } @Override public String getHeaderOption() { return getStringValue( OPT.HEADER ); } @Override public boolean hasFooterOption() { return isTrue( OPT.FOOTER ); } @Override public String getFooterOption() { return getStringValue( OPT.FOOTER ); } @Override public boolean hasMarkerOption() { return hasValue( OPT.MARKER ); } @Override public String getMarkerOption() { return getStringValue( OPT.MARKER ); } @Override public boolean hasPackagenameOption() { return hasValue( OPT.PACKAGENAME ); } @Override public String getPackagenameOption() { return getStringValue( OPT.PACKAGENAME ); } @Override public boolean hasOntologyOption() { return isTrue( OPT.ONTOLOGY ); } @Override public String getOntologyOption() { return getStringValue( OPT.ONTOLOGY ); } @Override public boolean hasClassnameOption() { return hasValue( OPT.CLASSNAME ); } @Override public String getClassnameOption() { return getStringValue( OPT.CLASSNAME ); } @Override public boolean hasClassdecOption() { return hasValue( OPT.CLASSDEC ); } @Override public String getClassdecOption() { return getStringValue( OPT.CLASSDEC ); } @Override public boolean hasNamespaceOption() { return hasValue( OPT.NAMESPACE ); } @Override public Resource getNamespaceOption() { return getResource( OPT.NAMESPACE ); } @Override public boolean hasDeclarationsOption() { return hasValue( OPT.DECLARATIONS ); } @Override public String getDeclarationsOption() { return getStringValue( OPT.DECLARATIONS ); } @Override public boolean hasPropertySectionOption() { return hasValue( OPT.PROPERTY_SECTION ); } @Override public String getPropertySectionOption() { return getStringValue( OPT.PROPERTY_SECTION ); } @Override public boolean hasClassSectionOption() { return hasValue( OPT.CLASS_SECTION ); } @Override public String getClassSectionOption() { return getStringValue( OPT.CLASS_SECTION ); } @Override public boolean hasIndividualsSectionOption() { return hasValue( OPT.INDIVIDUALS_SECTION ); } @Override public String getIndividualsSectionOption() { return getStringValue( OPT.INDIVIDUALS_SECTION ); } @Override public boolean hasDatatypesSectionOption() { return hasValue( OPT.DATATYPES_SECTION ); } @Override public String getDatatypesSectionOption() { return getStringValue( OPT.DATATYPES_SECTION ); } @Override public boolean hasNopropertiesOption() { return isTrue( OPT.NOPROPERTIES ); } @Override public boolean hasNoclassesOption() { return isTrue( OPT.NOCLASSES ); } @Override public boolean hasNoindividualsOption() { return isTrue( OPT.NOINDIVIDUALS ); } @Override public boolean hasNodatatypesOption() { return isTrue( OPT.NODATATYPES ); } @Override public boolean hasPropTemplateOption() { return hasValue( OPT.PROP_TEMPLATE ); } @Override public String getPropTemplateOption() { return getStringValue( OPT.PROP_TEMPLATE ); } @Override public boolean hasClassTemplateOption() { return hasValue( OPT.CLASS_TEMPLATE ); } @Override public String getClassTemplateOption() { return getStringValue( OPT.CLASS_TEMPLATE ); } @Override public boolean hasIndividualTemplateOption() { return hasValue( OPT.INDIVIDUAL_TEMPLATE ); } @Override public String getIndividualTemplateOption() { return getStringValue( OPT.INDIVIDUAL_TEMPLATE ); } @Override public boolean hasDatatypeTemplateOption() { return hasValue( OPT.DATATYPE_TEMPLATE ); } @Override public String getDatatypeTemplateOption() { return getStringValue( OPT.DATATYPE_TEMPLATE ); } @Override public boolean hasUcNamesOption() { return isTrue( OPT.UC_NAMES ); } @Override public boolean hasIncludeOption() { return hasValue( OPT.INCLUDE ); } @Override public List<String> getIncludeOption() { return getAllValues( OPT.INCLUDE ); } @Override public boolean hasClassnameSuffixOption() { return hasValue( OPT.CLASSNAME_SUFFIX ); } @Override public String getClassnameSuffixOption() { return getStringValue( OPT.CLASSNAME_SUFFIX ); } @Override public boolean hasNoheaderOption() { return isTrue( OPT.NOHEADER ); } @Override public boolean hasEncodingOption() { return hasValue( OPT.ENCODING ); } @Override public String getEncodingOption() { return getStringValue( OPT.ENCODING ); } @Override public boolean hasHelpOption() { return hasValue( OPT.HELP ); } @Override public String getHelpOption() { return getStringValue( OPT.HELP ); } @Override public boolean hasDosOption() { return isTrue( OPT.DOS ); } @Override public boolean hasUseInfOption() { return isTrue( OPT.USE_INF ); } @Override public boolean hasStrictIndividualsOption() { return isTrue( OPT.STRICT_INDIVIDUALS ); } @Override public boolean hasIncludeSourceOption() { return isTrue( OPT.INCLUDE_SOURCE ); } @Override public boolean hasNoStrictOption() { return isTrue( OPT.NO_STRICT ); } } /** An option that can be set either on the command line or in the RDF config */ public static class OptionDefinition { protected String m_cmdLineForm; protected Property m_prop; protected OptionDefinition( String cmdLineForm, String name ) { m_cmdLineForm = cmdLineForm; if (name != null) { m_prop = ResourceFactory.createProperty( NS, name ); } } /** * Return the RDF property that is used when configuring this option * via a {@link Model} * @return The declaration property, or null */ public Property getDeclarationProperty() { return m_prop; } /** * Return the command line form of this option * @return The command line form as a String */ public String getCommandLineForm() { return m_cmdLineForm; } /** * Answer true if this option is set to true, either on the command line * or in the config model * * @return boolean */ protected boolean isTrue( List<String> cmdLineArgs, Resource confRoot ) { if (cmdLineArgs.contains( m_cmdLineForm )) { return true; } if (confRoot.hasProperty( m_prop )) { return confRoot.getRequiredProperty( m_prop ).getBoolean(); } return false; } /** * Answer the string value of the parameter if set, or null otherwise. Note command line * has precedence. * * @return String */ protected String getStringValue( List<String> cmdLineArgs, Resource confRoot ) { RDFNode n = getValue( cmdLineArgs, confRoot ); return (n == null) ? null : (n.isLiteral() ? n.asLiteral().getLexicalForm() : n.toString() ); } /** * Return the value of the parameter if set, or null otherwise. Note command line * has precedence. * * @return The argument value as an RDFNode */ protected RDFNode getValue( List<String> cmdLineArgs, Resource confRoot ) { int index = cmdLineArgs.indexOf( m_cmdLineForm ); if (index >= 0) { try { return ResourceFactory.createPlainLiteral( cmdLineArgs.get( index + 1 ) ); } catch (IndexOutOfBoundsException e) { throw new SchemagenException( "Value for parameter " + m_cmdLineForm + " not set! Aborting.", e ); } } if (m_prop != null && confRoot != null && confRoot.hasProperty( m_prop )) { return confRoot.getRequiredProperty( m_prop ).getObject(); } // not set return null; } /** * Answer true if the parameter has a value at all. * * @return boolean */ protected boolean hasValue( List<String> cmdLineArgs, Resource confRoot ) { return getValue( cmdLineArgs, confRoot ) != null; } /** * Answer the resource value of the parameter if set, or null otherwise. * * @return String */ protected Resource getResource( List<String> cmdLineArgs, Resource confRoot ) { int index = cmdLineArgs.indexOf( m_cmdLineForm ); if (index >= 0) { try { return confRoot.getModel().getResource( cmdLineArgs.get( index + 1 ) ); } catch (IndexOutOfBoundsException e) { System.err.println( "Value for parameter " + m_cmdLineForm + " not set! Aborting."); } } if (m_prop != null && confRoot.hasProperty( m_prop )) { return confRoot.getRequiredProperty( m_prop ).getResource(); } // not set return null; } /** * Answer true if the parameter has a value at all. * * @return boolean */ protected boolean hasResourceValue( List<String> cmdLineArgs, Resource confRoot ) { return getResource( cmdLineArgs, confRoot ) != null; } } // end inner class OptionDefinition /** A pairing of pattern and substitution we want to apply to output */ protected class Replacement { protected String sub; protected Pattern pattern; protected Replacement( Pattern pattern, String sub) { this.sub = sub; this.pattern = pattern; } } // end inner class Replacement /** * <p>Schemagen runtime exception</p> */ public static class SchemagenException extends RuntimeException { public SchemagenException( String msg, Throwable cause ) { super( msg, cause ); } } /** Utility method container */ public static class SchemagenUtils { /** Return a URI formed from the given string, unchanged if it's already a URI or * converted to a file URI otherwise. If not recognisable as a URL, abort. */ public static String urlCheck( String uriOrFile ) { boolean legal = true; String url = uriOrFile; // is it a URI already? to check, we make a URL and see what happens! try { new URL( url ); } catch (MalformedURLException ignore) { legal = false; } // if not a legal url, assume it's a file if (!legal) { legal = true; String slash = System.getProperty( "file.separator" ); url = "file:" + (uriOrFile.startsWith( slash ) ? (slash + slash) : "") + uriOrFile; try { new URL( url ); } catch (MalformedURLException ignore) { legal = false; } } if (!legal) { throw new SchemagenException( "Could not parse " + uriOrFile + " as a legal URL or a file reference. Aborting.", null ); } return url; } } /* End class SchemagenUtils */ }
jena-cmds/src/main/java/jena/schemagen.java
/* * 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 /////////////// package jena; import static org.apache.jena.atlas.logging.LogCtl.setCmdLogging; import java.io.ByteArrayOutputStream ; import java.io.File ; import java.io.FileOutputStream ; import java.io.PrintStream ; import java.net.MalformedURLException ; import java.net.URL ; import java.text.SimpleDateFormat ; import java.util.* ; import java.util.regex.Pattern ; import java.util.regex.PatternSyntaxException ; import org.apache.jena.ext.xerces.util.XMLChar; import org.apache.jena.ontology.Individual ; import org.apache.jena.ontology.OntModel ; import org.apache.jena.ontology.OntModelSpec ; import org.apache.jena.rdf.model.* ; import org.apache.jena.shared.JenaException ; import org.apache.jena.util.FileManager ; import org.apache.jena.util.iterator.ExtendedIterator ; import org.apache.jena.util.iterator.WrappedIterator ; import org.apache.jena.vocabulary.OWL ; import org.apache.jena.vocabulary.RDF ; import org.apache.jena.vocabulary.RDFS ; import org.apache.jena.vocabulary.XSD ; /** * <p> * A vocabulary generator, that will consume an ontology or other vocabulary file, * and generate a Java file with the constants from the vocabulary compiled in. * Designed to be highly flexible and customisable. * </p> */ public class schemagen { static { setCmdLogging(); } // Constants ////////////////////////////////// /** The namespace for the configuration model is {@value} */ public static final String NS = "http://jena.hpl.hp.com/2003/04/schemagen#"; /** The default location of the configuration model is {@value} */ public static final String DEFAULT_CONFIG_URI = "file:schemagen.rdf"; /** The default marker string for denoting substitutions is {@value} */ public static final String DEFAULT_MARKER = "%"; /** Default template for writing out value declarations */ public static final String DEFAULT_TEMPLATE = "public static final %valclass% %valname% = M_MODEL.%valcreator%( \"%valuri%\" );"; /** Default template for writing out individual declarations */ public static final String DEFAULT_INDIVIDUAL_TEMPLATE = "public static final %valclass% %valname% = M_MODEL.%valcreator%( \"%valuri%\", %valtype% );"; /** Default template for writing out individual declarations for non-ontology vocabularies */ public static final String DEFAULT_RDFS_INDIVIDUAL_TEMPLATE = "public static final %valclass% %valname% = M_MODEL.%valcreator%( \"%valuri%\" );"; /** Default template for the file header */ public static final String DEFAULT_HEADER_TEMPLATE = "/* CVS $" + "Id: $ */%nl%%package% %nl%%imports% %nl%/**%nl% * Vocabulary definitions from %sourceURI% %nl% * @author Auto-generated by schemagen on %date% %nl% */"; /** Default line length for comments before wrap */ public static final int COMMENT_LENGTH_LIMIT = 80; /** List of Java reserved keywords, see <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html">this list</a>. */ public static final String[] JAVA_KEYWORDS = { "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while" }; // Static variables ////////////////////////////////// private static List<String> KEYWORD_LIST; static { KEYWORD_LIST = Arrays.asList( JAVA_KEYWORDS ); } // Instance variables ////////////////////////////////// /** Schemagen options interface */ protected SchemagenOptions m_options; /** The model that contains the input source */ protected OntModel m_source; /** The output stream we write to */ protected PrintStream m_output; /** Option definitions */ /** Stack of replacements to apply */ protected List<Replacement> m_replacements = new ArrayList<>(); /** Output file newline char - default is Unix, override with --dos */ protected String m_nl = "\n"; /** Size of indent step */ protected int m_indentStep = 4; /** Set of names used so far */ protected Set<String> m_usedNames = new HashSet<>(); /** Map from resources to java names */ protected Map<Resource,String> m_resourcesToNames = new HashMap<>(); /** List of allowed namespace URI strings for admissible values */ protected List<String> m_includeURI = new ArrayList<>(); // Constructors ////////////////////////////////// // External signature methods ////////////////////////////////// /* Main entry point. See Javadoc for details of the many command line arguments */ public static void main( String... args ) { try { new schemagen().go( args ); } catch (SchemagenException e) { System.err.println( "Schemagen failed to run:" ); System.err.println( e.getMessage() ); if (e.getCause() != null) { System.err.println( "Caused by: " + e.getCause().getMessage() ); } System.exit( 1 ); } } // Internal implementation methods ////////////////////////////////// /** Read the configuration parameters and do setup */ protected void go( String[] args ) { go( new SchemagenOptionsImpl( args ) ); } /** Handle initial configuration options, then initiate processing */ protected void go( SchemagenOptions options ) { m_options = options; // check for user requesting help if (m_options.hasHelpOption()) { usage(); } // got the configuration, now we can begin processing processInput(); } /** The sequence of steps to process an entire file */ protected void processInput() { addIncludes(); determineLanguage(); selectInput(); selectOutput(); setGlobalReplacements(); processHeader(); writeClassDeclaration(); writeInitialDeclarations(); writeProperties(); writeClasses(); writeIndividuals(); writeDatatypes(); writeClassClose(); processFooter(); closeOutput(); } /** Add the included files */ protected void addIncludes() { // add any extra uri's that are allowed in the filter m_includeURI.addAll( m_options.getIncludeOption() ); } /** Create the source model after determining which input language */ protected void determineLanguage() { OntModelSpec s = null; if (m_options.hasLangRdfsOption()) { // RDFS language specified if (m_options.hasUseInfOption()) { s = OntModelSpec.RDFS_MEM_RDFS_INF; } else { s = OntModelSpec.RDFS_MEM; } } else { // owl is the default // s = OntModelSpec.getDefaultSpec( ProfileRegistry.OWL_LANG ); if (m_options.hasUseInfOption()) { s = OntModelSpec.OWL_MEM_RULE_INF; } else { s = OntModelSpec.OWL_MEM; } } m_source = ModelFactory.createOntologyModel( s, null ); m_source.getDocumentManager().setProcessImports( false ); // turn off strict checking on request if (m_options.hasNoStrictOption()) { m_source.setStrictMode( false ); } } /** Identify the URL that is to be read in and translated to a vocabulary file, and load the source into the source model */ protected void selectInput() { if (!m_options.hasInputOption()) { usage(); } String input = SchemagenUtils.urlCheck( m_options.getInputOption().getURI() ); String syntax = m_options.getEncodingOption(); try { FileManager.get().readModel( m_source, input, syntax ); } catch (JenaException e) { abort( "Failed to read input source " + input, e ); } } /** Identify the file we are to write the output to */ protected void selectOutput() { String outFile = m_options.getOutputOption(); if (outFile == null) { m_output = System.out; } else { try { // check for package name String packageName = m_options.getPackagenameOption(); if (packageName != null) { String packagePath = ""; // build the package path (e.g. com.foo.bar -> /com/foo/bar) for (String p: packageName.split( "\\." )) { packagePath = packagePath + File.separator + p; } if (!outFile.endsWith( packagePath )) { outFile = outFile + packagePath; } } File out = new File( outFile ); if (!out.exists() && !outFile.endsWith( ".java" )) { // create the directory if needed out.mkdirs(); } if (out.isDirectory()) { // create a file in this directory named classname.java String fileName = outFile + File.separator + getClassName() + ".java"; out = new File( fileName ); } m_output = new PrintStream( new FileOutputStream( out ) ); } catch (Exception e) { abort( "I/O error while trying to open file for writing: " + outFile, e ); } } // check for DOS line endings if (m_options.hasDosOption()) { m_nl = "\r\n"; } } /** Process the header at the start of the file, if defined */ protected void processHeader() { String header = m_options.hasHeaderOption() ? m_options.getHeaderOption() : DEFAULT_HEADER_TEMPLATE; // user can turn of header processing, default is to have it on if (!m_options.hasNoheaderOption()) { writeln( 0, substitute( header ) ); } else { // we have to do the imports at least writeln( 0, "import org.apache.jena.rdf.model.*;" ); if (m_options.hasOntologyOption()) { writeln( 0, "import org.apache.jena.ontology.*;" ); } if (m_options.hasIncludeSourceOption()) { writeln( 0, "import java.io.ByteArrayInputStream;" ); } } } /** Process the footer at the end of the file, if defined */ protected void processFooter() { String footer = m_options.getFooterOption(); if (footer != null) { writeln( 0, substitute( footer ) ); } } /** The list of replacements that are always available */ protected void setGlobalReplacements() { addReplacementPattern( "date", new SimpleDateFormat( "dd MMM yyyy HH:mm").format( new Date() ) ); addReplacementPattern( "package", m_options.hasPackagenameOption() ? ("package " + m_options.getPackagenameOption() + ";") : "" ); addReplacementPattern( "imports", getImports() ); addReplacementPattern( "classname", getClassName() ); addReplacementPattern( "nl", m_nl ); // protect \ in Windows file pathnames // looks for file:.* or C:.* (or variants thereof) String source = m_options.getInputOption().getURI(); if (source.matches( "(file:|[A-Za-z]:).*$" )) { source = source.replace( "\\", "\\\\" ); } addReplacementPattern( "sourceURI", source ); } /** Add a pattern-value pair to the list of available patterns */ protected void addReplacementPattern( String key, String replacement ) { if (replacement != null && key != null) { String marker = m_options.getMarkerOption(); marker = (marker == null) ? DEFAULT_MARKER : marker; try { m_replacements.add( new Replacement( Pattern.compile( marker + key + marker ), replacement ) ); } catch (PatternSyntaxException e) { abort( "Malformed regexp pattern " + marker + key + marker, e ); } } } /** Pop n replacements off the stack */ protected void pop( int n ) { for (int i = 0; i < n; i++) { m_replacements.remove( m_replacements.size() - 1 ); } } /** Close the output file */ protected void closeOutput() { m_output.flush(); m_output.close(); } /** Abort due to exception */ protected void abort( String msg, Exception cause ) { throw new SchemagenException( msg, cause ); } /** Print usage message and abort */ protected void usage() { System.err.println( "Usage:" ); System.err.println( " java jena.schemagen [options ...]" ); System.err.println(); System.err.println( "Commonly used options include:" ); System.err.println( " -i <input> the source document as a file or URL." ); System.err.println( " -n <name> the name of the created Java class." ); System.err.println( " -a <uri> the namespace URI of the source document." ); System.err.println( " -o <file> the file to write the generated class into." ); System.err.println( " -o <dir> the directory in which the generated Java class is created." ); System.err.println( " By default, output goes to stdout." ); System.err.println( " -e <encoding> the encoding of the input document (N3, RDF/XML, etc)." ); System.err.println( " -c <config> a filename or URL for an RDF document containing " ); System.err.println( " configuration parameters." ); System.err.println(); System.err.println( "Many other options are available. See the schemagen HOWTO in the " ); System.err.println( "Jena documentation for full details." ); System.exit( 1 ); } /** Use the current replacements list to do the subs in the given string */ protected String substitute( String sIn ) { String s = sIn; for ( Replacement r : m_replacements ) { s = r.pattern.matcher( s ).replaceAll( r.sub ); } return s; } /** Add the appropriate indent to a buffer */ protected int indentTo( int i, StringBuffer buf ) { int indent = i * m_indentStep; for (int j = 0; j < indent; j++) { buf.append( ' ' ); } return indent; } /** Write a blank line, with indent and newline */ protected void writeln( int indent ) { writeln( indent, "" ); } /** Write out the given string with n spaces of indent, with newline */ protected void writeln( int indent, String s ) { write( indent, s ); m_output.print( m_nl ); } /** Write out the given string with n spaces of indent */ protected void write( int indentLevel, String s ) { for (int i = 0; i < (m_indentStep * indentLevel); i++) { m_output.print( " " ); } m_output.print( s ); } /** Determine the list of imports to include in the file */ protected String getImports() { StringBuffer buf = new StringBuffer(); buf.append( "import org.apache.jena.rdf.model.*;" ); buf.append( m_nl ); if (useOntology()) { buf.append( "import org.apache.jena.ontology.*;" ); buf.append( m_nl ); } if (includeSource()) { buf.append( "import java.io.ByteArrayInputStream;" ); buf.append( m_nl ); } return buf.toString(); } /** Determine the class name of the vocabulary from the URI */ protected String getClassName() { // if a class name is given, just use that if (m_options.hasClassnameOption()) { return m_options.getClassnameOption(); } // otherwise, we generate a name based on the URI String uri = m_options.getInputOption().getURI(); // remove any suffixes uri = (uri.endsWith( "#" )) ? uri.substring( 0, uri.length() - 1 ) : uri; uri = (uri.endsWith( ".daml" )) ? uri.substring( 0, uri.length() - 5 ) : uri; uri = (uri.endsWith( ".owl" )) ? uri.substring( 0, uri.length() - 4 ) : uri; uri = (uri.endsWith( ".rdf" )) ? uri.substring( 0, uri.length() - 4 ) : uri; uri = (uri.endsWith( ".rdfs" )) ? uri.substring( 0, uri.length() - 5 ) : uri; uri = (uri.endsWith( ".n3" )) ? uri.substring( 0, uri.length() - 3 ) : uri; uri = (uri.endsWith( ".xml" )) ? uri.substring( 0, uri.length() - 4 ) : uri; uri = (uri.endsWith( ".ttl" )) ? uri.substring( 0, uri.length() - 4 ) : uri; // now work back to the first non name character from the end int i = uri.length() - 1; for (; i > 0; i--) { if (!Character.isUnicodeIdentifierPart( uri.charAt( i ) ) && uri.charAt( i ) != '-') { i++; break; } } String name = uri.substring( i ); // optionally add name suffix if (m_options.hasClassnameSuffixOption()) { name = name + m_options.getClassnameSuffixOption(); } // now we make the name into a legal Java identifier return asLegalJavaID( name, true ); } /** Answer true if we are using ontology terms in this vocabulary */ protected boolean useOntology() { return m_options.hasOntologyOption(); } /** Answer true if all comments are suppressed */ protected boolean noComments() { return m_options.hasNoCommentsOption(); } /** Answer true if ontology source code is to be included */ protected boolean includeSource() { return m_options.hasIncludeSourceOption(); } /** Converts to a legal Java identifier; capitalise first char if cap is true */ protected String asLegalJavaID( String s, boolean cap ) { StringBuffer buf = new StringBuffer(); int i = 0; // treat the first character specially - must be able to start a Java ID, may have to up-case try { for (; !Character.isJavaIdentifierStart( s.charAt( i )); i++) { /**/ } } catch (StringIndexOutOfBoundsException e) { System.err.println( "Could not identify legal Java identifier start character in '" + s + "', replacing with __" ); return "__"; } buf.append( cap ? Character.toUpperCase( s.charAt( i ) ) : s.charAt( i ) ); // copy the remaining characters - replace non-legal chars with '_' for (++i; i < s.length(); i++) { char c = s.charAt( i ); buf.append( Character.isJavaIdentifierPart( c ) ? c : '_' ); } // check for illegal keyword if (KEYWORD_LIST.contains( buf.toString() )) { buf.append( '_' ); } return buf.toString(); } /** The opening class declaration */ protected void writeClassDeclaration() { write( 0, "public class " ); write( 0, getClassName() ); write( 0, " " ); if (m_options.hasClassdecOption()) { write( 0, m_options.getClassdecOption() ); } writeln( 0, "{" ); } /** The close of the class decoration */ protected void writeClassClose() { writeln( 0, "}" ); } /** Write the declarations at the head of the class */ protected void writeInitialDeclarations() { writeModelDeclaration(); writeSource(); writeNamespace(); writeOntologyVersionInfo(); if (m_options.hasDeclarationsOption()) { writeln( 0, m_options.getDeclarationsOption() ); } } /** Write the declaration of the model */ protected void writeModelDeclaration() { if (useOntology()) { String lang = "OWL"; if (m_options.hasLangRdfsOption()) { lang = "RDFS"; } writeln( 1, "/** <p>The ontology model that holds the vocabulary terms</p> */" ); writeln( 1, "private static final OntModel M_MODEL = ModelFactory.createOntologyModel( OntModelSpec." + lang + "_MEM, null );" ); } else { writeln( 1, "/** <p>The RDF model that holds the vocabulary terms</p> */" ); writeln( 1, "private static final Model M_MODEL = ModelFactory.createDefaultModel();" ); } writeln( 1 ); } /** Write the source code of the input model into the file itself */ protected void writeSource() { if (includeSource()) { // first save a copy of the source in compact form into a buffer ByteArrayOutputStream bos = new ByteArrayOutputStream(); RDFWriter rw = m_source.getWriter( "Turtle" ); rw.setProperty( "objectLists", Boolean.FALSE.toString() ); rw.write( m_source, bos, null ); String output = bos.toString(); // now we embed each line of the source in the output writeln( 1, "private static final String SOURCE = " ); boolean first = true; StringTokenizer st = new StringTokenizer( output, "\n" ); while (st.hasMoreTokens()) { String tok = st.nextToken(); if (tok.endsWith( "\r" )) { tok = tok.substring( 0, tok.length() - 1 ); } write( 2, first ? " " : " + " ); write( 0, "\"" ); write( 0, protectQuotes( tok ) ); writeln( 2, "\\n\"" ); first = false; } // then we reference the string constant when reading the source // note that we avoid StringReader due to charset encoding issues writeln( 1, ";" ); writeln( 0, "" ); writeln( 1, "/** Read the ontology definition into the source model */ " ); writeln( 1, "static { " ); writeln( 2, "M_MODEL.read( new ByteArrayInputStream( SOURCE.getBytes() ), null, \"N3\" );" ); writeln( 1, "}" ); writeln( 0, "" ); } } /** Protect any double quotes in the given string so that it's a legal Java String */ private String protectQuotes( String s ) { return s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\"", "\\\\\"" ); } /** Write owl:versionInfo string if it exists **/ protected void writeOntologyVersionInfo() { String versionInfo = getOntologyElementVersionInfo(); if (null != versionInfo) { writeln( 1, "/** <p>The ontology's owl:versionInfo as a string</p> */" ); writeln( 1, "public static final String VERSION_INFO = \"" + protectQuotes(versionInfo) + "\";" ); writeln( 1 ); } } /** Write the string and resource that represent the namespace */ protected void writeNamespace() { String nsURI = determineNamespaceURI(); writeln( 1, "/** <p>The namespace of the vocabulary as a string</p> */" ); writeln( 1, "public static final String NS = \"" + nsURI + "\";" ); writeln( 1 ); writeln( 1, "/** <p>The namespace of the vocabulary as a string</p>" ); writeln( 1, " * @return namespace as String" ); writeln( 1, " * @see #NS */" ); writeln( 1, "public static String getURI() {return NS;}" ); writeln( 1 ); writeln( 1, "/** <p>The namespace of the vocabulary as a resource</p> */" ); writeln( 1, "public static final Resource NAMESPACE = M_MODEL.createResource( NS );" ); writeln( 1 ); } /** Determine what the namespace URI for this vocabulary is */ protected String determineNamespaceURI() { // we have a sequence of strategies for determining the ontology namespace String ns = getOptionNamespace(); if (ns == null) { ns = getDefaultPrefixNamespace(); } if (ns == null) { ns = getOntologyElementNamespace(); } if (ns == null) { ns = guessNamespace(); } // did we get one? if (ns == null) { abort( "Could not determine the base URI for the input vocabulary", null ); } m_includeURI.add( ns ); return ns; } /** User has set namespace via a schemagen option */ protected String getOptionNamespace() { return m_options.hasNamespaceOption() ? m_options.getNamespaceOption().getURI() : null; } /** Document has set an empty prefix for the model */ protected String getDefaultPrefixNamespace() { // alternatively, the default namespace may be set in the prefix mapping read from the input document String defaultNS = m_source.getNsPrefixURI( "" ); if (defaultNS == null) { defaultNS = m_source.getBaseModel().getNsPrefixURI( "" ); } return defaultNS; } /** Document has an owl:Ontology or daml:Ontology element */ protected String getOntologyElementVersionInfo() { String versionInfo = null; Resource ontologyClass = m_source.getProfile().ONTOLOGY(); if (null != ontologyClass) { StmtIterator i = m_source.getBaseModel().listStatements( null, RDF.type, ontologyClass ); if (i.hasNext()) { Resource ont = i.nextStatement().getSubject(); StmtIterator j = m_source.getBaseModel().listStatements( ont, OWL.versionInfo, (RDFNode)null ); if (j.hasNext()) { versionInfo = j.nextStatement().getObject().asLiteral().getLexicalForm(); // check for ambiguous answers if (j.hasNext()) { System.err.println( "Warning: ambiguous owl:versionInfo - there are more than one owl:versionInfo statements." ); System.err.println( "Picking first choice: " + versionInfo + ". Other choices are:" ); while (j.hasNext()) { System.err.print( " " ); System.err.print( j.nextStatement().getObject().toString() ); } System.err.println(); } } // check for ambiguous answers if (i.hasNext()) { System.err.println( "Warning: ambiguous owl:versionInfo - there is more than one owl:Ontology element." ); System.err.println( "Picking first choice: " + ont.getURI() + ". Other choices are:" ); while (i.hasNext()) { System.err.print( " " ); System.err.print( i.nextStatement().getObject().toString() ); } System.err.println(); } } } return versionInfo; } /** Document has an owl:Ontology or daml:Ontology element */ protected String getOntologyElementNamespace() { // if we are using an ontology model, we can get the namespace URI from the ontology element String uri = null; StmtIterator i = m_source.getBaseModel() .listStatements( null, RDF.type, m_source.getProfile().ONTOLOGY() ); if (i.hasNext()) { Resource ont = i.nextStatement().getSubject(); uri = ont.getURI(); // ensure ends with namespace separator char char ch = uri.charAt( uri.length() - 1 ); boolean endsWithNCNameCh = XMLChar.isNCName( ch ); uri = endsWithNCNameCh ? uri + "#" : uri; // check for ambiguous answers if (i.hasNext()) { System.err.println( "Warning: ambiguous default namespace - there is more than one owl:Ontology element." ); System.err.println( "Picking first choice: " + uri + ". Other choices are:" ); while (i.hasNext()) { System.err.print( " " ); System.err.print( i.nextStatement().getString() ); } System.err.println(); System.err.println( "Use the -a option to specify a particular namespace if required." ); } } return uri; } /** Guess the URI from the most prevalent URI */ protected String guessNamespace() { Map<String,Integer> nsCount = new HashMap<>(); // count all of the namespaces used in the model for (StmtIterator i = m_source.listStatements(); i.hasNext(); ) { Statement s = i.next(); countNamespace( s.getSubject(), nsCount ); countNamespace( s.getPredicate(), nsCount ); if (s.getObject().isResource()) { countNamespace( s.getResource(), nsCount ); } } // now find the maximal element String ns = null; int max = 0; for ( String nsKey : nsCount.keySet() ) { // we ignore the usual suspects if ( !( OWL.getURI().equals( nsKey ) || RDF.getURI().equals( nsKey ) || RDFS.getURI().equals( nsKey ) || XSD.getURI().equals( nsKey ) ) ) { // not an ignorable namespace int count = nsCount.get( nsKey ).intValue(); if ( count > max ) { // highest count seen so far max = count; ns = nsKey; } } } return ns; } /** Record a use of the given namespace in the count map */ private void countNamespace( Resource r, Map<String,Integer> nsCount ) { if (!r.isAnon()) { String ns = r.getNameSpace(); // increment the count for this namespace Integer count = nsCount.containsKey( ns ) ? (Integer) nsCount.get( ns ) : new Integer( 0 ); Integer count1 = new Integer( count.intValue() + 1 ); nsCount.put( ns, count1 ); } } /** Write the list of properties */ protected void writeProperties() { if (m_options.hasNopropertiesOption()) { return; } if (m_options.hasPropertySectionOption()) { writeln( 0, m_options.getPropertySectionOption()); } if (useOntology()) { writeObjectProperties(); writeDatatypeProperties(); writeAnnotationProperties(); // we also write out the RDF properties, to mop up any props that are not stated as // object, datatype or annotation properties writeRDFProperties( true ); } else { writeRDFProperties( false ); } } /** Write any object properties in the vocabulary */ protected void writeObjectProperties() { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; if (!m_options.hasLangRdfsOption()) { for (Iterator<? extends RDFNode> i = sorted( m_source.listObjectProperties() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "ObjectProperty", "createObjectProperty", "_PROP" ); } } } /** Write any datatype properties in the vocabulary */ protected void writeDatatypeProperties() { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; if (!m_options.hasLangRdfsOption()) { for (Iterator<? extends RDFNode> i = sorted( m_source.listDatatypeProperties() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "DatatypeProperty", "createDatatypeProperty", "_PROP" ); } } } /** Write any annotation properties in the vocabulary */ protected void writeAnnotationProperties() { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; if (!m_options.hasLangRdfsOption()) { for (Iterator<? extends RDFNode> i = sorted( m_source.listAnnotationProperties() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "AnnotationProperty", "createAnnotationProperty", "_PROP" ); } } } /** Write any vanilla RDF properties in the vocabulary */ protected void writeRDFProperties( boolean useOntProperty ) { String template = m_options.hasPropTemplateOption() ? m_options.getPropTemplateOption() : DEFAULT_TEMPLATE; String propType = useOntProperty ? "OntProperty" : "Property"; // select the appropriate properties based on the language choice Resource[] props; if (m_options.hasLangOwlOption()) { props = new Resource[] {OWL.ObjectProperty, OWL.DatatypeProperty, RDF.Property}; } else { props = new Resource[] {RDF.Property}; } // collect the properties to be written List<Resource> propertyResources = new ArrayList<>(); for ( Resource prop : props ) { for ( StmtIterator i = m_source.listStatements( null, RDF.type, prop ); i.hasNext(); ) { propertyResources.add( i.nextStatement().getSubject() ); } } // now write the properties for (Iterator<? extends RDFNode> i = sorted( propertyResources ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, propType, "create" + propType, "_PROP" ); } } /** Write any classes in the vocabulary */ protected void writeClasses() { if (m_options.hasNoclassesOption()) { return; } if (m_options.hasClassSectionOption()) { writeln( 0, m_options.getClassSectionOption()); } if (useOntology()) { writeOntClasses(); } else { writeRDFClasses(); } } /** Write classes as ontology terms */ protected void writeOntClasses() { String template = m_options.hasClassTemplateOption() ? m_options.getClassTemplateOption() : DEFAULT_TEMPLATE; for (Iterator<? extends RDFNode> i = sorted( m_source.listClasses() ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "OntClass", "createClass", "_CLASS" ); } } /** Write classes as vanilla RDF terms */ protected void writeRDFClasses() { String template = m_options.hasClassTemplateOption() ? m_options.getClassTemplateOption() : DEFAULT_TEMPLATE; // make sure we're looking for the appropriate type of class Resource cls = OWL.Class; if (m_options.hasLangRdfsOption()) { cls = RDFS.Class; } // collect the classes to list List<Resource> classes = m_source.listStatements( null, RDF.type, cls ).mapWith( s -> s.getSubject()).toList(); for (Iterator<? extends RDFNode> i = sorted( classes ); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "Resource", "createResource", "_CLASS" ); } } /** Write any instances (individuals) in the vocabulary */ protected void writeIndividuals() { if (m_options.hasNoindividualsOption()) { return; } if (m_options.hasIndividualsSectionOption()) { writeln( 0, m_options.getIndividualsSectionOption() ); } if (useOntology()) { writeOntIndividuals(); } else { writeRDFIndividuals(); } } /** Write individuals as ontology terms */ protected void writeOntIndividuals() { String template = m_options.hasIndividualTemplateOption() ? m_options.getIndividualTemplateOption() : DEFAULT_INDIVIDUAL_TEMPLATE; for (Iterator<? extends RDFNode> i = selectIndividuals(); i.hasNext(); ) { Individual ind = ((Resource) i.next()).as( Individual.class ); // do we have a local class resource Resource cls = ind.getOntClass(); if (cls == null) { cls = OWL.Thing; } String varName = m_resourcesToNames.get( cls ); String valType = (varName != null) ? varName : "M_MODEL.createClass( \"" + cls.getURI() + "\" )"; // push the individuals type onto the stack addReplacementPattern( "valtype", valType ); writeValue( ind, template, "Individual", "createIndividual", "_INSTANCE" ); pop( 1 ); } } /** Write individuals as vanilla RDF terms */ protected void writeRDFIndividuals() { String template = m_options.hasIndividualTemplateOption() ? m_options.getIndividualTemplateOption() : DEFAULT_RDFS_INDIVIDUAL_TEMPLATE; for (Iterator<? extends RDFNode> i = selectIndividuals(); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "Resource", "createResource", "_INSTANCE" ); } } /** Answer an iterator over the individuals selected for output */ protected ExtendedIterator<? extends RDFNode> selectIndividuals() { List<Resource> candidates = new ArrayList<>(); for (StmtIterator i = m_source.listStatements( null, RDF.type, (RDFNode) null ); i.hasNext(); ) { Statement candidate = i.nextStatement(); if (candidate.getObject().isResource()) { Resource candObj = candidate.getResource(); Resource candSubj = candidate.getSubject(); // ignore RDFS and OWL builtins if (!candObj.isAnon()) { String candTypeURI = candObj.getURI(); if (candTypeURI.startsWith( RDF.getURI() ) || candTypeURI.startsWith( OWL.getURI() ) || candTypeURI.startsWith( RDFS.getURI() )) { continue; } } // note that whether candSubj is included is tested later on by {@link #filter} if (!candSubj.isAnon() && (isIncluded( candObj ) || isIncluded( candSubj )) && !candidates.contains( candSubj )) { candidates.add( candSubj ); } } } return sorted( candidates ); } /** * Answer true if the given resource is accepted for presentation in the output, which * is true iff it is a URI node, whose namespace is one of the accepted namespaces in * {@link #m_includeURI}. * @param r A resource to test * @return True if the resource is to be included in the generated output */ protected boolean isIncluded( Resource r ) { boolean accepted = false; if (!r.isAnon()) { String uri = r.getURI(); for (Iterator<String> j = m_includeURI.iterator(); !accepted && j.hasNext(); ) { accepted = uri.startsWith( j.next() ); } } return accepted; } /** Write any datatypes in the vocabulary */ protected void writeDatatypes() { if (m_options.hasNodatatypesOption()) { return; } if (m_options.hasDatatypesSectionOption()) { writeln( 0, m_options.getDatatypesSectionOption() ); } String template = m_options.hasDatatypeTemplateOption() ? m_options.getDatatypeTemplateOption() : DEFAULT_TEMPLATE; // Cannot create a full RDFDatatype object since we don't know how to parse these custom types, but we can at least specify a Resource for (Iterator<? extends RDFNode> i = selectDatatypes(); i.hasNext(); ) { writeValue( (Resource) i.next(), template, "Resource", "createResource", "_DATATYPE" ); } } /** Answer an iterator over the datatypes selected for output */ protected ExtendedIterator<? extends RDFNode> selectDatatypes() { List<Resource> candidates = new ArrayList<>(); for (StmtIterator i = m_source.listStatements( null, RDF.type, RDFS.Datatype ); i.hasNext(); ) { Statement candidate = i.nextStatement(); if (candidate.getObject().isResource()) { Resource candSubj = candidate.getSubject(); // ignore XSD builtins if (!candSubj.isAnon()) { String candTypeURI = candSubj.getURI(); if (candTypeURI.startsWith( XSD.getURI() )) { continue; } } // note that whether candSubj is included is tested later on by {@link #filter} if (!candSubj.isAnon() && !candidates.contains( candSubj )) { candidates.add( candSubj ); } } } return sorted( candidates ); } /** Write the value declaration out using the given template, optionally creating comments */ protected void writeValue( Resource r, String template, String valueClass, String creator, String disambiguator ) { if (!filter( r )) { if (!noComments() && hasComment( r )) { writeln( 1, formatComment( getComment( r ) ) ); } // push the local bindings for the substitution onto the stack addReplacementPattern( "valuri", r.getURI() ); addReplacementPattern( "valname", getValueName( r, disambiguator )); addReplacementPattern( "valclass", valueClass ); addReplacementPattern( "valcreator", creator ); // write out the value writeln( 1, substitute( template ) ); writeln( 1 ); // pop the local replacements off the stack pop( 4 ); } } /** Answer true if the given resource has an rdf:comment */ protected boolean hasComment( Resource r ) { return r.hasProperty( RDFS.comment ) ; } /** Answer all of the commentary on the given resource, as a string */ protected String getComment( Resource r ) { StringBuffer comment = new StringBuffer(); // collect any RDFS or DAML comments attached to the node for (NodeIterator ni = m_source.listObjectsOfProperty( r, RDFS.comment ); ni.hasNext(); ) { RDFNode n = ni.nextNode(); if (n instanceof Literal) { comment.append( ((Literal) n).getLexicalForm().trim() ); } else { System.err.println( "Warning: Comment on resource <" + r.getURI() + "> is not a literal: " + n ); } } return comment.toString(); } /** Format the comment as Javadoc, and limit the line width */ protected String formatComment( String comment ) { StringBuffer buf = new StringBuffer(); buf.append( "/** <p>" ); boolean inSpace = false; int pos = buf.length(); boolean singleLine = true; // now format the comment by compacting whitespace and limiting the line length // add the prefix to the start of each line for (int i = 0; i < comment.length(); i++ ) { char c = comment.charAt( i ); // compress whitespace if (Character.isWhitespace( c )) { if (inSpace) { continue; // more than one space is ignored } else { c = ' '; // map all whitespace to 0x20 inSpace = true; } } else { inSpace = false; } // escapes? if (c == '\\') { c = comment.charAt( ++i ); switch (c) { case 'n': buf.append( m_nl ); pos = indentTo( 1, buf ); buf.append( " * " ); pos += 3; singleLine = false; break; default: // add other escape sequences above break; } } else if (c == '<') { buf.append( "&lt;" ); pos += 4; } else if (c == '>') { buf.append( "&gt;" ); pos += 4; } else if (c == '&') { buf.append( "&amp;" ); pos += 5; } else { // add the char buf.append( c ); pos++; } // wrap any very long lines at 120 chars if ((pos > COMMENT_LENGTH_LIMIT) && (inSpace)) { buf.append( m_nl ); pos = indentTo( 1, buf ); buf.append( " * " ); pos += 3; singleLine = false; } } buf.append( "</p>" ); buf.append( singleLine ? "" : m_nl ); indentTo( singleLine ? 0 : 1, buf ); buf.append( " */" ); return buf.toString(); } /** Answer true if resource r <b>does not</b> show in output */ protected boolean filter( Resource r ) { if (r.isAnon()) { return true; } // if we've already processed this resource once, ignore it next time if (m_resourcesToNames.containsKey( r )) { return true; } // search the allowed URI's for ( String uri : m_includeURI ) { if ( r.getURI().startsWith( uri ) ) { // in return false; } } // we allow individuals whose class is not in the included NS's, unless opt strict-individuals is true */ if (!m_options.hasStrictIndividualsOption()) { for (StmtIterator j = r.listProperties( RDF.type ); j.hasNext(); ) { // we search the rdf:types of this resource Resource typeRes = j.nextStatement().getResource(); if (!typeRes.isAnon()) { String typeURI = typeRes.getURI(); // for any type that is in a permitted NS for ( String uri : m_includeURI ) { if ( typeURI.startsWith( uri ) ) { // in return false; } } } } } // default is out return true; } /** Answer the Java value name for the URI */ protected String getValueName( Resource r, String disambiguator ) { // the id name is basically the local name of the resource, possibly in upper case String name = m_options.hasUcNamesOption() ? getUCValueName( r ) : r.getLocalName(); // must be legal java name = asLegalJavaID( name, false ); // must not clash with an existing name int attempt = 0; String baseName = name; while (m_usedNames.contains( name )) { name = (attempt == 0) ? (name + disambiguator) : (baseName + disambiguator + attempt); attempt++; } // record this name so that we don't use it again (which will stop the vocabulary from compiling) m_usedNames.add( name ); // record the mapping from resource to name m_resourcesToNames.put( r, name ); return name; } /** Answer the local name of resource r mapped to upper case */ protected String getUCValueName( Resource r ) { StringBuffer buf = new StringBuffer(); String localName = r.getLocalName(); char lastChar = 0; for (int i = 0; i < localName.length(); i++) { char c = localName.charAt(i); if (Character.isLowerCase(lastChar) && Character.isUpperCase(c)) { buf.append( '_' ); } buf.append( Character.toUpperCase(c) ); lastChar = c; } return buf.toString(); } /** Answer an iterator that contains the elements of the given list, but sorted by URI */ protected ExtendedIterator<? extends RDFNode> sorted( ExtendedIterator<? extends RDFNode> i ) { return sorted( i.toList() ); } /** Answer an iterator that contains the elements of the given iterator, but sorted by URI */ protected ExtendedIterator<? extends RDFNode> sorted( List<? extends RDFNode> members ) { Collections.sort( members, new Comparator<RDFNode>() { @Override public int compare( RDFNode n0, RDFNode n1 ) { if (n0.isLiteral() || n1.isLiteral()) { if (n0.isLiteral() && n1.isLiteral()) { // two literals Literal l0 = (Literal) n0; Literal l1 = (Literal) n1; return l0.getLexicalForm().compareTo( l1.getLexicalForm() ); } else { return n0.isLiteral() ? -1 : 1; } } else { Resource r0 = (Resource) n0; Resource r1 = (Resource) n1; if (r0.isAnon() && r1.isAnon()) { // two anonID's - the order is important as long as its consistent return r0.getId().toString().compareTo( r1.getId().toString() ); } else if (r0.isAnon()) { return -1; } else if (r1.isAnon()) { return 1; } else { // two named resources return r0.getURI().compareTo( r1.getURI() ); } } }} ); return WrappedIterator.create( members.iterator() ); } //============================================================================== // Inner class definitions //============================================================================== public interface SchemagenOptions { /* Constants for the various options we can set */ public enum OPT { /** Select an alternative config file; use <code>-c &lt;filename&gt;</code> on command line */ CONFIG_FILE, /** Turn off all comment output; use <code>--nocomments</code> on command line; use <code>sgen:noComments</code> in config file */ NO_COMMENTS, /** Nominate the URL of the input document; use <code>-i &lt;URL&gt;</code> on command line; use <code>sgen:input</code> in config file */ INPUT, /** Specify that the language of the source is DAML+OIL; use <code>--daml</code> on command line; use <code>sgen:daml</code> in config file */ LANG_DAML, /** Specify that the language of the source is OWL (the default); use <code>--owl</code> on command line; use <code>sgen:owl</code> in config file */ LANG_OWL, /** Specify that the language of the source is RDFS; use <code>--rdfs</code> on command line; use <code>sgen:rdfs</code> in config file */ LANG_RDFS, /** Specify that destination file; use <code>-o &lt;fileName&gt;</code> on command line; use <code>sgen:output</code> in config file */ OUTPUT, /** Specify the file header; use <code>--header "..."</code> on command line; use <code>sgen:header</code> in config file */ HEADER, /** Specify the file footer; use <code>--footer "..."</code> on command line; use <code>sgen:footer</code> in config file */ FOOTER, /** Specify the uri of the configuration root node; use <code>--root &lt;URL&gt;</code> on command line */ ROOT, /** Specify the marker string for substitutions, default is '%'; use <code>-m "..."</code> on command line; use <code>sgen:marker</code> in config file */ MARKER, /** Specify the packagename; use <code>--package &lt;packagename&gt;</code> on command line; use <code>sgen:package</code> in config file */ PACKAGENAME, /** Use ontology terms in preference to vanilla RDF; use <code>--ontology</code> on command line; use <code>sgen:ontology</code> in config file */ ONTOLOGY, /** The name of the generated class; use <code>-n &lt;classname&gt;</code> on command line; use <code>sgen:classname</code> in config file */ CLASSNAME, /** Additional decoration for class header (such as implements); use <code>--classdec &lt;classname&gt;</code> on command line; use <code>sgen:classdec</code> in config file */ CLASSDEC, /** The namespace URI for the vocabulary; use <code>-a &lt;uri&gt;</code> on command line; use <code>sgen:namespace</code> in config file */ NAMESPACE, /** Additional declarations to add at the top of the class; use <code>--declarations &lt;...&gt;</code> on command line; use <code>sgen:declarations</code> in config file */ DECLARATIONS, /** Section declaration for properties section; use <code>--propSection &lt;...&gt;</code> on command line; use <code>sgen:propSection</code> in config file */ PROPERTY_SECTION, /** Section declaration for class section; use <code>--classSection &lt;...&gt;</code> on command line; use <code>sgen:classSection</code> in config file */ CLASS_SECTION, /** Section declaration for individuals section; use <code>--individualsSection &lt;...&gt;</code> on command line; use <code>sgen:individualsSection</code> in config file */ INDIVIDUALS_SECTION, /** Section declaration for datatypes section; use <code>--datatypesSection &lt;...&gt;</code> on command line; use <code>sgen:datatypesSection</code> in config file */ DATATYPES_SECTION, /** Option to suppress properties in vocab file; use <code>--noproperties &lt;...&gt;</code> on command line; use <code>sgen:noproperties</code> in config file */ NOPROPERTIES, /** Option to suppress classes in vocab file; use <code>--noclasses &lt;...&gt;</code> on command line; use <code>sgen:noclasses</code> in config file */ NOCLASSES, /** Option to suppress individuals in vocab file; use <code>--noindividuals &lt;...&gt;</code> on command line; use <code>sgen:noindividuals</code> in config file */ NOINDIVIDUALS, /** Option to suppress datatypes in vocab file; use <code>--nodatatypes &lt;...&gt;</code> on command line; use <code>sgen:nodatatypes</code> in config file */ NODATATYPES, /** Option for no file header; use <code>--noheader &lt;...&gt;</code> on command line; use <code>sgen:noheader</code> in config file */ NOHEADER, /** Template for writing out property declarations; use <code>--propTemplate &lt;...&gt;</code> on command line; use <code>sgen:propTemplate</code> in config file */ PROP_TEMPLATE, /** Template for writing out class declarations; use <code>--classTemplate &lt;...&gt;</code> on command line; use <code>sgen:classTemplate</code> in config file */ CLASS_TEMPLATE, /** Template for writing out individual declarations; use <code>--individualTemplate &lt;...&gt;</code> on command line; use <code>sgen:individualTemplate</code> in config file */ INDIVIDUAL_TEMPLATE, /** Template for writing out datatype declarations; use <code>--datatypeTemplate &lt;...&gt;</code> on command line; use <code>sgen:datatypeTemplate</code> in config file */ DATATYPE_TEMPLATE, /** Option for mapping constant names to uppercase; use <code>--uppercase &lt;...&gt;</code> on command line; use <code>sgen:uppercase</code> in config file */ UC_NAMES, /** Option for including non-local URI's in vocabulary; use <code>--include &lt;uri&gt;</code> on command line; use <code>sgen:include</code> in config file */ INCLUDE, /** Option for adding a suffix to the generated class name; use <code>--classnamesuffix &lt;uri&gt;</code> on command line; use <code>sgen:classnamesuffix</code> in config file */ CLASSNAME_SUFFIX, /** Option for the presentation syntax (encoding) of the file; use <code>-e <i>encoding</i></code> on command line; use <code>sgen:encoding</code> in config file */ ENCODING, /** Option to show the usage message; use --help on command line */ HELP, /** Option to generate an output file with DOS (\r\n) line endings. Default is Unix line endings. */ DOS, /** Option to generate to force the model to perform inference, off by default. */ USE_INF, /** Option to exclude instances of classes in the allowed namespaces, where the individuals themselves are in other namespaces; use <code>--strictIndividuals</code> on command line; use <code>sgen:strictIndividuals</code> in config file */ STRICT_INDIVIDUALS, /** Option to include the ontology source code in the generated file */ INCLUDE_SOURCE, /** Option to turn off strict checking in .a() */ NO_STRICT } public static final Object[][] m_optionDefinitions = new Object[][] { {OPT.CONFIG_FILE, new OptionDefinition( "-c", "configFile" ) }, {OPT.ROOT, new OptionDefinition( "-r", "root" ) }, {OPT.NO_COMMENTS, new OptionDefinition( "--nocomments", "noComments" ) }, {OPT.INPUT, new OptionDefinition( "-i", "input" ) }, {OPT.LANG_DAML, new OptionDefinition( "--daml", "daml" ) }, {OPT.LANG_OWL, new OptionDefinition( "--owl", "owl" ) }, {OPT.LANG_RDFS, new OptionDefinition( "--rdfs", "rdfs" ) }, {OPT.OUTPUT, new OptionDefinition( "-o", "output" ) }, {OPT.HEADER, new OptionDefinition( "--header", "header" ) }, {OPT.FOOTER, new OptionDefinition( "--footer", "footer" ) }, {OPT.MARKER, new OptionDefinition( "--marker", "marker" ) }, {OPT.PACKAGENAME, new OptionDefinition( "--package", "package" ) }, {OPT.ONTOLOGY, new OptionDefinition( "--ontology", "ontology" ) }, {OPT.CLASSNAME, new OptionDefinition( "-n", "classname" ) }, {OPT.CLASSDEC, new OptionDefinition( "--classdec", "classdec" ) }, {OPT.NAMESPACE, new OptionDefinition( "-a", "namespace" ) }, {OPT.DECLARATIONS, new OptionDefinition( "--declarations", "declarations" ) }, {OPT.PROPERTY_SECTION, new OptionDefinition( "--propSection", "propSection" ) }, {OPT.CLASS_SECTION, new OptionDefinition( "--classSection", "classSection" ) }, {OPT.INDIVIDUALS_SECTION, new OptionDefinition( "--individualsSection", "individualsSection" ) }, {OPT.DATATYPES_SECTION, new OptionDefinition( "--datatypesSection", "datatypesSection" ) }, {OPT.NOPROPERTIES, new OptionDefinition( "--noproperties", "noproperties" ) }, {OPT.NOCLASSES, new OptionDefinition( "--noclasses", "noclasses" ) }, {OPT.NOINDIVIDUALS, new OptionDefinition( "--noindividuals", "noindividuals" ) }, {OPT.NODATATYPES, new OptionDefinition( "--nodatatypes", "nodatatypes" ) }, {OPT.PROP_TEMPLATE, new OptionDefinition( "--propTemplate", "propTemplate" ) }, {OPT.CLASS_TEMPLATE, new OptionDefinition( "--classTemplate", "classTemplate" ) }, {OPT.INDIVIDUAL_TEMPLATE, new OptionDefinition( "--individualTemplate", "individualTemplate" ) }, {OPT.DATATYPE_TEMPLATE, new OptionDefinition( "--datatypeTemplate", "datatypeTemplate" ) }, {OPT.UC_NAMES, new OptionDefinition( "--uppercase", "uppercase" ) }, {OPT.INCLUDE, new OptionDefinition( "--include", "include" ) }, {OPT.CLASSNAME_SUFFIX, new OptionDefinition( "--classnamesuffix", "classnamesuffix" )}, {OPT.NOHEADER, new OptionDefinition( "--noheader", "noheader" )}, {OPT.ENCODING, new OptionDefinition( "-e", "encoding" )}, {OPT.HELP, new OptionDefinition( "--help", "help" )}, {OPT.DOS, new OptionDefinition( "--dos", "dos" )}, {OPT.USE_INF, new OptionDefinition( "--inference", "inference" )}, {OPT.STRICT_INDIVIDUALS, new OptionDefinition( "--strictIndividuals", "strictIndividuals" )}, {OPT.INCLUDE_SOURCE, new OptionDefinition( "--includeSource", "includeSource" )}, {OPT.NO_STRICT, new OptionDefinition( "--nostrict", "noStrict")}, }; public boolean hasConfigFileOption(); public String getConfigFileOption(); public boolean hasRootOption(); public String getRootOption(); public boolean hasNoCommentsOption(); public String getNoCommentsOption(); public boolean hasInputOption(); public Resource getInputOption(); public boolean hasLangOwlOption(); public String getLangOwlOption(); public boolean hasLangRdfsOption(); public String getLangRdfsOption(); public boolean hasOutputOption(); public String getOutputOption(); public boolean hasHeaderOption(); public String getHeaderOption(); public boolean hasFooterOption(); public String getFooterOption(); public boolean hasMarkerOption(); public String getMarkerOption(); public boolean hasPackagenameOption(); public String getPackagenameOption(); public boolean hasOntologyOption(); public String getOntologyOption(); public boolean hasClassnameOption(); public String getClassnameOption(); public boolean hasClassdecOption(); public String getClassdecOption(); public boolean hasNamespaceOption(); public Resource getNamespaceOption(); public boolean hasDeclarationsOption(); public String getDeclarationsOption(); public boolean hasPropertySectionOption(); public String getPropertySectionOption(); public boolean hasClassSectionOption(); public String getClassSectionOption(); public boolean hasIndividualsSectionOption(); public String getIndividualsSectionOption(); public boolean hasDatatypesSectionOption(); public String getDatatypesSectionOption(); public boolean hasNopropertiesOption(); public boolean hasNoclassesOption(); public boolean hasNoindividualsOption(); public boolean hasNodatatypesOption(); public boolean hasPropTemplateOption(); public String getPropTemplateOption(); public boolean hasClassTemplateOption(); public String getClassTemplateOption(); public boolean hasIndividualTemplateOption(); public String getIndividualTemplateOption(); public boolean hasDatatypeTemplateOption(); public String getDatatypeTemplateOption(); public boolean hasUcNamesOption(); public boolean hasIncludeOption(); public List<String> getIncludeOption(); public boolean hasClassnameSuffixOption(); public String getClassnameSuffixOption(); public boolean hasNoheaderOption(); public boolean hasEncodingOption(); public String getEncodingOption(); public boolean hasHelpOption(); public String getHelpOption(); public boolean hasDosOption(); public boolean hasUseInfOption(); public boolean hasStrictIndividualsOption(); public boolean hasIncludeSourceOption(); public boolean hasNoStrictOption(); } public static class SchemagenOptionsImpl implements SchemagenOptions { // Instance variables /** The list of command line arguments */ private List<String> m_cmdLineArgs = new ArrayList<>(); /** The root of the options in the config file */ private Resource m_root; /** The model that contains the configuration information */ private Model m_config = ModelFactory.createDefaultModel(); // Constructor public SchemagenOptionsImpl( String[] args ) { m_cmdLineArgs = Arrays.asList( args ); // check to see if there's a specified config file String configURL = DEFAULT_CONFIG_URI; if (hasConfigFileOption()) { // check for protocol; add file: if not specified configURL = SchemagenUtils.urlCheck( getConfigFileOption() ); } // try to read the config URI try { FileManager.get().readModel( m_config, configURL ); } catch (Exception e) { // if the user left the default config URI in place, it's not an error to fail to read it if (!configURL.equals( DEFAULT_CONFIG_URI )) { throw new SchemagenException( "Failed to read configuration from URL: " + configURL, e ); } } // ensure we have a root URI for the configuration model determineConfigRoot(); } /** * Return the configuration model used to hold config information * @return Model */ protected Model getConfigModel() { return m_config; } /** * Return the root resource to which configuration information is attached * @return Resource */ protected Resource getConfigRoot() { if (m_root == null) { determineConfigRoot(); } return m_root; } // Internal implementation methods /** Determine the root resource in the configuration file */ protected void determineConfigRoot() { if (hasValue( OPT.ROOT )) { m_root = m_config.getResource( getStringValue( OPT.ROOT ) ); } else { // no specified root, we assume there is only one with type sgen:Config StmtIterator i = m_config.listStatements( null, RDF.type, m_config.getResource( NS + "Config" ) ); if (i.hasNext()) { m_root = i.nextStatement().getSubject(); } else { // no configuration root, so we invent one m_root = m_config.createResource(); } } } /** Answer true if the given option is set to true */ protected boolean isTrue( OPT option ) { return getOpt( option ).isTrue( m_cmdLineArgs, m_root ); } /** Answer true if the given option has value */ protected boolean hasValue( OPT option ) { return getOpt( option ).hasValue( m_cmdLineArgs, m_root ); } /** Answer the value of the option or null */ protected RDFNode getValue( OPT option ) { return getOpt( option ).getValue( m_cmdLineArgs, m_root ); } /** Answer the String value of the option or null */ protected String getStringValue( OPT option ) { return getOpt( option ).getStringValue( m_cmdLineArgs, m_root ); } /** Answer true if the given option has a resource value */ protected boolean hasResourceValue( OPT option ) { return getOpt( option ).hasResourceValue( m_cmdLineArgs, m_root ); } /** Answer the value of the option or null */ protected Resource getResource( OPT option ) { return getOpt( option ).getResource( m_cmdLineArgs, m_root ); } /** Answer all values for the given options as Strings */ protected List<String> getAllValues( OPT option ) { List<String> values = new ArrayList<>(); OptionDefinition opt = getOpt( option ); // look in the command line arguments for (Iterator<String> i = m_cmdLineArgs.iterator(); i.hasNext(); ) { String s = i.next(); if (s.equals( opt.m_cmdLineForm )) { // next iterator value is the arg value values.add( i.next() ); } } // now look in the config file for (StmtIterator i = m_root.listProperties( opt.m_prop ); i.hasNext(); ) { Statement s = i.nextStatement(); if (s.getObject() instanceof Literal) { values.add( s.getString() ); } else { values.add( s.getResource().getURI() ); } } return values; } /** Answer the option object for the given option */ protected OptionDefinition getOpt( OPT option ) { for ( Object[] m_optionDefinition : m_optionDefinitions ) { if ( m_optionDefinition[0] == option ) { return (OptionDefinition) m_optionDefinition[1]; } } return null; } // External interface methods @Override public boolean hasConfigFileOption() { return hasValue( OPT.CONFIG_FILE ); } @Override public String getConfigFileOption() { return getStringValue( OPT.CONFIG_FILE ); } @Override public boolean hasRootOption() { return hasValue( OPT.ROOT ); } @Override public String getRootOption() { return getStringValue( OPT.ROOT ); } @Override public boolean hasNoCommentsOption() { return isTrue( OPT.NO_COMMENTS ); } @Override public String getNoCommentsOption() { return getStringValue( OPT.NO_COMMENTS ); } @Override public boolean hasInputOption() { return hasValue( OPT.INPUT ); } @Override public Resource getInputOption() { return getResource( OPT.INPUT ); } @Override public boolean hasLangOwlOption() { return isTrue( OPT.LANG_OWL ); } @Override public String getLangOwlOption() { return getStringValue( OPT.LANG_OWL ); } @Override public boolean hasLangRdfsOption() { return isTrue( OPT.LANG_RDFS ); } @Override public String getLangRdfsOption() { return getStringValue( OPT.LANG_RDFS ); } @Override public boolean hasOutputOption() { return hasValue( OPT.OUTPUT ); } @Override public String getOutputOption() { return getStringValue( OPT.OUTPUT ); } @Override public boolean hasHeaderOption() { return hasValue( OPT.HEADER ); } @Override public String getHeaderOption() { return getStringValue( OPT.HEADER ); } @Override public boolean hasFooterOption() { return isTrue( OPT.FOOTER ); } @Override public String getFooterOption() { return getStringValue( OPT.FOOTER ); } @Override public boolean hasMarkerOption() { return hasValue( OPT.MARKER ); } @Override public String getMarkerOption() { return getStringValue( OPT.MARKER ); } @Override public boolean hasPackagenameOption() { return hasValue( OPT.PACKAGENAME ); } @Override public String getPackagenameOption() { return getStringValue( OPT.PACKAGENAME ); } @Override public boolean hasOntologyOption() { return isTrue( OPT.ONTOLOGY ); } @Override public String getOntologyOption() { return getStringValue( OPT.ONTOLOGY ); } @Override public boolean hasClassnameOption() { return hasValue( OPT.CLASSNAME ); } @Override public String getClassnameOption() { return getStringValue( OPT.CLASSNAME ); } @Override public boolean hasClassdecOption() { return hasValue( OPT.CLASSDEC ); } @Override public String getClassdecOption() { return getStringValue( OPT.CLASSDEC ); } @Override public boolean hasNamespaceOption() { return hasValue( OPT.NAMESPACE ); } @Override public Resource getNamespaceOption() { return getResource( OPT.NAMESPACE ); } @Override public boolean hasDeclarationsOption() { return hasValue( OPT.DECLARATIONS ); } @Override public String getDeclarationsOption() { return getStringValue( OPT.DECLARATIONS ); } @Override public boolean hasPropertySectionOption() { return hasValue( OPT.PROPERTY_SECTION ); } @Override public String getPropertySectionOption() { return getStringValue( OPT.PROPERTY_SECTION ); } @Override public boolean hasClassSectionOption() { return hasValue( OPT.CLASS_SECTION ); } @Override public String getClassSectionOption() { return getStringValue( OPT.CLASS_SECTION ); } @Override public boolean hasIndividualsSectionOption() { return hasValue( OPT.INDIVIDUALS_SECTION ); } @Override public String getIndividualsSectionOption() { return getStringValue( OPT.INDIVIDUALS_SECTION ); } @Override public boolean hasDatatypesSectionOption() { return hasValue( OPT.DATATYPES_SECTION ); } @Override public String getDatatypesSectionOption() { return getStringValue( OPT.DATATYPES_SECTION ); } @Override public boolean hasNopropertiesOption() { return isTrue( OPT.NOPROPERTIES ); } @Override public boolean hasNoclassesOption() { return isTrue( OPT.NOCLASSES ); } @Override public boolean hasNoindividualsOption() { return isTrue( OPT.NOINDIVIDUALS ); } @Override public boolean hasNodatatypesOption() { return isTrue( OPT.NODATATYPES ); } @Override public boolean hasPropTemplateOption() { return hasValue( OPT.PROP_TEMPLATE ); } @Override public String getPropTemplateOption() { return getStringValue( OPT.PROP_TEMPLATE ); } @Override public boolean hasClassTemplateOption() { return hasValue( OPT.CLASS_TEMPLATE ); } @Override public String getClassTemplateOption() { return getStringValue( OPT.CLASS_TEMPLATE ); } @Override public boolean hasIndividualTemplateOption() { return hasValue( OPT.INDIVIDUAL_TEMPLATE ); } @Override public String getIndividualTemplateOption() { return getStringValue( OPT.INDIVIDUAL_TEMPLATE ); } @Override public boolean hasDatatypeTemplateOption() { return hasValue( OPT.DATATYPE_TEMPLATE ); } @Override public String getDatatypeTemplateOption() { return getStringValue( OPT.DATATYPE_TEMPLATE ); } @Override public boolean hasUcNamesOption() { return isTrue( OPT.UC_NAMES ); } @Override public boolean hasIncludeOption() { return hasValue( OPT.INCLUDE ); } @Override public List<String> getIncludeOption() { return getAllValues( OPT.INCLUDE ); } @Override public boolean hasClassnameSuffixOption() { return hasValue( OPT.CLASSNAME_SUFFIX ); } @Override public String getClassnameSuffixOption() { return getStringValue( OPT.CLASSNAME_SUFFIX ); } @Override public boolean hasNoheaderOption() { return isTrue( OPT.NOHEADER ); } @Override public boolean hasEncodingOption() { return hasValue( OPT.ENCODING ); } @Override public String getEncodingOption() { return getStringValue( OPT.ENCODING ); } @Override public boolean hasHelpOption() { return hasValue( OPT.HELP ); } @Override public String getHelpOption() { return getStringValue( OPT.HELP ); } @Override public boolean hasDosOption() { return isTrue( OPT.DOS ); } @Override public boolean hasUseInfOption() { return isTrue( OPT.USE_INF ); } @Override public boolean hasStrictIndividualsOption() { return isTrue( OPT.STRICT_INDIVIDUALS ); } @Override public boolean hasIncludeSourceOption() { return isTrue( OPT.INCLUDE_SOURCE ); } @Override public boolean hasNoStrictOption() { return isTrue( OPT.NO_STRICT ); } } /** An option that can be set either on the command line or in the RDF config */ public static class OptionDefinition { protected String m_cmdLineForm; protected Property m_prop; protected OptionDefinition( String cmdLineForm, String name ) { m_cmdLineForm = cmdLineForm; if (name != null) { m_prop = ResourceFactory.createProperty( NS, name ); } } /** * Return the RDF property that is used when configuring this option * via a {@link Model} * @return The declaration property, or null */ public Property getDeclarationProperty() { return m_prop; } /** * Return the command line form of this option * @return The command line form as a String */ public String getCommandLineForm() { return m_cmdLineForm; } /** * Answer true if this option is set to true, either on the command line * or in the config model * * @return boolean */ protected boolean isTrue( List<String> cmdLineArgs, Resource confRoot ) { if (cmdLineArgs.contains( m_cmdLineForm )) { return true; } if (confRoot.hasProperty( m_prop )) { return confRoot.getRequiredProperty( m_prop ).getBoolean(); } return false; } /** * Answer the string value of the parameter if set, or null otherwise. Note command line * has precedence. * * @return String */ protected String getStringValue( List<String> cmdLineArgs, Resource confRoot ) { RDFNode n = getValue( cmdLineArgs, confRoot ); return (n == null) ? null : (n.isLiteral() ? n.asLiteral().getLexicalForm() : n.toString() ); } /** * Return the value of the parameter if set, or null otherwise. Note command line * has precedence. * * @return The argument value as an RDFNode */ protected RDFNode getValue( List<String> cmdLineArgs, Resource confRoot ) { int index = cmdLineArgs.indexOf( m_cmdLineForm ); if (index >= 0) { try { return ResourceFactory.createPlainLiteral( cmdLineArgs.get( index + 1 ) ); } catch (IndexOutOfBoundsException e) { throw new SchemagenException( "Value for parameter " + m_cmdLineForm + " not set! Aborting.", e ); } } if (m_prop != null && confRoot != null && confRoot.hasProperty( m_prop )) { return confRoot.getRequiredProperty( m_prop ).getObject(); } // not set return null; } /** * Answer true if the parameter has a value at all. * * @return boolean */ protected boolean hasValue( List<String> cmdLineArgs, Resource confRoot ) { return getValue( cmdLineArgs, confRoot ) != null; } /** * Answer the resource value of the parameter if set, or null otherwise. * * @return String */ protected Resource getResource( List<String> cmdLineArgs, Resource confRoot ) { int index = cmdLineArgs.indexOf( m_cmdLineForm ); if (index >= 0) { try { return confRoot.getModel().getResource( cmdLineArgs.get( index + 1 ) ); } catch (IndexOutOfBoundsException e) { System.err.println( "Value for parameter " + m_cmdLineForm + " not set! Aborting."); } } if (m_prop != null && confRoot.hasProperty( m_prop )) { return confRoot.getRequiredProperty( m_prop ).getResource(); } // not set return null; } /** * Answer true if the parameter has a value at all. * * @return boolean */ protected boolean hasResourceValue( List<String> cmdLineArgs, Resource confRoot ) { return getResource( cmdLineArgs, confRoot ) != null; } } // end inner class OptionDefinition /** A pairing of pattern and substitution we want to apply to output */ protected class Replacement { protected String sub; protected Pattern pattern; protected Replacement( Pattern pattern, String sub) { this.sub = sub; this.pattern = pattern; } } // end inner class Replacement /** * <p>Schemagen runtime exception</p> */ public static class SchemagenException extends RuntimeException { public SchemagenException( String msg, Throwable cause ) { super( msg, cause ); } } /** Utility method container */ public static class SchemagenUtils { /** Return a URI formed from the given string, unchanged if it's already a URI or * converted to a file URI otherwise. If not recognisable as a URL, abort. */ public static String urlCheck( String uriOrFile ) { boolean legal = true; String url = uriOrFile; // is it a URI already? to check, we make a URL and see what happens! try { new URL( url ); } catch (MalformedURLException ignore) { legal = false; } // if not a legal url, assume it's a file if (!legal) { legal = true; String slash = System.getProperty( "file.separator" ); url = "file:" + (uriOrFile.startsWith( slash ) ? (slash + slash) : "") + uriOrFile; try { new URL( url ); } catch (MalformedURLException ignore) { legal = false; } } if (!legal) { throw new SchemagenException( "Could not parse " + uriOrFile + " as a legal URL or a file reference. Aborting.", null ); } return url; } } /* End class SchemagenUtils */ }
JENA-204: replace StringBuffer by StringBuilder
jena-cmds/src/main/java/jena/schemagen.java
JENA-204: replace StringBuffer by StringBuilder
<ide><path>ena-cmds/src/main/java/jena/schemagen.java <ide> } <ide> <ide> /** Add the appropriate indent to a buffer */ <del> protected int indentTo( int i, StringBuffer buf ) { <add> protected int indentTo( int i, StringBuilder buf ) { <ide> int indent = i * m_indentStep; <ide> for (int j = 0; j < indent; j++) { <ide> buf.append( ' ' ); <ide> <ide> /** Determine the list of imports to include in the file */ <ide> protected String getImports() { <del> StringBuffer buf = new StringBuffer(); <add> StringBuilder buf = new StringBuilder(); <ide> buf.append( "import org.apache.jena.rdf.model.*;" ); <ide> buf.append( m_nl ); <ide> <ide> <ide> /** Converts to a legal Java identifier; capitalise first char if cap is true */ <ide> protected String asLegalJavaID( String s, boolean cap ) { <del> StringBuffer buf = new StringBuffer(); <add> StringBuilder buf = new StringBuilder(); <ide> int i = 0; <ide> <ide> // treat the first character specially - must be able to start a Java ID, may have to up-case <ide> <ide> /** Answer all of the commentary on the given resource, as a string */ <ide> protected String getComment( Resource r ) { <del> StringBuffer comment = new StringBuffer(); <add> StringBuilder comment = new StringBuilder(); <ide> <ide> // collect any RDFS or DAML comments attached to the node <ide> for (NodeIterator ni = m_source.listObjectsOfProperty( r, RDFS.comment ); ni.hasNext(); ) { <ide> <ide> /** Format the comment as Javadoc, and limit the line width */ <ide> protected String formatComment( String comment ) { <del> StringBuffer buf = new StringBuffer(); <add> StringBuilder buf = new StringBuilder(); <ide> buf.append( "/** <p>" ); <ide> <ide> boolean inSpace = false; <ide> <ide> /** Answer the local name of resource r mapped to upper case */ <ide> protected String getUCValueName( Resource r ) { <del> StringBuffer buf = new StringBuffer(); <add> StringBuilder buf = new StringBuilder(); <ide> String localName = r.getLocalName(); <ide> char lastChar = 0; <ide>
Java
apache-2.0
b4fe0ada3101efffa5526db8734e0b79946e128c
0
nlalevee/jst
/* * Copyright 2013 JST contributors * * 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.hibnet.jst.ant; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileProvider; import org.eclipse.xtext.diagnostics.Severity; import org.eclipse.xtext.validation.Issue; import org.hibnet.jst.JstStandaloneSetup; import org.hibnet.jst.generator.JstJavaFileGenerator; import com.google.inject.Injector; public class JstGenerateTask extends Task { private ResourceCollection sources; private File output; public void add(ResourceCollection sources) { this.sources = sources; } public void setOutput(File output) { this.output = output; } @Override public void execute() throws BuildException { if (!sources.isFilesystemOnly()) { throw new BuildException("Only local files are supported for the sources"); } List<File> jstFiles = new ArrayList<File>(); @SuppressWarnings("unchecked") Iterator<Resource> itResource = sources.iterator(); while (itResource.hasNext()) { FileProvider fp = (FileProvider) itResource.next().as(FileProvider.class); jstFiles.add(fp.getFile()); } Injector injector = new JstStandaloneSetup().createInjectorAndDoEMFRegistration(); JstJavaFileGenerator generator = injector.getInstance(JstJavaFileGenerator.class); List<Issue> issues = generator.generate(jstFiles, output); boolean hasError = false; if (issues != null) { Map<String, List<Issue>> issuesByFile = new TreeMap<String, List<Issue>>(); Map<String, Severity> worstSeverityByFile = new TreeMap<String, Severity>(); for (Issue issue : issues) { if (issue.getSeverity() == Severity.ERROR) { hasError = true; } String file = issue.getUriToProblem().trimFragment().toFileString(); List<Issue> fileIssues = issuesByFile.get(file); Severity severity = worstSeverityByFile.get(file); if (fileIssues == null) { fileIssues = new ArrayList<Issue>(); issuesByFile.put(file, fileIssues); } if (severity == null || issue.getSeverity().ordinal() < severity.ordinal()) { worstSeverityByFile.put(file, issue.getSeverity()); } fileIssues.add(issue); } for (Entry<String, List<Issue>> entry : issuesByFile.entrySet()) { log("In file " + entry.getKey(), getLogLevel(worstSeverityByFile.get(entry.getKey()))); for (Issue issue : entry.getValue()) { int level = getLogLevel(issue.getSeverity()); log(" line " + issue.getLineNumber() + ": [" + issue.getSeverity() + "] " + issue.getMessage(), level); } } } if (hasError) { throw new BuildException("Error compiling jst templates"); } } private int getLogLevel(Severity severity) { switch (severity) { case ERROR: return Project.MSG_ERR; case WARNING: return Project.MSG_WARN; case INFO: return Project.MSG_INFO; default: return Project.MSG_INFO; } } }
org.hibnet.jst/src/org/hibnet/jst/ant/JstGenerateTask.java
/* * Copyright 2013 JST contributors * * 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.hibnet.jst.ant; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileProvider; import org.eclipse.xtext.validation.Issue; import org.hibnet.jst.JstStandaloneSetup; import org.hibnet.jst.generator.JstJavaFileGenerator; import com.google.inject.Injector; public class JstGenerateTask extends Task { private ResourceCollection sources; private File output; public void add(ResourceCollection sources) { this.sources = sources; } public void setOutput(File output) { this.output = output; } @Override public void execute() throws BuildException { if (!sources.isFilesystemOnly()) { throw new BuildException("Only local files are supported for the sources"); } List<File> jstFiles = new ArrayList<File>(); @SuppressWarnings("unchecked") Iterator<Resource> itResource = sources.iterator(); while (itResource.hasNext()) { FileProvider fp = (FileProvider) itResource.next().as(FileProvider.class); jstFiles.add(fp.getFile()); } Injector injector = new JstStandaloneSetup().createInjectorAndDoEMFRegistration(); JstJavaFileGenerator generator = injector.getInstance(JstJavaFileGenerator.class); List<Issue> issues = generator.generate(jstFiles, output); if (issues != null) { throw new BuildException("Error compiling jst templates"); } } }
better error log
org.hibnet.jst/src/org/hibnet/jst/ant/JstGenerateTask.java
better error log
<ide><path>rg.hibnet.jst/src/org/hibnet/jst/ant/JstGenerateTask.java <ide> import java.util.ArrayList; <ide> import java.util.Iterator; <ide> import java.util.List; <add>import java.util.Map; <add>import java.util.Map.Entry; <add>import java.util.TreeMap; <ide> <ide> import org.apache.tools.ant.BuildException; <add>import org.apache.tools.ant.Project; <ide> import org.apache.tools.ant.Task; <ide> import org.apache.tools.ant.types.Resource; <ide> import org.apache.tools.ant.types.ResourceCollection; <ide> import org.apache.tools.ant.types.resources.FileProvider; <add>import org.eclipse.xtext.diagnostics.Severity; <ide> import org.eclipse.xtext.validation.Issue; <ide> import org.hibnet.jst.JstStandaloneSetup; <ide> import org.hibnet.jst.generator.JstJavaFileGenerator; <ide> JstJavaFileGenerator generator = injector.getInstance(JstJavaFileGenerator.class); <ide> <ide> List<Issue> issues = generator.generate(jstFiles, output); <add> boolean hasError = false; <ide> if (issues != null) { <add> Map<String, List<Issue>> issuesByFile = new TreeMap<String, List<Issue>>(); <add> Map<String, Severity> worstSeverityByFile = new TreeMap<String, Severity>(); <add> for (Issue issue : issues) { <add> if (issue.getSeverity() == Severity.ERROR) { <add> hasError = true; <add> } <add> String file = issue.getUriToProblem().trimFragment().toFileString(); <add> List<Issue> fileIssues = issuesByFile.get(file); <add> Severity severity = worstSeverityByFile.get(file); <add> if (fileIssues == null) { <add> fileIssues = new ArrayList<Issue>(); <add> issuesByFile.put(file, fileIssues); <add> } <add> if (severity == null || issue.getSeverity().ordinal() < severity.ordinal()) { <add> worstSeverityByFile.put(file, issue.getSeverity()); <add> } <add> fileIssues.add(issue); <add> } <add> <add> for (Entry<String, List<Issue>> entry : issuesByFile.entrySet()) { <add> log("In file " + entry.getKey(), getLogLevel(worstSeverityByFile.get(entry.getKey()))); <add> for (Issue issue : entry.getValue()) { <add> int level = getLogLevel(issue.getSeverity()); <add> log(" line " + issue.getLineNumber() + ": [" + issue.getSeverity() + "] " + issue.getMessage(), <add> level); <add> } <add> } <add> } <add> <add> if (hasError) { <ide> throw new BuildException("Error compiling jst templates"); <ide> } <ide> } <ide> <add> private int getLogLevel(Severity severity) { <add> switch (severity) { <add> case ERROR: <add> return Project.MSG_ERR; <add> case WARNING: <add> return Project.MSG_WARN; <add> case INFO: <add> return Project.MSG_INFO; <add> default: <add> return Project.MSG_INFO; <add> } <add> } <ide> }
Java
apache-2.0
b393b988f7d732d496cad3900afd47330e0f0dd0
0
f2prateek/android-couchpotato
/* * Copyright 2014 Prateek Srivastava * * 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.f2prateek.couchpotato.ui.widget; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import android.view.ViewPropertyAnimator; import android.widget.FrameLayout; import android.widget.ImageView; import butterknife.ButterKnife; import butterknife.InjectView; import com.f2prateek.couchpotato.R; import com.squareup.picasso.Picasso; import java.util.Arrays; import java.util.List; import java.util.Random; public class KenBurnsView extends FrameLayout { private static final int SWAP_DURATION = 10000; private static final int FADE_DURATION = 500; private static final float MAX_SCALE_FACTOR = 1.5F; private static final float MIN_SCALE_FACTOR = 1.2F; private final Random random = new Random(); private final Handler handler = new Handler(); @InjectView(R.id.image0) ImageView activeImageView; @InjectView(R.id.image1) ImageView inactiveImageView; private List<String> images; private int currentImageIndex = 0; private Picasso picasso; private Runnable swapImageRunnable = new Runnable() { @Override public void run() { swapImage(); handler.postDelayed(this, SWAP_DURATION - FADE_DURATION * 2); } }; public KenBurnsView(Context context) { this(context, null); } public KenBurnsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public KenBurnsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private void swapImage() { // Swap our active and inactive image views for transition final ImageView swapper = inactiveImageView; inactiveImageView = activeImageView; activeImageView = swapper; // load the next image currentImageIndex = (1 + currentImageIndex) % images.size(); loadImage(inactiveImageView, images.get(currentImageIndex)); // Animate the active ImageView animate(activeImageView); // Fade in the active ImageView and fade out the inactive ImageView AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setDuration(FADE_DURATION); animatorSet.playTogether(ObjectAnimator.ofFloat(activeImageView, "alpha", 0.0f, 1.0f), ObjectAnimator.ofFloat(inactiveImageView, "alpha", 1.0f, 0.0f)); animatorSet.start(); } /** * Animate the view with a KenBurns effect. */ public void animate(View view) { float fromScale = pickScale(); float toScale = pickScale(); float fromTranslationX = pickTranslation(view.getWidth(), fromScale); float fromTranslationY = pickTranslation(view.getHeight(), fromScale); float toTranslationX = pickTranslation(view.getWidth(), toScale); float toTranslationY = pickTranslation(view.getHeight(), toScale); start(view, SWAP_DURATION, fromScale, toScale, fromTranslationX, fromTranslationY, toTranslationX, toTranslationY); } private float pickScale() { return MIN_SCALE_FACTOR + random.nextFloat() * (MAX_SCALE_FACTOR - MIN_SCALE_FACTOR); } private float pickTranslation(int value, float ratio) { return value * (ratio - 1.0f) * (random.nextFloat() - 0.5f); } private void start(View view, long duration, float fromScale, float toScale, float fromTranslationX, float fromTranslationY, float toTranslationX, float toTranslationY) { view.setScaleX(fromScale); view.setScaleY(fromScale); view.setTranslationX(fromTranslationX); view.setTranslationY(fromTranslationY); ViewPropertyAnimator propertyAnimator = view.animate() .translationX(toTranslationX) .translationY(toTranslationY) .scaleX(toScale) .scaleY(toScale) .setDuration(duration); propertyAnimator.start(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); handler.removeCallbacks(swapImageRunnable); } private void startKenBurnsAnimation() { handler.post(swapImageRunnable); } @Override protected void onFinishInflate() { super.onFinishInflate(); inflate(getContext(), R.layout.kenburns_view, this); ButterKnife.inject(this); } /** Initial load of images, we only have one image that we can display. */ public void load(Picasso picasso, String image) { this.picasso = picasso; this.images = Arrays.asList(image); loadImage(activeImageView, image); loadImage(inactiveImageView, image); startKenBurnsAnimation(); } public void update(List<String> images) { this.images = images; if (images.size() > 1) { currentImageIndex = 1; loadImage(inactiveImageView, images.get(currentImageIndex)); } } private void loadImage(ImageView imageView, String image) { picasso.load(image).fit().centerCrop().noFade().into(imageView); } }
couchpotato/src/main/java/com/f2prateek/couchpotato/ui/widget/KenBurnsView.java
/* * Copyright 2014 Prateek Srivastava * * 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.f2prateek.couchpotato.ui.widget; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import android.view.ViewPropertyAnimator; import android.widget.FrameLayout; import android.widget.ImageView; import butterknife.ButterKnife; import butterknife.InjectView; import com.f2prateek.couchpotato.R; import com.squareup.picasso.Picasso; import java.util.Arrays; import java.util.List; import java.util.Random; public class KenBurnsView extends FrameLayout { private static final int SWAP_DURATION = 10000; private static final int FADE_DURATION = 500; private static final float MAX_SCALE_FACTOR = 1.5F; private static final float MIN_SCALE_FACTOR = 1.2F; private final Random random = new Random(); private final Handler handler = new Handler(); @InjectView(R.id.image0) ImageView activeImageView; @InjectView(R.id.image1) ImageView inactiveImageView; private List<String> images; private int currentImageIndex = 0; private Picasso picasso; private Runnable swapImageRunnable = new Runnable() { @Override public void run() { swapImage(); handler.postDelayed(this, SWAP_DURATION - FADE_DURATION * 2); } }; public KenBurnsView(Context context) { this(context, null); } public KenBurnsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public KenBurnsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private void swapImage() { // Swap our active and inactive image views for transition final ImageView swapper = inactiveImageView; inactiveImageView = activeImageView; activeImageView = swapper; // Animate the active ImageView animate(activeImageView); // Fade in the active ImageView and fade out the inactive ImageView activeImageView.animate().alpha(1).withEndAction(new Runnable() { @Override public void run() { inactiveImageView.animate().alpha(0).withEndAction(new Runnable() { @Override public void run() { // Fetch the next image currentImageIndex = (1 + currentImageIndex) % images.size(); loadImage(inactiveImageView, images.get(currentImageIndex)); } }); } }); } /** * Animate the view with a KenBurns effect. */ public void animate(View view) { float fromScale = pickScale(); float toScale = pickScale(); float fromTranslationX = pickTranslation(view.getWidth(), fromScale); float fromTranslationY = pickTranslation(view.getHeight(), fromScale); float toTranslationX = pickTranslation(view.getWidth(), toScale); float toTranslationY = pickTranslation(view.getHeight(), toScale); start(view, SWAP_DURATION, fromScale, toScale, fromTranslationX, fromTranslationY, toTranslationX, toTranslationY); } private float pickScale() { return MIN_SCALE_FACTOR + random.nextFloat() * (MAX_SCALE_FACTOR - MIN_SCALE_FACTOR); } private float pickTranslation(int value, float ratio) { return value * (ratio - 1.0f) * (random.nextFloat() - 0.5f); } private void start(View view, long duration, float fromScale, float toScale, float fromTranslationX, float fromTranslationY, float toTranslationX, float toTranslationY) { view.setScaleX(fromScale); view.setScaleY(fromScale); view.setTranslationX(fromTranslationX); view.setTranslationY(fromTranslationY); ViewPropertyAnimator propertyAnimator = view.animate() .translationX(toTranslationX) .translationY(toTranslationY) .scaleX(toScale) .scaleY(toScale) .setDuration(duration); propertyAnimator.start(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); handler.removeCallbacks(swapImageRunnable); } private void startKenBurnsAnimation() { handler.post(swapImageRunnable); } @Override protected void onFinishInflate() { super.onFinishInflate(); inflate(getContext(), R.layout.kenburns_view, this); ButterKnife.inject(this); } /** Initial load of images, we only have one image that we can display. */ public void load(Picasso picasso, String image) { this.picasso = picasso; this.images = Arrays.asList(image); loadImage(activeImageView, image); loadImage(inactiveImageView, image); startKenBurnsAnimation(); } public void update(List<String> images) { this.images = images; if (images.size() > 1) { currentImageIndex = 1; loadImage(inactiveImageView, images.get(currentImageIndex)); } } private void loadImage(ImageView imageView, String image) { picasso.load(image).fit().centerCrop().noFade().into(imageView); } }
Nope!
couchpotato/src/main/java/com/f2prateek/couchpotato/ui/widget/KenBurnsView.java
Nope!
<ide><path>ouchpotato/src/main/java/com/f2prateek/couchpotato/ui/widget/KenBurnsView.java <ide> <ide> package com.f2prateek.couchpotato.ui.widget; <ide> <add>import android.animation.AnimatorSet; <add>import android.animation.ObjectAnimator; <ide> import android.content.Context; <ide> import android.os.Handler; <ide> import android.util.AttributeSet; <ide> inactiveImageView = activeImageView; <ide> activeImageView = swapper; <ide> <add> // load the next image <add> currentImageIndex = (1 + currentImageIndex) % images.size(); <add> loadImage(inactiveImageView, images.get(currentImageIndex)); <add> <ide> // Animate the active ImageView <ide> animate(activeImageView); <ide> <ide> // Fade in the active ImageView and fade out the inactive ImageView <del> activeImageView.animate().alpha(1).withEndAction(new Runnable() { <del> @Override public void run() { <del> inactiveImageView.animate().alpha(0).withEndAction(new Runnable() { <del> @Override public void run() { <del> // Fetch the next image <del> currentImageIndex = (1 + currentImageIndex) % images.size(); <del> loadImage(inactiveImageView, images.get(currentImageIndex)); <del> } <del> }); <del> } <del> }); <add> AnimatorSet animatorSet = new AnimatorSet(); <add> animatorSet.setDuration(FADE_DURATION); <add> animatorSet.playTogether(ObjectAnimator.ofFloat(activeImageView, "alpha", 0.0f, 1.0f), <add> ObjectAnimator.ofFloat(inactiveImageView, "alpha", 1.0f, 0.0f)); <add> animatorSet.start(); <ide> } <ide> <ide> /**
Java
bsd-3-clause
f7e7e1c708acdf4676c89bba2b28f20276a9a416
0
dimitarp/basex,dimitarp/basex,BaseXdb/basex,vincentml/basex,ksclarke/basex,dimitarp/basex,joansmith/basex,deshmnnit04/basex,joansmith/basex,dimitarp/basex,vincentml/basex,ksclarke/basex,BaseXdb/basex,BaseXdb/basex,deshmnnit04/basex,vincentml/basex,dimitarp/basex,dimitarp/basex,drmacro/basex,BaseXdb/basex,vincentml/basex,BaseXdb/basex,vincentml/basex,BaseXdb/basex,JensErat/basex,dimitarp/basex,ksclarke/basex,JensErat/basex,vincentml/basex,deshmnnit04/basex,vincentml/basex,JensErat/basex,ksclarke/basex,dimitarp/basex,JensErat/basex,joansmith/basex,deshmnnit04/basex,joansmith/basex,JensErat/basex,vincentml/basex,deshmnnit04/basex,JensErat/basex,drmacro/basex,BaseXdb/basex,dimitarp/basex,joansmith/basex,ksclarke/basex,drmacro/basex,deshmnnit04/basex,joansmith/basex,BaseXdb/basex,dimitarp/basex,vincentml/basex,joansmith/basex,dimitarp/basex,JensErat/basex,ksclarke/basex,deshmnnit04/basex,dimitarp/basex,vincentml/basex,drmacro/basex,joansmith/basex,drmacro/basex,JensErat/basex,vincentml/basex,deshmnnit04/basex,deshmnnit04/basex,JensErat/basex,deshmnnit04/basex,drmacro/basex,ksclarke/basex,BaseXdb/basex,drmacro/basex,joansmith/basex,drmacro/basex,deshmnnit04/basex,joansmith/basex,BaseXdb/basex,joansmith/basex,ksclarke/basex,drmacro/basex,BaseXdb/basex,drmacro/basex,ksclarke/basex,JensErat/basex,drmacro/basex,ksclarke/basex,drmacro/basex,JensErat/basex,joansmith/basex,ksclarke/basex,deshmnnit04/basex,vincentml/basex,JensErat/basex,BaseXdb/basex,ksclarke/basex
package org.basex.api.xqj; import static org.basex.api.xqj.BXQText.*; import java.net.URI; import javax.xml.namespace.QName; import javax.xml.xquery.XQItemType; import javax.xml.xquery.XQSequenceType; import org.basex.query.QueryTokens; import org.basex.query.item.Type; import org.basex.util.Token; /** * Java XQuery API - Item type. * * @author Workgroup DBIS, University of Konstanz 2005-09, ISC License * @author Christian Gruen */ final class BXQItemType implements XQItemType { /** Default item type. */ static final BXQItemType DEFAULT = new BXQItemType( Type.ITEM, null, -1, XQSequenceType.OCC_ZERO_OR_MORE); /** Existing base types. */ private static final Type[] BASE = { null , null , null , null , Type.AAT, Type.ATM, Type.DTD, //0 Type.YMD, Type.URI, Type.B6B, Type.BLN, Type.DAT, Type.INT, Type.ITR, //7 Type.SHR, Type.LNG, Type.DTM, Type.DEC, Type.DBL, Type.DUR, Type.FLT, //14 Type.DAY, Type.MON, Type.MDA, Type.YEA, Type.YMO, Type.HEX, Type.NOT, //21 Type.QNM, Type.STR, Type.TIM, Type.BYT, Type.NPI, Type.NNI, Type.NIN, //28 Type.PIN, Type.ULN, Type.UIN, Type.USH, Type.UBY, Type.NST, Type.TOK, //35 Type.LAN, Type.NAM, Type.NCN, Type.NMT, Type.ID , Type.IDR, Type.ENT, //42 null, null, null // 49 }; /** Name. */ private final QName name; /** Base type. */ private final int base; /** Occurrence. */ private final int occ; /** Data type. */ private final Type type; /** * Constructor. * @param b item type * @throws BXQException exception */ BXQItemType(final int b) throws BXQException { this(BASE[b], null, b); if(type == null) throw new BXQException(ATOM); } /** * Constructor. * @param t type */ BXQItemType(final Type t) { this(t, null, -1); } /** * Constructor. * @param t type * @param n name * @param b base type */ BXQItemType(final Type t, final QName n, final int b) { this(t, n, b, XQSequenceType.OCC_EXACTLY_ONE); } /** * Constructor. * @param t type * @param n name * @param b base type * @param o occurrence */ BXQItemType(final Type t, final QName n, final int b, final int o) { name = n; type = t; base = b; occ = o; } public int getBaseType() throws BXQException { if(type.unt) check(Type.DEL, Type.ELM, Type.ATT, Type.ATM); if(base != -1) return base; for(int b = 0; b < BASE.length; b++) if(BASE[b] == type) return b; throw new BXQException(NOBASE); } public int getItemKind() { switch(type) { case ATT : return XQITEMKIND_ATTRIBUTE; case COM : return XQITEMKIND_COMMENT; case DOC : return XQITEMKIND_DOCUMENT; case DEL : return XQITEMKIND_DOCUMENT_ELEMENT; case ELM : return XQITEMKIND_ELEMENT; case ITEM: return XQITEMKIND_ITEM; case NOD : return XQITEMKIND_NODE; case PI : return XQITEMKIND_PI; case TXT : return XQITEMKIND_TEXT; default : return XQITEMKIND_ATOMIC; } } public int getItemOccurrence() { return occ; } public QName getNodeName() throws BXQException { check(Type.DEL, Type.ELM, Type.ATT); return name; } public String getPIName() throws BXQException { if(type != Type.PI) throw new BXQException(PI); return name == null ? null : name.getLocalPart(); } public URI getSchemaURI() { return null; } public QName getTypeName() throws BXQException { if(type.unt) check(Type.DEL, Type.ELM, Type.ATT, Type.ATM); if(type == Type.ITEM) throw new BXQException(TYPE); final Type t = base != -1 ? BASE[base] : type; return new QName(Token.string(QueryTokens.XSURI), t.name); } public boolean isAnonymousType() { return false; } public boolean isElementNillable() { return false; } public XQItemType getItemType() { return this; } /** * Returns the item type. * @return type */ Type getType() { return type; } /** * Matches the input types against the instance type. * @param types input types * @throws BXQException exception */ private void check(final Type... types) throws BXQException { for(final Type t : types) if(type == t) return; throw new BXQException(TYPE); } @Override public String toString() { return type.name; } }
src/org/basex/api/xqj/BXQItemType.java
package org.basex.api.xqj; import static org.basex.api.xqj.BXQText.*; import java.net.URI; import javax.xml.namespace.QName; import javax.xml.xquery.XQItemType; import javax.xml.xquery.XQSequenceType; import org.basex.query.QueryTokens; import org.basex.query.item.Type; import org.basex.util.Token; /** * Java XQuery API - Item type. * * @author Workgroup DBIS, University of Konstanz 2005-09, ISC License * @author Christian Gruen */ final class BXQItemType implements XQItemType { /** Default item type. */ static final BXQItemType DEFAULT = new BXQItemType( Type.ITEM, null, -1, XQSequenceType.OCC_ZERO_OR_MORE); /** Existing base types. */ private static final Type[] BASE = { null , null , null , null , Type.AAT, Type.ATM, Type.DTD, //0 Type.YMD, Type.URI, Type.B6B, Type.BLN, Type.DAT, Type.INT, Type.ITR, //7 Type.SHR, Type.LNG, Type.DTM, Type.DEC, Type.DBL, Type.DUR, Type.FLT, //14 Type.DAY, Type.MON, Type.MDA, Type.YEA, Type.YMO, Type.HEX, Type.NOT, //21 Type.QNM, Type.STR, Type.TIM, Type.BYT, Type.NPI, Type.NNI, Type.NIN, //28 Type.PIN, Type.ULN, Type.UIN, Type.USH, Type.UBY, Type.NST, Type.TOK, //35 Type.LAN, Type.NAM, Type.NCN, Type.NMT, Type.ID , Type.IDR, Type.ENT, //42 null, null, null // 49 }; /** Name. */ private final QName name; /** Base type. */ private final int base; /** Occurrence. */ private final int occ; /** Data type. */ private final Type type; /** * Constructor. * @param b item type * @throws BXQException exception */ BXQItemType(final int b) throws BXQException { this(BASE[b], null, b); if(type == null) throw new BXQException(ATOM); } /** * Constructor. * @param t type */ BXQItemType(final Type t) { this(t, null, -1); } /** * Constructor. * @param t type * @param n name * @param b base type */ BXQItemType(final Type t, final QName n, final int b) { this(t, n, b, XQSequenceType.OCC_EXACTLY_ONE); } /** * Constructor. * @param t type * @param n name * @param b base type * @param o occurrence */ BXQItemType(final Type t, final QName n, final int b, final int o) { name = n; type = t; base = b; occ = o; } public int getBaseType() throws BXQException { if(type.unt) check(Type.DEL, Type.ELM, Type.ATT, Type.ATM); if(base != -1) return base; for(int b = 0; b < BASE.length; b++) if(BASE[b] == type) return b; throw new BXQException(NOBASE); } public int getItemKind() { switch(type) { case ATT : return XQITEMKIND_ATTRIBUTE; case COM : return XQITEMKIND_COMMENT; case DOC : return XQITEMKIND_DOCUMENT; case DEL : return XQITEMKIND_DOCUMENT_ELEMENT; case ELM : return XQITEMKIND_ELEMENT; case ITEM: return XQITEMKIND_ITEM; case NOD : return XQITEMKIND_NODE; case PI : return XQITEMKIND_PI; case TXT : return XQITEMKIND_TEXT; default : return XQITEMKIND_ATOMIC; } } public int getItemOccurrence() { return occ; } public QName getNodeName() throws BXQException { check(Type.DEL, Type.ELM, Type.ATT); return name; } public String getPIName() throws BXQException { if(type != Type.PI) throw new BXQException(PI); return name == null ? null : name.getLocalPart(); } public URI getSchemaURI() { return null; } public QName getTypeName() throws BXQException { if(type.unt) check(Type.DEL, Type.ELM, Type.ATT, Type.ATM); if(type == Type.ITEM) throw new BXQException(TYPE); final Type t = base != -1 ? BASE[base] : type; return new QName(Token.string(QueryTokens.XSURI), t.name); } public boolean isAnonymousType() { return false; } public boolean isElementNillable() { return false; } public XQItemType getItemType() { return this; } /** * Returns the item type. * @return type. */ Type getType() { return type; } /** * Matches the input types against the instance type. * @param types input types * @throws BXQException exception */ private void check(final Type... types) throws BXQException { for(final Type t : types) if(type == t) return; throw new BXQException(TYPE); } @Override public String toString() { return type.name; } }
Unification cont.. fixes, cleanups
src/org/basex/api/xqj/BXQItemType.java
Unification cont.. fixes, cleanups
<ide><path>rc/org/basex/api/xqj/BXQItemType.java <ide> <ide> /** <ide> * Returns the item type. <del> * @return type. <add> * @return type <ide> */ <ide> Type getType() { <ide> return type;
Java
apache-2.0
788ae2df904758fc08a7b922613f6f7def2726cb
0
thnaeff/GuiUtil
/** * Copyright 2014 Thomas Naeff (github.com/thnaeff) * * 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 ch.thn.guiutil.component; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; /** * A panel with a specific number of columns where label-component pairs can be * added to. It also offers parameters to configure the vertical, horizontal and * column space and if there should be divider lines shown. * * * @author Thomas Naeff (github.com/thnaeff) * */ public class LabelledComponentPanel extends JPanel { private static final long serialVersionUID = 6955100393791654848L; private static int COL_WIDTH = 4; private static int LABEL = 0; private static int COMPONENT = 1; private static int SPACERVERTICAL = 2; private JPanel pContent = null; private int[] rows = null; private int hgap = 0; private int vgap = 0; private int colspace = 0; private boolean labelAlignmentRight = true; private boolean componentAlignmentRight = false; private boolean verticalDivider = true; private boolean horizontalDivider = true; /** * * * @param numberOfColumns */ public LabelledComponentPanel(int numberOfColumns) { this(numberOfColumns, 5, 2, 10, true, false, false, false); } /** * * * @param numberOfColumns * @param verticalDivider * @param horizontalDivider */ public LabelledComponentPanel(int numberOfColumns, boolean verticalDivider, boolean horizontalDivider) { this(numberOfColumns, 5, 2, 10, true, false, verticalDivider, horizontalDivider); } /** * * * @param numberOfColumns * @param hgap * @param vgap * @param colspace * @param labelAlignmentRight * @param componentAlignmentRight * @param verticalDivider * @param horizontalDivider */ public LabelledComponentPanel(int numberOfColumns, int hgap, int vgap, int colspace, boolean labelAlignmentRight, boolean componentAlignmentRight, boolean verticalDivider, boolean horizontalDivider) { this.hgap = hgap; this.vgap = vgap; this.colspace = colspace; this.labelAlignmentRight = labelAlignmentRight; this.componentAlignmentRight = componentAlignmentRight; this.verticalDivider = verticalDivider; this.horizontalDivider = horizontalDivider; rows = new int[numberOfColumns]; pContent = new JPanel(new GridBagLayout()); setLayout(new BorderLayout()); super.add(pContent, BorderLayout.NORTH); } @Override public void removeAll() { pContent.removeAll(); } @Override public void remove(Component comp) { throw new UnsupportedOperationException("Operation not implemented"); } @Override public void remove(int index) { throw new UnsupportedOperationException("Operation not implemented"); } @Override public Component add(Component comp) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public Component add(Component comp, int index) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public void add(Component comp, Object constraints) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public void add(Component comp, Object constraints, int index) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public Component add(String name, Component comp) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } /** * * * @param label * @param comp */ public void addLabelComponent(String label, JComponent comp) { addLabelComponent(0, new JLabel(label), comp, false); } /** * * * @param label * @param comp */ public void addLabelComponent(JLabel label, JComponent comp) { addLabelComponent(0, label, comp, false); } /** * * * @param column * @param label * @param comp */ public void addLabelComponent(int column, String label, JComponent comp) { addLabelComponent(column, new JLabel(label), comp, false); } /** * * * @param column * @param label * @param comp */ public void addLabelComponent(int column, JLabel label, JComponent comp) { addLabelComponent(column, label, comp, false); } /** * * * @param label * @param comp * @param fill */ public void addLabelComponent(String label, JComponent comp, boolean fill) { addLabelComponent(0, new JLabel(label), comp, fill); } /** * * * @param label * @param comp * @param fill */ public void addLabelComponent(JLabel label, JComponent comp, boolean fill) { addLabelComponent(0, label, comp, fill); } /** * * * @param column * @param label * @param comp * @param fill */ public void addLabelComponent(int column, String label, JComponent comp, boolean fill) { addLabelComponent(column, new JLabel(label), comp, fill); } /** * * * @param column * @param label * @param comp * @param fill Ignores left/right alignment and fills entire space with given * component */ public void addLabelComponent(int column, JLabel label, JComponent comp, boolean fill) { if (column > rows.length - 1) { throw new LabelledComponentPanelError("Column " + column + " out of bounds. " + "Number of available columns: " + rows.length); } if (horizontalDivider && rows[column] > 0) { //There is already a row -> add the spacers pContent.add(createSeparator(JSeparator.HORIZONTAL), createConstraints(LABEL, column, true)); pContent.add(createSeparator(JSeparator.HORIZONTAL), createConstraints(COMPONENT, column, true)); if (verticalDivider && column < rows.length - 1) { pContent.add(createSeparator(JSeparator.VERTICAL), createConstraints(SPACERVERTICAL, column, true)); } rows[column]++; } JPanel p1 = new JPanel(new FlowLayout(labelAlignmentRight ? FlowLayout.RIGHT : FlowLayout.LEFT)); p1.add(label); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); if (fill) { p2.add(comp, BorderLayout.CENTER); } else { if (componentAlignmentRight) { p2.add(comp, BorderLayout.EAST); } else { p2.add(comp, BorderLayout.WEST); } } pContent.add(p1, createConstraints(LABEL, column, false)); pContent.add(p2, createConstraints(COMPONENT, column, false)); if (verticalDivider && column < rows.length - 1) { pContent.add(createSeparator(JSeparator.VERTICAL), createConstraints(SPACERVERTICAL, column, true)); } rows[column]++; } /** * * * @param label * @param column * @param spacer * @return */ private GridBagConstraints createConstraints(int x, int column, boolean spacer) { GridBagConstraints c = new GridBagConstraints(); boolean label = x == LABEL; boolean component = x == COMPONENT; int top = 0; int left = 0; int bottom = 0; int right = 0; c.gridx = x + column * COL_WIDTH; c.gridy = rows[column]; c.gridwidth = 1; c.gridheight = 1; if (label || component) { //A label or component position c.anchor = label ? GridBagConstraints.WEST : GridBagConstraints.EAST; c.fill = GridBagConstraints.HORIZONTAL; if (!component && !spacer) { right = hgap; } if (spacer) { top = vgap/2; bottom = vgap/2; } //Do not adjust the label width c.weightx = label ? 0 : 1.0; c.weighty = 1.0; } else { //Vertical spacer position c.weightx = 0; c.weighty = 0; c.fill = GridBagConstraints.VERTICAL; //Distribute the space equally to both sides of the spacer if (spacer) { left = colspace/2; right = colspace/2; } } c.insets = new Insets(top, left, bottom, right); return c; } /** * * * @param orientation * @return */ private JSeparator createSeparator(int orientation) { JSeparator s = new JSeparator(orientation); s.setForeground(Color.lightGray); return s; } /************************************************************************* * * * @author Thomas Naeff (github.com/thnaeff) * */ private class LabelledComponentPanelError extends Error { private static final long serialVersionUID = -1467270182957413906L; /** * * * @param message */ public LabelledComponentPanelError(String message) { super(message); } } }
src/ch/thn/guiutil/component/LabelledComponentPanel.java
/** * Copyright 2014 Thomas Naeff (github.com/thnaeff) * * 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 ch.thn.guiutil.component; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; /** * A panel with a specific number of columns where label-component pairs can be * added to. It also offers parameters to configure the vertical, horizontal and * column space and if there should be divider lines shown. * * * @author Thomas Naeff (github.com/thnaeff) * */ public class LabelledComponentPanel extends JPanel { private static final long serialVersionUID = 6955100393791654848L; private static int COL_WIDTH = 4; private static int LABEL = 0; private static int COMPONENT = 1; private static int SPACERVERTICAL = 2; private JPanel pContent = null; private int[] rows = null; private int hgap = 0; private int vgap = 0; private int colspace = 0; private boolean labelAlignmentRight = true; private boolean componentAlignmentRight = false; private boolean verticalDivider = true; private boolean horizontalDivider = true; /** * * * @param numberOfColumns */ public LabelledComponentPanel(int numberOfColumns) { this(numberOfColumns, 5, 2, 10, true, false, false, false); } /** * * * @param numberOfColumns * @param verticalDivider * @param horizontalDivider */ public LabelledComponentPanel(int numberOfColumns, boolean verticalDivider, boolean horizontalDivider) { this(numberOfColumns, 5, 2, 10, true, false, verticalDivider, horizontalDivider); } /** * * * @param numberOfColumns * @param hgap * @param vgap * @param colspace * @param labelAlignmentRight * @param componentAlignmentRight * @param verticalDivider * @param horizontalDivider */ public LabelledComponentPanel(int numberOfColumns, int hgap, int vgap, int colspace, boolean labelAlignmentRight, boolean componentAlignmentRight, boolean verticalDivider, boolean horizontalDivider) { this.hgap = hgap; this.vgap = vgap; this.colspace = colspace; this.labelAlignmentRight = labelAlignmentRight; this.componentAlignmentRight = componentAlignmentRight; this.verticalDivider = verticalDivider; this.horizontalDivider = horizontalDivider; rows = new int[numberOfColumns]; pContent = new JPanel(new GridBagLayout()); setLayout(new BorderLayout()); add(pContent, BorderLayout.NORTH); } @Override public void removeAll() { pContent.removeAll(); } @Override public void remove(Component comp) { throw new UnsupportedOperationException("Operation not implemented"); } @Override public void remove(int index) { throw new UnsupportedOperationException("Operation not implemented"); } @Override public Component add(Component comp) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public Component add(Component comp, int index) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public void add(Component comp, Object constraints) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public void add(Component comp, Object constraints, int index) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } @Override public Component add(String name, Component comp) { throw new UnsupportedOperationException("Operation not supported. Use addLabelComponent instead."); } /** * * * @param label * @param comp */ public void addLabelComponent(String label, JComponent comp) { addLabelComponent(0, new JLabel(label), comp, false); } /** * * * @param label * @param comp */ public void addLabelComponent(JLabel label, JComponent comp) { addLabelComponent(0, label, comp, false); } /** * * * @param column * @param label * @param comp */ public void addLabelComponent(int column, String label, JComponent comp) { addLabelComponent(column, new JLabel(label), comp, false); } /** * * * @param column * @param label * @param comp */ public void addLabelComponent(int column, JLabel label, JComponent comp) { addLabelComponent(column, label, comp, false); } /** * * * @param label * @param comp * @param fill */ public void addLabelComponent(String label, JComponent comp, boolean fill) { addLabelComponent(0, new JLabel(label), comp, fill); } /** * * * @param label * @param comp * @param fill */ public void addLabelComponent(JLabel label, JComponent comp, boolean fill) { addLabelComponent(0, label, comp, fill); } /** * * * @param column * @param label * @param comp * @param fill */ public void addLabelComponent(int column, String label, JComponent comp, boolean fill) { addLabelComponent(column, new JLabel(label), comp, fill); } /** * * * @param column * @param label * @param comp * @param fill Ignores left/right alignment and fills entire space with given * component */ public void addLabelComponent(int column, JLabel label, JComponent comp, boolean fill) { if (column > rows.length - 1) { throw new LabelledComponentPanelError("Column " + column + " out of bounds. " + "Number of available columns: " + rows.length); } if (horizontalDivider && rows[column] > 0) { //There is already a row -> add the spacers pContent.add(createSeparator(JSeparator.HORIZONTAL), createConstraints(LABEL, column, true)); pContent.add(createSeparator(JSeparator.HORIZONTAL), createConstraints(COMPONENT, column, true)); if (verticalDivider && column < rows.length - 1) { pContent.add(createSeparator(JSeparator.VERTICAL), createConstraints(SPACERVERTICAL, column, true)); } rows[column]++; } JPanel p1 = new JPanel(new FlowLayout(labelAlignmentRight ? FlowLayout.RIGHT : FlowLayout.LEFT)); p1.add(label); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); if (fill) { p2.add(comp, BorderLayout.CENTER); } else { if (componentAlignmentRight) { p2.add(comp, BorderLayout.EAST); } else { p2.add(comp, BorderLayout.WEST); } } pContent.add(p1, createConstraints(LABEL, column, false)); pContent.add(p2, createConstraints(COMPONENT, column, false)); if (verticalDivider && column < rows.length - 1) { pContent.add(createSeparator(JSeparator.VERTICAL), createConstraints(SPACERVERTICAL, column, true)); } rows[column]++; } /** * * * @param label * @param column * @param spacer * @return */ private GridBagConstraints createConstraints(int x, int column, boolean spacer) { GridBagConstraints c = new GridBagConstraints(); boolean label = x == LABEL; boolean component = x == COMPONENT; int top = 0; int left = 0; int bottom = 0; int right = 0; c.gridx = x + column * COL_WIDTH; c.gridy = rows[column]; c.gridwidth = 1; c.gridheight = 1; if (label || component) { //A label or component position c.anchor = label ? GridBagConstraints.WEST : GridBagConstraints.EAST; c.fill = GridBagConstraints.HORIZONTAL; if (!component && !spacer) { right = hgap; } if (spacer) { top = vgap/2; bottom = vgap/2; } //Do not adjust the label width c.weightx = label ? 0 : 1.0; c.weighty = 1.0; } else { //Vertical spacer position c.weightx = 0; c.weighty = 0; c.fill = GridBagConstraints.VERTICAL; //Distribute the space equally to both sides of the spacer if (spacer) { left = colspace/2; right = colspace/2; } } c.insets = new Insets(top, left, bottom, right); return c; } /** * * * @param orientation * @return */ private JSeparator createSeparator(int orientation) { JSeparator s = new JSeparator(orientation); s.setForeground(Color.lightGray); return s; } /************************************************************************* * * * @author Thomas Naeff (github.com/thnaeff) * */ private class LabelledComponentPanelError extends Error { private static final long serialVersionUID = -1467270182957413906L; /** * * * @param message */ public LabelledComponentPanelError(String message) { super(message); } } }
Fix for bypassing internal add method with super.add
src/ch/thn/guiutil/component/LabelledComponentPanel.java
Fix for bypassing internal add method with super.add
<ide><path>rc/ch/thn/guiutil/component/LabelledComponentPanel.java <ide> pContent = new JPanel(new GridBagLayout()); <ide> <ide> setLayout(new BorderLayout()); <del> add(pContent, BorderLayout.NORTH); <add> super.add(pContent, BorderLayout.NORTH); <ide> <ide> } <ide>