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
e81ee641d7ee7dbb7e4dbde792d7e79af4a7df72
0
apache/jena,apache/jena,samaitra/jena,apache/jena,tr3vr/jena,atsolakid/jena,kidaa/jena,kamir/jena,kamir/jena,adrapereira/jena,kamir/jena,CesarPantoja/jena,CesarPantoja/jena,atsolakid/jena,kidaa/jena,CesarPantoja/jena,adrapereira/jena,jianglili007/jena,adrapereira/jena,apache/jena,atsolakid/jena,kamir/jena,atsolakid/jena,kamir/jena,kidaa/jena,tr3vr/jena,CesarPantoja/jena,jianglili007/jena,samaitra/jena,tr3vr/jena,jianglili007/jena,tr3vr/jena,CesarPantoja/jena,apache/jena,apache/jena,samaitra/jena,adrapereira/jena,samaitra/jena,atsolakid/jena,jianglili007/jena,kamir/jena,samaitra/jena,CesarPantoja/jena,kidaa/jena,tr3vr/jena,kamir/jena,samaitra/jena,kidaa/jena,CesarPantoja/jena,jianglili007/jena,atsolakid/jena,kidaa/jena,tr3vr/jena,adrapereira/jena,apache/jena,tr3vr/jena,kidaa/jena,adrapereira/jena,jianglili007/jena,samaitra/jena,jianglili007/jena,apache/jena,adrapereira/jena,atsolakid/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 org.apache.jena.atlas.lib.cache; import java.util.Iterator ; import java.util.concurrent.Callable ; import java.util.concurrent.ExecutionException ; import java.util.function.BiConsumer ; import org.apache.jena.atlas.lib.Cache ; import org.apache.jena.atlas.logging.Log ; import org.apache.jena.ext.com.google.common.cache.CacheBuilder ; import org.apache.jena.ext.com.google.common.cache.RemovalListener ; /** Wrapper around a shaded com.google.common.cache */ final public class CacheGuava<K,V> implements Cache<K, V> { private BiConsumer<K, V> dropHandler = null ; private org.apache.jena.ext.com.google.common.cache.Cache<K,V> cache ; public CacheGuava(int size) { RemovalListener<K,V> drop = (notification)-> { if ( dropHandler != null ) dropHandler.accept(notification.getKey(), notification.getValue()) ; } ; cache = CacheBuilder.newBuilder() .maximumSize(size) .removalListener(drop) .recordStats() .concurrencyLevel(8) .build() ; } @Override public V getOrFill(K key, Callable<V> filler) { try { return cache.get(key, filler) ; } catch (ExecutionException e) { Log.warn(CacheGuava.class, "Execution exception filling cache", e) ; return null ; } } @Override public V getIfPresent(K key) { return cache.getIfPresent(key) ; } @Override public void put(K key, V thing) { if ( thing == null ) { cache.invalidate(key); return ; } cache.put(key, thing) ; } @Override public boolean containsKey(K key) { return cache.getIfPresent(key) != null ; } @Override public void remove(K key) { cache.invalidate(key) ; } @Override public Iterator<K> keys() { return cache.asMap().keySet().iterator() ; } @Override public boolean isEmpty() { return cache.size() == 0 ; } @Override public void clear() { cache.invalidateAll() ; } @Override public long size() { return cache.size() ; } @Override public void setDropHandler(BiConsumer<K, V> dropHandler) { this.dropHandler = dropHandler ; } }
jena-base/src/main/java/org/apache/jena/atlas/lib/cache/CacheGuava.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.jena.atlas.lib.cache; import java.util.Iterator ; import java.util.concurrent.Callable ; import java.util.concurrent.ExecutionException ; import java.util.function.BiConsumer; import org.apache.jena.atlas.lib.Cache ; import org.apache.jena.atlas.logging.Log ; import org.apache.jena.ext.com.google.common.cache.CacheBuilder ; import org.apache.jena.ext.com.google.common.cache.RemovalListener ; import org.apache.jena.ext.com.google.common.cache.RemovalNotification ; /** Wrapper around com.google.common.cache */ final public class CacheGuava<K,V> implements Cache<K, V> { private BiConsumer<K, V> dropHandler = null ; /*private*/ org.apache.jena.ext.com.google.common.cache.Cache<K,V> cache ; public CacheGuava(int size) { RemovalListener<K,V> drop = new RemovalListener<K, V>() { @Override public void onRemoval(RemovalNotification<K, V> notification) { if ( dropHandler != null ) dropHandler.accept(notification.getKey(), notification.getValue()) ; } } ; cache = CacheBuilder.newBuilder() .maximumSize(size) .removalListener(drop) .recordStats() .concurrencyLevel(8) .build() ; } // Change the interface to be ... @Override public V getOrFill(K key, Callable<V> filler) { try { return cache.get(key, filler) ; } catch (ExecutionException e) { Log.warn(CacheGuava.class, "Execution exception filling cache", e) ; return null ; } } @Override public V getIfPresent(K key) { return cache.getIfPresent(key) ; } @Override public void put(K key, V thing) { if ( thing == null ) { cache.invalidate(key); return ; } cache.put(key, thing) ; } @Override public boolean containsKey(K key) { return cache.getIfPresent(key) != null ; } @Override public void remove(K key) { cache.invalidate(key) ; } @Override public Iterator<K> keys() { return cache.asMap().keySet().iterator() ; } @Override public boolean isEmpty() { return cache.size() == 0 ; } @Override public void clear() { cache.invalidateAll() ; } @Override public long size() { return cache.size() ; } @Override public void setDropHandler(BiConsumer<K, V> dropHandler) { this.dropHandler = dropHandler ; } }
Clean code.
jena-base/src/main/java/org/apache/jena/atlas/lib/cache/CacheGuava.java
Clean code.
<ide><path>ena-base/src/main/java/org/apache/jena/atlas/lib/cache/CacheGuava.java <ide> import java.util.Iterator ; <ide> import java.util.concurrent.Callable ; <ide> import java.util.concurrent.ExecutionException ; <del>import java.util.function.BiConsumer; <add>import java.util.function.BiConsumer ; <ide> <ide> import org.apache.jena.atlas.lib.Cache ; <ide> import org.apache.jena.atlas.logging.Log ; <ide> import org.apache.jena.ext.com.google.common.cache.CacheBuilder ; <ide> import org.apache.jena.ext.com.google.common.cache.RemovalListener ; <del>import org.apache.jena.ext.com.google.common.cache.RemovalNotification ; <ide> <del>/** Wrapper around com.google.common.cache */ <add>/** Wrapper around a shaded com.google.common.cache */ <ide> final <ide> public class CacheGuava<K,V> implements Cache<K, V> <ide> { <ide> private BiConsumer<K, V> dropHandler = null ; <del> /*private*/ org.apache.jena.ext.com.google.common.cache.Cache<K,V> cache ; <add> private org.apache.jena.ext.com.google.common.cache.Cache<K,V> cache ; <ide> <ide> public CacheGuava(int size) <ide> { <del> RemovalListener<K,V> drop = new RemovalListener<K, V>() { <del> @Override <del> public void onRemoval(RemovalNotification<K, V> notification) { <del> if ( dropHandler != null ) <del> dropHandler.accept(notification.getKey(), <del> notification.getValue()) ; <del> } <add> RemovalListener<K,V> drop = (notification)-> { <add> if ( dropHandler != null ) <add> dropHandler.accept(notification.getKey(), <add> notification.getValue()) ; <ide> } ; <add> <ide> cache = CacheBuilder.newBuilder() <ide> .maximumSize(size) <ide> .removalListener(drop) <ide> .build() ; <ide> } <ide> <del> // Change the interface to be ... <ide> @Override <ide> public V getOrFill(K key, Callable<V> filler) { <ide> try {
Java
bsd-3-clause
7a7c784ec853481bc194629babafbde56959f320
0
tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,joansmith/tripleplay
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui; import playn.core.PlayN; import pythagoras.f.Dimension; import pythagoras.f.IPoint; import pythagoras.f.IRectangle; import pythagoras.f.Point; import pythagoras.f.Rectangle; import playn.core.Connection; import playn.core.Events; import playn.core.GroupLayer; import playn.core.Layer; import playn.core.Pointer; import react.Slot; import tripleplay.ui.Style.HAlign; import tripleplay.ui.Style.VAlign; import static playn.core.PlayN.graphics; /** * Provides a context for popping up a menu. */ public class MenuHost { /** The root layer that will contain all menus that pop up. It should normally be close to the * top of the hierarchy so that it draws on top of everything. */ public final GroupLayer rootLayer; /** The interface we use to create the menu's root and do animation. */ public final Interface iface; /** * An event type for triggering a menu popup. Also acts as a menu constraint so the integrated * host layout can make sure the whole menu is on screen and near to the triggering event * position or element. */ public static class Pop extends Layout.Constraint { /** The element that triggered the popup. {@link #position} is relative to this. */ public final Element<?> trigger; /** The menu to show. */ public final Menu menu; /** The position where the menu should pop up, e.g. a touch event position. Relative to * {@link #trigger}. */ public IPoint position; /** The bounds to confine the menu, in screen coordinates; usually the whole screen. */ public IRectangle bounds; /** Creates a new event and initializes {@link #trigger} and {@link #menu}. */ public Pop (Element<?> trigger, Menu menu) { this.menu = menu; this.trigger = trigger; position = new Point(0, 0); } /** * Causes the menu to handle further events on the given layer. This is usually the layer * handling a pointer start that caused the popup. A listener will be added to the layer * and the menu notified of pointer drag and end events. */ public Pop relayEvents (Layer layer) { _relayTarget = layer; return this; } /** * Positions the menu popup at the given positional event. */ public Pop atEventPos (Events.Position pos) { return atScreenPos(pos.x(), pos.y()); } /** * Positions the menu popup at the given screen position. */ public Pop atScreenPos (float x, float y) { position = new Point(x, y); return this; } /** * Positions the menu horizontally relative to the given layer, with an offset. The * vertical position remains unchanged. */ public Pop atLayerX (Layer layer, float x) { return atScreenPos(Layer.Util.layerToScreen(layer, x, 0).x, position.y()); } /** * Positions the menu vertically relative to the given layer, with an offset. The * horizontal position remains unchanged. */ public Pop atLayerY (Layer layer, float y) { return atScreenPos(position.x(), Layer.Util.layerToScreen(layer, 0, y).y); } /** * Sets the horizontal alignment of the menu relative to the popup position. */ public Pop halign (HAlign halign) { _halign = halign; return this; } /** * Sets the vertical alignment of the menu relative to the popup position. */ public Pop valign (VAlign valign) { _valign = valign; return this; } /** * Positions the right edge of the menu relative to the left edge of the trigger, offset * by the given value. */ public Pop toLeft (float x) { return atLayerX(trigger.layer, x).halign(HAlign.RIGHT); } /** * Positions the left edge of the menu relative to the right edge of the trigger, offset * by the given value. */ public Pop toRight (float x) { return atLayerX(trigger.layer, trigger.size().width() + x).halign(HAlign.LEFT); } /** * Positions the top edge of the menu relative to the top edge of the trigger, offset * by the given value. */ public Pop toTop (float y) { return atLayerY(trigger.layer, y).valign(VAlign.TOP); } /** * Positions the bottom edge of the menu relative to the bottom edge of the trigger, offset * by the given value. */ public Pop toBottom (float y) { return atLayerY(trigger.layer, trigger.size().height() + y).valign(VAlign.BOTTOM); } /** * Flags this {@code Pop} event so that the menu will not be destroyed automatically when * it is deactivated. Returns this instance for chaining. */ public Pop retainMenu () { _retain = true; return this; } /** * Optionally confines the menu area to the given screen area. By default the menu is * confined by the hosts's screen area (see {@link MenuHost#getScreenArea()}). */ public Pop inScreenArea (IRectangle area) { bounds = new Rectangle(area); return this; } /** * Optionally confines the menu area to the given element. By default the menu is confined * by the hosts's screen area (see {@link MenuHost#getScreenArea()}). */ public Pop inElement (Element<?> elem) { Point tl = Layer.Util.layerToScreen(elem.layer, 0, 0); Point br = Layer.Util.layerToScreen(elem.layer, elem.size().width(), elem.size().height()); bounds = new Rectangle(tl.x(), tl.y(), br.x() - tl.x(), br.y() - tl.y()); return this; } /** Whether we should keep the menu around (i.e. not destroy it). */ protected boolean _retain; /** The layer that will be sending pointer drag and end events to us. */ protected Layer _relayTarget; protected HAlign _halign = HAlign.LEFT; protected VAlign _valign = VAlign.TOP; } public static Connection relayEvents (Layer from, final Menu to) { return from.addListener(new Pointer.Adapter() { @Override public void onPointerDrag (Pointer.Event e) { to.onPointerDrag(e); } @Override public void onPointerEnd (Pointer.Event e) { to.onPointerEnd(e); } }); } /** * Creates a menu host using the given values. The root layer is set to the layer of the given * root and the stylesheet to its stylesheet. */ public MenuHost (Interface iface, Elements<?> root) { this(iface, root.layer); _stylesheet = root.stylesheet(); } /** * Creates a new menu host using the given values. The stylesheet is set to an empty * one and can be changed via the {@link #setStylesheet(Stylesheet)} method. */ public MenuHost (Interface iface, GroupLayer rootLayer) { this.iface = iface; this.rootLayer = rootLayer; } /** * Sets the stylesheet for menus popped by this host. */ public MenuHost setStylesheet (Stylesheet sheet) { _stylesheet = sheet; return this; } /** * Directs a menu pop signal to {@link #popup(Pop)}. */ public Slot<Pop> onPopup () { return new Slot<Pop>() { @Override public void onEmit (Pop event) { popup(event); } }; } /** * Sets the area to which menus should be confined when there isn't any other associated * bounds. */ public void setScreenArea (IRectangle screenArea) { _screenArea.setBounds(screenArea); } /** * Gets the area to which menus should be confined when there isn't any other associated * bounds. By default, the entire available area is used, as given by * {@link playn.core.Graphics}. */ public IRectangle getScreenArea () { return _screenArea; } /** * Displays the menu specified by the given pop, incorporating all the configured attributes * therein. */ public void popup (final Pop pop) { // if there is no explicit constraint area requested, use the graphics if (pop.bounds == null) pop.inScreenArea(_screenArea); // set up the menu root, the RootLayout will do the complicated bounds jockeying final Root menuRoot = iface.createRoot(new RootLayout(), _stylesheet, rootLayer); menuRoot.layer.setDepth(1); menuRoot.layer.setHitTester(null); // get hits from out of bounds menuRoot.add(pop.menu.setConstraint(pop)); menuRoot.pack(); menuRoot.layer.setTranslation(pop.position.x(), pop.position.y()); // set up the activation final Activation activation = new Activation(pop); // cleanup final Runnable cleanup = new Runnable() { @Override public void run () { // check parentage, it's possible the menu has been repopped already if (pop.menu.parent() == menuRoot) { // free the constraint to gc pop.menu.setConstraint(null); // remove or destroy it, depending on the caller's preference if (pop._retain) menuRoot.remove(pop.menu); else menuRoot.destroy(pop.menu); // remove the hidden area we added PlayN.uiOverlay().hideOverlay(null); } // clear all connections activation.clear(); // always kill off the transient root iface.destroyRoot(menuRoot); // if this was our active menu, clear it if (_active != null && _active.pop == pop) _active = null; } }; // connect to deactivation signal and do our cleanup activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() { @Override public void onEmit (Menu event) { // due to animations, deactivation can happen during layout, so do it next frame PlayN.invokeLater(cleanup); } }); // close the menu any time the trigger is removed from the hierarchy activation.triggerRemoved = pop.trigger.hierarchyChanged().connect(new Slot<Boolean>() { @Override public void onEmit (Boolean event) { if (!event) pop.menu.deactivate(); } }); // deactivate the old menu if (_active != null) _active.pop.menu.deactivate(); // pass along the animator pop.menu.init(iface.animator()); // activate _active = activation; pop.menu.activate(); } public Menu active () { return _active != null ? _active.pop.menu : null; } /** Simple layout for positioning the menu within the transient {@code Root}. */ protected static class RootLayout extends Layout { @Override public Dimension computeSize (Elements<?> elems, float hintX, float hintY) { return new Dimension(preferredSize(elems.childAt(0), hintX, hintY)); } @Override public void layout (Elements<?> elems, float left, float top, float width, float height) { if (elems.childCount() == 0) return; // get the constraint, it will always be a Pop Pop pop = (Pop)elems.childAt(0).constraint(); // figure out the best place to put the menu, in screen coordinates; starting with // the requested popup position Rectangle bounds = new Rectangle( pop.position.x() + pop._halign.offset(width, 0), pop.position.y() + pop._valign.offset(height, 0), width, height); // make sure the menu lies inside the requested bounds if the menu doesn't do // that itself if (pop.menu.automaticallyConfine()) { confine(pop.bounds, bounds); // keep the bounds from overlapping the position float fudge = 2; if (bounds.width > fudge * 2 && bounds.height > fudge * 2) { Rectangle ibounds = new Rectangle(bounds); ibounds.grow(-fudge, -fudge); if (ibounds.contains(pop.position)) { avoidPoint(pop.bounds, ibounds, pop.position); bounds.setLocation(ibounds.x() - fudge, ibounds.y() - fudge); } } } // save a copy of bounds in screen coordinates Rectangle screenBounds = new Rectangle(bounds); // relocate to layer coordinates bounds.setLocation(Layer.Util.screenToLayer(elems.layer, bounds.x, bounds.y)); // set the menu bounds setBounds(elems.childAt(0), bounds.x, bounds.y, bounds.width, bounds.height); // tell the UI overlay to let the real dimensions of the menu through PlayN.uiOverlay().hideOverlay(screenBounds); } } /** Tries to place the inner bounds within the outer bounds, such that the inner bounds does * not contain the position. */ protected static void avoidPoint (IRectangle outer, Rectangle inner, IPoint pos) { Rectangle checkBounds = new Rectangle(); Rectangle best = new Rectangle(inner); float bestDist = Float.MAX_VALUE; float dx = pos.x() - outer.x(), dy = pos.y() - outer.y(); // confine to the left checkBounds.setBounds(outer.x(), outer.y(), dx, outer.height()); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); // right checkBounds.setBounds(pos.x(), outer.y(), outer.width() - dx, outer.height()); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); // top checkBounds.setBounds(outer.x(), outer.y(), outer.width(), dy); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); // bottom checkBounds.setBounds(outer.x(), pos.y(), outer.width(), outer.height() - dy); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); inner.setBounds(best); } /** Confines a rectangle and updates the current best fit based on the moved distance. */ protected static float compareAndConfine ( IRectangle outer, IRectangle inner, Rectangle best, float bestDist) { // don't bother if there isn't even enough space if (outer.width() <= inner.width() || outer.height() < inner.height()) return bestDist; // confine Rectangle confined = confine(outer, new Rectangle(inner)); // check distance and overwrite the best fit if we have a new winner float dx = confined.x - inner.x(), dy = confined.y - inner.y(); float dist = dx * dx + dy * dy; if (dist < bestDist) { best.setBounds(confined); bestDist = dist; } return bestDist; } /** Moves ths given inner rectangle such that it lies within the given outer rectangle. * The results are undefined if either the inner width or height is greater that the outer's * width or height, respectively. */ protected static Rectangle confine (IRectangle outer, Rectangle inner) { float dx = outer.x() - inner.x(), dy = outer.y() - inner.y(); if (dx <= 0) dx = Math.min(0, outer.maxX() - inner.maxX()); if (dy <= 0) dy = Math.min(0, outer.maxY() - inner.maxY()); inner.translate(dx, dy); return inner; } /** Holds a few variables related to the menu's activation. */ protected static class Activation { /** The configuration of the menu. */ public final Pop pop; /** Connects to the pointer events from the relay. */ public Connection pointerRelay; /** Connection to the trigger's hierarchy change. */ public react.Connection triggerRemoved; /** Connection to the menu's deactivation. */ public react.Connection deactivated; /** Creates a new activation. */ public Activation (Pop pop) { this.pop = pop; // handle pointer events from the relay Layer target = pop._relayTarget; if (target != null) pointerRelay = relayEvents(target, pop.menu); } /** Clears out the connections. */ public void clear () { if (pointerRelay != null) pointerRelay.disconnect(); if (triggerRemoved != null) triggerRemoved.disconnect(); if (deactivated != null) deactivated.disconnect(); pointerRelay = null; triggerRemoved = null; deactivated = null; } } /** The stylesheet used for popped menus. */ protected Stylesheet _stylesheet = Stylesheet.builder().create(); /** Currently active. */ protected Activation _active; /** When confining the menu to the graphics' bounds, use this. */ protected final Rectangle _screenArea = new Rectangle( 0, 0, graphics().width(), graphics().height()); }
core/src/main/java/tripleplay/ui/MenuHost.java
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui; import playn.core.PlayN; import pythagoras.f.Dimension; import pythagoras.f.IPoint; import pythagoras.f.IRectangle; import pythagoras.f.Point; import pythagoras.f.Rectangle; import playn.core.Connection; import playn.core.Events; import playn.core.GroupLayer; import playn.core.Layer; import playn.core.Pointer; import react.Slot; import tripleplay.ui.Style.HAlign; import tripleplay.ui.Style.VAlign; import static playn.core.PlayN.graphics; /** * Provides a context for popping up a menu. */ public class MenuHost { /** The root layer that will contain all menus that pop up. It should normally be close to the * top of the hierarchy so that it draws on top of everything. */ public final GroupLayer rootLayer; /** The interface we use to create the menu's root and do animation. */ public final Interface iface; /** * An event type for triggering a menu popup. Also acts as a menu constraint so the integrated * host layout can make sure the whole menu is on screen and near to the triggering event * position or element. */ public static class Pop extends Layout.Constraint { /** The element that triggered the popup. {@link #position} is relative to this. */ public final Element<?> trigger; /** The menu to show. */ public final Menu menu; /** The position where the menu should pop up, e.g. a touch event position. Relative to * {@link #trigger}. */ public IPoint position; /** The bounds to confine the menu, in screen coordinates; usually the whole screen. */ public IRectangle bounds; /** Creates a new event and initializes {@link #trigger} and {@link #menu}. */ public Pop (Element<?> trigger, Menu menu) { this.menu = menu; this.trigger = trigger; position = new Point(0, 0); } /** * Causes the menu to handle further events on the given layer. This is usually the layer * handling a pointer start that caused the popup. A listener will be added to the layer * and the menu notified of pointer drag and end events. */ public Pop relayEvents (Layer layer) { _relayTarget = layer; return this; } /** * Positions the menu popup at the given positional event. */ public Pop atEventPos (Events.Position pos) { return atScreenPos(pos.x(), pos.y()); } /** * Positions the menu popup at the given screen position. */ public Pop atScreenPos (float x, float y) { position = new Point(x, y); return this; } /** * Positions the menu horizontally relative to the given layer, with an offset. The * vertical position remains unchanged. */ public Pop atLayerX (Layer layer, float x) { return atScreenPos(Layer.Util.layerToScreen(layer, x, 0).x, position.y()); } /** * Positions the menu vertically relative to the given layer, with an offset. The * horizontal position remains unchanged. */ public Pop atLayerY (Layer layer, float y) { return atScreenPos(position.x(), Layer.Util.layerToScreen(layer, 0, y).y); } /** * Sets the horizontal alignment of the menu relative to the popup position. */ public Pop halign (HAlign halign) { _halign = halign; return this; } /** * Sets the vertical alignment of the menu relative to the popup position. */ public Pop valign (VAlign valign) { _valign = valign; return this; } /** * Positions the right edge of the menu relative to the left edge of the trigger, offset * by the given value. */ public Pop toLeft (float x) { return atLayerX(trigger.layer, x).halign(HAlign.RIGHT); } /** * Positions the left edge of the menu relative to the right edge of the trigger, offset * by the given value. */ public Pop toRight (float x) { return atLayerX(trigger.layer, trigger.size().width() + x).halign(HAlign.LEFT); } /** * Positions the top edge of the menu relative to the top edge of the trigger, offset * by the given value. */ public Pop toTop (float y) { return atLayerY(trigger.layer, y).valign(VAlign.TOP); } /** * Positions the bottom edge of the menu relative to the bottom edge of the trigger, offset * by the given value. */ public Pop toBottom (float y) { return atLayerY(trigger.layer, trigger.size().height() + y).valign(VAlign.BOTTOM); } /** * Flags this {@code Pop} event so that the menu will not be destroyed automatically when * it is deactivated. Returns this instance for chaining. */ public Pop retainMenu () { _retain = true; return this; } /** * Optionally confines the menu area to the given screen area. By default the menu is * confined by the hosts's screen area (see {@link MenuHost#getScreenArea()}). */ public Pop inScreenArea (IRectangle area) { bounds = new Rectangle(area); return this; } /** * Optionally confines the menu area to the given element. By default the menu is confined * by the hosts's screen area (see {@link MenuHost#getScreenArea()}). */ public Pop inElement (Element<?> elem) { Point tl = Layer.Util.layerToScreen(elem.layer, 0, 0); Point br = Layer.Util.layerToScreen(elem.layer, elem.size().width(), elem.size().height()); bounds = new Rectangle(tl.x(), tl.y(), br.x() - tl.x(), br.y() - tl.y()); return this; } /** Whether we should keep the menu around (i.e. not destroy it). */ protected boolean _retain; /** The layer that will be sending pointer drag and end events to us. */ protected Layer _relayTarget; protected HAlign _halign = HAlign.LEFT; protected VAlign _valign = VAlign.TOP; } public static Connection relayEvents (Layer from, final Menu to) { return from.addListener(new Pointer.Adapter() { @Override public void onPointerDrag (Pointer.Event e) { to.onPointerDrag(e); } @Override public void onPointerEnd (Pointer.Event e) { to.onPointerEnd(e); } }); } /** * Creates a menu host using the given values. The root layer is set to the layer of the given * root and the stylesheet to its stylesheet. */ public MenuHost (Interface iface, Elements<?> root) { this(iface, root.layer); _stylesheet = root.stylesheet(); } /** * Creates a new menu host using the given values. The stylesheet is set to an empty * one and can be changed via the {@link #setStylesheet(Stylesheet)} method. */ public MenuHost (Interface iface, GroupLayer rootLayer) { this.iface = iface; this.rootLayer = rootLayer; } /** * Sets the stylesheet for menus popped by this host. */ public MenuHost setStylesheet (Stylesheet sheet) { _stylesheet = sheet; return this; } /** * Directs a menu pop signal to {@link #popup(Pop)}. */ public Slot<Pop> onPopup () { return new Slot<Pop>() { @Override public void onEmit (Pop event) { popup(event); } }; } /** * Sets the area to which menus should be confined when there isn't any other associated * bounds. */ public void setScreenArea (IRectangle screenArea) { _screenArea.setBounds(screenArea); } /** * Gets the area to which menus should be confined when there isn't any other associated * bounds. By default, the entire available area is used, as given by * {@link playn.core.Graphics}. */ public IRectangle getScreenArea () { return _screenArea; } /** * Displays the menu specified by the given pop, incorporating all the configured attributes * therein. */ public void popup (final Pop pop) { // if there is no explicit constraint area requested, use the graphics if (pop.bounds == null) pop.inScreenArea(_screenArea); // set up the menu root, the RootLayout will do the complicated bounds jockeying final Root menuRoot = iface.createRoot(new RootLayout(), _stylesheet, rootLayer); menuRoot.layer.setDepth(1); menuRoot.layer.setHitTester(null); // get hits from out of bounds menuRoot.add(pop.menu.setConstraint(pop)); menuRoot.pack(); menuRoot.layer.setTranslation(pop.position.x(), pop.position.y()); // set up the activation final Activation activation = new Activation(pop); // connect to deactivation signal and do our cleanup activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() { @Override public void onEmit (Menu event) { // check parentage, it's possible the menu has been repopped already if (pop.menu.parent() == menuRoot) { // free the constraint to gc pop.menu.setConstraint(null); // remove or destroy it, depending on the caller's preference if (pop._retain) menuRoot.remove(pop.menu); else menuRoot.destroy(pop.menu); // remove the hidden area we added PlayN.uiOverlay().hideOverlay(null); } // clear all connections activation.clear(); // TODO: do we need to stop menu animation here? it should be automatic since // by the time we reach this method, the deactivation animation is complete // always kill off the transient root iface.destroyRoot(menuRoot); // if this was our active menu, clear it if (_active != null && _active.pop.menu == event) _active = null; } }); // close the menu any time the trigger is removed from the hierarchy activation.triggerRemoved = pop.trigger.hierarchyChanged().connect(new Slot<Boolean>() { @Override public void onEmit (Boolean event) { if (!event) pop.menu.deactivate(); } }); // deactivate the old menu if (_active != null) _active.pop.menu.deactivate(); // pass along the animator pop.menu.init(iface.animator()); // activate _active = activation; pop.menu.activate(); } public Menu active () { return _active != null ? _active.pop.menu : null; } /** Simple layout for positioning the menu within the transient {@code Root}. */ protected static class RootLayout extends Layout { @Override public Dimension computeSize (Elements<?> elems, float hintX, float hintY) { return new Dimension(preferredSize(elems.childAt(0), hintX, hintY)); } @Override public void layout (Elements<?> elems, float left, float top, float width, float height) { if (elems.childCount() == 0) return; // get the constraint, it will always be a Pop Pop pop = (Pop)elems.childAt(0).constraint(); // figure out the best place to put the menu, in screen coordinates; starting with // the requested popup position Rectangle bounds = new Rectangle( pop.position.x() + pop._halign.offset(width, 0), pop.position.y() + pop._valign.offset(height, 0), width, height); // make sure the menu lies inside the requested bounds if the menu doesn't do // that itself if (pop.menu.automaticallyConfine()) { confine(pop.bounds, bounds); // keep the bounds from overlapping the position float fudge = 2; if (bounds.width > fudge * 2 && bounds.height > fudge * 2) { Rectangle ibounds = new Rectangle(bounds); ibounds.grow(-fudge, -fudge); if (ibounds.contains(pop.position)) { avoidPoint(pop.bounds, ibounds, pop.position); bounds.setLocation(ibounds.x() - fudge, ibounds.y() - fudge); } } } // save a copy of bounds in screen coordinates Rectangle screenBounds = new Rectangle(bounds); // relocate to layer coordinates bounds.setLocation(Layer.Util.screenToLayer(elems.layer, bounds.x, bounds.y)); // set the menu bounds setBounds(elems.childAt(0), bounds.x, bounds.y, bounds.width, bounds.height); // tell the UI overlay to let the real dimensions of the menu through PlayN.uiOverlay().hideOverlay(screenBounds); } } /** Tries to place the inner bounds within the outer bounds, such that the inner bounds does * not contain the position. */ protected static void avoidPoint (IRectangle outer, Rectangle inner, IPoint pos) { Rectangle checkBounds = new Rectangle(); Rectangle best = new Rectangle(inner); float bestDist = Float.MAX_VALUE; float dx = pos.x() - outer.x(), dy = pos.y() - outer.y(); // confine to the left checkBounds.setBounds(outer.x(), outer.y(), dx, outer.height()); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); // right checkBounds.setBounds(pos.x(), outer.y(), outer.width() - dx, outer.height()); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); // top checkBounds.setBounds(outer.x(), outer.y(), outer.width(), dy); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); // bottom checkBounds.setBounds(outer.x(), pos.y(), outer.width(), outer.height() - dy); bestDist = compareAndConfine(checkBounds, inner, best, bestDist); inner.setBounds(best); } /** Confines a rectangle and updates the current best fit based on the moved distance. */ protected static float compareAndConfine ( IRectangle outer, IRectangle inner, Rectangle best, float bestDist) { // don't bother if there isn't even enough space if (outer.width() <= inner.width() || outer.height() < inner.height()) return bestDist; // confine Rectangle confined = confine(outer, new Rectangle(inner)); // check distance and overwrite the best fit if we have a new winner float dx = confined.x - inner.x(), dy = confined.y - inner.y(); float dist = dx * dx + dy * dy; if (dist < bestDist) { best.setBounds(confined); bestDist = dist; } return bestDist; } /** Moves ths given inner rectangle such that it lies within the given outer rectangle. * The results are undefined if either the inner width or height is greater that the outer's * width or height, respectively. */ protected static Rectangle confine (IRectangle outer, Rectangle inner) { float dx = outer.x() - inner.x(), dy = outer.y() - inner.y(); if (dx <= 0) dx = Math.min(0, outer.maxX() - inner.maxX()); if (dy <= 0) dy = Math.min(0, outer.maxY() - inner.maxY()); inner.translate(dx, dy); return inner; } /** Holds a few variables related to the menu's activation. */ protected static class Activation { /** The configuration of the menu. */ public final Pop pop; /** Connects to the pointer events from the relay. */ public Connection pointerRelay; /** Connection to the trigger's hierarchy change. */ public react.Connection triggerRemoved; /** Connection to the menu's deactivation. */ public react.Connection deactivated; /** Creates a new activation. */ public Activation (Pop pop) { this.pop = pop; // handle pointer events from the relay Layer target = pop._relayTarget; if (target != null) pointerRelay = relayEvents(target, pop.menu); } /** Clears out the connections. */ public void clear () { if (pointerRelay != null) pointerRelay.disconnect(); if (triggerRemoved != null) triggerRemoved.disconnect(); if (deactivated != null) deactivated.disconnect(); pointerRelay = null; triggerRemoved = null; deactivated = null; } } /** The stylesheet used for popped menus. */ protected Stylesheet _stylesheet = Stylesheet.builder().create(); /** Currently active. */ protected Activation _active; /** When confining the menu to the graphics' bounds, use this. */ protected final Rectangle _screenArea = new Rectangle( 0, 0, graphics().width(), graphics().height()); }
Fix double menu pop bug This has been around for a while and not fixed because it's usually a logical error to popup a 2nd menu before the previous one is finished animating. However, very fast users can cause a crash by tapping quickly on a button that pops a menu. Fix by invoking the cleanup code later.
core/src/main/java/tripleplay/ui/MenuHost.java
Fix double menu pop bug
<ide><path>ore/src/main/java/tripleplay/ui/MenuHost.java <ide> // set up the activation <ide> final Activation activation = new Activation(pop); <ide> <del> // connect to deactivation signal and do our cleanup <del> activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() { <del> @Override public void onEmit (Menu event) { <add> // cleanup <add> final Runnable cleanup = new Runnable() { <add> @Override public void run () { <ide> // check parentage, it's possible the menu has been repopped already <ide> if (pop.menu.parent() == menuRoot) { <ide> // free the constraint to gc <ide> // clear all connections <ide> activation.clear(); <ide> <del> // TODO: do we need to stop menu animation here? it should be automatic since <del> // by the time we reach this method, the deactivation animation is complete <del> <ide> // always kill off the transient root <ide> iface.destroyRoot(menuRoot); <ide> <ide> // if this was our active menu, clear it <del> if (_active != null && _active.pop.menu == event) _active = null; <add> if (_active != null && _active.pop == pop) _active = null; <add> } <add> }; <add> <add> // connect to deactivation signal and do our cleanup <add> activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() { <add> @Override public void onEmit (Menu event) { <add> // due to animations, deactivation can happen during layout, so do it next frame <add> PlayN.invokeLater(cleanup); <ide> } <ide> }); <ide>
Java
apache-2.0
5be5e4addba99234d24335462122d561c9ae3e8a
0
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
/******************************************************************************* * Copyright 2015 EMBL - European Bioinformatics Institute * * 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.mousephenotype.cda.solr.service; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.apache.solr.client.solrj.response.Group; import org.apache.solr.client.solrj.response.PivotField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.mousephenotype.cda.enumerations.SexType; import org.mousephenotype.cda.solr.service.dto.ImageDTO; import org.mousephenotype.cda.solr.service.dto.MpDTO; import org.mousephenotype.cda.solr.service.dto.ObservationDTO; import org.mousephenotype.cda.solr.web.dto.AnatomyPageTableRow; import org.mousephenotype.cda.solr.web.dto.DataTableRow; import org.mousephenotype.cda.solr.web.dto.ImageSummary; import org.mousephenotype.cda.web.WebStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import javax.validation.constraints.NotNull; import java.util.*; @Service public class ImageService implements WebStatus{ @Autowired @Qualifier("impcImagesCore") private HttpSolrServer solr; private final Logger logger = LoggerFactory.getLogger(ImageService.class); public ImageService() { } @NotNull @Value("${drupalBaseUrl}") private String drupalBaseUrl; public List<ImageSummary> getImageSummary(String markerAccessionId) throws SolrServerException{ SolrQuery q = new SolrQuery(); q.setQuery("*:*"); q.setFilterQueries(ImageDTO.GENE_ACCESSION_ID + ":\"" + markerAccessionId + "\""); // TM decided only to display some procedures in the Summary q.addFilterQuery("(" + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_XRY* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_XRY* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_ALZ* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_PAT* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_EYE* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_HIS*" + ")"); q.set("group", true); q.set("group.field", ImageDTO.PROCEDURE_NAME); q.set("group.limit", 1); q.set("group.sort" , ImageDTO.DATE_OF_EXPERIMENT + " DESC"); List<ImageSummary> res = new ArrayList<>(); for (Group group : solr.query(q).getGroupResponse().getValues().get(0).getValues()){ ImageSummary iSummary = new ImageSummary(); iSummary.setNumberOfImages(group.getResult().getNumFound()); iSummary.setProcedureId(group.getResult().get(0).getFieldValue(ImageDTO.PROCEDURE_STABLE_ID).toString()); iSummary.setProcedureName(group.getResult().get(0).getFieldValue(ImageDTO.PROCEDURE_NAME).toString()); iSummary.setThumbnailUrl(group.getResult().get(0).getFieldValue(ImageDTO.JPEG_URL).toString().replace("render_image", "render_thumbnail")); res.add(iSummary); } return res; } /** * This method should not be used! This method should use the observation core and get categorical data as well as have image links where applicable!!! * @param anatomyTable * @param anatomyId * @param anatomyTerms * @param phenotypingCenter * @param procedure * @param paramAssoc * @param baseUrl * @return * @throws SolrServerException */ public List<AnatomyPageTableRow> getImagesForAnatomy(String anatomyId, List<String> anatomyTerms, List<String> phenotypingCenter, List<String> procedure, List<String> paramAssoc, String baseUrl) throws SolrServerException { System.out.println("calling get images for Anatomy"); Map<String, AnatomyPageTableRow> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( "(" + ImageDTO.ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.INTERMEDIATE_ANATOMY_ID + ":\"" + anatomyId + "\")") .addFilterQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ") .addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":\"experimental\"") .addFilterQuery("("+ImageDTO.PARAMETER_ASSOCIATION_VALUE+ ":\"no expression\" OR "+ImageDTO.PARAMETER_ASSOCIATION_VALUE+":\"expression\""+")") //only have expressed and not expressed ingnore ambiguous and no tissue .setRows(Integer.MAX_VALUE) .setFields(ImageDTO.SEX, ImageDTO.ALLELE_SYMBOL, ImageDTO.ALLELE_ACCESSION_ID, ImageDTO.ZYGOSITY, ImageDTO.ANATOMY_ID, ImageDTO.ANATOMY_TERM, ImageDTO.PROCEDURE_STABLE_ID, ImageDTO.DATASOURCE_NAME, ImageDTO.PARAMETER_ASSOCIATION_VALUE, ImageDTO.GENE_SYMBOL, ImageDTO.GENE_ACCESSION_ID, ImageDTO.PARAMETER_NAME, ImageDTO.PARAMETER_STABLE_ID, ImageDTO.PROCEDURE_NAME, ImageDTO.PHENOTYPING_CENTER, ImageDTO.INTERMEDIATE_ANATOMY_ID, ImageDTO.INTERMEDIATE_ANATOMY_TERM, ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_ID, ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_TERM ); if (anatomyTerms != null) { query.addFilterQuery(ImageDTO.ANATOMY_TERM + ":\"" + StringUtils.join(anatomyTerms, "\" OR " + ImageDTO.ANATOMY_TERM + ":\"") + "\""); } if (phenotypingCenter != null) { query.addFilterQuery(ImageDTO.PHENOTYPING_CENTER + ":\"" + StringUtils.join(phenotypingCenter, "\" OR " + ImageDTO.PHENOTYPING_CENTER + ":\"") + "\""); } if (procedure != null) { query.addFilterQuery(ImageDTO.PROCEDURE_NAME + ":\"" + StringUtils.join(procedure, "\" OR " + ImageDTO.PROCEDURE_NAME + ":\"") + "\""); } if (paramAssoc != null) { query.addFilterQuery(ImageDTO.PARAMETER_ASSOCIATION_VALUE + ":\"" + StringUtils.join(paramAssoc, "\" OR " + ImageDTO.PARAMETER_ASSOCIATION_VALUE + ":\"") + "\""); } List<ImageDTO> response = solr.query(query).getBeans(ImageDTO.class); System.out.println("image response size="+response.size()); for (ImageDTO image : response) { for (String expressionValue : image.getDistinctParameterAssociationsValue()) { if (paramAssoc == null || paramAssoc.contains(expressionValue)) { AnatomyPageTableRow row = new AnatomyPageTableRow(image, anatomyId, baseUrl, expressionValue); if (res.containsKey(row.getKey())) { row = res.get(row.getKey()); row.addSex(image.getSex()); row.addIncrementToNumberOfImages(); }else{ row.addIncrementToNumberOfImages(); res.put(row.getKey(), row); } } } } return new ArrayList<>(res.values()); } public Map<String, Set<String>> getFacets(String anatomyId) throws SolrServerException { Map<String, Set<String>> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ"); if (anatomyId != null) { query.addFilterQuery("(" + ImageDTO.ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.INTERMEDIATE_ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_ID + ":\"" + anatomyId + "\")"); } query.addFilterQuery(ImageDTO.BIOLOGICAL_SAMPLE_GROUP + ":\"experimental\"") .addFilterQuery("(" + ImageDTO.PARAMETER_ASSOCIATION_VALUE + ":\"no expression\" OR " + ObservationDTO.PARAMETER_ASSOCIATION_VALUE + ":\"expression\"" + ")"); // only have expressed and // not expressed ingnore // ambiguous and no tissue query.setFacet(true); query.setFacetLimit(-1); query.setFacetMinCount(1); query.addFacetField(ImageDTO.ANATOMY_TERM); query.addFacetField(ImageDTO.PHENOTYPING_CENTER); query.addFacetField(ImageDTO.PROCEDURE_NAME); query.addFacetField(ImageDTO.PARAMETER_ASSOCIATION_VALUE); System.out.println("images query facet="+query); QueryResponse response = solr.query(query); for (FacetField facetField : response.getFacetFields()) { Set<String> filter = new TreeSet<>(); for (Count facet : facetField.getValues()) { if (!facet.getName().equals("tissue not available") && !facet.getName().equals("ambiguous")) { filter.add(facet.getName()); } } res.put(facetField.getName(), filter); } return res; } public List<DataTableRow> getImagesForGene(String geneAccession, String baseUrl) throws SolrServerException { Map<String, AnatomyPageTableRow> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( ImageDTO.GENE_ACCESSION_ID + ":\"" + geneAccession + "\"") .addFilterQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ") .setRows(100000) .setFields(ImageDTO.SEX, ImageDTO.ALLELE_SYMBOL, ImageDTO.ALLELE_ACCESSION_ID, ImageDTO.ZYGOSITY, ImageDTO.ANATOMY_ID, ImageDTO.ANATOMY_TERM, ImageDTO.PROCEDURE_STABLE_ID, ImageDTO.DATASOURCE_NAME, ImageDTO.PARAMETER_ASSOCIATION_VALUE, ImageDTO.GENE_SYMBOL, ImageDTO.GENE_ACCESSION_ID, ImageDTO.PARAMETER_NAME, ImageDTO.PROCEDURE_NAME, ImageDTO.PHENOTYPING_CENTER); System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); List<ImageDTO> response = solr.query(query).getBeans(ImageDTO.class); for (ImageDTO image : response) { for (String maId : image.getAnatomyId()) { AnatomyPageTableRow row = new AnatomyPageTableRow(image, maId, baseUrl, "expression"); if (res.containsKey(row.getKey())) { row = res.get(row.getKey()); row.addSex(image.getSex()); row.addIncrementToNumberOfImages(); } res.put(row.getKey(), row); } } System.out.println("# rows added : " + res.size()); return new ArrayList<>(res.values()); } public long getNumberOfDocuments(List<String> resourceName, boolean experimentalOnly) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setRows(0); if (resourceName != null) { query.setQuery(ImageDTO.DATASOURCE_NAME + ":" + StringUtils.join(resourceName, " OR " + ImageDTO.DATASOURCE_NAME + ":")); } else { query.setQuery("*:*"); } if (experimentalOnly) { query.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":experimental"); } return solr.query(query).getResults().getNumFound(); } /** * * @param query * the url from the page name onwards e.g * q=observation_type:image_record * @return query response * @throws SolrServerException */ public QueryResponse getResponseForSolrQuery(String query) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); String[] paramsKeyValues = query.split("&"); for (String paramKV : paramsKeyValues) { logger.debug("paramKV=" + paramKV); String[] keyValue = paramKV.split("="); if (keyValue.length > 1) { String key = keyValue[0]; String value = keyValue[1]; // System.out.println("param=" + key + " value=" + value); solrQuery.setParam(key, value); } } QueryResponse response = solr.query(solrQuery); return response; } public static SolrQuery allImageRecordSolrQuery() throws SolrServerException { return new SolrQuery().setQuery("observation_type:image_record") .addFilterQuery( "(" + ObservationDTO.DOWNLOAD_FILE_PATH + ":" + "*mousephenotype.org*)"); } public QueryResponse getProcedureFacetsForGeneByProcedure( String mgiAccession, String experimentOrControl) throws SolrServerException { // Map<String, ResponseWrapper<ImageDTO>> map=new HashMap<String, // ResponseWrapper<ImageDTO>>(); // String queryString = "q=gene_accession_id:\"" + mgiAccession + // "\"&fq=" + ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + // experimentOrControl+"&facet=true&facet.field=procedure_name&facet.mincount=1"; // log.debug("queryString in ImageService getFacets=" + queryString); // make a facet request first to get the procedures and then reuturn // make requests for each procedure // http://wwwdev.ebi.ac.uk/mi/impc/dev/solr/impc_images/select?q=gene_accession_id:%22MGI:2384986%22&&fq=biological_sample_group:experimental&facet=true&facet.field=procedure_name SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("gene_accession_id:\"" + mgiAccession + "\""); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + experimentOrControl); solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); solrQuery.addFacetField("procedure_name"); // solrQuery.setRows(0); QueryResponse response = solr.query(solrQuery); return response; } public QueryResponse getImagesForGeneByProcedure(String mgiAccession, String procedure_name, String parameterStableId, String experimentOrControl, int numberOfImagesToRetrieve, SexType sex, String metadataGroup, String strain) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("gene_accession_id:\"" + mgiAccession + "\""); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + experimentOrControl); if (metadataGroup != null) { solrQuery.addFilterQuery(ObservationDTO.METADATA_GROUP + ":" + metadataGroup); } if (strain != null) { solrQuery.addFilterQuery(ObservationDTO.STRAIN_NAME + ":" + strain); } if (sex != null) { solrQuery.addFilterQuery("sex:" + sex.name()); } if (parameterStableId != null) { solrQuery.addFilterQuery(ObservationDTO.PARAMETER_STABLE_ID + ":" + parameterStableId); } solrQuery.addFilterQuery(ObservationDTO.PROCEDURE_NAME + ":\"" + procedure_name + "\""); solrQuery.setRows(numberOfImagesToRetrieve); QueryResponse response = solr.query(solrQuery); return response; } public QueryResponse getImagesForGeneByParameter(String mgiAccession, String parameterStableId, String experimentOrControl, int numberOfImagesToRetrieve, SexType sex, String metadataGroup, String strain, String anatomyId, String parameterAssociationValue, String mpId, String colonyId) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); //gene accession will take precedence if both acc and symbol supplied if(StringUtils.isNotEmpty(mgiAccession)){ solrQuery.setQuery("gene_accession_id:\"" + mgiAccession + "\""); } solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + experimentOrControl); if (StringUtils.isNotEmpty(metadataGroup)) { solrQuery.addFilterQuery(ObservationDTO.METADATA_GROUP + ":" + metadataGroup); } if (StringUtils.isNotEmpty(strain)) { solrQuery.addFilterQuery(ObservationDTO.STRAIN_NAME + ":" + strain); } if (sex != null) { solrQuery.addFilterQuery("sex:" + sex.name()); } if (StringUtils.isNotEmpty(parameterStableId)) { solrQuery.addFilterQuery(ObservationDTO.PARAMETER_STABLE_ID + ":" + parameterStableId); } if (StringUtils.isNotEmpty(parameterAssociationValue)) { solrQuery.addFilterQuery(ObservationDTO.PARAMETER_ASSOCIATION_VALUE + ":" + parameterAssociationValue); } if(StringUtils.isNotEmpty(anatomyId)){ solrQuery.addFilterQuery(ObservationDTO.ANATOMY_ID + ":\"" + anatomyId+"\" OR "+ObservationDTO.INTERMEDIATE_ANATOMY_ID + ":\"" + anatomyId+"\" OR "+ObservationDTO.TOP_LEVEL_ANATOMY_ID + ":\"" + anatomyId+"\""); } if (StringUtils.isNotEmpty(mpId)) { solrQuery.addFilterQuery(MpDTO.MP_ID + ":\"" + mpId+"\""); } if (StringUtils.isNotEmpty(colonyId)) { solrQuery.addFilterQuery(ObservationDTO.COLONY_ID + ":\"" + colonyId+"\""); } solrQuery.setRows(numberOfImagesToRetrieve); System.out.println("solr Query in image service"+solrQuery); QueryResponse response = solr.query(solrQuery); return response; } /** * * @return list of image DTOs with laczData. Selected fields only. * @throws SolrServerException */ public List<ImageDTO> getImagesForLacZ() throws SolrServerException{ SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ*"); query.setFilterQueries(ImageDTO.ANATOMY_ID + ":*"); query.addFilterQuery(ImageDTO.GENE_ACCESSION_ID + ":*"); query.setRows(1000000); query.addField(ImageDTO.GENE_SYMBOL); query.addField(ImageDTO.GENE_ACCESSION_ID); query.addField(ImageDTO.ANATOMY_ID); query.addField(ImageDTO.ANATOMY_TERM); return solr.query(query).getBeans(ImageDTO.class); } public List<String[]> getLaczExpressionSpreadsheet() { SolrQuery query = new SolrQuery(); ArrayList<String[]> res = new ArrayList<>(); String[] aux = new String[0]; query.setQuery(ImageDTO.PROCEDURE_NAME + ":\"Adult LacZ\" AND " + ImageDTO.BIOLOGICAL_SAMPLE_GROUP + ":experimental"); query.setRows(1000000); query.addField(ImageDTO.GENE_SYMBOL); query.addField(ImageDTO.GENE_ACCESSION_ID); query.addField(ImageDTO.ALLELE_SYMBOL); query.addField(ImageDTO.COLONY_ID); query.addField(ImageDTO.BIOLOGICAL_SAMPLE_ID); query.addField(ImageDTO.ZYGOSITY); query.addField(ImageDTO.SEX); query.addField(ImageDTO.PARAMETER_ASSOCIATION_NAME); query.addField(ImageDTO.PARAMETER_STABLE_ID); query.addField(ImageDTO.PARAMETER_ASSOCIATION_VALUE); query.addField(ImageDTO.GENE_ACCESSION_ID); query.addField(ImageDTO.PHENOTYPING_CENTER); query.setFacet(true); query.setFacetLimit(100); query.addFacetField(ImageDTO.PARAMETER_ASSOCIATION_NAME); query.set("group", true); query.set("group.limit", 100000); query.set("group.field", ImageDTO.BIOLOGICAL_SAMPLE_ID); try { QueryResponse solrResult = solr.query(query); ArrayList<String> allParameters = new ArrayList<>(); List<String> header = new ArrayList<>(); header.add("Gene Symbol"); header.add("MGI Gene Id"); header.add("Allele Symbol"); header.add("Colony Id"); header.add("Biological Sample Id"); header.add("Zygosity"); header.add("Sex"); header.add("Phenotyping Centre"); System.out.println(solr.getBaseURL() + "/select?" + query); // Get facets as we need to turn them into columns for (Count facet : solrResult.getFacetField( ImageDTO.PARAMETER_ASSOCIATION_NAME).getValues()) { allParameters.add(facet.getName()); header.add(facet.getName()); } header.add("image_collection_link"); res.add(header.toArray(aux)); for (Group group : solrResult.getGroupResponse().getValues().get(0) .getValues()) { List<String> row = new ArrayList<>(); ArrayList<String> params = new ArrayList<>(); ArrayList<String> paramValues = new ArrayList<>(); String urlToImagePicker = drupalBaseUrl + "/data/imageComparator/"; for (SolrDocument doc : group.getResult()) { if (row.size() == 0) { row.add(doc.getFieldValues(ImageDTO.GENE_SYMBOL) .iterator().next().toString()); row.add(doc.getFieldValues(ImageDTO.GENE_ACCESSION_ID) .iterator().next().toString()); urlToImagePicker += doc .getFieldValue(ImageDTO.GENE_ACCESSION_ID) + "/"; urlToImagePicker += doc .getFieldValue(ImageDTO.PARAMETER_STABLE_ID); if (doc.getFieldValue(ImageDTO.ALLELE_SYMBOL) != null) { row.add(doc.getFieldValue(ImageDTO.ALLELE_SYMBOL) .toString()); } row.add(doc.getFieldValue(ImageDTO.COLONY_ID) .toString()); row.add(doc .getFieldValue(ImageDTO.BIOLOGICAL_SAMPLE_ID) .toString()); if (doc.getFieldValue(ImageDTO.ZYGOSITY) != null) { row.add(doc.getFieldValue(ImageDTO.ZYGOSITY) .toString()); } row.add(doc.getFieldValue(ImageDTO.SEX).toString()); row.add(doc.getFieldValue(ImageDTO.PHENOTYPING_CENTER) .toString()); } if (doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_NAME) != null) { for (int i = 0; i < doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_NAME).size(); i++) { params.add(doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_NAME).toArray(new Object[0])[i].toString()); if (doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_VALUE) != null) { paramValues.add(doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_VALUE).toArray(new Object[0])[i].toString()); } else { paramValues.add(SolrIndex.IMG_NOT_FOUND); } } } } for (String tissue : allParameters) { if (params.contains(tissue)) { row.add(paramValues.get(params.indexOf(tissue))); } else { row.add(""); } } row.add(urlToImagePicker); res.add(row.toArray(aux)); } } catch (SolrServerException e) { e.printStackTrace(); } return res; } /** * * @param metadataGroup * @param center * @param strain * @param procedure_name * @param parameter * @param date * @param numberOfImagesToRetrieve * @param sex * @return * @throws SolrServerException */ public QueryResponse getControlImagesForProcedure(String metadataGroup, String center, String strain, String procedure_name, String parameter, Date date, int numberOfImagesToRetrieve, SexType sex) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":control", ObservationDTO.PHENOTYPING_CENTER + ":\"" + center + "\"", ObservationDTO.STRAIN_NAME + ":" + strain, ObservationDTO.PARAMETER_STABLE_ID + ":" + parameter, ObservationDTO.PROCEDURE_NAME + ":\"" + procedure_name + "\""); solrQuery.setSort("abs(ms(date_of_experiment," + org.apache.solr.common.util.DateUtil .getThreadLocalDateFormat().format(date) + "))", SolrQuery.ORDER.asc); solrQuery.setRows(numberOfImagesToRetrieve); if (StringUtils.isNotEmpty(metadataGroup)) { solrQuery.addFilterQuery(ObservationDTO.METADATA_GROUP + ":" + metadataGroup); } if (sex != null) { solrQuery.addFilterQuery(ObservationDTO.SEX + ":" + sex.name()); } QueryResponse response = solr.query(solrQuery); return response; } /** * * @param numberOfImagesToRetrieve * @param anatomy if this is specified then filter by parameter_association_name and don't filter on date * @return * @throws SolrServerException */ public QueryResponse getControlImagesForExpressionData(int numberOfImagesToRetrieve, String anatomy) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":control"); if (StringUtils.isNotEmpty(anatomy)) { solrQuery.addFilterQuery(ImageDTO.PARAMETER_ASSOCIATION_NAME + ":\"" + anatomy + "\""); } solrQuery.setRows(numberOfImagesToRetrieve); QueryResponse response = solr.query(solrQuery); return response; } /** * Get the first control and then experimental images if available for the * all procedures for a gene and then the first parameter for the procedure * that we come across * * @param acc * the gene to get the images for * @param model * the model to add the images to * @param numberOfControls * TODO * @param numberOfExperimental * TODO * @param getForAllParameters * TODO * @throws SolrServerException */ public void getImpcImagesForGenePage(String acc, Model model, int numberOfControls, int numberOfExperimental, boolean getForAllParameters) throws SolrServerException { String excludeProcedureName = null;// "Adult LacZ";// exclude adult lacz from // the images section as // this will now be in the // expression section on the // gene page QueryResponse solrR = this.getProcedureFacetsForGeneByProcedure(acc, "experimental"); if (solrR == null) { logger.error("no response from solr data source for acc=" + acc); return; } List<FacetField> procedures = solrR.getFacetFields(); if (procedures == null) { logger.error("no facets from solr data source for acc=" + acc); return; } List<Count> filteredCounts = new ArrayList<>(); Map<String, SolrDocumentList> facetToDocs = new HashMap<>(); for (FacetField procedureFacet : procedures) { if (procedureFacet.getValueCount() != 0) { // for (FacetField procedureFacet : procedures) { // System.out.println("proc facet name="+procedureFacet.getName()); // this.getControlAndExperimentalImpcImages(acc, model, // procedureFacet.getCount().getName(), null, 1, 1, // "Adult LacZ"); // } // get rid of wholemount expression/Adult LacZ facet as this is // displayed seperately in the using the other method // need to put the section in genes.jsp!!! for (Count count : procedures.get(0).getValues()) { if (!count.getName().equals(excludeProcedureName)) { filteredCounts.add(count); } } for (Count procedure : procedureFacet.getValues()) { if (!procedure.getName().equals(excludeProcedureName)) { this.getControlAndExperimentalImpcImages(acc, model, procedure.getName(), null, 0, 1, excludeProcedureName, filteredCounts, facetToDocs, null); } } } } model.addAttribute("impcImageFacets", filteredCounts); model.addAttribute("impcFacetToDocs", facetToDocs); } /** * Gets numberOfControls images which are "nearest in time" to the date of * experiment defined in the imgDoc parameter for the specified sex. * * @param numberOfControls * how many control images to collect * @param sex * the sex of the specimen in the images * @param imgDoc * the solr document representing the image record * @param anatomy * TODO * @return solr document list, now updated to include all appropriate * control images * @throws SolrServerException */ public SolrDocumentList getControls(int numberOfControls, SexType sex, SolrDocument imgDoc, String anatomy) throws SolrServerException { SolrDocumentList list = new SolrDocumentList(); final String metadataGroup = (String) imgDoc .get(ObservationDTO.METADATA_GROUP); final String center = (String) imgDoc .get(ObservationDTO.PHENOTYPING_CENTER); final String strain = (String) imgDoc.get(ObservationDTO.STRAIN_NAME); final String procedureName = (String) imgDoc .get(ObservationDTO.PROCEDURE_NAME); final String parameter = (String) imgDoc .get(ObservationDTO.PARAMETER_STABLE_ID); final Date date = (Date) imgDoc.get(ObservationDTO.DATE_OF_EXPERIMENT); QueryResponse responseControl =null; if(StringUtils.isNotEmpty(anatomy)){ responseControl=this.getControlImagesForExpressionData(numberOfControls, anatomy); }else{ responseControl=this.getControlImagesForProcedure(metadataGroup, center, strain, procedureName, parameter, date, numberOfControls, sex); } list.addAll(responseControl.getResults()); return list; } /** * * @param acc * gene accession mandatory * @param model * mvc model * @param procedureName * mandatory * @param parameterStableId * optional if we want to restrict to a parameter make not null * @param numberOfControls * can be 0 or any other number * @param numberOfExperimental * can be 0 or any other int * @param excludedProcedureName * for example if we don't want "Adult Lac Z" returned * @param filteredCounts * @param facetToDocs * @param anatomyId TODO * @throws SolrServerException */ public void getControlAndExperimentalImpcImages(String acc, Model model, String procedureName, String parameterStableId, int numberOfControls, int numberOfExperimental, String excludedProcedureName, List<Count> filteredCounts, Map<String, SolrDocumentList> facetToDocs, String anatomyId) throws SolrServerException { model.addAttribute("acc", acc);// forward the gene id along to the new // page for links QueryResponse solrR = this.getParameterFacetsForGeneByProcedure(acc, procedureName, "experimental"); if (solrR == null) { logger.error("no response from solr data source for acc=" + acc); return; } List<FacetField> facets = solrR.getFacetFields(); if (facets == null) { logger.error("no facets from solr data source for acc=" + acc); return; } // get rid of wholemount expression/Adult LacZ facet as this is // displayed seperately in the using the other method // need to put the section in genes.jsp!!! for (Count count : facets.get(0).getValues()) { if (!count.getName().equals(excludedProcedureName)) { filteredCounts.add(count); } } for (FacetField facet : facets) { if (facet.getValueCount() != 0) { for (Count count : facet.getValues()) { SolrDocumentList list = null;// list of // image // docs to // return to // the // procedure // section // of the // gene page if (!count.getName().equals(excludedProcedureName)) { QueryResponse responseExperimental = this .getImagesForGeneByParameter(acc,count.getName(), "experimental", 1,null, null, null, anatomyId, null, null, null); if (responseExperimental.getResults().size() > 0) { SolrDocument imgDoc = responseExperimental .getResults().get(0); QueryResponse responseExperimental2 = this .getImagesForGeneByParameter( acc, (String) imgDoc .get(ObservationDTO.PARAMETER_STABLE_ID), "experimental", numberOfExperimental, null, (String) imgDoc .get(ObservationDTO.METADATA_GROUP), (String) imgDoc .get(ObservationDTO.STRAIN_NAME), anatomyId, null, null, null); list = getControls(numberOfControls, null, imgDoc, null); if (responseExperimental2 != null) { list.addAll(responseExperimental2.getResults()); } } facetToDocs.put(count.getName(), list); } } } } } public QueryResponse getParameterFacetsForGeneByProcedure(String acc, String procedureName, String controlOrExperimental) throws SolrServerException { // e.g. // http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/impc_images/query?q=gene_accession_id:%22MGI:2384986%22&fq=biological_sample_group:experimental&fq=procedure_name:X-ray&facet=true&facet.field=parameter_stable_id SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("gene_accession_id:\"" + acc + "\""); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + controlOrExperimental); solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); solrQuery.addFilterQuery(ObservationDTO.PROCEDURE_NAME + ":\"" + procedureName + "\""); solrQuery.addFacetField(ObservationDTO.PARAMETER_STABLE_ID); // solrQuery.setRows(0); QueryResponse response = solr.query(solrQuery); return response; } public QueryResponse getImagesAnnotationsDetailsByOmeroId( List<String> omeroIds) throws SolrServerException { // e.g. // http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/impc_images/query?q=omero_id:(5815 // 5814) SolrQuery solrQuery = new SolrQuery(); String omeroIdString = "omero_id:("; String result = StringUtils.join(omeroIds, " OR "); omeroIdString += result + ")"; solrQuery.setQuery(omeroIdString); // System.out.println(omeroIdString); // solrQuery.setRows(0); QueryResponse response = solr.query(solrQuery); return response; } public Boolean hasImages(String geneAccessionId, String procedureName, String colonyId) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( "(" + ImageDTO.GENE_ACCESSION_ID + ":\"" + geneAccessionId + "\" AND " + ImageDTO.PROCEDURE_NAME + ":\"" + procedureName + "\" AND " + ImageDTO.COLONY_ID + ":\"" + colonyId + "\")") .setRows(0); //System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); if ( response.getResults().getNumFound() == 0 ){ return false; } return true; } public Boolean hasImagesWithMP(String geneAccessionId, String procedureName, String colonyId, String mpId) throws SolrServerException { //System.out.println("looking for mp term="+mpTerm +" colony Id="+colonyId); SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( "(" + ImageDTO.GENE_ACCESSION_ID + ":\"" + geneAccessionId + "\" AND " + ImageDTO.PROCEDURE_NAME + ":\"" + procedureName + "\" AND " + ImageDTO.COLONY_ID + ":\"" + colonyId + "\" AND " + MpDTO.MP_ID + ":\"" + mpId + "\")") .setRows(0); System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); if ( response.getResults().getNumFound() == 0 ){ return false; } System.out.println("returning true"); return true; } public long getWebStatus() throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery("*:*").setRows(0); //System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); return response.getResults().getNumFound(); } public String getServiceName(){ return "impc_images"; } public SolrDocument getImageByDownloadFilePath(String downloadFilePath) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.DOWNLOAD_FILE_PATH+":\""+downloadFilePath+"\"").setRows(1); //query.addField(ImageDTO.OMERO_ID); //query.addField(ImageDTO.INCREMENT_VALUE); //query.addField(ImageDTO.DOWNLOAD_URL); //query.addField(ImageDTO.EXTERNAL_SAMPLE_ID); //System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); SolrDocument img = response.getResults().get(0); //ImageDTO image = response.get(0); //System.out.println("image omero_id"+image.getOmeroId()+" increment_id="+image.getIncrement()); return img; } /** * * @param acc * @return a map containing the mp and colony_id combinations so that if we have these then we show an image link on the phenotype table on the gene page. Each row in table could have a different colony_id as well as mp id * @throws SolrServerException */ public Map<String, Set<String>> getImagePropertiesThatHaveMp(String acc) throws SolrServerException { //http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/impc_images/select?q=gene_accession_id:%22MGI:1913955%22&fq=mp_id:*&facet=true&facet.mincount=1&facet.limit=-1&facet.field=colony_id&facet.field=mp_id&facet.field=mp_term&rows=0 Map<String, Set<String>> mpToColony = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.GENE_ACCESSION_ID+":\""+acc+"\"").setRows(100000000); query.addFilterQuery(ImageDTO.MP_ID_TERM+":*"); query.setFacet(true); query.setFacetLimit(-1); query.setFacetMinCount(1); String pivotFacet=ImageDTO.MP_ID_TERM + "," + ImageDTO.COLONY_ID; query.set("facet.pivot", pivotFacet); query.addFacetField(ObservationDTO.COLONY_ID); //System.out.println("solr query for images properties for mp="+query); QueryResponse response = solr.query(query); for( PivotField pivot : response.getFacetPivot().get(pivotFacet)){ //System.out.println("pivot="+pivot.getValue()); String mpIdAndName=pivot.getValue().toString(); //System.out.println("mpIdAndName" +mpIdAndName); String mpId=""; Set<String> colonIds=new TreeSet<>(); if(mpIdAndName.contains("_")){ mpId=(mpIdAndName.split("_")[0]); } for (PivotField mp : pivot.getPivot()){ //System.out.println("adding mp="+pivot.getValue()+" adding value="+mp.getValue()); String colonyId=mp.getValue().toString(); colonIds.add(colonyId); } mpToColony.put(mpId, colonIds); } return mpToColony; } }
data-model-solr/src/main/java/org/mousephenotype/cda/solr/service/ImageService.java
/******************************************************************************* * Copyright 2015 EMBL - European Bioinformatics Institute * * 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.mousephenotype.cda.solr.service; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.apache.solr.client.solrj.response.Group; import org.apache.solr.client.solrj.response.PivotField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.mousephenotype.cda.enumerations.SexType; import org.mousephenotype.cda.solr.service.dto.ImageDTO; import org.mousephenotype.cda.solr.service.dto.MpDTO; import org.mousephenotype.cda.solr.service.dto.ObservationDTO; import org.mousephenotype.cda.solr.web.dto.AnatomyPageTableRow; import org.mousephenotype.cda.solr.web.dto.DataTableRow; import org.mousephenotype.cda.solr.web.dto.ImageSummary; import org.mousephenotype.cda.web.WebStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import javax.validation.constraints.NotNull; import java.util.*; @Service public class ImageService implements WebStatus{ @Autowired @Qualifier("impcImagesCore") private HttpSolrServer solr; private final Logger logger = LoggerFactory.getLogger(ImageService.class); public ImageService() { } @NotNull @Value("${drupalBaseUrl}") private String drupalBaseUrl; public List<ImageSummary> getImageSummary(String markerAccessionId) throws SolrServerException{ SolrQuery q = new SolrQuery(); q.setQuery("*:*"); q.setFilterQueries(ImageDTO.GENE_ACCESSION_ID + ":\"" + markerAccessionId + "\""); // TM decided only to display some procedures in the Summary q.addFilterQuery("(" + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_XRY* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_XRY* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_ALZ* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_PAT* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_EYE* OR " + ImageDTO.PROCEDURE_STABLE_ID + ":IMPC_HIS*" + ")"); q.set("group", true); q.set("group.field", ImageDTO.PROCEDURE_NAME); q.set("group.limit", 1); q.set("group.sort" , ImageDTO.DATE_OF_EXPERIMENT + " DESC"); List<ImageSummary> res = new ArrayList<>(); for (Group group : solr.query(q).getGroupResponse().getValues().get(0).getValues()){ ImageSummary iSummary = new ImageSummary(); iSummary.setNumberOfImages(group.getResult().getNumFound()); iSummary.setProcedureId(group.getResult().get(0).getFieldValue(ImageDTO.PROCEDURE_STABLE_ID).toString()); iSummary.setProcedureName(group.getResult().get(0).getFieldValue(ImageDTO.PROCEDURE_NAME).toString()); iSummary.setThumbnailUrl(group.getResult().get(0).getFieldValue(ImageDTO.JPEG_URL).toString().replace("render_image", "render_thumbnail")); res.add(iSummary); } return res; } /** * This method should not be used! This method should use the observation core and get categorical data as well as have image links where applicable!!! * @param anatomyTable * @param anatomyId * @param anatomyTerms * @param phenotypingCenter * @param procedure * @param paramAssoc * @param baseUrl * @return * @throws SolrServerException */ public List<AnatomyPageTableRow> getImagesForAnatomy(String anatomyId, List<String> anatomyTerms, List<String> phenotypingCenter, List<String> procedure, List<String> paramAssoc, String baseUrl) throws SolrServerException { System.out.println("calling get images for Anatomy"); Map<String, AnatomyPageTableRow> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( "(" + ImageDTO.ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.INTERMEDIATE_ANATOMY_ID + ":\"" + anatomyId + "\")") .addFilterQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ") .addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":\"experimental\"") .addFilterQuery("("+ImageDTO.PARAMETER_ASSOCIATION_VALUE+ ":\"no expression\" OR "+ImageDTO.PARAMETER_ASSOCIATION_VALUE+":\"expression\""+")") //only have expressed and not expressed ingnore ambiguous and no tissue .setRows(Integer.MAX_VALUE) .setFields(ImageDTO.SEX, ImageDTO.ALLELE_SYMBOL, ImageDTO.ALLELE_ACCESSION_ID, ImageDTO.ZYGOSITY, ImageDTO.ANATOMY_ID, ImageDTO.ANATOMY_TERM, ImageDTO.PROCEDURE_STABLE_ID, ImageDTO.DATASOURCE_NAME, ImageDTO.PARAMETER_ASSOCIATION_VALUE, ImageDTO.GENE_SYMBOL, ImageDTO.GENE_ACCESSION_ID, ImageDTO.PARAMETER_NAME, ImageDTO.PARAMETER_STABLE_ID, ImageDTO.PROCEDURE_NAME, ImageDTO.PHENOTYPING_CENTER, ImageDTO.INTERMEDIATE_ANATOMY_ID, ImageDTO.INTERMEDIATE_ANATOMY_TERM, ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_ID, ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_TERM ); if (anatomyTerms != null) { query.addFilterQuery(ImageDTO.ANATOMY_TERM + ":\"" + StringUtils.join(anatomyTerms, "\" OR " + ImageDTO.ANATOMY_TERM + ":\"") + "\""); } if (phenotypingCenter != null) { query.addFilterQuery(ImageDTO.PHENOTYPING_CENTER + ":\"" + StringUtils.join(phenotypingCenter, "\" OR " + ImageDTO.PHENOTYPING_CENTER + ":\"") + "\""); } if (procedure != null) { query.addFilterQuery(ImageDTO.PROCEDURE_NAME + ":\"" + StringUtils.join(procedure, "\" OR " + ImageDTO.PROCEDURE_NAME + ":\"") + "\""); } if (paramAssoc != null) { query.addFilterQuery(ImageDTO.PARAMETER_ASSOCIATION_VALUE + ":\"" + StringUtils.join(paramAssoc, "\" OR " + ImageDTO.PARAMETER_ASSOCIATION_VALUE + ":\"") + "\""); } List<ImageDTO> response = solr.query(query).getBeans(ImageDTO.class); System.out.println("image response size="+response.size()); for (ImageDTO image : response) { for (String expressionValue : image.getDistinctParameterAssociationsValue()) { if (paramAssoc == null || paramAssoc.contains(expressionValue)) { AnatomyPageTableRow row = new AnatomyPageTableRow(image, anatomyId, baseUrl, expressionValue); if (res.containsKey(row.getKey())) { row = res.get(row.getKey()); row.addSex(image.getSex()); row.addIncrementToNumberOfImages(); }else{ row.addIncrementToNumberOfImages(); res.put(row.getKey(), row); } } } } return new ArrayList<>(res.values()); } public Map<String, Set<String>> getFacets(String anatomyId) throws SolrServerException { Map<String, Set<String>> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ"); if (anatomyId != null) { query.addFilterQuery("(" + ImageDTO.ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.INTERMEDIATE_ANATOMY_ID + ":\"" + anatomyId + "\" OR " + ImageDTO.SELECTED_TOP_LEVEL_ANATOMY_ID + ":\"" + anatomyId + "\")"); } query.addFilterQuery(ImageDTO.BIOLOGICAL_SAMPLE_GROUP + ":\"experimental\"") .addFilterQuery("(" + ImageDTO.PARAMETER_ASSOCIATION_VALUE + ":\"no expression\" OR " + ObservationDTO.PARAMETER_ASSOCIATION_VALUE + ":\"expression\"" + ")"); // only have expressed and // not expressed ingnore // ambiguous and no tissue query.setFacet(true); query.setFacetLimit(-1); query.setFacetMinCount(1); query.addFacetField(ImageDTO.ANATOMY_TERM); query.addFacetField(ImageDTO.PHENOTYPING_CENTER); query.addFacetField(ImageDTO.PROCEDURE_NAME); query.addFacetField(ImageDTO.PARAMETER_ASSOCIATION_VALUE); System.out.println("images query facet="+query); QueryResponse response = solr.query(query); for (FacetField facetField : response.getFacetFields()) { Set<String> filter = new TreeSet<>(); for (Count facet : facetField.getValues()) { if (facet.getName().equals("expression") || facetField.getName().equals("no expression")) { filter.add(facet.getName()); } } res.put(facetField.getName(), filter); } return res; } public List<DataTableRow> getImagesForGene(String geneAccession, String baseUrl) throws SolrServerException { Map<String, AnatomyPageTableRow> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( ImageDTO.GENE_ACCESSION_ID + ":\"" + geneAccession + "\"") .addFilterQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ") .setRows(100000) .setFields(ImageDTO.SEX, ImageDTO.ALLELE_SYMBOL, ImageDTO.ALLELE_ACCESSION_ID, ImageDTO.ZYGOSITY, ImageDTO.ANATOMY_ID, ImageDTO.ANATOMY_TERM, ImageDTO.PROCEDURE_STABLE_ID, ImageDTO.DATASOURCE_NAME, ImageDTO.PARAMETER_ASSOCIATION_VALUE, ImageDTO.GENE_SYMBOL, ImageDTO.GENE_ACCESSION_ID, ImageDTO.PARAMETER_NAME, ImageDTO.PROCEDURE_NAME, ImageDTO.PHENOTYPING_CENTER); System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); List<ImageDTO> response = solr.query(query).getBeans(ImageDTO.class); for (ImageDTO image : response) { for (String maId : image.getAnatomyId()) { AnatomyPageTableRow row = new AnatomyPageTableRow(image, maId, baseUrl, "expression"); if (res.containsKey(row.getKey())) { row = res.get(row.getKey()); row.addSex(image.getSex()); row.addIncrementToNumberOfImages(); } res.put(row.getKey(), row); } } System.out.println("# rows added : " + res.size()); return new ArrayList<>(res.values()); } public long getNumberOfDocuments(List<String> resourceName, boolean experimentalOnly) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setRows(0); if (resourceName != null) { query.setQuery(ImageDTO.DATASOURCE_NAME + ":" + StringUtils.join(resourceName, " OR " + ImageDTO.DATASOURCE_NAME + ":")); } else { query.setQuery("*:*"); } if (experimentalOnly) { query.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":experimental"); } return solr.query(query).getResults().getNumFound(); } /** * * @param query * the url from the page name onwards e.g * q=observation_type:image_record * @return query response * @throws SolrServerException */ public QueryResponse getResponseForSolrQuery(String query) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); String[] paramsKeyValues = query.split("&"); for (String paramKV : paramsKeyValues) { logger.debug("paramKV=" + paramKV); String[] keyValue = paramKV.split("="); if (keyValue.length > 1) { String key = keyValue[0]; String value = keyValue[1]; // System.out.println("param=" + key + " value=" + value); solrQuery.setParam(key, value); } } QueryResponse response = solr.query(solrQuery); return response; } public static SolrQuery allImageRecordSolrQuery() throws SolrServerException { return new SolrQuery().setQuery("observation_type:image_record") .addFilterQuery( "(" + ObservationDTO.DOWNLOAD_FILE_PATH + ":" + "*mousephenotype.org*)"); } public QueryResponse getProcedureFacetsForGeneByProcedure( String mgiAccession, String experimentOrControl) throws SolrServerException { // Map<String, ResponseWrapper<ImageDTO>> map=new HashMap<String, // ResponseWrapper<ImageDTO>>(); // String queryString = "q=gene_accession_id:\"" + mgiAccession + // "\"&fq=" + ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + // experimentOrControl+"&facet=true&facet.field=procedure_name&facet.mincount=1"; // log.debug("queryString in ImageService getFacets=" + queryString); // make a facet request first to get the procedures and then reuturn // make requests for each procedure // http://wwwdev.ebi.ac.uk/mi/impc/dev/solr/impc_images/select?q=gene_accession_id:%22MGI:2384986%22&&fq=biological_sample_group:experimental&facet=true&facet.field=procedure_name SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("gene_accession_id:\"" + mgiAccession + "\""); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + experimentOrControl); solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); solrQuery.addFacetField("procedure_name"); // solrQuery.setRows(0); QueryResponse response = solr.query(solrQuery); return response; } public QueryResponse getImagesForGeneByProcedure(String mgiAccession, String procedure_name, String parameterStableId, String experimentOrControl, int numberOfImagesToRetrieve, SexType sex, String metadataGroup, String strain) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("gene_accession_id:\"" + mgiAccession + "\""); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + experimentOrControl); if (metadataGroup != null) { solrQuery.addFilterQuery(ObservationDTO.METADATA_GROUP + ":" + metadataGroup); } if (strain != null) { solrQuery.addFilterQuery(ObservationDTO.STRAIN_NAME + ":" + strain); } if (sex != null) { solrQuery.addFilterQuery("sex:" + sex.name()); } if (parameterStableId != null) { solrQuery.addFilterQuery(ObservationDTO.PARAMETER_STABLE_ID + ":" + parameterStableId); } solrQuery.addFilterQuery(ObservationDTO.PROCEDURE_NAME + ":\"" + procedure_name + "\""); solrQuery.setRows(numberOfImagesToRetrieve); QueryResponse response = solr.query(solrQuery); return response; } public QueryResponse getImagesForGeneByParameter(String mgiAccession, String parameterStableId, String experimentOrControl, int numberOfImagesToRetrieve, SexType sex, String metadataGroup, String strain, String anatomyId, String parameterAssociationValue, String mpId, String colonyId) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); //gene accession will take precedence if both acc and symbol supplied if(StringUtils.isNotEmpty(mgiAccession)){ solrQuery.setQuery("gene_accession_id:\"" + mgiAccession + "\""); } solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + experimentOrControl); if (StringUtils.isNotEmpty(metadataGroup)) { solrQuery.addFilterQuery(ObservationDTO.METADATA_GROUP + ":" + metadataGroup); } if (StringUtils.isNotEmpty(strain)) { solrQuery.addFilterQuery(ObservationDTO.STRAIN_NAME + ":" + strain); } if (sex != null) { solrQuery.addFilterQuery("sex:" + sex.name()); } if (StringUtils.isNotEmpty(parameterStableId)) { solrQuery.addFilterQuery(ObservationDTO.PARAMETER_STABLE_ID + ":" + parameterStableId); } if (StringUtils.isNotEmpty(parameterAssociationValue)) { solrQuery.addFilterQuery(ObservationDTO.PARAMETER_ASSOCIATION_VALUE + ":" + parameterAssociationValue); } if(StringUtils.isNotEmpty(anatomyId)){ solrQuery.addFilterQuery(ObservationDTO.ANATOMY_ID + ":\"" + anatomyId+"\" OR "+ObservationDTO.INTERMEDIATE_ANATOMY_ID + ":\"" + anatomyId+"\" OR "+ObservationDTO.TOP_LEVEL_ANATOMY_ID + ":\"" + anatomyId+"\""); } if (StringUtils.isNotEmpty(mpId)) { solrQuery.addFilterQuery(MpDTO.MP_ID + ":\"" + mpId+"\""); } if (StringUtils.isNotEmpty(colonyId)) { solrQuery.addFilterQuery(ObservationDTO.COLONY_ID + ":\"" + colonyId+"\""); } solrQuery.setRows(numberOfImagesToRetrieve); System.out.println("solr Query in image service"+solrQuery); QueryResponse response = solr.query(solrQuery); return response; } /** * * @return list of image DTOs with laczData. Selected fields only. * @throws SolrServerException */ public List<ImageDTO> getImagesForLacZ() throws SolrServerException{ SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.PROCEDURE_NAME + ":*LacZ*"); query.setFilterQueries(ImageDTO.ANATOMY_ID + ":*"); query.addFilterQuery(ImageDTO.GENE_ACCESSION_ID + ":*"); query.setRows(1000000); query.addField(ImageDTO.GENE_SYMBOL); query.addField(ImageDTO.GENE_ACCESSION_ID); query.addField(ImageDTO.ANATOMY_ID); query.addField(ImageDTO.ANATOMY_TERM); return solr.query(query).getBeans(ImageDTO.class); } public List<String[]> getLaczExpressionSpreadsheet() { SolrQuery query = new SolrQuery(); ArrayList<String[]> res = new ArrayList<>(); String[] aux = new String[0]; query.setQuery(ImageDTO.PROCEDURE_NAME + ":\"Adult LacZ\" AND " + ImageDTO.BIOLOGICAL_SAMPLE_GROUP + ":experimental"); query.setRows(1000000); query.addField(ImageDTO.GENE_SYMBOL); query.addField(ImageDTO.GENE_ACCESSION_ID); query.addField(ImageDTO.ALLELE_SYMBOL); query.addField(ImageDTO.COLONY_ID); query.addField(ImageDTO.BIOLOGICAL_SAMPLE_ID); query.addField(ImageDTO.ZYGOSITY); query.addField(ImageDTO.SEX); query.addField(ImageDTO.PARAMETER_ASSOCIATION_NAME); query.addField(ImageDTO.PARAMETER_STABLE_ID); query.addField(ImageDTO.PARAMETER_ASSOCIATION_VALUE); query.addField(ImageDTO.GENE_ACCESSION_ID); query.addField(ImageDTO.PHENOTYPING_CENTER); query.setFacet(true); query.setFacetLimit(100); query.addFacetField(ImageDTO.PARAMETER_ASSOCIATION_NAME); query.set("group", true); query.set("group.limit", 100000); query.set("group.field", ImageDTO.BIOLOGICAL_SAMPLE_ID); try { QueryResponse solrResult = solr.query(query); ArrayList<String> allParameters = new ArrayList<>(); List<String> header = new ArrayList<>(); header.add("Gene Symbol"); header.add("MGI Gene Id"); header.add("Allele Symbol"); header.add("Colony Id"); header.add("Biological Sample Id"); header.add("Zygosity"); header.add("Sex"); header.add("Phenotyping Centre"); System.out.println(solr.getBaseURL() + "/select?" + query); // Get facets as we need to turn them into columns for (Count facet : solrResult.getFacetField( ImageDTO.PARAMETER_ASSOCIATION_NAME).getValues()) { allParameters.add(facet.getName()); header.add(facet.getName()); } header.add("image_collection_link"); res.add(header.toArray(aux)); for (Group group : solrResult.getGroupResponse().getValues().get(0) .getValues()) { List<String> row = new ArrayList<>(); ArrayList<String> params = new ArrayList<>(); ArrayList<String> paramValues = new ArrayList<>(); String urlToImagePicker = drupalBaseUrl + "/data/imageComparator/"; for (SolrDocument doc : group.getResult()) { if (row.size() == 0) { row.add(doc.getFieldValues(ImageDTO.GENE_SYMBOL) .iterator().next().toString()); row.add(doc.getFieldValues(ImageDTO.GENE_ACCESSION_ID) .iterator().next().toString()); urlToImagePicker += doc .getFieldValue(ImageDTO.GENE_ACCESSION_ID) + "/"; urlToImagePicker += doc .getFieldValue(ImageDTO.PARAMETER_STABLE_ID); if (doc.getFieldValue(ImageDTO.ALLELE_SYMBOL) != null) { row.add(doc.getFieldValue(ImageDTO.ALLELE_SYMBOL) .toString()); } row.add(doc.getFieldValue(ImageDTO.COLONY_ID) .toString()); row.add(doc .getFieldValue(ImageDTO.BIOLOGICAL_SAMPLE_ID) .toString()); if (doc.getFieldValue(ImageDTO.ZYGOSITY) != null) { row.add(doc.getFieldValue(ImageDTO.ZYGOSITY) .toString()); } row.add(doc.getFieldValue(ImageDTO.SEX).toString()); row.add(doc.getFieldValue(ImageDTO.PHENOTYPING_CENTER) .toString()); } if (doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_NAME) != null) { for (int i = 0; i < doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_NAME).size(); i++) { params.add(doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_NAME).toArray(new Object[0])[i].toString()); if (doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_VALUE) != null) { paramValues.add(doc.getFieldValues(ImageDTO.PARAMETER_ASSOCIATION_VALUE).toArray(new Object[0])[i].toString()); } else { paramValues.add(SolrIndex.IMG_NOT_FOUND); } } } } for (String tissue : allParameters) { if (params.contains(tissue)) { row.add(paramValues.get(params.indexOf(tissue))); } else { row.add(""); } } row.add(urlToImagePicker); res.add(row.toArray(aux)); } } catch (SolrServerException e) { e.printStackTrace(); } return res; } /** * * @param metadataGroup * @param center * @param strain * @param procedure_name * @param parameter * @param date * @param numberOfImagesToRetrieve * @param sex * @return * @throws SolrServerException */ public QueryResponse getControlImagesForProcedure(String metadataGroup, String center, String strain, String procedure_name, String parameter, Date date, int numberOfImagesToRetrieve, SexType sex) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":control", ObservationDTO.PHENOTYPING_CENTER + ":\"" + center + "\"", ObservationDTO.STRAIN_NAME + ":" + strain, ObservationDTO.PARAMETER_STABLE_ID + ":" + parameter, ObservationDTO.PROCEDURE_NAME + ":\"" + procedure_name + "\""); solrQuery.setSort("abs(ms(date_of_experiment," + org.apache.solr.common.util.DateUtil .getThreadLocalDateFormat().format(date) + "))", SolrQuery.ORDER.asc); solrQuery.setRows(numberOfImagesToRetrieve); if (StringUtils.isNotEmpty(metadataGroup)) { solrQuery.addFilterQuery(ObservationDTO.METADATA_GROUP + ":" + metadataGroup); } if (sex != null) { solrQuery.addFilterQuery(ObservationDTO.SEX + ":" + sex.name()); } QueryResponse response = solr.query(solrQuery); return response; } /** * * @param numberOfImagesToRetrieve * @param anatomy if this is specified then filter by parameter_association_name and don't filter on date * @return * @throws SolrServerException */ public QueryResponse getControlImagesForExpressionData(int numberOfImagesToRetrieve, String anatomy) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":control"); if (StringUtils.isNotEmpty(anatomy)) { solrQuery.addFilterQuery(ImageDTO.PARAMETER_ASSOCIATION_NAME + ":\"" + anatomy + "\""); } solrQuery.setRows(numberOfImagesToRetrieve); QueryResponse response = solr.query(solrQuery); return response; } /** * Get the first control and then experimental images if available for the * all procedures for a gene and then the first parameter for the procedure * that we come across * * @param acc * the gene to get the images for * @param model * the model to add the images to * @param numberOfControls * TODO * @param numberOfExperimental * TODO * @param getForAllParameters * TODO * @throws SolrServerException */ public void getImpcImagesForGenePage(String acc, Model model, int numberOfControls, int numberOfExperimental, boolean getForAllParameters) throws SolrServerException { String excludeProcedureName = null;// "Adult LacZ";// exclude adult lacz from // the images section as // this will now be in the // expression section on the // gene page QueryResponse solrR = this.getProcedureFacetsForGeneByProcedure(acc, "experimental"); if (solrR == null) { logger.error("no response from solr data source for acc=" + acc); return; } List<FacetField> procedures = solrR.getFacetFields(); if (procedures == null) { logger.error("no facets from solr data source for acc=" + acc); return; } List<Count> filteredCounts = new ArrayList<>(); Map<String, SolrDocumentList> facetToDocs = new HashMap<>(); for (FacetField procedureFacet : procedures) { if (procedureFacet.getValueCount() != 0) { // for (FacetField procedureFacet : procedures) { // System.out.println("proc facet name="+procedureFacet.getName()); // this.getControlAndExperimentalImpcImages(acc, model, // procedureFacet.getCount().getName(), null, 1, 1, // "Adult LacZ"); // } // get rid of wholemount expression/Adult LacZ facet as this is // displayed seperately in the using the other method // need to put the section in genes.jsp!!! for (Count count : procedures.get(0).getValues()) { if (!count.getName().equals(excludeProcedureName)) { filteredCounts.add(count); } } for (Count procedure : procedureFacet.getValues()) { if (!procedure.getName().equals(excludeProcedureName)) { this.getControlAndExperimentalImpcImages(acc, model, procedure.getName(), null, 0, 1, excludeProcedureName, filteredCounts, facetToDocs, null); } } } } model.addAttribute("impcImageFacets", filteredCounts); model.addAttribute("impcFacetToDocs", facetToDocs); } /** * Gets numberOfControls images which are "nearest in time" to the date of * experiment defined in the imgDoc parameter for the specified sex. * * @param numberOfControls * how many control images to collect * @param sex * the sex of the specimen in the images * @param imgDoc * the solr document representing the image record * @param anatomy * TODO * @return solr document list, now updated to include all appropriate * control images * @throws SolrServerException */ public SolrDocumentList getControls(int numberOfControls, SexType sex, SolrDocument imgDoc, String anatomy) throws SolrServerException { SolrDocumentList list = new SolrDocumentList(); final String metadataGroup = (String) imgDoc .get(ObservationDTO.METADATA_GROUP); final String center = (String) imgDoc .get(ObservationDTO.PHENOTYPING_CENTER); final String strain = (String) imgDoc.get(ObservationDTO.STRAIN_NAME); final String procedureName = (String) imgDoc .get(ObservationDTO.PROCEDURE_NAME); final String parameter = (String) imgDoc .get(ObservationDTO.PARAMETER_STABLE_ID); final Date date = (Date) imgDoc.get(ObservationDTO.DATE_OF_EXPERIMENT); QueryResponse responseControl =null; if(StringUtils.isNotEmpty(anatomy)){ responseControl=this.getControlImagesForExpressionData(numberOfControls, anatomy); }else{ responseControl=this.getControlImagesForProcedure(metadataGroup, center, strain, procedureName, parameter, date, numberOfControls, sex); } list.addAll(responseControl.getResults()); return list; } /** * * @param acc * gene accession mandatory * @param model * mvc model * @param procedureName * mandatory * @param parameterStableId * optional if we want to restrict to a parameter make not null * @param numberOfControls * can be 0 or any other number * @param numberOfExperimental * can be 0 or any other int * @param excludedProcedureName * for example if we don't want "Adult Lac Z" returned * @param filteredCounts * @param facetToDocs * @param anatomyId TODO * @throws SolrServerException */ public void getControlAndExperimentalImpcImages(String acc, Model model, String procedureName, String parameterStableId, int numberOfControls, int numberOfExperimental, String excludedProcedureName, List<Count> filteredCounts, Map<String, SolrDocumentList> facetToDocs, String anatomyId) throws SolrServerException { model.addAttribute("acc", acc);// forward the gene id along to the new // page for links QueryResponse solrR = this.getParameterFacetsForGeneByProcedure(acc, procedureName, "experimental"); if (solrR == null) { logger.error("no response from solr data source for acc=" + acc); return; } List<FacetField> facets = solrR.getFacetFields(); if (facets == null) { logger.error("no facets from solr data source for acc=" + acc); return; } // get rid of wholemount expression/Adult LacZ facet as this is // displayed seperately in the using the other method // need to put the section in genes.jsp!!! for (Count count : facets.get(0).getValues()) { if (!count.getName().equals(excludedProcedureName)) { filteredCounts.add(count); } } for (FacetField facet : facets) { if (facet.getValueCount() != 0) { for (Count count : facet.getValues()) { SolrDocumentList list = null;// list of // image // docs to // return to // the // procedure // section // of the // gene page if (!count.getName().equals(excludedProcedureName)) { QueryResponse responseExperimental = this .getImagesForGeneByParameter(acc,count.getName(), "experimental", 1,null, null, null, anatomyId, null, null, null); if (responseExperimental.getResults().size() > 0) { SolrDocument imgDoc = responseExperimental .getResults().get(0); QueryResponse responseExperimental2 = this .getImagesForGeneByParameter( acc, (String) imgDoc .get(ObservationDTO.PARAMETER_STABLE_ID), "experimental", numberOfExperimental, null, (String) imgDoc .get(ObservationDTO.METADATA_GROUP), (String) imgDoc .get(ObservationDTO.STRAIN_NAME), anatomyId, null, null, null); list = getControls(numberOfControls, null, imgDoc, null); if (responseExperimental2 != null) { list.addAll(responseExperimental2.getResults()); } } facetToDocs.put(count.getName(), list); } } } } } public QueryResponse getParameterFacetsForGeneByProcedure(String acc, String procedureName, String controlOrExperimental) throws SolrServerException { // e.g. // http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/impc_images/query?q=gene_accession_id:%22MGI:2384986%22&fq=biological_sample_group:experimental&fq=procedure_name:X-ray&facet=true&facet.field=parameter_stable_id SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("gene_accession_id:\"" + acc + "\""); solrQuery.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":" + controlOrExperimental); solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); solrQuery.addFilterQuery(ObservationDTO.PROCEDURE_NAME + ":\"" + procedureName + "\""); solrQuery.addFacetField(ObservationDTO.PARAMETER_STABLE_ID); // solrQuery.setRows(0); QueryResponse response = solr.query(solrQuery); return response; } public QueryResponse getImagesAnnotationsDetailsByOmeroId( List<String> omeroIds) throws SolrServerException { // e.g. // http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/impc_images/query?q=omero_id:(5815 // 5814) SolrQuery solrQuery = new SolrQuery(); String omeroIdString = "omero_id:("; String result = StringUtils.join(omeroIds, " OR "); omeroIdString += result + ")"; solrQuery.setQuery(omeroIdString); // System.out.println(omeroIdString); // solrQuery.setRows(0); QueryResponse response = solr.query(solrQuery); return response; } public Boolean hasImages(String geneAccessionId, String procedureName, String colonyId) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( "(" + ImageDTO.GENE_ACCESSION_ID + ":\"" + geneAccessionId + "\" AND " + ImageDTO.PROCEDURE_NAME + ":\"" + procedureName + "\" AND " + ImageDTO.COLONY_ID + ":\"" + colonyId + "\")") .setRows(0); //System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); if ( response.getResults().getNumFound() == 0 ){ return false; } return true; } public Boolean hasImagesWithMP(String geneAccessionId, String procedureName, String colonyId, String mpId) throws SolrServerException { //System.out.println("looking for mp term="+mpTerm +" colony Id="+colonyId); SolrQuery query = new SolrQuery(); query.setQuery("*:*") .addFilterQuery( "(" + ImageDTO.GENE_ACCESSION_ID + ":\"" + geneAccessionId + "\" AND " + ImageDTO.PROCEDURE_NAME + ":\"" + procedureName + "\" AND " + ImageDTO.COLONY_ID + ":\"" + colonyId + "\" AND " + MpDTO.MP_ID + ":\"" + mpId + "\")") .setRows(0); System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); if ( response.getResults().getNumFound() == 0 ){ return false; } System.out.println("returning true"); return true; } public long getWebStatus() throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery("*:*").setRows(0); //System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); return response.getResults().getNumFound(); } public String getServiceName(){ return "impc_images"; } public SolrDocument getImageByDownloadFilePath(String downloadFilePath) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.DOWNLOAD_FILE_PATH+":\""+downloadFilePath+"\"").setRows(1); //query.addField(ImageDTO.OMERO_ID); //query.addField(ImageDTO.INCREMENT_VALUE); //query.addField(ImageDTO.DOWNLOAD_URL); //query.addField(ImageDTO.EXTERNAL_SAMPLE_ID); //System.out.println("SOLR URL WAS " + solr.getBaseURL() + "/select?" + query); QueryResponse response = solr.query(query); SolrDocument img = response.getResults().get(0); //ImageDTO image = response.get(0); //System.out.println("image omero_id"+image.getOmeroId()+" increment_id="+image.getIncrement()); return img; } /** * * @param acc * @return a map containing the mp and colony_id combinations so that if we have these then we show an image link on the phenotype table on the gene page. Each row in table could have a different colony_id as well as mp id * @throws SolrServerException */ public Map<String, Set<String>> getImagePropertiesThatHaveMp(String acc) throws SolrServerException { //http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/impc_images/select?q=gene_accession_id:%22MGI:1913955%22&fq=mp_id:*&facet=true&facet.mincount=1&facet.limit=-1&facet.field=colony_id&facet.field=mp_id&facet.field=mp_term&rows=0 Map<String, Set<String>> mpToColony = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery(ImageDTO.GENE_ACCESSION_ID+":\""+acc+"\"").setRows(100000000); query.addFilterQuery(ImageDTO.MP_ID_TERM+":*"); query.setFacet(true); query.setFacetLimit(-1); query.setFacetMinCount(1); String pivotFacet=ImageDTO.MP_ID_TERM + "," + ImageDTO.COLONY_ID; query.set("facet.pivot", pivotFacet); query.addFacetField(ObservationDTO.COLONY_ID); //System.out.println("solr query for images properties for mp="+query); QueryResponse response = solr.query(query); for( PivotField pivot : response.getFacetPivot().get(pivotFacet)){ //System.out.println("pivot="+pivot.getValue()); String mpIdAndName=pivot.getValue().toString(); //System.out.println("mpIdAndName" +mpIdAndName); String mpId=""; Set<String> colonIds=new TreeSet<>(); if(mpIdAndName.contains("_")){ mpId=(mpIdAndName.split("_")[0]); } for (PivotField mp : pivot.getPivot()){ //System.out.println("adding mp="+pivot.getValue()+" adding value="+mp.getValue()); String colonyId=mp.getValue().toString(); colonIds.add(colonyId); } mpToColony.put(mpId, colonIds); } return mpToColony; } }
filters refactored
data-model-solr/src/main/java/org/mousephenotype/cda/solr/service/ImageService.java
filters refactored
<ide><path>ata-model-solr/src/main/java/org/mousephenotype/cda/solr/service/ImageService.java <ide> for (FacetField facetField : response.getFacetFields()) { <ide> Set<String> filter = new TreeSet<>(); <ide> for (Count facet : facetField.getValues()) { <del> if (facet.getName().equals("expression") || facetField.getName().equals("no expression")) { <add> if (!facet.getName().equals("tissue not available") && !facet.getName().equals("ambiguous")) { <ide> filter.add(facet.getName()); <ide> } <ide> }
Java
bsd-2-clause
84952522ffc07b6e4639c0bc09dbac90a112b0d1
0
imagej/imagej-launcher,imagej/imagej-launcher,imagej/imagej-launcher
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.launcher; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLClassLoader; import java.util.Arrays; /** * TODO * * @author Johannes Schindelin */ public class ClassLauncher { protected static boolean debug; static { try { debug = Boolean.getBoolean("ij.debug") || System.getenv("DEBUG_IJ_LAUNCHER") != null; } catch (Throwable t) { // ignore; Java 1.4 pretended that getenv() goes away } } protected static String[] originalArguments; /** * Patch ij.jar and launch the class given as first argument passing on the * remaining arguments * * @param arguments A list containing the name of the class whose main() * method is to be called with the remaining arguments. */ public static void main(final String[] arguments) { originalArguments = arguments; run(arguments); } public static void restart() { Thread.currentThread().setContextClassLoader( ClassLoader.class.getClassLoader()); run(originalArguments); } protected static void run(String[] arguments) { boolean retrotranslator = false, jdb = false, passClasspath = false; URLClassLoader classLoader = null; int i = 0; for (; i < arguments.length && arguments[i].charAt(0) == '-'; i++) { final String option = arguments[i]; if (option.equals("-cp") || option.equals("-classpath")) { classLoader = ClassLoaderPlus.get(classLoader, new File(arguments[++i])); } else if (option.equals("-ijcp") || option.equals("-ijclasspath")) { classLoader = ClassLoaderPlus.getInImageJDirectory(classLoader, arguments[++i]); } else if (option.equals("-jarpath")) { classLoader = ClassLoaderPlus.getRecursively(classLoader, true, new File(arguments[++i])); } else if (option.equals("-ijjarpath")) { classLoader = ClassLoaderPlus.getRecursivelyInImageJDirectory(classLoader, true, arguments[++i]); } else if (option.equals("-jdb")) jdb = true; else if (option.equals("-retrotranslator")) { classLoader = ClassLoaderPlus.getRecursivelyInImageJDirectory(classLoader, true, "retro"); retrotranslator = true; } else if (option.equals("-pass-classpath")) passClasspath = true; else if (option.equals("-freeze-classloader")) ClassLoaderPlus.freeze(classLoader); else { System.err.println("Unknown option: " + option + "!"); System.exit(1); } } if (i >= arguments.length) { System.err.println("Missing argument: main class"); System.exit(1); } String mainClass = arguments[i]; arguments = slice(arguments, i + 1); if (!"false".equals(System.getProperty("patch.ij1")) && !mainClass.equals("net.imagej.Main") && !mainClass.equals("org.scijava.minimaven.MiniMaven")) { classLoader = ClassLoaderPlus.getInImageJDirectory(null, "jars/fiji-compat.jar"); try { patchIJ1(classLoader); } catch (final Exception e) { if (!"fiji.IJ1Patcher".equals(e.getMessage())) { e.printStackTrace(); } } } if (passClasspath && classLoader != null) { arguments = prepend(arguments, "-classpath", ClassLoaderPlus.getClassPath(classLoader)); } if (jdb) { arguments = prepend(arguments, mainClass); if (classLoader != null) { arguments = prepend(arguments, "-classpath", ClassLoaderPlus.getClassPath(classLoader)); } mainClass = "com.sun.tools.example.debug.tty.TTY"; } if (retrotranslator) { arguments = prepend(arguments, "-advanced", mainClass); mainClass = "net.sf.retrotranslator.transformer.JITRetrotranslator"; } if (debug) System.err.println("Launching main class " + mainClass + " with parameters " + Arrays.toString(arguments)); launch(classLoader, mainClass, arguments); } protected static void patchIJ1(final ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException { @SuppressWarnings("unchecked") final Class<Runnable> clazz = (Class<Runnable>) classLoader.loadClass("fiji.IJ1Patcher"); final Runnable ij1Patcher = clazz.newInstance(); ij1Patcher.run(); } protected static String[] slice(final String[] array, final int from) { return slice(array, from, array.length); } protected static String[] slice(final String[] array, final int from, final int to) { final String[] result = new String[to - from]; if (result.length > 0) System.arraycopy(array, from, result, 0, result.length); return result; } protected static String[] prepend(final String[] array, final String... before) { if (before.length == 0) return array; final String[] result = new String[before.length + array.length]; System.arraycopy(before, 0, result, 0, before.length); System.arraycopy(array, 0, result, before.length, array.length); return result; } protected static void launch(ClassLoader classLoader, final String className, final String[] arguments) { Class<?> main = null; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final String noSlashes = className.replace('/', '.'); try { main = classLoader.loadClass(noSlashes); } catch (final ClassNotFoundException e) { if (noSlashes.startsWith("net.imagej.")) try { // fall back to old package name main = classLoader.loadClass(noSlashes.substring(4)); } catch (final ClassNotFoundException e2) { System.err.println("Class '" + noSlashes + "' was not found"); System.exit(1); } } final Class<?>[] argsType = new Class<?>[] { arguments.getClass() }; Method mainMethod = null; try { mainMethod = main.getMethod("main", argsType); } catch (final NoSuchMethodException e) { System.err.println("Class '" + className + "' does not have a main() method."); System.exit(1); } Integer result = new Integer(1); try { result = (Integer) mainMethod.invoke(null, new Object[] { arguments }); } catch (final IllegalAccessException e) { System.err.println("The main() method of class '" + className + "' is not public."); } catch (final InvocationTargetException e) { System.err.println("Error while executing the main() " + "method of class '" + className + "':"); e.getTargetException().printStackTrace(); } if (result != null) System.exit(result.intValue()); } }
src/main/java/net/imagej/launcher/ClassLauncher.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.launcher; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLClassLoader; import java.util.Arrays; /** * TODO * * @author Johannes Schindelin */ public class ClassLauncher { protected static boolean debug; static { try { debug = System.getenv("DEBUG_IJ_LAUNCHER") != null; } catch (Throwable t) { // ignore; Java 1.4 pretended that getenv() goes away } } protected static String[] originalArguments; /** * Patch ij.jar and launch the class given as first argument passing on the * remaining arguments * * @param arguments A list containing the name of the class whose main() * method is to be called with the remaining arguments. */ public static void main(final String[] arguments) { originalArguments = arguments; run(arguments); } public static void restart() { Thread.currentThread().setContextClassLoader( ClassLoader.class.getClassLoader()); run(originalArguments); } protected static void run(String[] arguments) { boolean retrotranslator = false, jdb = false, passClasspath = false; URLClassLoader classLoader = null; int i = 0; for (; i < arguments.length && arguments[i].charAt(0) == '-'; i++) { final String option = arguments[i]; if (option.equals("-cp") || option.equals("-classpath")) { classLoader = ClassLoaderPlus.get(classLoader, new File(arguments[++i])); } else if (option.equals("-ijcp") || option.equals("-ijclasspath")) { classLoader = ClassLoaderPlus.getInImageJDirectory(classLoader, arguments[++i]); } else if (option.equals("-jarpath")) { classLoader = ClassLoaderPlus.getRecursively(classLoader, true, new File(arguments[++i])); } else if (option.equals("-ijjarpath")) { classLoader = ClassLoaderPlus.getRecursivelyInImageJDirectory(classLoader, true, arguments[++i]); } else if (option.equals("-jdb")) jdb = true; else if (option.equals("-retrotranslator")) { classLoader = ClassLoaderPlus.getRecursivelyInImageJDirectory(classLoader, true, "retro"); retrotranslator = true; } else if (option.equals("-pass-classpath")) passClasspath = true; else if (option.equals("-freeze-classloader")) ClassLoaderPlus.freeze(classLoader); else { System.err.println("Unknown option: " + option + "!"); System.exit(1); } } if (i >= arguments.length) { System.err.println("Missing argument: main class"); System.exit(1); } String mainClass = arguments[i]; arguments = slice(arguments, i + 1); if (!"false".equals(System.getProperty("patch.ij1")) && !mainClass.equals("net.imagej.Main") && !mainClass.equals("org.scijava.minimaven.MiniMaven")) { classLoader = ClassLoaderPlus.getInImageJDirectory(null, "jars/fiji-compat.jar"); try { patchIJ1(classLoader); } catch (final Exception e) { if (!"fiji.IJ1Patcher".equals(e.getMessage())) { e.printStackTrace(); } } } if (passClasspath && classLoader != null) { arguments = prepend(arguments, "-classpath", ClassLoaderPlus.getClassPath(classLoader)); } if (jdb) { arguments = prepend(arguments, mainClass); if (classLoader != null) { arguments = prepend(arguments, "-classpath", ClassLoaderPlus.getClassPath(classLoader)); } mainClass = "com.sun.tools.example.debug.tty.TTY"; } if (retrotranslator) { arguments = prepend(arguments, "-advanced", mainClass); mainClass = "net.sf.retrotranslator.transformer.JITRetrotranslator"; } if (debug) System.err.println("Launching main class " + mainClass + " with parameters " + Arrays.toString(arguments)); launch(classLoader, mainClass, arguments); } protected static void patchIJ1(final ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException { @SuppressWarnings("unchecked") final Class<Runnable> clazz = (Class<Runnable>) classLoader.loadClass("fiji.IJ1Patcher"); final Runnable ij1Patcher = clazz.newInstance(); ij1Patcher.run(); } protected static String[] slice(final String[] array, final int from) { return slice(array, from, array.length); } protected static String[] slice(final String[] array, final int from, final int to) { final String[] result = new String[to - from]; if (result.length > 0) System.arraycopy(array, from, result, 0, result.length); return result; } protected static String[] prepend(final String[] array, final String... before) { if (before.length == 0) return array; final String[] result = new String[before.length + array.length]; System.arraycopy(before, 0, result, 0, before.length); System.arraycopy(array, 0, result, before.length, array.length); return result; } protected static void launch(ClassLoader classLoader, final String className, final String[] arguments) { Class<?> main = null; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final String noSlashes = className.replace('/', '.'); try { main = classLoader.loadClass(noSlashes); } catch (final ClassNotFoundException e) { if (noSlashes.startsWith("net.imagej.")) try { // fall back to old package name main = classLoader.loadClass(noSlashes.substring(4)); } catch (final ClassNotFoundException e2) { System.err.println("Class '" + noSlashes + "' was not found"); System.exit(1); } } final Class<?>[] argsType = new Class<?>[] { arguments.getClass() }; Method mainMethod = null; try { mainMethod = main.getMethod("main", argsType); } catch (final NoSuchMethodException e) { System.err.println("Class '" + className + "' does not have a main() method."); System.exit(1); } Integer result = new Integer(1); try { result = (Integer) mainMethod.invoke(null, new Object[] { arguments }); } catch (final IllegalAccessException e) { System.err.println("The main() method of class '" + className + "' is not public."); } catch (final InvocationTargetException e) { System.err.println("Error while executing the main() " + "method of class '" + className + "':"); e.getTargetException().printStackTrace(); } if (result != null) System.exit(result.intValue()); } }
ClassLauncher: respect ij.debug when set Previously, ClassLauncher only entered debug mode if the DEBUG_IJ_LAUNCHER environment variable was set.
src/main/java/net/imagej/launcher/ClassLauncher.java
ClassLauncher: respect ij.debug when set
<ide><path>rc/main/java/net/imagej/launcher/ClassLauncher.java <ide> <ide> static { <ide> try { <del> debug = System.getenv("DEBUG_IJ_LAUNCHER") != null; <add> debug = Boolean.getBoolean("ij.debug") || <add> System.getenv("DEBUG_IJ_LAUNCHER") != null; <ide> } catch (Throwable t) { <ide> // ignore; Java 1.4 pretended that getenv() goes away <ide> }
Java
apache-2.0
ff0dbdf68236a39640c94e4e978da65553b426c9
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * 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.slc.sli.api.security.context.resolver; import java.util.*; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.slc.sli.api.resources.security.DelegationUtil; import org.slc.sli.api.security.SLIPrincipal; import org.slc.sli.api.security.context.EntityOwnershipValidator; import org.slc.sli.api.security.context.PagingRepositoryDelegate; import org.slc.sli.api.util.SecurityUtil; import org.slc.sli.common.constants.EntityNames; import org.slc.sli.common.constants.ParameterConstants; import org.slc.sli.common.util.datetime.DateHelper; import org.slc.sli.domain.Entity; import org.slc.sli.domain.NeutralCriteria; import org.slc.sli.domain.NeutralQuery; import org.slc.sli.domain.utils.EdOrgHierarchyHelper; /** * Contains helper methods for traversing the edorg hierarchy. * * Assumptions it makes * * <ul> * <li>SEAs, LEAs, and Schools are all edorgs with organizationCategories of 'State Education * Agency' 'Local Education Agency', and 'School' respectively.</li> * <li>The parentEducationAgencyReference of a school always points to an LEA</li> * <li>The parentEducationAgencyReference of an LEA can point to either an SEA or another LEA</li> * <li>SEAs don't have a parentEducationAgencyReference and therefore are always at the top of the * tree</li> * </ul> * * */ @Component public class EdOrgHelper { @Autowired protected PagingRepositoryDelegate<Entity> repo; @Autowired protected DateHelper dateHelper; @Autowired protected EntityOwnershipValidator ownership; @Autowired protected DelegationUtil delegationUtil; private EdOrgHierarchyHelper helper; @PostConstruct public void init() { helper = new EdOrgHierarchyHelper(repo); } /** * Determine the districts of the user. * * If the user is directly associated with an SEA, this is any LEA directly below the SEA. If * the user is directly * associated with an LEA, this is the top-most LEA i.e. the LEA directly associated with the * SEA. * * @param user - User entity * * @return - List of entity IDs */ public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } /** * Determine the districts based upon the EdOrgs supplied. * * If an SEA is encountered, this is any LEA directly below the SEA. * If an LEA or school is encountered, this is the top-most LEA, i.e. the LEA directly associated with the SEA. * * @param edOrgs - EdOrgs to search * * @return - List of district entity IDs */ public List<String> getDistricts(Set<String> edOrgs) { NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, edOrgs, false)); Set<String> entities = new HashSet<String>(); for (Entity entity : repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query)) { if (helper.isLEA(entity)) { List<Entity> topLEAs = helper.getTopLEAOfEdOrg(entity); if(topLEAs!=null) { for(Entity topLEA: topLEAs) { entities.add(topLEA.getEntityId()); } } } else if (helper.isSchool(entity)) { List<Entity> topLEAs = helper.getTopLEAOfEdOrg(entity); if(topLEAs!=null) { for(Entity topLEA: topLEAs) { entities.add(topLEA.getEntityId()); } } } else { // isSEA entities.addAll(getDirectChildLEAsOfEdOrg(entity)); } } return new ArrayList<String>(entities); } /** * Get a list of the direct child LEAs of an EdOrg. * * @param edOrgEntity - EdOrg from which to get child LEAs * * @return - List of the EdOrg's child LEAs */ public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } private Set<String> getDirectChildLEAsOfEdOrg(String edOrgId) { Set<String> toReturn = new HashSet<String>(); NeutralQuery query = new NeutralQuery(0); query.addCriteria(new NeutralCriteria("parentEducationAgencyReference", "=", edOrgId)); for (Entity entity : repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query)) { if (helper.isLEA(entity)) { toReturn.add(entity.getEntityId()); } } return toReturn; } public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } private Set<String> getAllChildLEAsOfEdOrg(Set<String> edOrgIds, Set<String>toReturn) { Set<String> childLEAs = new HashSet<String>(); // collect all direct child LEAs for (String edOrgId : edOrgIds) { childLEAs.addAll(getDirectChildLEAsOfEdOrg(edOrgId)); } // remove any we have already processed if (toReturn != null) { childLEAs.removeAll(toReturn); } // base case: no new children so just return the accumulated set if (childLEAs.isEmpty()) { return toReturn; } // add the new children to those we will ultimately return toReturn.addAll(childLEAs); return getAllChildLEAsOfEdOrg(childLEAs, toReturn); } /** * Get the parents of an EdOrg. * * @param edOrgEntity - EdOrg from which to get parents * * @return - set of the EdOrg's parents */ public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } private List<String> getParentEdOrgs(final Entity edOrg, final Map<String, Entity> edOrgCache, final Set<String> visitedEdOrgs, List<String> toReturn) { // base case if (edOrg == null || visitedEdOrgs.contains(edOrg)) { return toReturn; } if (edOrg != null && edOrg.getBody() != null) { @SuppressWarnings("unchecked") List<String> parentIds = (List<String>) edOrg.getBody().get("parentEducationAgencyReference"); if (parentIds != null) { for (String parentId : parentIds) { if (parentId != null && !visitedEdOrgs.contains(parentId)) { visitedEdOrgs.add(parentId); Entity parentEdOrg = edOrgCache.get(parentId); if (parentEdOrg != null) { toReturn.add(parentId); getParentEdOrgs(parentEdOrg, edOrgCache, visitedEdOrgs, toReturn); } } } } } return toReturn; } private Map<String, Entity> loadEdOrgCache() { Map<String, Entity> edOrgCache = new HashMap<String, Entity>(); Iterator<Entity> edOrgs = repo.findEach(EntityNames.EDUCATION_ORGANIZATION, (NeutralQuery) null); while (edOrgs != null && edOrgs.hasNext()) { Entity eo = edOrgs.next(); edOrgCache.put(eo.getEntityId(), eo); } return edOrgCache; } public Entity byId(String edOrgId) { return repo.findById(EntityNames.EDUCATION_ORGANIZATION, edOrgId); } public boolean isSEA(Entity entity) { // passing through return helper.isSEA(entity); } /** * Given an edorg entity, returns the SEA to which it belongs * * @param entity * * @return SEA */ public String getSEAOfEdOrg(Entity entity) { return helper.getSEAOfEdOrg(entity); } /** * Finds schools directly associated to this user * * @param principal * @return */ public List<String> getDirectSchools(Entity principal) { return getDirectSchoolsLineage(principal, false); } public List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage) { Set<String> ids = getDirectEdorgs(principal); Iterable<Entity> edorgs = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, new NeutralQuery( new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids, false))); List<String> schools = new ArrayList<String>(); for (Entity e : edorgs) { if (helper.isSchool(e)) { schools.add(e.getEntityId()); if (getLineage) { schools.addAll(extractEdorgFromMeta(e)); } } } return schools; } @SuppressWarnings("unchecked") private Set<String> extractEdorgFromMeta( Entity e) { Set<String> edOrgs = new HashSet<String>(); Map<String,Object> meta = e.getMetaData(); if( meta == null || !meta.containsKey( ParameterConstants.EDORGS_ARRAY )) { return edOrgs; } edOrgs.addAll( (Collection<? extends String>) meta.get( ParameterConstants.EDORGS_ARRAY )); return edOrgs; } /** * Recursively returns the list of all child edorgs * * @param edOrgs * @return */ public Set<String> getChildEdOrgs(Collection<String> edOrgs) { Set<String> visitedEdOrgs = new HashSet<String>(); return getChildEdOrgs(visitedEdOrgs, edOrgs); } public Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs) { if (edOrgs.isEmpty()) { return new HashSet<String>(); } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_EDUCATION_AGENCY_REFERENCE, NeutralCriteria.CRITERIA_IN, edOrgs)); Iterable<Entity> children = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); visitedEdOrgs.addAll(edOrgs); Set<String> childIds = new HashSet<String>(); for (Entity child : children) { if (!visitedEdOrgs.contains(child.getEntityId())) { childIds.add(child.getEntityId()); } } if (!childIds.isEmpty()) { childIds.addAll(getChildEdOrgs(visitedEdOrgs, childIds)); } return childIds; } /** * Recursively returns the list of all child edorgs By Name * * @param edOrgs * @return */ public Set<String> getChildEdOrgsName(Collection<String> edOrgs) { // get child edOrgs reusing existing code Set<String> childEdOrgIds = getChildEdOrgs(edOrgs); // do a single query to get the names (stateOrganizationId) NeutralQuery query = new NeutralQuery( new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(childEdOrgIds))).setIncludeFields(Arrays.asList(ParameterConstants.STATE_ORGANIZATION_ID)); Iterable<Entity> children = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); Set<String> names = new HashSet<String>(); for (Entity child : children) { names.add((String) child.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID)); } return names; } private Entity getTopLEAOfEdOrg(Entity entity) { if (entity.getBody().containsKey("parentEducationAgencyReference")) { @SuppressWarnings("unchecked") List<String> parents = (List<String>) entity.getBody().get("parentEducationAgencyReference"); if ( null != parents ) { for ( String parent : parents ) { Entity parentEdorg = repo.findById(EntityNames.EDUCATION_ORGANIZATION, parent); if (isLEA(parentEdorg)) { return getTopLEAOfEdOrg(parentEdorg); } } } } return entity; } /** * Get the collection of ed-orgs that will determine a user's security context * * @param principal * @return */ public Collection<String> getUserEdOrgs(Entity principal) { return (isTeacher(principal)) ? getDirectSchools(principal) : getStaffEdOrgsAndChildren(); } /** * Will go through staffEdorgAssociations that are current and get the descendant * edorgs that you have. * * @return a set of the edorgs you are associated to and their children. */ public Set<String> getStaffEdOrgsAndChildren() { Set<String> edOrgLineage = getDirectEdorgs(); return getEdorgDescendents(edOrgLineage); } public Set<String> getEdorgDescendents(Set<String> edOrgLineage) { edOrgLineage.addAll(getChildEdOrgs(edOrgLineage)); return edOrgLineage; } public Set<String> getDelegatedEdorgDescendents() { List<String> getSecurityEventDelegateEdOrg = delegationUtil.getSecurityEventDelegateStateIds(); List<String> getSecurityEventDelegateEdOrgIds = delegationUtil.getSecurityEventDelegateEdOrgs(); Set<String> result = new HashSet<String>(); result.addAll(getSecurityEventDelegateEdOrg); result.addAll(getChildEdOrgsName(getSecurityEventDelegateEdOrgIds)); return result; } /** * Calls date helper to check whether the specified field on the input body is expired. * * @param body * Map representing entity's body. * @param fieldName * Name of field to extract from entity's body. * @param useGracePeriod * Flag indicating whether to allow for grace period when determining expiration. * @return True if field is expired, false otherwise. */ public boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod) { return dateHelper.isFieldExpired(body, fieldName, useGracePeriod); } @SuppressWarnings("unchecked") public boolean isLEA(Entity entity) { // passing through return helper.isLEA(entity); } @SuppressWarnings("unchecked") public boolean isSchool(Entity entity) { // passing through return helper.isSchool(entity); } /** * Determines if the specified principal is of type 'teacher'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'teacher', false otherwise. */ private boolean isTeacher(Entity principal) { return principal.getType().equals(EntityNames.TEACHER); } /** * Determines if the specified principal is of type 'staff'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'staff', false otherwise. */ private boolean isStaff(Entity principal) { return principal.getType().equals(EntityNames.STAFF); } /** * Determines if the specified principal is of type 'student'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'student', false otherwise. */ private boolean isStudent(Entity principal) { return principal.getType().equals(EntityNames.STUDENT); } /** * Determines if the specified principal is of type 'parent'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'parent', false otherwise. */ private boolean isParent(Entity principal) { return principal.getType().equals(EntityNames.PARENT); } /** * Get directly associated education organizations for the authenticated principal. */ public Set<String> getDirectEdorgs() { return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } /** * Get directly associated education organizations for the specified principal, filtered by * data ownership. */ public Set<String> getDirectEdorgs(Entity principal) { return getEdOrgs(principal, true); } /** * Get directly associated education organizations for the specified principal, not filtered by * data ownership. */ public Set<String> locateDirectEdorgs(Entity principal) { return getEdOrgs(principal, false); } private Set<String> getEdOrgs(Entity principal, boolean filterByOwnership) { if (isStaff(principal) || isTeacher(principal)) { return getStaffDirectlyAssociatedEdorgs(principal, filterByOwnership); } else if (isStudent(principal)) { return getStudentsCurrentAssociatedEdOrgs(Collections.singleton(principal.getEntityId()), filterByOwnership); } else if (isParent(principal)) { SLIPrincipal prince = new SLIPrincipal(); prince.setEntity(principal); prince.populateChildren(repo); return getStudentsCurrentAssociatedEdOrgs(prince.getOwnedStudentIds(), false); } return new HashSet<String>(); } /** * Get all the valid StaffEdorg associations. * @param staffId * The staffId the SEOAs belong to. * @param filterByOwnership * flag to check ownership * @return */ public Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership) { Set<Entity> validAssociations = new HashSet<Entity>(); Iterable<Entity> associations = locateNonExpiredSEOAs(staffId); for (Entity association : associations) { if (!filterByOwnership || ownership.canAccess(association)) { validAssociations.add(association); } } return validAssociations; } /** * Get all non expired StaffEdorg associations. * @param staffId * The staffId the SEOAs belong to. * @return */ public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } /** * Get current education organizations for the specified staff member. */ private Set<String> getStaffDirectlyAssociatedEdorgs(Entity staff, boolean filterByOwnership) { Set<String> edorgs = new HashSet<String>(); Iterable<Entity> associations = locateValidSEOAs(staff.getEntityId(), filterByOwnership); for (Entity association : associations) { edorgs.add((String) association.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE)); } return edorgs; } /** * Get current education organizations for the specified students. */ private Set<String> getStudentsCurrentAssociatedEdOrgs(Set<String> studentIds, boolean filterByOwnership) { Set<String> edOrgIds = new HashSet<String>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); Iterable<Entity> associations = repo.findAll(EntityNames.STUDENT_SCHOOL_ASSOCIATION, basicQuery); if (associations != null) { for (Entity association : associations) { if (!filterByOwnership || ownership.canAccess(association)) { if (!isFieldExpired(association.getBody(), ParameterConstants.EXIT_WITHDRAW_DATE, false)) { edOrgIds.add((String) association.getBody().get(ParameterConstants.SCHOOL_ID)); } } } } return edOrgIds; } public Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds) { NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, edOrgIds)); Iterable<Entity> edOrgs = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, basicQuery); Set<String> stateOrganizationIds = new HashSet<String>(); for (Entity edOrg : edOrgs) { Map<String, Object> body = edOrg.getBody(); if (body != null) { String stateId = (String) body.get("stateOrganizationId"); if (stateId != null) { stateOrganizationIds.add(stateId); } } } return stateOrganizationIds; } /** * Set the entity ownership validator (used primarily for unit testing). */ protected void setEntityOwnershipValidator(EntityOwnershipValidator newOwner) { this.ownership = newOwner; } }
sli/api/src/main/java/org/slc/sli/api/security/context/resolver/EdOrgHelper.java
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * 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.slc.sli.api.security.context.resolver; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.slc.sli.api.resources.security.DelegationUtil; import org.slc.sli.api.security.SLIPrincipal; import org.slc.sli.api.security.context.EntityOwnershipValidator; import org.slc.sli.api.security.context.PagingRepositoryDelegate; import org.slc.sli.api.util.SecurityUtil; import org.slc.sli.common.constants.EntityNames; import org.slc.sli.common.constants.ParameterConstants; import org.slc.sli.common.util.datetime.DateHelper; import org.slc.sli.domain.Entity; import org.slc.sli.domain.NeutralCriteria; import org.slc.sli.domain.NeutralQuery; import org.slc.sli.domain.utils.EdOrgHierarchyHelper; /** * Contains helper methods for traversing the edorg hierarchy. * * Assumptions it makes * * <ul> * <li>SEAs, LEAs, and Schools are all edorgs with organizationCategories of 'State Education * Agency' 'Local Education Agency', and 'School' respectively.</li> * <li>The parentEducationAgencyReference of a school always points to an LEA</li> * <li>The parentEducationAgencyReference of an LEA can point to either an SEA or another LEA</li> * <li>SEAs don't have a parentEducationAgencyReference and therefore are always at the top of the * tree</li> * </ul> * * */ @Component public class EdOrgHelper { @Autowired protected PagingRepositoryDelegate<Entity> repo; @Autowired protected DateHelper dateHelper; @Autowired protected EntityOwnershipValidator ownership; @Autowired protected DelegationUtil delegationUtil; private EdOrgHierarchyHelper helper; @PostConstruct public void init() { helper = new EdOrgHierarchyHelper(repo); } /** * Determine the districts of the user. * * If the user is directly associated with an SEA, this is any LEA directly below the SEA. If * the user is directly * associated with an LEA, this is the top-most LEA i.e. the LEA directly associated with the * SEA. * * @param user - User entity * * @return - List of entity IDs */ public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } /** * Determine the districts based upon the EdOrgs supplied. * * If an SEA is encountered, this is any LEA directly below the SEA. * If an LEA or school is encountered, this is the top-most LEA, i.e. the LEA directly associated with the SEA. * * @param edOrgs - EdOrgs to search * * @return - List of district entity IDs */ public List<String> getDistricts(Set<String> edOrgs) { NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, edOrgs, false)); Set<String> entities = new HashSet<String>(); for (Entity entity : repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query)) { if (helper.isLEA(entity)) { List<Entity> topLEAs = helper.getTopLEAOfEdOrg(entity); if(topLEAs!=null) { for(Entity topLEA: topLEAs) { entities.add(topLEA.getEntityId()); } } } else if (helper.isSchool(entity)) { List<Entity> topLEAs = helper.getTopLEAOfEdOrg(entity); if(topLEAs!=null) { for(Entity topLEA: topLEAs) { entities.add(topLEA.getEntityId()); } } } else { // isSEA entities.addAll(getDirectChildLEAsOfEdOrg(entity)); } } return new ArrayList<String>(entities); } /** * Get a list of the direct child LEAs of an EdOrg. * * @param edOrgEntity - EdOrg from which to get child LEAs * * @return - List of the EdOrg's child LEAs */ public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } private Set<String> getDirectChildLEAsOfEdOrg(String edOrgId) { Set<String> toReturn = new HashSet<String>(); NeutralQuery query = new NeutralQuery(0); query.addCriteria(new NeutralCriteria("parentEducationAgencyReference", "=", edOrgId)); for (Entity entity : repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query)) { if (helper.isLEA(entity)) { toReturn.add(entity.getEntityId()); } } return toReturn; } public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } private Set<String> getAllChildLEAsOfEdOrg(Set<String> edOrgIds, Set<String>toReturn) { Set<String> childLEAs = new HashSet<String>(); // collect all direct child LEAs for (String edOrgId : edOrgIds) { childLEAs.addAll(getDirectChildLEAsOfEdOrg(edOrgId)); } // remove any we have already processed if (toReturn != null) { childLEAs.removeAll(toReturn); } // base case: no new children so just return the accumulated set if (childLEAs.isEmpty()) { return toReturn; } // add the new children to those we will ultimately return toReturn.addAll(childLEAs); return getAllChildLEAsOfEdOrg(childLEAs, toReturn); } /** * Get the parents of an EdOrg. * * @param edOrgEntity - EdOrg from which to get parents * * @return - set of the EdOrg's parents */ public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } private List<String> getParentEdOrgs(final Entity edOrg, final Map<String, Entity> edOrgCache, final Set<String> visitedEdOrgs, List<String> toReturn) { // base case if (edOrg == null || visitedEdOrgs.contains(edOrg)) { return toReturn; } if (edOrg != null && edOrg.getBody() != null) { @SuppressWarnings("unchecked") List<String> parentIds = (List<String>) edOrg.getBody().get("parentEducationAgencyReference"); if (parentIds != null) { for (String parentId : parentIds) { if (parentId != null && !visitedEdOrgs.contains(parentId)) { visitedEdOrgs.add(parentId); Entity parentEdOrg = edOrgCache.get(parentId); if (parentEdOrg != null) { toReturn.add(parentId); getParentEdOrgs(parentEdOrg, edOrgCache, visitedEdOrgs, toReturn); } } } } } return toReturn; } private Map<String, Entity> loadEdOrgCache() { Map<String, Entity> edOrgCache = new HashMap<String, Entity>(); Iterator<Entity> edOrgs = repo.findEach(EntityNames.EDUCATION_ORGANIZATION, (NeutralQuery) null); while (edOrgs != null && edOrgs.hasNext()) { Entity eo = edOrgs.next(); edOrgCache.put(eo.getEntityId(), eo); } return edOrgCache; } public Entity byId(String edOrgId) { return repo.findById(EntityNames.EDUCATION_ORGANIZATION, edOrgId); } public boolean isSEA(Entity entity) { // passing through return helper.isSEA(entity); } /** * Given an edorg entity, returns the SEA to which it belongs * * @param entity * * @return SEA */ public String getSEAOfEdOrg(Entity entity) { return helper.getSEAOfEdOrg(entity); } /** * Finds schools directly associated to this user * * @param principal * @return */ public List<String> getDirectSchools(Entity principal) { return getDirectSchoolsLineage( principal, false ); } public List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage) { Set<String> ids = getDirectEdorgs(principal); Iterable<Entity> edorgs = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, new NeutralQuery( new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids, false))); List<String> schools = new ArrayList<String>(); for (Entity e : edorgs) { if (helper.isSchool(e)) { schools.add(e.getEntityId()); if (getLineage) { schools.addAll(extractEdorgFromMeta(e)); } } } return schools; } @SuppressWarnings("unchecked") private Set<String> extractEdorgFromMeta( Entity e) { Set<String> edOrgs = new HashSet<String>(); Map<String,Object> meta = e.getMetaData(); if( meta == null || !meta.containsKey( ParameterConstants.EDORGS_ARRAY )) { return edOrgs; } edOrgs.addAll( (Collection<? extends String>) meta.get( ParameterConstants.EDORGS_ARRAY )); return edOrgs; } /** * Recursively returns the list of all child edorgs * * @param edOrgs * @return */ public Set<String> getChildEdOrgs(Collection<String> edOrgs) { if (edOrgs.isEmpty()) { return new HashSet<String>(); } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_EDUCATION_AGENCY_REFERENCE, NeutralCriteria.CRITERIA_IN, edOrgs)); Iterable<Entity> childrenIds = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); Set<String> children = new HashSet<String>(); for (Entity child : childrenIds) { children.add(child.getEntityId()); } if (!children.isEmpty()) { children.addAll(getChildEdOrgs(children)); } return children; } /** * Recursively returns the list of all child edorgs By Name * * @param edOrgs * @return */ public Set<String> getChildEdOrgsName(Collection<String> edOrgs) { NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_EDUCATION_AGENCY_REFERENCE, NeutralCriteria.CRITERIA_IN, edOrgs)); Iterable<Entity> childrenEntities = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); Set<String> children = new HashSet<String>(); for (Entity child : childrenEntities) { children.add((String) child.getBody().get("stateOrganizationId")); } Set<String> childrenIds = new HashSet<String>(); for (Entity child : childrenEntities) { childrenIds.add(child.getEntityId()); } if (!children.isEmpty()) { children.addAll(getChildEdOrgsName(childrenIds)); } return children; } private Entity getTopLEAOfEdOrg(Entity entity) { if (entity.getBody().containsKey("parentEducationAgencyReference")) { @SuppressWarnings("unchecked") List<String> parents = (List<String>) entity.getBody().get("parentEducationAgencyReference"); if ( null != parents ) { for ( String parent : parents ) { Entity parentEdorg = repo.findById(EntityNames.EDUCATION_ORGANIZATION, parent); if (isLEA(parentEdorg)) { return getTopLEAOfEdOrg(parentEdorg); } } } } return entity; } /** * Get the collection of ed-orgs that will determine a user's security context * * @param principal * @return */ public Collection<String> getUserEdOrgs(Entity principal) { return (isTeacher(principal)) ? getDirectSchools(principal) : getStaffEdOrgsAndChildren(); } /** * Will go through staffEdorgAssociations that are current and get the descendant * edorgs that you have. * * @return a set of the edorgs you are associated to and their children. */ public Set<String> getStaffEdOrgsAndChildren() { Set<String> edOrgLineage = getDirectEdorgs(); return getEdorgDescendents(edOrgLineage); } public Set<String> getEdorgDescendents(Set<String> edOrgLineage) { edOrgLineage.addAll(getChildEdOrgs(edOrgLineage)); return edOrgLineage; } public Set<String> getDelegatedEdorgDescendents() { List<String> getSecurityEventDelegateEdOrg = delegationUtil.getSecurityEventDelegateStateIds(); List<String> getSecurityEventDelegateEdOrgIds = delegationUtil.getSecurityEventDelegateEdOrgs(); Set<String> result = new HashSet<String>(); result.addAll(getSecurityEventDelegateEdOrg); result.addAll(getChildEdOrgsName(getSecurityEventDelegateEdOrgIds)); return result; } /** * Calls date helper to check whether the specified field on the input body is expired. * * @param body * Map representing entity's body. * @param fieldName * Name of field to extract from entity's body. * @param useGracePeriod * Flag indicating whether to allow for grace period when determining expiration. * @return True if field is expired, false otherwise. */ public boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod) { return dateHelper.isFieldExpired(body, fieldName, useGracePeriod); } @SuppressWarnings("unchecked") public boolean isLEA(Entity entity) { // passing through return helper.isLEA(entity); } @SuppressWarnings("unchecked") public boolean isSchool(Entity entity) { // passing through return helper.isSchool(entity); } /** * Determines if the specified principal is of type 'teacher'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'teacher', false otherwise. */ private boolean isTeacher(Entity principal) { return principal.getType().equals(EntityNames.TEACHER); } /** * Determines if the specified principal is of type 'staff'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'staff', false otherwise. */ private boolean isStaff(Entity principal) { return principal.getType().equals(EntityNames.STAFF); } /** * Determines if the specified principal is of type 'student'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'student', false otherwise. */ private boolean isStudent(Entity principal) { return principal.getType().equals(EntityNames.STUDENT); } /** * Determines if the specified principal is of type 'parent'. * * @param principal * Principal to check type for. * * @return True if the principal is of type 'parent', false otherwise. */ private boolean isParent(Entity principal) { return principal.getType().equals(EntityNames.PARENT); } /** * Get directly associated education organizations for the authenticated principal. */ public Set<String> getDirectEdorgs() { return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } /** * Get directly associated education organizations for the specified principal, filtered by * data ownership. */ public Set<String> getDirectEdorgs(Entity principal) { return getEdOrgs(principal, true); } /** * Get directly associated education organizations for the specified principal, not filtered by * data ownership. */ public Set<String> locateDirectEdorgs(Entity principal) { return getEdOrgs(principal, false); } private Set<String> getEdOrgs(Entity principal, boolean filterByOwnership) { if (isStaff(principal) || isTeacher(principal)) { return getStaffDirectlyAssociatedEdorgs(principal, filterByOwnership); } else if (isStudent(principal)) { return getStudentsCurrentAssociatedEdOrgs(Collections.singleton(principal.getEntityId()), filterByOwnership); } else if (isParent(principal)) { SLIPrincipal prince = new SLIPrincipal(); prince.setEntity(principal); prince.populateChildren(repo); return getStudentsCurrentAssociatedEdOrgs(prince.getOwnedStudentIds(), false); } return new HashSet<String>(); } /** * Get all the valid StaffEdorg associations. * @param staffId * The staffId the SEOAs belong to. * @param filterByOwnership * flag to check ownership * @return */ public Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership) { Set<Entity> validAssociations = new HashSet<Entity>(); Iterable<Entity> associations = locateNonExpiredSEOAs(staffId); for (Entity association : associations) { if (!filterByOwnership || ownership.canAccess(association)) { validAssociations.add(association); } } return validAssociations; } /** * Get all non expired StaffEdorg associations. * @param staffId * The staffId the SEOAs belong to. * @return */ public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } /** * Get current education organizations for the specified staff member. */ private Set<String> getStaffDirectlyAssociatedEdorgs(Entity staff, boolean filterByOwnership) { Set<String> edorgs = new HashSet<String>(); Iterable<Entity> associations = locateValidSEOAs(staff.getEntityId(), filterByOwnership); for (Entity association : associations) { edorgs.add((String) association.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE)); } return edorgs; } /** * Get current education organizations for the specified students. */ private Set<String> getStudentsCurrentAssociatedEdOrgs(Set<String> studentIds, boolean filterByOwnership) { Set<String> edOrgIds = new HashSet<String>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.CRITERIA_IN, studentIds)); Iterable<Entity> associations = repo.findAll(EntityNames.STUDENT_SCHOOL_ASSOCIATION, basicQuery); if (associations != null) { for (Entity association : associations) { if (!filterByOwnership || ownership.canAccess(association)) { if (!isFieldExpired(association.getBody(), ParameterConstants.EXIT_WITHDRAW_DATE, false)) { edOrgIds.add((String) association.getBody().get(ParameterConstants.SCHOOL_ID)); } } } } return edOrgIds; } public Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds) { NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, edOrgIds)); Iterable<Entity> edOrgs = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, basicQuery); Set<String> stateOrganizationIds = new HashSet<String>(); for (Entity edOrg : edOrgs) { Map<String, Object> body = edOrg.getBody(); if (body != null) { String stateId = (String) body.get("stateOrganizationId"); if (stateId != null) { stateOrganizationIds.add(stateId); } } } return stateOrganizationIds; } /** * Set the entity ownership validator (used primarily for unit testing). */ protected void setEntityOwnershipValidator(EntityOwnershipValidator newOwner) { this.ownership = newOwner; } }
de2950 handle cycles when determining the set of edorg children
sli/api/src/main/java/org/slc/sli/api/security/context/resolver/EdOrgHelper.java
de2950 handle cycles when determining the set of edorg children
<ide><path>li/api/src/main/java/org/slc/sli/api/security/context/resolver/EdOrgHelper.java <ide> <ide> package org.slc.sli.api.security.context.resolver; <ide> <del>import java.util.ArrayList; <del>import java.util.Collection; <del>import java.util.Collections; <del>import java.util.HashMap; <del>import java.util.HashSet; <del>import java.util.Iterator; <del>import java.util.List; <del>import java.util.Map; <del>import java.util.Set; <add>import java.util.*; <ide> <ide> import javax.annotation.PostConstruct; <ide> <ide> * @return <ide> */ <ide> public List<String> getDirectSchools(Entity principal) { <del> return getDirectSchoolsLineage( principal, false ); <add> return getDirectSchoolsLineage(principal, false); <ide> } <ide> <ide> public List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage) { <ide> * @return <ide> */ <ide> public Set<String> getChildEdOrgs(Collection<String> edOrgs) { <add> Set<String> visitedEdOrgs = new HashSet<String>(); <add> return getChildEdOrgs(visitedEdOrgs, edOrgs); <add> } <add> <add> public Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs) { <ide> <ide> if (edOrgs.isEmpty()) { <ide> return new HashSet<String>(); <ide> <ide> NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_EDUCATION_AGENCY_REFERENCE, <ide> NeutralCriteria.CRITERIA_IN, edOrgs)); <del> Iterable<Entity> childrenIds = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); <del> Set<String> children = new HashSet<String>(); <del> for (Entity child : childrenIds) { <del> children.add(child.getEntityId()); <del> } <del> if (!children.isEmpty()) { <del> children.addAll(getChildEdOrgs(children)); <del> } <del> return children; <add> Iterable<Entity> children = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); <add> <add> visitedEdOrgs.addAll(edOrgs); <add> <add> Set<String> childIds = new HashSet<String>(); <add> for (Entity child : children) { <add> if (!visitedEdOrgs.contains(child.getEntityId())) { <add> childIds.add(child.getEntityId()); <add> } <add> } <add> if (!childIds.isEmpty()) { <add> childIds.addAll(getChildEdOrgs(visitedEdOrgs, childIds)); <add> } <add> return childIds; <ide> } <ide> <ide> <ide> * @return <ide> */ <ide> public Set<String> getChildEdOrgsName(Collection<String> edOrgs) { <del> <del> NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_EDUCATION_AGENCY_REFERENCE, <del> NeutralCriteria.CRITERIA_IN, edOrgs)); <del> Iterable<Entity> childrenEntities = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); <del> Set<String> children = new HashSet<String>(); <del> for (Entity child : childrenEntities) { <del> children.add((String) child.getBody().get("stateOrganizationId")); <del> } <del> Set<String> childrenIds = new HashSet<String>(); <del> for (Entity child : childrenEntities) { <del> childrenIds.add(child.getEntityId()); <del> } <del> if (!children.isEmpty()) { <del> children.addAll(getChildEdOrgsName(childrenIds)); <del> } <del> return children; <del> } <del> <add> // get child edOrgs reusing existing code <add> Set<String> childEdOrgIds = getChildEdOrgs(edOrgs); <add> <add> // do a single query to get the names (stateOrganizationId) <add> NeutralQuery query = new NeutralQuery( <add> new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, <add> new ArrayList<String>(childEdOrgIds))).setIncludeFields(Arrays.asList(ParameterConstants.STATE_ORGANIZATION_ID)); <add> <add> Iterable<Entity> children = repo.findAll(EntityNames.EDUCATION_ORGANIZATION, query); <add> Set<String> names = new HashSet<String>(); <add> for (Entity child : children) { <add> names.add((String) child.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID)); <add> } <add> return names; <add> } <ide> <ide> private Entity getTopLEAOfEdOrg(Entity entity) { <ide> if (entity.getBody().containsKey("parentEducationAgencyReference")) {
Java
bsd-3-clause
ebcfd6e659d98d9895a319ea4c56a26a6c271fa9
0
MaddTheSane/MacPaf,MaddTheSane/MacPaf,MaddTheSane/MacPaf
//MyDocument.java //MAF //Created by Logan Allred on Sun Dec 22 2002. //Copyright (c) 2002-2004 RedBugz Software. All rights reserved. import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.apple.cocoa.application.*; import com.apple.cocoa.foundation.*; import com.redbugz.maf.*; import com.redbugz.maf.jdom.MAFDocumentJDOM; import com.redbugz.maf.util.CocoaUtils; import com.redbugz.maf.util.DateUtils; import com.redbugz.maf.util.MultimediaUtils; import com.redbugz.maf.util.StringUtils; /** * @todo This document is getting too large. I need to subclass NSDocumentController and move * some of this functionality over there, as well as split up my MyDocument.nib file into * several smaller nib files. */ public class MyDocument extends NSDocument implements Observer { private static final Logger log = Logger.getLogger(MyDocument.class); // static initializer { log.debug("<><><> MyDocument static initializer. this="+this); // Tests.testBase64(); // Tests.testImageFiles(); // Tests.testTrimLeadingWhitespace(); log.debug("System property user.dir: "+System.getProperty("user.dir")); log.debug("System property user.home: "+System.getProperty("user.home")); //initDoc(); } public static final String GEDCOM_DOCUMENT_TYPE = "GEDCOM File (.ged)"; public static final String PAF21_DOCUMENT_TYPE = "PAF 2.1/2.3.1 File"; public static final String MAF_DOCUMENT_TYPE = "MAF File"; public static final String TEMPLEREADY_UPDATE_DOCUMENT_TYPE = "TempleReady Update File"; MafDocument doc;// = null;//new MAFDocumentJDOM(); // Maps the buttons to the individuals they represent protected NSMutableDictionary individualsButtonMap = new NSMutableDictionary(); // /** // * This is the main individual to whom apply all actions // */ // private Individual primaryIndividual = new Individual.UnknownIndividual(); // This was originally to check for the constructor getting called twice // public boolean firstconstr = true; // All of the outlets in the nib public NSWindow mainWindow; /* IBOutlet */ public NSWindow reportsWindow; /* IBOutlet */ public NSWindow individualEditWindow; /* IBOutlet */ public NSWindow familyEditWindow; /* IBOutlet */ public NSWindow taskProgressSheetWindow; /* IBOutlet */ public FamilyListController familyListWindowController; /* IBOutlet */ public IndividualListController individualListWindowController; /* IBOutlet */ public FamilyListController tabFamilyListController; /* IBOutlet */ public IndividualListController tabIndividualListController; /* IBOutlet */ public NSObject importController; /* IBOutlet */ public FamilyList familyList; /* IBOutlet */ public IndividualList individualList; /* IBOutlet */ public SurnameList surnameList; /* IBOutlet */ public LocationList locationList; /* IBOutlet */ public HistoryController historyController; /* IBOutlet */ public PedigreeViewController pedigreeViewController; /* IBOutlet */ public NSButton fatherButton; /* IBOutlet */ public NSButton individualButton; /* IBOutlet */ public NSButton individualFamilyButton; /* IBOutlet */ public NSButton maternalGrandfatherButton; /* IBOutlet */ public NSButton maternalGrandmotherButton; /* IBOutlet */ public NSButton motherButton; /* IBOutlet */ public NSButton paternalGrandfatherButton; /* IBOutlet */ public NSButton paternalGrandmotherButton; /* IBOutlet */ public NSButton spouseButton; /* IBOutlet */ public NSButton familyAsSpouseButton; /* IBOutlet */ public NSButton familyAsChildButton; /* IBOutlet */ public NSWindow noteWindow; /* IBOutlet */ public NSMatrix reportsRadio; /* IBOutlet */ public NSTableView childrenTable; /* IBOutlet */ public NSTableView spouseTable; /* IBOutlet */ public PedigreeView pedigreeView; /* IBOutlet */ public NSTabView mainTabView; /* IBOutlet */ public NSWindow bugReportWindow; /* IBOutlet */ public NSButton bugReportFileCheckbox; /* IBOutlet */ public NSTextView bugReportText; /* IBOutlet */ // public IndividualDetailController individualDetailController = new IndividualDetailController(); /* IBOutlet */ // public FamilyDetailController familyDetailController = new FamilyDetailController(); /* IBOutlet */ private NSView printableView; // used to suppress GUI updates while non-GUI updates are happening, for example during import private boolean suppressUpdates; // used to temporarily hold loaded data before import process begins private NSData importData; private NSFileWrapper fileWrapperToLoad; // private IndividualList startupIndividualList; // private FamilyList startupFamilyList; /** * This the internal name for the gedcom file in the .MAF file package */ private static final String DEFAULT_GEDCOM_FILENAME = "data.ged"; /** * This the internal name for the data xml file in the .MAF file package */ private static final String DEFAULT_XML_FILENAME = "data.xml"; private static final String TEMPLEREADY_UPDATE_EXTENSION = "oup"; public static final RuntimeException USER_CANCELLED_OPERATION_EXCEPTION = new RuntimeException("User Cancelled Operation"); /** * This method was originally started to avoid the bug that in Java-Cocoa applications, * constructors get called twice, so if you initialize anything in a constructor, it can get * nuked later by another constructor */ private void initDoc() { log.debug("MyDocument.initDoc()"); try { if (doc == null) { log.info("MyDocument.initDoc(): doc is null, making new doc"); doc = new MAFDocumentJDOM();//GdbiDocument(); } } catch (Exception e) { log.error("Exception: ", e); //To change body of catch statement use Options | File Templates. } } public MyDocument() { super(); log.info("MyDocument.MyDocument():"+this); initDoc(); } public MyDocument(String fileName, String fileType) { super(fileName, fileType); log.info("MyDocument.MyDocument(" + fileName + ", " + fileType + "):"+this); initDoc(); } // public void closeFamilyEditSheet(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); // NSApplication.sharedApplication().endSheet(familyEditWindow); // familyEditWindow.orderOut(this); // } // public void closeIndividualEditSheet(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); // } public void cancel(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); NSApplication.sharedApplication().endSheet(reportsWindow); reportsWindow.orderOut(sender); } public void openFamilyEditSheet(Object sender) { /* IBAction */ try { ( (NSWindowController) familyEditWindow.delegate()).setDocument(this); if (sender instanceof NSControl) { if ( ( (NSControl) sender).tag() == 1) { Family familyAsChild = getPrimaryIndividual().getFamilyAsChild(); ( (FamilyEditController) familyEditWindow.delegate()).setFamilyAsChild(familyAsChild); } else { Family familyAsSpouse = getCurrentFamily(); ( (FamilyEditController) familyEditWindow.delegate()).setFamily(familyAsSpouse); } } else if (sender instanceof NSValidatedUserInterfaceItem) { if ( ( (NSValidatedUserInterfaceItem) sender).tag() == 1) { Family familyAsChild = getPrimaryIndividual().getFamilyAsChild(); ( (FamilyEditController) familyEditWindow.delegate()).setFamilyAsChild(familyAsChild); } else { Family familyAsSpouse = getCurrentFamily(); ( (FamilyEditController) familyEditWindow.delegate()).setFamily(familyAsSpouse); } } NSApplication nsapp = NSApplication.sharedApplication(); nsapp.beginSheet(familyEditWindow, mainWindow, this, new NSSelector("sheetDidEndShouldClose2", new Class[] {}), null); // sheet is up here, control passes to the sheet controller } catch (RuntimeException e) { if (e != USER_CANCELLED_OPERATION_EXCEPTION) { e.printStackTrace(); MyDocument.showUserErrorMessage("An unexpected error occurred.", "Message: "+e.getMessage()); } } } public void deletePrimaryIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.deletePrimaryIndividual()"); String msg = "Are you sure you want to delete the individual named " + getPrimaryIndividual().getFullName() + "?"; String details = "This will delete this person from your file and remove them from any family relationships."; boolean shouldDelete = confirmCriticalActionMessage(msg, details, "Delete", "Cancel"); if (shouldDelete) { doc.removeIndividual(getPrimaryIndividual()); } setPrimaryIndividual(doc.getPrimaryIndividual()); } public void deletePrimaryFamily(Object sender) { /* IBAction */ log.debug("MyDocument.deletePrimaryFamily()"); String msg = "Are you sure you want to delete the family with parents " + getCurrentFamily().getFather().getFullName() + " and "+ getCurrentFamily().getMother().getFullName()+"?"; String details = "This will delete the relationship between the parents and children, but will leave the individual records."; boolean shouldDelete = confirmCriticalActionMessage(msg, details, "Delete", "Cancel"); if (shouldDelete) { doc.removeFamily(getCurrentFamily()); } } // private Individual getKnownPrimaryIndividual() { // Individual indi = getPrimaryIndividual(); // if (indi instanceof Individual.UnknownIndividual) { // indi = createAndInsertNewIndividual(); // } // return indi; // } public void sheetDidEndShouldClose2() { log.debug("sheetDidEndShouldClose2"); } public void openIndividualEditSheet(Object sender) { /* IBAction */ ( (NSWindowController) individualEditWindow.delegate()).setDocument(this); NSApplication nsapp = NSApplication.sharedApplication(); nsapp.beginSheet(individualEditWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); // sheet is up here, control passes to the sheet controller } public void sheetDidEnd(NSWindow sheet, int returnCode, Object contextInfo) { log.debug("Called did-end selector"); log.debug("sheetdidend contextInfo:"+contextInfo); try { refreshData(); save(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } sheet.orderOut(this); } public void editPrimaryIndividual(Object sender) { /* IBAction */ openIndividualEditSheet(sender); } public void editCurrentFamily(Object sender) { /* IBAction */ openFamilyEditSheet(sender); } public void printDocument(Object sender) { /* IBAction */ openReportsSheet(sender); } public void openReportsSheet(Object sender) { /* IBAction */ ( (NSWindowController) reportsWindow.delegate()).setDocument(this); // if (!myCustomSheet) // [NSBundle loadNibNamed: @"MyCustomSheet" owner: self]; NSApplication nsapp = NSApplication.sharedApplication(); log.debug("openReportsSheet mainWindow:" + mainWindow); // reportsWindow.makeKeyAndOrderFront(this); nsapp.beginSheet(reportsWindow, mainWindow, this, null, null); //nsapp.runModalForWindow(reportsWindow); //nsapp.endSheet(individualEditWindow); //individualEditWindow.orderOut(this); } public void setPrintableView(Object sender) { /* IBAction */ try { log.debug("setPrintableView selected=" + reportsRadio.selectedTag()); printInfo().setTopMargin(36); printInfo().setBottomMargin(36); printInfo().setLeftMargin(72); printInfo().setRightMargin(36); setPrintInfo(printInfo()); switch (reportsRadio.selectedTag()) { case 0: printableView = new PedigreeView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getPrimaryIndividual(), 4); break; case 1: printableView = new FamilyGroupSheetView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getCurrentFamily()); break; case 3: printableView = new PocketPedigreeView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getPrimaryIndividual(), 6); break; default: printableView = new PedigreeView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getPrimaryIndividual(), 4); } // printableView = new PedigreeView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual(), 4); // printableView = new FamilyGroupSheetView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); // printableView = new IndividualSummaryView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); } catch (Exception e) { e.printStackTrace(); } } // public void saveFamily(Object sender) { /* IBAction */ //// save family info // closeFamilyEditSheet(sender); // } // public void saveIndividual(Object sender) { /* IBAction */ //// save individual info // closeIndividualEditSheet(sender); // } public Individual getPrimaryIndividual() { return doc.getPrimaryIndividual(); } public void setPrimaryIndividual(Individual newIndividual) { setPrimaryIndividualAndSpouse(newIndividual, newIndividual.getPreferredSpouse()); } public void setPrimaryIndividualAndSpouse(Individual individual, Individual spouse) { try { Family familyAsSpouse = MyDocument.getFamilyForSpouse(individual, spouse); doc.setPrimaryIndividual(individual); assignIndividualToButton(individual, individualButton); // if primary individual is unknown, change button back to enabled individualButton.setEnabled(true); assignIndividualToButton(spouse, spouseButton); assignIndividualToButton(individual.getFather(), fatherButton); assignIndividualToButton(individual.getMother(), motherButton); assignIndividualToButton(individual.getFather().getFather(), paternalGrandfatherButton); assignIndividualToButton(individual.getFather().getMother(), paternalGrandmotherButton); assignIndividualToButton(individual.getMother().getFather(), maternalGrandfatherButton); assignIndividualToButton(individual.getMother().getMother(), maternalGrandmotherButton); pedigreeViewController.setPrimaryIndividual(individual); // individualDetailController.setIndividual(individual); log.debug("famsp id:"+familyAsSpouse.getId()); log.debug("famch id:"+individual.getFamilyAsChild().getId()); familyAsSpouseButton.setTitle("Family: "+familyAsSpouse.getId()); familyAsChildButton.setTitle("Family: "+individual.getFamilyAsChild().getId()); spouseTable.selectRow(0, false); spouseTable.reloadData(); childrenTable.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Family getFamilyForSpouse(Individual individual, Individual spouse) { Family matchingFamily = Family.UNKNOWN_FAMILY; for (Iterator iter = individual.getFamiliesAsSpouse().iterator(); iter.hasNext();) { Family family = (Family) iter.next(); if (spouse.equals(family.getFather()) || spouse.equals(family.getMother())) { matchingFamily = family; } } return matchingFamily; } public void setIndividual(Object sender) { /* IBAction */ try { log.debug("setIndividual to " + sender); if (sender instanceof NSButton) { try { log.debug("individuals=" + individualsButtonMap.objectForKey(sender.toString())); Individual newIndividual = (Individual) individualsButtonMap.objectForKey(sender.toString()); if (newIndividual == null) { newIndividual = Individual.UNKNOWN; } NSButton animateButton = (NSButton) sender; NSPoint individualButtonOrigin = individualButton.frame().origin(); NSPoint animateButtonOrigin = animateButton.frame().origin(); log.debug("animating from " + animateButtonOrigin + " to " + individualButtonOrigin); if (!animateButtonOrigin.equals(individualButtonOrigin)) { float stepx = (individualButtonOrigin.x() - animateButtonOrigin.x()) / 10; float stepy = (individualButtonOrigin.y() - animateButtonOrigin.y()) / 10; NSImage image = new NSImage(); log.debug("animatebutton.bounds:" + animateButton.bounds()); animateButton.lockFocus(); image.addRepresentation(new NSBitmapImageRep(animateButton.bounds())); animateButton.unlockFocus(); NSImageView view = new NSImageView(animateButton.frame()); view.setImage(image); animateButton.superview().addSubview(view); for (int steps = 0; steps < 10; steps++) { animateButtonOrigin = new NSPoint(animateButtonOrigin.x() + stepx, animateButtonOrigin.y() + stepy); view.setFrameOrigin(animateButtonOrigin); view.display(); } view.removeFromSuperview(); animateButton.superview().setNeedsDisplay(true); } setPrimaryIndividual(newIndividual); } catch (Exception e) { log.error("Exception: ", e); } } else if (sender instanceof NSTableView) { NSTableView tv = (NSTableView) sender; NSView superview = individualButton.superview(); log.debug("tableview selectedRow = "+tv.selectedRow()); if (tv.selectedRow() >= 0) { log.debug("individualList=" + individualsButtonMap.objectForKey("child" + tv.selectedRow())); NSPoint individualButtonOrigin = individualButton.frame().origin(); Individual newIndividual = (Individual) individualsButtonMap.objectForKey("child" + tv.selectedRow()); if (tv.tag() == 2) { newIndividual = (Individual) individualsButtonMap.objectForKey("spouse" + tv.selectedRow()); individualButtonOrigin = spouseButton.frame().origin(); } NSRect rowRect = tv.convertRectToView(tv.rectOfRow(tv.selectedRow()), superview); NSPoint tvOrigin = rowRect.origin(); log.debug("animating from " + tvOrigin + " to " + individualButtonOrigin); float stepx = (individualButtonOrigin.x() - tvOrigin.x()) / 10; float stepy = (individualButtonOrigin.y() - tvOrigin.y()) / 10; NSImage image = new NSImage(); log.debug("rowrect:" + rowRect); superview.lockFocus(); image.addRepresentation(new NSBitmapImageRep(rowRect)); superview.unlockFocus(); NSImageView view = new NSImageView(rowRect); view.setImage(image); superview.addSubview(view); for (int steps = 0; steps < 10; steps++) { tvOrigin = new NSPoint(tvOrigin.x() + stepx, tvOrigin.y() + stepy); view.setFrameOrigin(tvOrigin); view.display(); } view.removeFromSuperview(); superview.setNeedsDisplay(true); if (tv.tag() == 2) { setCurrentSpouse(newIndividual); } else { setPrimaryIndividual(newIndividual); } } } else if (sender instanceof IndividualList) { IndividualList iList = (IndividualList) sender; setPrimaryIndividual(iList.getSelectedIndividual()); } else if (sender instanceof FamilyList) { FamilyList fList = (FamilyList) sender; setPrimaryIndividual(fList.getSelectedFamily().getFather()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String windowNibName() { return "MyDocument"; } public void showWindows() { log.debug("showWindows()"); super.showWindows(); log.debug("done with super show windows. Now loading document..."); try { log.debug("fileWrapperToLoad:"+fileWrapperToLoad); if (fileWrapperToLoad != null) { log.debug("posting loaddocumentdata notification..."); startSuppressUpdates(); NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this, new NSDictionary(new Object[] {dataForFileWrapper(fileWrapperToLoad), doc}, new Object[] {"data", "doc"})); } // NSApplication.sharedApplication().beginSheet(taskProgressSheetWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); // // Thread.sleep(10000); // // NSApplication.sharedApplication().endSheet(taskProgressSheetWindow); // taskProgressSheetWindow.orderOut(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // called after the document finished loading the data or file wrapper for the document public void documentDidFinishLoading() { importData = null; fileWrapperToLoad = null; endSuppressUpdates(); } public void windowControllerDidLoadNib(NSWindowController aController) { try { super.windowControllerDidLoadNib(aController); // Add any code here that need to be executed once the windowController has loaded the document's window. mainWindow = aController.window(); mainWindow.setToolbar(new MainToolbar()); log.debug("mainWindow:" + mainWindow); log.debug("indivEditWindow:" + individualEditWindow); //myAction(this); NSAttributedString text = individualButton.attributedTitle(); log.debug("indivButton attrTitle: " + text); // log.debug("indivButton attr at index 5:" + text.attributesAtIndex(5, null)); log.debug("individualList: " + individualsButtonMap.count() + "(" + individualsButtonMap + ")"); log.debug("individualList="+individualList); log.debug("individualList: " + individualList.size()); // + "(" + indiMap + ")"); individualList.document = this; familyList.document = this; // individualList.setIndividualMap(doc.getIndividualsMap()); // familyList.setFamilyMap(doc.getFamiliesMap()); if (individualList.size() > 0) { log.debug("individualList.size() > 0: "+individualList.size()); assignIndividualToButton( (Individual) individualList.getFirstIndividual(), individualButton); setIndividual(individualButton); } else { log.info("!!! Setting primary individual to UNKNOWN--No individuals in file:"+this); setPrimaryIndividual(Individual.UNKNOWN); } // add famMap to FamilyList // for (Iterator iter = famMap.values().iterator(); iter.hasNext(); ) { // Family fam = (Family) iter.next(); // familyList.add(fam); // } // NSImage testImage = new NSImage("/Users/logan/Pictures/iPhoto Library/Albums/Proposal/GQ.jpg", false); // testImage.setSize(new NSSize(50f, 50f)); // testImage.setScalesWhenResized(true); log.debug("indivButton cell type: " + individualButton.cell().type()); // individualButton.setImage(testImage); // save(); tabFamilyListController.setup(); tabFamilyListController.setDocument(this); tabIndividualListController.setup(); tabIndividualListController.setDocument(this); // register as an observer of the MAFDocumentJDOM doc.addObserver(this); NSNotificationCenter.defaultCenter().addObserver(importController, CocoaUtils.BEGIN_IMPORT_PROCESS_SELECTOR, CocoaUtils.BEGIN_IMPORT_PROCESS_NOTIFICATION, this); NSNotificationCenter.defaultCenter().addObserver(importController, CocoaUtils.IMPORT_DATA_SELECTOR, CocoaUtils.IMPORT_DATA_NOTIFICATION, this); NSNotificationCenter.defaultCenter().addObserver(importController, CocoaUtils.LOAD_DOCUMENT_SELECTOR, CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this); if (importData != null && importData.length() > 0) { NSRunLoop.currentRunLoop().performSelectorWithOrder(CocoaUtils.IMPORT_DATA_SELECTOR, importController, new NSNotification(CocoaUtils.IMPORT_DATA_NOTIFICATION, this, null), 0, new NSArray(NSRunLoop.DefaultRunLoopMode)); } if (false && fileWrapperToLoad != null) { // NSRunLoop.currentRunLoop().performSelectorWithOrder(CocoaUtils.LOAD_DOCUMENT_SELECTOR, importController, new NSNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this, null), 0, new NSArray(NSRunLoop.DefaultRunLoopMode)); log.debug("taskprogresswindow:"+taskProgressSheetWindow); NSApplication.sharedApplication().beginSheet(taskProgressSheetWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); NSFileWrapper nsFileWrapper = fileWrapperToLoad; log.debug("wrapper isDir:" + nsFileWrapper.isDirectory()); log.debug("attributes:" + nsFileWrapper.fileAttributes()); log.debug("filename: " + fileName() + " type:" + fileType()); log.debug("setFileAttr result=" + NSPathUtilities.setFileAttributes(fileName() + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer(NSHFSFileTypes.hfsTypeCodeFromFileType("TEXT")), NSPathUtilities.FileHFSTypeCode))); if (nsFileWrapper.isDirectory()) { log.debug("wrappers:" + nsFileWrapper.fileWrappers()); } // NSFileWrapper familiesPlist = (NSFileWrapper) // nsFileWrapper.fileWrappers().valueForKey("families.plist"); // log.error("start extract"); // families = (NSMutableDictionary) // NSPropertyListSerialization.propertyListFromData(familiesPlist.regularFileContents(), // NSPropertyListSerialization.PropertyListMutableContainersAndLeaves, // new int[]{NSPropertyListSerialization.PropertyListXMLFormat}, // errors); // log.error("end extract"); Enumeration en = nsFileWrapper.fileWrappers() .objectEnumerator(); while (en.hasMoreElements()) { NSFileWrapper wrapper = ((NSFileWrapper) en.nextElement()); log.debug(wrapper.filename() + " subattr:" + wrapper.fileAttributes()); if (NSPathUtilities.pathExtension(wrapper.filename()) .equalsIgnoreCase("ged")) { String fullPath = fileName() + "/" + wrapper.filename(); log.debug("..................Loading gedcom: " + fullPath); try { importGEDCOM(new File(fullPath)); } catch (RuntimeException e) { e.printStackTrace(); // return false; } // save individualList in a temporary so I can restore // it when the // Cocoa startup sequence calls the constructor twice // and clobbers it // startupIndividualList = individualList; } } } taskProgressSheetWindow.orderOut(this); //fileWrapperToLoad = null; // } } catch (Exception e) { log.error("Exception: ", e); //To change body of catch statement use Options | File Templates. } } // public boolean readFromFile(String filename, String aType) { // log.debug("********* readFromFile:" + filename + " ofType:"+aType); // // We will open GEDCOM file directly from Java File I/O, all others will pass up // // to readFileWrapper or loadDataRepresentation // // At some point, we may decide to have importGEDCOM just work on NSData as well // // instead of the File directly // try { // if (GEDCOM_DOCUMENT_TYPE.equals(aType)) { // // import GEDCOM into this file // boolean success = super.readFromFile(filename, aType); // if (success) { // importGEDCOM(new File(filename)); // setFileType(MACPAF_DOCUMENT_TYPE); // setFileName(null); // } // return success; // } else { // return super.readFromFile(filename, aType); // } // } // catch (Exception e) { // log.error("Exception: ", e); // return false; // } // } private NSData dataForFileWrapper(NSFileWrapper nsFileWrapper) { log.debug("MyDocument.dataForFileWrapper():"+nsFileWrapper); log.debug("wrapper isDir:" + nsFileWrapper.isDirectory()); log.debug("attributes:" + nsFileWrapper.fileAttributes()); log.debug("filename: " + fileName() + " type:" + fileType()); log.debug("setFileAttr result=" + NSPathUtilities.setFileAttributes(fileName() + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer(NSHFSFileTypes.hfsTypeCodeFromFileType("TEXT")), NSPathUtilities.FileHFSTypeCode))); if (nsFileWrapper.isDirectory()) { log.debug("wrappers:" + nsFileWrapper.fileWrappers()); } // NSFileWrapper familiesPlist = (NSFileWrapper) // nsFileWrapper.fileWrappers().valueForKey("families.plist"); // log.error("start extract"); // families = (NSMutableDictionary) // NSPropertyListSerialization.propertyListFromData(familiesPlist.regularFileContents(), // NSPropertyListSerialization.PropertyListMutableContainersAndLeaves, // new int[]{NSPropertyListSerialization.PropertyListXMLFormat}, // errors); // log.error("end extract"); Enumeration en = nsFileWrapper.fileWrappers().objectEnumerator(); while (en.hasMoreElements()) { NSFileWrapper wrapper = ((NSFileWrapper) en.nextElement()); log.debug(wrapper.filename() + " subattr:" + wrapper.fileAttributes()); if (NSPathUtilities.pathExtension(wrapper.filename()) .equalsIgnoreCase("ged")) { String fullPath = fileName() + "/" + wrapper.filename(); log.debug("..................Loading gedcom: " + fullPath); try { System.out.println("MyDocument.dataForFileWrapper() data:"+new NSData(new File(fullPath))); return new NSData(new File(fullPath)); } catch (RuntimeException e) { e.printStackTrace(); } // save individualList in a temporary so I can restore // it when the // Cocoa startup sequence calls the constructor twice // and clobbers it // startupIndividualList = individualList; } } return new NSData(); } public boolean loadFileWrapperRepresentation(NSFileWrapper nsFileWrapper, String aType) { log.info("MyDocument.loadFileWrapperRepresentation():" + nsFileWrapper + ":" + aType); try { // If this is not a MAF document, then pass it up to loadDataRepresentation for import. if (!MAF_DOCUMENT_TYPE.equals(aType)) { return super.loadFileWrapperRepresentation(nsFileWrapper, aType); } else { // Since MAF files are File Packages, we will load the various files here NDC.push(this.toString()); // NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this); fileWrapperToLoad = nsFileWrapper; if (true) return true; NSApplication.sharedApplication().beginSheet(taskProgressSheetWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); log.debug("wrapper isDir:" + nsFileWrapper.isDirectory()); log.debug("attributes:" + nsFileWrapper.fileAttributes()); log.debug("filename: " + fileName() + " type:" + fileType()); log.debug("setFileAttr result=" + NSPathUtilities.setFileAttributes(fileName() + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer(NSHFSFileTypes.hfsTypeCodeFromFileType("TEXT")), NSPathUtilities.FileHFSTypeCode))); if (nsFileWrapper.isDirectory()) { log.debug("wrappers:" + nsFileWrapper.fileWrappers()); } // NSFileWrapper familiesPlist = (NSFileWrapper) // nsFileWrapper.fileWrappers().valueForKey("families.plist"); // log.error("start extract"); // families = (NSMutableDictionary) // NSPropertyListSerialization.propertyListFromData(familiesPlist.regularFileContents(), // NSPropertyListSerialization.PropertyListMutableContainersAndLeaves, // new int[]{NSPropertyListSerialization.PropertyListXMLFormat}, // errors); // log.error("end extract"); Enumeration en = nsFileWrapper.fileWrappers() .objectEnumerator(); while (en.hasMoreElements()) { NSFileWrapper wrapper = ((NSFileWrapper) en.nextElement()); log.debug(wrapper.filename() + " subattr:" + wrapper.fileAttributes()); if (NSPathUtilities.pathExtension(wrapper.filename()) .equalsIgnoreCase("ged")) { String fullPath = fileName() + "/" + wrapper.filename(); log.debug("..................Loading gedcom: " + fullPath); try { importGEDCOM(new File(fullPath)); } catch (RuntimeException e) { e.printStackTrace(); return false; } // save individualList in a temporary so I can restore // it when the // Cocoa startup sequence calls the constructor twice // and clobbers it // startupIndividualList = individualList; } } } taskProgressSheetWindow.orderOut(this); return true; } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); } finally { NDC.pop(); } showUserErrorMessage( "There was a problem opening the file:\n" + nsFileWrapper.filename() + ".", "This is usually caused by a corrupt file. If the file is a GEDCOM file, it may not be the right version" + " or it may not conform to the GEDCOM 5.5 specification. If this is a MAF file, it is missing " + "some required data or the data has become corrupted. This can often be fixed by manually inspecting " + "the contents of the file. Please contact support to see if this can be fixed."); return false; } /* (non-Javadoc) * @see com.apple.cocoa.application.NSDocument#loadDataRepresentation(com.apple.cocoa.foundation.NSData, java.lang.String) */ public boolean loadDataRepresentation(NSData data, String aType) { log.info("MyDocument.loadDataRepresentation():<"+data.length() + " bytes>:"+aType); log.debug("MyDocument.loadDataRepresentation():filename:"+fileName()+" filetype:"+fileType()); try { if (GEDCOM_DOCUMENT_TYPE.equals(aType)) { // importGEDCOM(data); importData = data; } else if (PAF21_DOCUMENT_TYPE.equals(aType)) { // Insert code here to read your document from the given data. You can also choose to override -loadFileWrapperRepresentation:ofType: or -readFromFile:ofType: instead. log.debug(data.length()+", chunks "+(data.length()-512)/1024); // importPAF21(data); importData = data; } else if (TEMPLEREADY_UPDATE_DOCUMENT_TYPE.equals(aType)) { // importTempleReadyUpdate(data); importData = data; } else { // not sure what type of document this is, look at the data and see if we can find out // TODO look at the data to figure out the type showUserErrorMessage("Unable to load document", "Could not determine what type of document this is. Data may be corrupted or is a file that MAF cannot understand."); } // PAF21Data pafData = new PAF21Data(data); // [self setString: [[NSAttributedString alloc] initWithString:[pafData hexString:40] attributes:attrsDictionary]]; // pafData.importData(); // [textField setStringValue:[pafData hexString:40]]; // For applications targeted for Tiger or later systems, you should use the new Tiger API readFromData:ofType:error:. In this case you can also choose to override -readFromURL:ofType:error: or -readFromFileWrapper:ofType:error: instead. return true; } catch (RuntimeException e) { // TODO Auto-generated catch block log.error("Exception: ", e); e.printStackTrace(); } return super.loadDataRepresentation(data, aType); } public NSFileWrapper fileWrapperRepresentationOfType(String aType) { log.debug("MyDocument.fileWrapperRepresentationOfType:" + aType); try { if (MAF_DOCUMENT_TYPE.equals(aType)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baosGed = new ByteArrayOutputStream(); try { // out.output( // doc, // new FileWriter("/Projects/MAF/savetest.xml")); doc.outputToXML(baos); // doc.outputToXML(System.out); // XMLTest.outputWithKay( // doc, // new FileOutputStream("/Projects/MAF/savetest.ged")); doc.outputToGedcom(baosGed); // doc.outputToGedcom(System.out); } catch (IOException e) { log.error("Exception: ", e); } NSFileWrapper mainFile = new NSFileWrapper(new NSDictionary()); NSFileWrapper imagesFolder = new NSFileWrapper(new NSDictionary()); imagesFolder.setPreferredFilename("multimedia"); String images1 = mainFile.addFileWrapper(imagesFolder); // NSData data = new NSAttributedString("some data goes // here").RTFFromRange(new NSRange(0, 15), new NSDictionary()); // mainFile.addRegularFileWithContents(NSPropertyListSerialization.dataFromPropertyList(individuals), // "individuals.plist"); // for (int i=0; i< 10000; i++) { // families.takeValueForKey("familyvalue"+i, ""+i); // } // notes.takeValueForKey("notevalue", "notekey"); // log.debug("start serialize"); // String plist1 = // mainFile.addRegularFileWithContents(NSPropertyListSerialization.XMLDataFromPropertyList(families), // "families.plist"); // String plist2 = // mainFile.addRegularFileWithContents(NSPropertyListSerialization.XMLDataFromPropertyList(notes), // "notes.plist"); // log.debug("end serialize"); // String file1 = // imagesFolder.addFileWithPath( // "/Projects/MAF/macpaf-screenshot.png"); // String file2 = // imagesFolder.addFileWithPath( // "/Projects/MAF/macpaf-screenshot.tiff"); // String file3 = // imagesFolder.addFileWithPath( // "/Projects/MAF/macpaf-screenshot.jpg"); // String file4 = // imagesFolder.addFileWithPath( // "/Projects/Mcreenshot.gif"); String dataXmlFilename = DEFAULT_XML_FILENAME; String dataGedcomFilename = DEFAULT_GEDCOM_FILENAME; // if (fileName() != null && fileName().length() > 0) { // dataXmlFilename = fileName()+".xml"; // dataGedcomFilename = fileName()+".ged"; // } String xml1 = mainFile.addRegularFileWithContents( new NSData(baos.toByteArray()), dataXmlFilename); String ged1 = mainFile.addRegularFileWithContents( new NSData(baosGed.toByteArray()), dataGedcomFilename); log.debug("" // "file1=" // + file1 // + ", file2=" // + file2 // + ", file3=" // + file3 // + ", file4=" // + file4 + ", images1=" + images1 + ", xml1=" + xml1 + ", ged1=" + ged1); return mainFile; //super.fileWrapperRepresentationOfType(s); } // unknown file type log.error("fileWrapperRep unknown file type " + aType); return null; } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); return null; } } /** * @param string * @param string2 */ public static void showUserErrorMessage(String message, String details) { NSAlertPanel.runCriticalAlert(message, details, "OK", null, null); } /** * @param string * @param string2 */ public static boolean confirmCriticalActionMessage(String message, String details, String confirmActionText, String cancelActionText) { int result = NSAlertPanel.runCriticalAlert(message, details, confirmActionText, cancelActionText, null); return result == NSAlertPanel.DefaultReturn; } /* (non-Javadoc) * @see com.apple.cocoa.application.NSDocument#setFileName(java.lang.String) */ public void setFileName(String arg0) { try { super.setFileName(arg0); log.debug("super.setfilename() done." + arg0); log.debug("setfilename set file attrs result=" + NSPathUtilities.setFileAttributes(arg0 + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer( NSHFSFileTypes.hfsTypeCodeFromFileType("'TEXT'")), NSPathUtilities.FileHFSTypeCode))); // log.debug("setfilename " + arg0 + "/" + DEFAULT_GEDCOM_FILENAME + " attr aft:" + // NSPathUtilities.fileAttributes(arg0 + "/" + DEFAULT_GEDCOM_FILENAME, false)); } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); } } public void addFamily(Family newFamily) { try { doc.addFamily(newFamily); // TODO notification // if (familyListTableView != null) { // familyListTableView.reloadData(); // } } catch (Exception ex) { ex.printStackTrace(); } } public void addIndividual(Individual newIndividual) { try { doc.addIndividual(newIndividual); log.debug("added newIndividual with key: "+newIndividual.getId()+" newIndividual name: "+newIndividual.getFullName()); // TODO notification // if (individualListTableView != null) { // individualListTableView.reloadData(); // } } catch (Exception ex) { ex.printStackTrace(); /** @todo figure out what to do here */ } } // public NSData dataRepresentationOfType(String aType) { // // Insert code here to create and return the data for your document. // log.debug("MyDocument.dataRepresentationOfType():" + aType); // return new NSAttributedString("some data goes here").RTFFromRange(new NSRange(0, 15), new NSDictionary()); // } // public boolean loadDataRepresentation(NSData data, String aType) { // // Insert code here to read your document from the given data. // log.debug("MyDocument.loadDataRepresentation():" + aType); // log.debug("load data:" + aType + ":" + new NSStringReference(data, NSStringReference.ASCIIStringEncoding)); // return true; // } private void assignIndividualToButton(Individual indiv, NSButton button) { try { button.setObjectValue(indiv); NSAttributedString newLine = new NSAttributedString("\n"); NSMutableAttributedString nameText = new NSMutableAttributedString(indiv.getFullName()); button.setEnabled(true); if (indiv instanceof Individual.UnknownIndividual) { nameText = new NSMutableAttributedString("Unknown"); button.setEnabled(false); } NSMutableAttributedString birthdateText = new NSMutableAttributedString(""); NSMutableAttributedString birthplaceText = new NSMutableAttributedString(""); NSMutableAttributedString ordinancesText = makeOrdinanceString(indiv); if (indiv.getBirthEvent() != null) { birthdateText = new NSMutableAttributedString(indiv.getBirthEvent().getDateString()); if (indiv.getBirthEvent().getPlace() != null) { birthplaceText = new NSMutableAttributedString(indiv.getBirthEvent().getPlace().getFormatString()); } } NSMutableAttributedString text = nameText; text.appendAttributedString(newLine); text.appendAttributedString(birthdateText); text.appendAttributedString(newLine); text.appendAttributedString(birthplaceText); text.appendAttributedString(newLine); text.appendAttributedString(ordinancesText); button.setAttributedTitle(text); // URL imageURL = indiv.getImagePath(); // if (imageURL != null && imageURL.toString().length() > 0) { NSImage testImage = MultimediaUtils.makeImageFromMultimedia(indiv.getPreferredImage()); // log.debug("button image:"+testImage); if (!testImage.size().isEmpty()) { testImage.setSize(new NSSize(50f, 50f)); testImage.setScalesWhenResized(true); button.setImage(testImage); } // } individualsButtonMap.setObjectForKey(indiv, button.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private NSMutableAttributedString makeOrdinanceString(Individual individual) { NSMutableAttributedString ordinanceString = new NSMutableAttributedString("BEPSC"); if (individual.getLDSBaptism().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(0,1)); } if (individual.getLDSEndowment().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(1,1)); } if (individual.getLDSSealingToParents().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(2,1)); } if (individual.getPreferredFamilyAsSpouse().getPreferredSealingToSpouse().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(3,1)); } if (individual.childrensOrdinancesAreCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(4,1)); } return ordinanceString; } public int numberOfRowsInTableView(NSTableView nsTableView) { try { log.debug("MyDocument.numberOfRowsInTableView():tag=" + nsTableView.tag()); if (nsTableView.tag() == 1) { if (getPrimaryIndividual().getPreferredFamilyAsSpouse() != null) { int numChildren = getCurrentFamily().getChildren().size(); log.debug("numberOfRowsInTableView children: " + numChildren); return numChildren; } } else if (nsTableView.tag() == 2) { int numSpouses = getPrimaryIndividual().getSpouseList().size(); log.debug("numberOfRowsInTableView spouses: " + numSpouses); return numSpouses; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } public Object tableViewObjectValueForLocation(NSTableView nsTableView, NSTableColumn nsTableColumn, int i) { try { // log.debug("nsTableColumn=" + nsTableColumn.identifier()+"; i="+i+"; tag="+nsTableView.tag()); if (nsTableView.tag() == 1) { if (nsTableColumn.identifier() != null && nsTableColumn.identifier().equals("num")) { nsTableColumn.setWidth(5.0f); return String.valueOf(i + 1); } Individual individual = (Individual) getCurrentFamily().getChildren().get(i); individualsButtonMap.setObjectForKey(individual, "child" + i); return individual.getFullName(); } else if (nsTableView.tag() == 2) { Individual individual = (Individual) getPrimaryIndividual().getSpouseList().get(i); individualsButtonMap.setObjectForKey(individual, "spouse" + i); return individual.getFullName(); } return "Unknown"; } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); return "An Error Has Occurred"; } } // used to display row in bold if the child also has children public void tableViewWillDisplayCell(NSTableView aTableView, Object aCell, NSTableColumn aTableColumn, int rowIndex) { // log.debug("MyDocument.tableViewWillDisplayCell():"+aTableView.tag()+":"+aCell+":"+aTableColumn.headerCell().stringValue()+":"+rowIndex); // Thread.dumpStack(); try { if (aTableView.tag() == 1 ) { if (aCell instanceof NSCell) { NSCell cell = (NSCell) aCell; // log.debug("cell str val:"+cell.stringValue()); Individual child = (Individual) getCurrentFamily().getChildren().get(rowIndex); if (child.getPreferredFamilyAsSpouse().getChildren().size() > 0) { // log.debug("bolding child name:"+child.getFullName()); cell.setFont(NSFontManager.sharedFontManager().convertFontToHaveTrait(cell.font(), NSFontManager.BoldMask)); } else { // log.debug("unbolding child name:"+child.getFullName()); cell.setFont(NSFontManager.sharedFontManager().convertFontToNotHaveTrait(cell.font(), NSFontManager.BoldMask)); } } } } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Family getCurrentFamily() { Family result = getPrimaryIndividual().getPreferredFamilyAsSpouse(); List families = getPrimaryIndividual().getFamiliesAsSpouse(); if (getPrimaryIndividual().getSpouseList().size() > 0 && spouseTable.selectedRow() >= 0) { Individual selectedSpouse = (Individual) getPrimaryIndividual().getSpouseList().get(spouseTable.selectedRow()); for (Iterator iter = families.iterator(); iter.hasNext();) { Family family = (Family) iter.next(); if (family.getMother().getId().equals(selectedSpouse.getId()) || family.getFather().getId().equals(selectedSpouse.getId())) { result = family; } } } return result; } private void setCurrentSpouse(Individual spouse) { log.debug("MyDocument.setCurrentSpouse():"+spouse.getFullName()); assignIndividualToButton(spouse, spouseButton); familyAsSpouseButton.setTitle("Family: "+getCurrentFamily().getId()); childrenTable.reloadData(); } public void setCurrentFamily(Family family) { setPrimaryIndividual(family.getFather()); setCurrentSpouse(family.getMother()); } public void printShowingPrintPanel(boolean showPanels) { log.debug("printshowingprintpanel:" + showPanels); try { // Obtain a custom view that will be printed printInfo().setTopMargin(36); printInfo().setBottomMargin(36); printInfo().setLeftMargin(72); printInfo().setRightMargin(36); setPrintInfo(printInfo()); // NSView printView = printableView; // Construct the print operation and setup Print panel NSPrintOperation op = NSPrintOperation.printOperationWithView(printableView, printInfo()); log.debug("papersize: " + printInfo().paperSize()); log.debug("left margin: " + printInfo().leftMargin()); log.debug("right margin: " + printInfo().rightMargin()); log.debug("top margin: " + printInfo().topMargin()); log.debug("bottom margin: " + printInfo().bottomMargin()); op.setShowPanels(showPanels); if (showPanels) { // Add accessory view, if needed } // Run operation, which shows the Print panel if showPanels was YES runModalPrintOperation(op, null, null, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // private NSView printableView() { // return printableView; // return new PedigreeView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual(), 4); // return new FamilyGroupSheetView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); // return new IndividualSummaryView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); // } /** * Saves this document to disk with all files in the file package */ public void save() { log.info("___||| save()"); long watch = System.currentTimeMillis(); // call the standard Cocoa save action saveDocument(this); log.debug("it took "+(System.currentTimeMillis()-watch)+" ms to save files"); // individualListWindowController.refreshData(); // familyListWindowController.refreshData(); log.debug("MyDocument.save() end ("+(System.currentTimeMillis()-watch)+" ms), filename=" + fileName()); } public void openImportSheet(Object sender) { /* IBAction */ log.debug("openImportSheet"); try { NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.BEGIN_IMPORT_PROCESS_NOTIFICATION, this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // public void importFile(Object sender) { /* IBAction */ // log.debug("importFile: " + sender); // try { // // NSApplication nsapp = NSApplication.sharedApplication(); // // nsapp.beginSheet(importSheet, mainWindow, this, null, null); // NSOpenPanel panel = NSOpenPanel.openPanel(); // //panther only? panel.setMessage("Please select a GEDCOM file to import into this MAF file."); // panel.beginSheetForDirectory(null, null, new NSArray(new Object[] {"GED"}), mainWindow, // this, // new NSSelector("openPanelDidEnd", new Class[] {NSOpenPanel.class, int.class, Object.class}), null); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } /** * @param sheet * @param returnCode * @param contextInfo */ // public void openPanelDidEnd(NSOpenPanel sheet, int returnCode, Object contextInfo) { // if (returnCode == NSPanel.OKButton) { // log.debug("import filenames:" + sheet.filenames()); // for (Enumeration enumerator = sheet.filenames().objectEnumerator(); enumerator.hasMoreElements();) { // String filename = (String) enumerator.nextElement(); // if (TEMPLEREADY_UPDATE_EXTENSION.equalsIgnoreCase(NSPathUtilities.pathExtension(sheet.filename()))) { // importTempleReadyUpdate(new NSData(new File(filename))); // } // importGEDCOM(new File(filename)); // } // } // } private void importMAF(NSFileWrapper importFile) { log.debug("MyDocument.importMAF():" + importFile); try { // doc.loadXMLFile(importFile); if (true) throw new RuntimeException("Importing from another MAF file not yet implemented"); if (getPrimaryIndividual().equals(Individual.UNKNOWN)) { // set first individual in imported file to primary individual setPrimaryIndividual(individualList.getSelectedIndividual()); } // individualListTableView.reloadData(); // familyListTableView.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); } } private void importTempleReadyUpdate(NSData data) { showUserErrorMessage("We're sorry, but we do not yet handle TempleReady Update Files", "This functionality will be added later. Look for a future update."); } // private void importGEDCOM(NSData data) { // log.debug("MyDocument.importGEDCOM():" + data.length()+" bytes"); // try { // doc.loadXMLData(data); // if (Individual.UNKNOWN.equals(getPrimaryIndividual()) && individualList != null) { // // set first individual in imported file to primary individual // setPrimaryIndividual(individualList.getSelectedIndividual()); // } //// individualListTableView.reloadData(); //// familyListTableView.reloadData(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); // } // } private void importGEDCOM(File importFile) { log.debug("MyDocument.importGEDCOM():" + importFile); try { doc.importGedcom(importFile, null); if (getPrimaryIndividual().equals(Individual.UNKNOWN)) { // set first individual in imported file to primary individual setPrimaryIndividual(individualList.getSelectedIndividual()); } // individualListTableView.reloadData(); // familyListTableView.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); } } private void importPAF21(NSData data) { log.debug("MyDocument.importPAF21():" + data); try { // invoke ObjC NSDictionary importParams = new NSDictionary(new Object[] {data, taskProgressSheetWindow}, new Object[] {"data", "progress"}); NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.IMPORT_DATA_NOTIFICATION, this, importParams); if (getPrimaryIndividual().equals(Individual.UNKNOWN)) { // set first individual in imported file to primary individual setPrimaryIndividual(individualList.getSelectedIndividual()); } // individualListTableView.reloadData(); // familyListTableView.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); } } public void exportFile(Object sender) { /* IBAction */ log.debug("exportFile: " + sender); try { // save(); NSSavePanel panel = NSSavePanel.savePanel(); // Jaguar-only code // panel.setCanSelectHiddenExtension(true); // panel.setExtensionHidden(false); //panther only? panel.setMessage("Choose the name and location for the exported GEDCOM file.\n\nThe file name should end with .ged"); // panel.setNameFieldLabel("Name Field Label:"); // panel.setPrompt("Prompt:"); panel.setRequiredFileType("ged"); // panel.setTitle("Title"); panel.beginSheetForDirectory(null, null, mainWindow, this, new NSSelector("savePanelDidEndReturnCode", new Class[] {NSSavePanel.class, int.class, Object.class}), null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void savePanelDidEndReturnCode(NSSavePanel sheet, int returnCode, Object contextInfo) { log.debug("MyDocument.savePanelDidEndReturnCode(sheet, returnCode, contextInfo):" + sheet + ":" + returnCode + ":" + contextInfo); if (returnCode == NSPanel.OKButton) { log.debug("export filename:" + sheet.filename()); try { // bring up selection window to choose what to export if (contextInfo.toString().indexOf("oup") > 0) { doc.outputToTempleReady(new FileOutputStream(sheet.filename())); } doc.outputToGedcom(new FileOutputStream(sheet.filename())); } catch (Exception e) { log.error("Exception: ", e); //To change body of catch statement use Options | File Templates. } } else if (returnCode == NSPanel.CancelButton) { log.debug("save panel cancelled, sheet filename=" + sheet.filename() + ", doc filename=" + fileName()); if (fileName() == null || fileName().length() == 0) { log.debug("cancel with null filename, should I close the document?"); // close(); } } } public void windowDidBecomeMain(NSNotification aNotification) { log.debug("MyDocument.windowDidBecomeMain()"); if (!isLoadingDocument()) { save(); } } private boolean isLoadingDocument() { // TODO Auto-generated method stub return fileWrapperToLoad != null || importData != null; } public Individual createAndInsertNewIndividual() { return doc.createAndInsertNewIndividual();//new IndividualJDOM(doc); } public Family createAndInsertNewFamily() { return doc.createAndInsertNewFamily();//new IndividualJDOM(doc); } public Note createAndInsertNewNote() { log.debug("MyDocument.createAndInsertNewNote()"); return doc.createAndInsertNewNote(); } /** * prepareSavePanel * * @param nSSavePanel NSSavePanel * @return boolean * @todo Implement this com.apple.cocoa.application.NSDocument method */ public boolean prepareSavePanel(NSSavePanel nSSavePanel) { log.debug("MyDocument.prepareSavePanel(nSSavePanel):" + nSSavePanel); nSSavePanel.setDelegate(this); return true; } public boolean panelIsValidFilename(Object sender, String filename) { log.debug("MyDocument.panelIsValidFilename(sender, filename):" + sender + ":" + filename); return true; } public void addNewIndividual(Object sender) { /* IBAction */ log.debug("addNewIndividual: " + sender); try { Individual newIndividual = createAndInsertNewIndividual(); // addIndividual(newIndividual); setPrimaryIndividual(newIndividual); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewChild(Object sender) { /* IBAction */ log.debug("addNewChild: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); Family familyAsSpouse = primaryIndividual.getPreferredFamilyAsSpouse(); if (familyAsSpouse instanceof Family.UnknownFamily) { familyAsSpouse = createAndInsertNewFamily(); if (Gender.MALE.equals(primaryIndividual.getGender())) { familyAsSpouse.setFather(primaryIndividual); } else { familyAsSpouse.setMother(primaryIndividual); } primaryIndividual.setFamilyAsSpouse(familyAsSpouse); } Individual newChild = createAndInsertNewIndividual(); familyAsSpouse.addChild(newChild); newChild.setFamilyAsChild(familyAsSpouse); setPrimaryIndividual(newChild); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewSpouse(Object sender) { /* IBAction */ log.debug("addNewSpouse: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); boolean isMale = Gender.MALE.equals(primaryIndividual.getGender()); Family familyAsSpouse = primaryIndividual.getPreferredFamilyAsSpouse(); if (familyAsSpouse instanceof Family.UnknownFamily) { familyAsSpouse = createAndInsertNewFamily(); if (isMale) { familyAsSpouse.setFather(primaryIndividual); } else { familyAsSpouse.setMother(primaryIndividual); } primaryIndividual.setFamilyAsSpouse(familyAsSpouse); } Individual newSpouse = createAndInsertNewIndividual(); primaryIndividual.addSpouse(newSpouse); newSpouse.addSpouse(primaryIndividual); setPrimaryIndividual(newSpouse); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFather(Object sender) { /* IBAction */ log.debug("addNewFather: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); Family familyAsChild = primaryIndividual.getFamilyAsChild(); if (familyAsChild instanceof Family.UnknownFamily) { familyAsChild = createAndInsertNewFamily(); familyAsChild.addChild(primaryIndividual); primaryIndividual.setFamilyAsChild(familyAsChild); } Individual newFather = createAndInsertNewIndividual(); newFather.setGender(Gender.MALE); newFather.setSurname(primaryIndividual.getSurname()); newFather.setFamilyAsSpouse(familyAsChild); familyAsChild.setFather(newFather); setPrimaryIndividual(newFather); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewMother(Object sender) { /* IBAction */ log.debug("addNewMother: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); Family familyAsChild = primaryIndividual.getFamilyAsChild(); if (familyAsChild instanceof Family.UnknownFamily) { familyAsChild = createAndInsertNewFamily(); familyAsChild.addChild(primaryIndividual); primaryIndividual.setFamilyAsChild(familyAsChild); } Individual newMother = createAndInsertNewIndividual(); newMother.setGender(Gender.FEMALE); newMother.setFamilyAsSpouse(familyAsChild); familyAsChild.setMother(newMother); setPrimaryIndividual(newMother); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFamily(Object sender) { /* IBAction */ log.debug("addNewFamily: " + sender); try { // I think the family edit sheet takes care of creating a new family // Family newFamily = createAndInsertNewFamily(); // save(); openFamilyEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFamilyAsSpouse(Object sender) { /* IBAction */ log.debug("addNewFamilyAsSpouse: " + sender); try { Family newFamily = createAndInsertNewFamily(); Individual primaryIndividual = getPrimaryIndividual(); primaryIndividual.setFamilyAsSpouse(newFamily); if (Gender.MALE.equals(primaryIndividual.getGender())) { newFamily.setFather(primaryIndividual); } else { newFamily.setMother(primaryIndividual); } save(); openFamilyEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFamilyAsChild(Object sender) { /* IBAction */ log.debug("addNewFamilyAsChild: " + sender); try { Family newFamily = createAndInsertNewFamily(); Individual primaryIndividual = getPrimaryIndividual(); primaryIndividual.setFamilyAsChild(newFamily); newFamily.addChild(primaryIndividual); save(); openFamilyEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void displayFamilyView(Object sender) { /* IBAction */ mainTabView.selectFirstTabViewItem(sender); } public void displayPedigreeView(Object sender) { /* IBAction */ mainTabView.selectTabViewItemAtIndex(1); } public void displayIndividualListView(Object sender) { /* IBAction */ mainTabView.selectTabViewItemAtIndex(2); } public void displayFamilyListView(Object sender) { /* IBAction */ mainTabView.selectLastTabViewItem(sender); } public void showFamilyList(Object sender) { /* IBAction */ log.debug("showFamilyList: " + sender); try { if (familyListWindowController == null) { familyListWindowController = new FamilyListController(familyList); } addWindowController(familyListWindowController); familyListWindowController.showWindow(this); // log.debug(familyListWindowController.familyCountText.stringValue()); // log.debug(familyListWindowController.window()); // log.debug( familyListWindowController.owner()); // familyListWindowController.window().makeKeyAndOrderFront(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void showIndividualList(Object sender) { /* IBAction */ log.debug("showIndividualList: " + sender); try { if (individualListWindowController == null) { individualListWindowController = new IndividualListController(individualList); } addWindowController(individualListWindowController); individualListWindowController.showWindow(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void showBugReportWindow(Object sender) { /* IBAction */ log.debug("showBugReportWindow: " + sender); if (bugReportWindow != null) { bugReportText.setString(""); bugReportWindow.makeKeyAndOrderFront(sender); } } public void transmitBugReport(Object sender) { /* IBAction */ log.debug("transmitBugReport: " + sender); log.info(System.getProperties().toString()); // These are the files to include in the ZIP file NSMutableArray filePaths = new NSMutableArray(); NSArray searchPaths = NSPathUtilities.searchPathForDirectoriesInDomains(NSPathUtilities.LibraryDirectory, NSPathUtilities.UserDomainMask, true); if (searchPaths.count() > 0) { String logFileDirectoryPath = NSPathUtilities.stringByAppendingPathComponent((String) searchPaths.objectAtIndex(0), "Logs"); log.debug("logFileDirectoryPath:"+logFileDirectoryPath); String logFileBasePath = NSPathUtilities.stringByAppendingPathComponent(logFileDirectoryPath, "maf.log"); log.debug("logFileBasePath:"+logFileBasePath); NSArray logFileExtensions = new NSArray(new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}); log.debug("logFileExtensions:"+logFileExtensions); String logFilePath = NSPathUtilities.stringByStandardizingPath(logFileBasePath); log.debug("logFilePath:"+logFilePath); if (new File(logFilePath).exists()) { log.debug(logFilePath+" exists!"); filePaths.addObject(logFilePath); } Enumeration extensions = logFileExtensions.objectEnumerator(); while (extensions.hasMoreElements()) { String extension = (String) extensions.nextElement(); logFilePath = NSPathUtilities.stringByStandardizingPath(NSPathUtilities.stringByAppendingPathExtension(logFileBasePath, extension)); log.debug("logFilePath:"+logFilePath); if (new File(logFilePath).exists()) { log.debug(logFilePath+" exists!"); filePaths.addObject(logFilePath); } } } if (bugReportFileCheckbox.state() == NSCell.OnState) { filePaths.addObject(NSPathUtilities.stringByAppendingPathComponent(fileName(),DEFAULT_XML_FILENAME)); } log.debug("filePaths:"+filePaths); String targetURL = "http://www.macpaf.org/submitbug.php"; PostMethod filePost = new PostMethod(targetURL); try { List parts = new ArrayList(); parts.add(new StringPart("message", bugReportText.string())); if (filePaths.count() > 0) { File targetFile = createZipFile(null, CocoaUtils.arrayAsList(filePaths));//new File("/Users/logan/Library/Logs/maf.log"); FilePart filePart = new FilePart("fileatt", targetFile); log.debug("Uploading " + targetFile.getName() + " to " + targetURL); parts.add(filePart); } Object[] srcArray = parts.toArray(); Part[] targetArray = new Part[srcArray.length]; System.arraycopy(srcArray, 0, targetArray, 0, srcArray.length); filePost.setRequestEntity(new MultipartRequestEntity(targetArray, filePost.getParams())); // HttpClient client = new HttpClient(); // int status = client.executeMethod(filePost); // filePost.addParameter(targetFile.getName(), targetFile); HttpClient client = new HttpClient(); client.setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { log.debug( "Upload complete, response=" + filePost.getResponseBodyAsString() ); } else { log.debug( "Upload failed, response=" + HttpStatus.getStatusText(status) ); } } catch (Exception ex) { log.debug("Error trasmitting bug report: " + ex.getMessage()); ex.printStackTrace(); showUserErrorMessage("Could not submit feedback.", "If you are not connected to the internet, please try again after connecting."); } finally { filePost.releaseConnection(); } bugReportWindow.close(); } private File createZipFile(String outFilename, Collection filenames) throws IOException { // Create a buffer for reading the files byte[] buf = new byte[1024]; if (StringUtils.isEmpty(outFilename)) { outFilename = NSPathUtilities.stringByAppendingPathComponent(NSPathUtilities.temporaryDirectory(),"maf"+DateUtils.makeFileTimestampString()+".zip"); } // try { // Create the ZIP file ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); // Compress the files for (Iterator iter = filenames.iterator(); iter.hasNext();) { String filename = (String) iter.next(); File file = new File(filename); // } // for (int i=0; i<filenames.length; i++) { if (file.exists()) { FileInputStream in = new FileInputStream(file); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(NSPathUtilities.lastPathComponent(filename))); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } else { log.warn("createZipFile could not find file: "+filename); } } // Complete the ZIP file out.close(); // } catch (IOException e) { // } return new File(outFilename); } public void forgetIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.forgetIndividual():"+sender); historyController.forgetIndividual(getPrimaryIndividual()); } public void recallIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.recallIndividual():"+sender); historyController.recallIndividual(((NSMenuItem) sender).tag()); } public void recallLastFoundIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.recallLastFoundIndividual():"+sender); historyController.recallLastFoundIndividual(); } public void recallLastSavedIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.recallLastSavedIndividual():"+sender); historyController.recallLastSavedIndividual(); } public void rememberIndividual(Individual individual) { /* IBAction */ log.debug("MyDocument.rememberIndividual():"+individual); historyController.rememberIndividual(getPrimaryIndividual()); } public boolean validateMenuItem(_NSObsoleteMenuItemProtocol menuItem) { if ("History".equals(menuItem.menu().title())) { log.debug("MyDocument.validateMenuItem():"+menuItem); log.debug("tag:"+menuItem.tag()); log.debug("action:"+menuItem.action().name()); log.debug("target:"+menuItem.target()); log.debug("representedObject:"+menuItem.representedObject()); log.debug("menu:"+menuItem.menu().title()); // log.debug("menu DELEGATE:"+menuItem.menu().delegate()); return historyController.validateMenuItem(menuItem); } else if (menuItemShouldBeInactiveWithUnknownIndividual(menuItem)) { // familyAsChildButton.setEnabled(false); return false; } else if (menuItemShouldBeInactiveWithUnknownFamily(menuItem)) { // familyAsChildButton.setEnabled(false); return false; } else { // familyAsChildButton.setEnabled(true); return super.validateMenuItem((NSMenuItem) menuItem); } } private boolean menuItemShouldBeInactiveWithUnknownIndividual(_NSObsoleteMenuItemProtocol menuItem) { NSArray menuItemsToDeactivate = new NSArray(new String[] { "Add Family As Spouse", "Add Family As Child", "Add Spouse", "Add Father", "Delete Individual" }); return menuItemsToDeactivate.containsObject(menuItem.title()) && getPrimaryIndividual() instanceof Individual.UnknownIndividual; } private boolean menuItemShouldBeInactiveWithUnknownFamily(_NSObsoleteMenuItemProtocol menuItem) { NSArray menuItemsToDeactivate = new NSArray(new String[] { "Delete Family", "Edit Family" }); return menuItemsToDeactivate.containsObject(menuItem.title()) && getCurrentFamily() instanceof Family.UnknownFamily; } /* (non-Javadoc) * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ public void update(Observable o, Object arg) { log.debug("MyDocument.update(): o="+o+" : arg="+arg); // The MAFDocumentJDOM has changed // @todo: do something here updateChangeCount(NSDocument.ChangeDone); if (familyListWindowController != null) { familyListWindowController.refreshData(); } if (individualListWindowController != null) { individualListWindowController.refreshData(); } refreshData(); } private void refreshData() { log.debug("MyDocument.refreshData() suppress:"+suppressUpdates); if (!suppressUpdates) { setPrimaryIndividual(getPrimaryIndividual()); childrenTable.reloadData(); spouseTable.reloadData(); tabFamilyListController.refreshData(); tabIndividualListController.refreshData(); } } public void startSuppressUpdates() { log.debug("MyDocument.startSuppressUpdates()"); NDC.push("suppressUpdates"); suppressUpdates = true; doc.startSuppressUpdates(); } public void endSuppressUpdates() { doc.endSuppressUpdates(); suppressUpdates = false; NDC.pop(); } public void cancelSheets(NSObject sender) { try { System.out.println("MyDocument.cancelSheets()"); NSSelector.invoke("cancel", NSObject.class, importController, sender); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * getMaf\Document */ public MafDocument getMafDocument() { return doc; } }
MAF/src/MyDocument.java
//MyDocument.java //MAF //Created by Logan Allred on Sun Dec 22 2002. //Copyright (c) 2002-2004 RedBugz Software. All rights reserved. import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.apple.cocoa.application.*; import com.apple.cocoa.foundation.*; import com.redbugz.maf.*; import com.redbugz.maf.jdom.MAFDocumentJDOM; import com.redbugz.maf.util.CocoaUtils; import com.redbugz.maf.util.DateUtils; import com.redbugz.maf.util.MultimediaUtils; import com.redbugz.maf.util.StringUtils; /** * @todo This document is getting too large. I need to subclass NSDocumentController and move * some of this functionality over there, as well as split up my MyDocument.nib file into * several smaller nib files. */ public class MyDocument extends NSDocument implements Observer { private static final Logger log = Logger.getLogger(MyDocument.class); // static initializer { log.debug("<><><> MyDocument static initializer. this="+this); // Tests.testBase64(); // Tests.testImageFiles(); // Tests.testTrimLeadingWhitespace(); log.debug("System property user.dir: "+System.getProperty("user.dir")); log.debug("System property user.home: "+System.getProperty("user.home")); //initDoc(); } public static final String GEDCOM_DOCUMENT_TYPE = "GEDCOM File (.ged)"; public static final String PAF21_DOCUMENT_TYPE = "PAF 2.1/2.3.1 File"; public static final String MAF_DOCUMENT_TYPE = "MAF File"; public static final String TEMPLEREADY_UPDATE_DOCUMENT_TYPE = "TempleReady Update File"; MafDocument doc;// = null;//new MAFDocumentJDOM(); // Maps the buttons to the individuals they represent protected NSMutableDictionary individualsButtonMap = new NSMutableDictionary(); // /** // * This is the main individual to whom apply all actions // */ // private Individual primaryIndividual = new Individual.UnknownIndividual(); // This was originally to check for the constructor getting called twice // public boolean firstconstr = true; // All of the outlets in the nib public NSWindow mainWindow; /* IBOutlet */ public NSWindow reportsWindow; /* IBOutlet */ public NSWindow individualEditWindow; /* IBOutlet */ public NSWindow familyEditWindow; /* IBOutlet */ public NSWindow taskProgressSheetWindow; /* IBOutlet */ public FamilyListController familyListWindowController; /* IBOutlet */ public IndividualListController individualListWindowController; /* IBOutlet */ public FamilyListController tabFamilyListController; /* IBOutlet */ public IndividualListController tabIndividualListController; /* IBOutlet */ public NSObject importController; /* IBOutlet */ public FamilyList familyList; /* IBOutlet */ public IndividualList individualList; /* IBOutlet */ public SurnameList surnameList; /* IBOutlet */ public LocationList locationList; /* IBOutlet */ public HistoryController historyController; /* IBOutlet */ public PedigreeViewController pedigreeViewController; /* IBOutlet */ public NSButton fatherButton; /* IBOutlet */ public NSButton individualButton; /* IBOutlet */ public NSButton individualFamilyButton; /* IBOutlet */ public NSButton maternalGrandfatherButton; /* IBOutlet */ public NSButton maternalGrandmotherButton; /* IBOutlet */ public NSButton motherButton; /* IBOutlet */ public NSButton paternalGrandfatherButton; /* IBOutlet */ public NSButton paternalGrandmotherButton; /* IBOutlet */ public NSButton spouseButton; /* IBOutlet */ public NSButton familyAsSpouseButton; /* IBOutlet */ public NSButton familyAsChildButton; /* IBOutlet */ public NSWindow noteWindow; /* IBOutlet */ public NSMatrix reportsRadio; /* IBOutlet */ public NSTableView childrenTable; /* IBOutlet */ public NSTableView spouseTable; /* IBOutlet */ public PedigreeView pedigreeView; /* IBOutlet */ public NSTabView mainTabView; /* IBOutlet */ public NSWindow bugReportWindow; /* IBOutlet */ public NSButton bugReportFileCheckbox; /* IBOutlet */ public NSTextView bugReportText; /* IBOutlet */ // public IndividualDetailController individualDetailController = new IndividualDetailController(); /* IBOutlet */ // public FamilyDetailController familyDetailController = new FamilyDetailController(); /* IBOutlet */ private NSView printableView; // used to suppress GUI updates while non-GUI updates are happening, for example during import private boolean suppressUpdates; // used to temporarily hold loaded data before import process begins private NSData importData; private NSFileWrapper fileWrapperToLoad; // private IndividualList startupIndividualList; // private FamilyList startupFamilyList; /** * This the internal name for the gedcom file in the .MAF file package */ private static final String DEFAULT_GEDCOM_FILENAME = "data.ged"; /** * This the internal name for the data xml file in the .MAF file package */ private static final String DEFAULT_XML_FILENAME = "data.xml"; private static final String TEMPLEREADY_UPDATE_EXTENSION = "oup"; public static final RuntimeException USER_CANCELLED_OPERATION_EXCEPTION = new RuntimeException("User Cancelled Operation"); /** * This method was originally started to avoid the bug that in Java-Cocoa applications, * constructors get called twice, so if you initialize anything in a constructor, it can get * nuked later by another constructor */ private void initDoc() { log.debug("MyDocument.initDoc()"); try { if (doc == null) { log.info("MyDocument.initDoc(): doc is null, making new doc"); doc = new MAFDocumentJDOM();//GdbiDocument(); } } catch (Exception e) { log.error("Exception: ", e); //To change body of catch statement use Options | File Templates. } } public MyDocument() { super(); log.info("MyDocument.MyDocument():"+this); initDoc(); } public MyDocument(String fileName, String fileType) { super(fileName, fileType); log.info("MyDocument.MyDocument(" + fileName + ", " + fileType + "):"+this); initDoc(); } // public void closeFamilyEditSheet(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); // NSApplication.sharedApplication().endSheet(familyEditWindow); // familyEditWindow.orderOut(this); // } // public void closeIndividualEditSheet(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); // } public void cancel(Object sender) { /* IBAction */ // NSApplication.sharedApplication().stopModal(); NSApplication.sharedApplication().endSheet(reportsWindow); reportsWindow.orderOut(sender); } public void openFamilyEditSheet(Object sender) { /* IBAction */ try { ( (NSWindowController) familyEditWindow.delegate()).setDocument(this); if (sender instanceof NSControl) { if ( ( (NSControl) sender).tag() == 1) { Family familyAsChild = getPrimaryIndividual().getFamilyAsChild(); ( (FamilyEditController) familyEditWindow.delegate()).setFamilyAsChild(familyAsChild); } else { Family familyAsSpouse = getCurrentFamily(); ( (FamilyEditController) familyEditWindow.delegate()).setFamily(familyAsSpouse); } } else if (sender instanceof NSValidatedUserInterfaceItem) { if ( ( (NSValidatedUserInterfaceItem) sender).tag() == 1) { Family familyAsChild = getPrimaryIndividual().getFamilyAsChild(); ( (FamilyEditController) familyEditWindow.delegate()).setFamilyAsChild(familyAsChild); } else { Family familyAsSpouse = getCurrentFamily(); ( (FamilyEditController) familyEditWindow.delegate()).setFamily(familyAsSpouse); } } NSApplication nsapp = NSApplication.sharedApplication(); nsapp.beginSheet(familyEditWindow, mainWindow, this, new NSSelector("sheetDidEndShouldClose2", new Class[] {}), null); // sheet is up here, control passes to the sheet controller } catch (RuntimeException e) { if (e != USER_CANCELLED_OPERATION_EXCEPTION) { e.printStackTrace(); MyDocument.showUserErrorMessage("An unexpected error occurred.", "Message: "+e.getMessage()); } } } public void deletePrimaryIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.deletePrimaryIndividual()"); String msg = "Are you sure you want to delete the individual named " + getPrimaryIndividual().getFullName() + "?"; String details = "This will delete this person from your file and remove them from any family relationships."; boolean shouldDelete = confirmCriticalActionMessage(msg, details, "Delete", "Cancel"); if (shouldDelete) { doc.removeIndividual(getPrimaryIndividual()); } setPrimaryIndividual(doc.getPrimaryIndividual()); } public void deletePrimaryFamily(Object sender) { /* IBAction */ log.debug("MyDocument.deletePrimaryFamily()"); String msg = "Are you sure you want to delete the family with parents " + getCurrentFamily().getFather().getFullName() + " and "+ getCurrentFamily().getMother().getFullName()+"?"; String details = "This will delete the relationship between the parents and children, but will leave the individual records."; boolean shouldDelete = confirmCriticalActionMessage(msg, details, "Delete", "Cancel"); if (shouldDelete) { doc.removeFamily(getCurrentFamily()); } } // private Individual getKnownPrimaryIndividual() { // Individual indi = getPrimaryIndividual(); // if (indi instanceof Individual.UnknownIndividual) { // indi = createAndInsertNewIndividual(); // } // return indi; // } public void sheetDidEndShouldClose2() { log.debug("sheetDidEndShouldClose2"); } public void openIndividualEditSheet(Object sender) { /* IBAction */ ( (NSWindowController) individualEditWindow.delegate()).setDocument(this); NSApplication nsapp = NSApplication.sharedApplication(); nsapp.beginSheet(individualEditWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); // sheet is up here, control passes to the sheet controller } public void sheetDidEnd(NSWindow sheet, int returnCode, Object contextInfo) { log.debug("Called did-end selector"); log.debug("sheetdidend contextInfo:"+contextInfo); try { refreshData(); save(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } sheet.orderOut(this); } public void editPrimaryIndividual(Object sender) { /* IBAction */ openIndividualEditSheet(sender); } public void editCurrentFamily(Object sender) { /* IBAction */ openFamilyEditSheet(sender); } public void printDocument(Object sender) { /* IBAction */ openReportsSheet(sender); } public void openReportsSheet(Object sender) { /* IBAction */ ( (NSWindowController) reportsWindow.delegate()).setDocument(this); // if (!myCustomSheet) // [NSBundle loadNibNamed: @"MyCustomSheet" owner: self]; NSApplication nsapp = NSApplication.sharedApplication(); log.debug("openReportsSheet mainWindow:" + mainWindow); // reportsWindow.makeKeyAndOrderFront(this); nsapp.beginSheet(reportsWindow, mainWindow, this, null, null); //nsapp.runModalForWindow(reportsWindow); //nsapp.endSheet(individualEditWindow); //individualEditWindow.orderOut(this); } public void setPrintableView(Object sender) { /* IBAction */ try { log.debug("setPrintableView selected=" + reportsRadio.selectedTag()); printInfo().setTopMargin(36); printInfo().setBottomMargin(36); printInfo().setLeftMargin(72); printInfo().setRightMargin(36); setPrintInfo(printInfo()); switch (reportsRadio.selectedTag()) { case 0: printableView = new PedigreeView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getPrimaryIndividual(), 4); break; case 1: printableView = new FamilyGroupSheetView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getCurrentFamily()); break; case 3: printableView = new PocketPedigreeView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getPrimaryIndividual(), 6); break; default: printableView = new PedigreeView(new NSRect(0, 0, printInfo().paperSize().width() - printInfo().leftMargin() - printInfo().rightMargin(), printInfo().paperSize().height() - printInfo().topMargin() - printInfo().bottomMargin()), getPrimaryIndividual(), 4); } // printableView = new PedigreeView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual(), 4); // printableView = new FamilyGroupSheetView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); // printableView = new IndividualSummaryView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); } catch (Exception e) { e.printStackTrace(); } } // public void saveFamily(Object sender) { /* IBAction */ //// save family info // closeFamilyEditSheet(sender); // } // public void saveIndividual(Object sender) { /* IBAction */ //// save individual info // closeIndividualEditSheet(sender); // } public Individual getPrimaryIndividual() { return doc.getPrimaryIndividual(); } public void setPrimaryIndividual(Individual newIndividual) { setPrimaryIndividualAndSpouse(newIndividual, newIndividual.getPreferredSpouse()); } public void setPrimaryIndividualAndSpouse(Individual individual, Individual spouse) { try { Family familyAsSpouse = MyDocument.getFamilyForSpouse(individual, spouse); doc.setPrimaryIndividual(individual); assignIndividualToButton(individual, individualButton); // if primary individual is unknown, change button back to enabled individualButton.setEnabled(true); assignIndividualToButton(spouse, spouseButton); assignIndividualToButton(individual.getFather(), fatherButton); assignIndividualToButton(individual.getMother(), motherButton); assignIndividualToButton(individual.getFather().getFather(), paternalGrandfatherButton); assignIndividualToButton(individual.getFather().getMother(), paternalGrandmotherButton); assignIndividualToButton(individual.getMother().getFather(), maternalGrandfatherButton); assignIndividualToButton(individual.getMother().getMother(), maternalGrandmotherButton); pedigreeViewController.setPrimaryIndividual(individual); // individualDetailController.setIndividual(individual); log.debug("famsp id:"+familyAsSpouse.getId()); log.debug("famch id:"+individual.getFamilyAsChild().getId()); familyAsSpouseButton.setTitle("Family: "+familyAsSpouse.getId()); familyAsChildButton.setTitle("Family: "+individual.getFamilyAsChild().getId()); spouseTable.selectRow(0, false); spouseTable.reloadData(); childrenTable.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Family getFamilyForSpouse(Individual individual, Individual spouse) { Family matchingFamily = Family.UNKNOWN_FAMILY; for (Iterator iter = individual.getFamiliesAsSpouse().iterator(); iter.hasNext();) { Family family = (Family) iter.next(); if (spouse.equals(family.getFather()) || spouse.equals(family.getMother())) { matchingFamily = family; } } return matchingFamily; } public void setIndividual(Object sender) { /* IBAction */ try { log.debug("setIndividual to " + sender); if (sender instanceof NSButton) { try { log.debug("individuals=" + individualsButtonMap.objectForKey(sender.toString())); Individual newIndividual = (Individual) individualsButtonMap.objectForKey(sender.toString()); if (newIndividual == null) { newIndividual = Individual.UNKNOWN; } NSButton animateButton = (NSButton) sender; NSPoint individualButtonOrigin = individualButton.frame().origin(); NSPoint animateButtonOrigin = animateButton.frame().origin(); log.debug("animating from " + animateButtonOrigin + " to " + individualButtonOrigin); if (!animateButtonOrigin.equals(individualButtonOrigin)) { float stepx = (individualButtonOrigin.x() - animateButtonOrigin.x()) / 10; float stepy = (individualButtonOrigin.y() - animateButtonOrigin.y()) / 10; NSImage image = new NSImage(); log.debug("animatebutton.bounds:" + animateButton.bounds()); animateButton.lockFocus(); image.addRepresentation(new NSBitmapImageRep(animateButton.bounds())); animateButton.unlockFocus(); NSImageView view = new NSImageView(animateButton.frame()); view.setImage(image); animateButton.superview().addSubview(view); for (int steps = 0; steps < 10; steps++) { animateButtonOrigin = new NSPoint(animateButtonOrigin.x() + stepx, animateButtonOrigin.y() + stepy); view.setFrameOrigin(animateButtonOrigin); view.display(); } view.removeFromSuperview(); animateButton.superview().setNeedsDisplay(true); } setPrimaryIndividual(newIndividual); } catch (Exception e) { log.error("Exception: ", e); } } else if (sender instanceof NSTableView) { NSTableView tv = (NSTableView) sender; NSView superview = individualButton.superview(); log.debug("tableview selectedRow = "+tv.selectedRow()); if (tv.selectedRow() >= 0) { log.debug("individualList=" + individualsButtonMap.objectForKey("child" + tv.selectedRow())); NSPoint individualButtonOrigin = individualButton.frame().origin(); Individual newIndividual = (Individual) individualsButtonMap.objectForKey("child" + tv.selectedRow()); if (tv.tag() == 2) { newIndividual = (Individual) individualsButtonMap.objectForKey("spouse" + tv.selectedRow()); individualButtonOrigin = spouseButton.frame().origin(); } NSRect rowRect = tv.convertRectToView(tv.rectOfRow(tv.selectedRow()), superview); NSPoint tvOrigin = rowRect.origin(); log.debug("animating from " + tvOrigin + " to " + individualButtonOrigin); float stepx = (individualButtonOrigin.x() - tvOrigin.x()) / 10; float stepy = (individualButtonOrigin.y() - tvOrigin.y()) / 10; NSImage image = new NSImage(); log.debug("rowrect:" + rowRect); superview.lockFocus(); image.addRepresentation(new NSBitmapImageRep(rowRect)); superview.unlockFocus(); NSImageView view = new NSImageView(rowRect); view.setImage(image); superview.addSubview(view); for (int steps = 0; steps < 10; steps++) { tvOrigin = new NSPoint(tvOrigin.x() + stepx, tvOrigin.y() + stepy); view.setFrameOrigin(tvOrigin); view.display(); } view.removeFromSuperview(); superview.setNeedsDisplay(true); if (tv.tag() == 2) { setCurrentSpouse(newIndividual); } else { setPrimaryIndividual(newIndividual); } } } else if (sender instanceof IndividualList) { IndividualList iList = (IndividualList) sender; setPrimaryIndividual(iList.getSelectedIndividual()); } else if (sender instanceof FamilyList) { FamilyList fList = (FamilyList) sender; setPrimaryIndividual(fList.getSelectedFamily().getFather()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String windowNibName() { return "MyDocument"; } public void showWindows() { log.debug("showWindows()"); super.showWindows(); log.debug("done with super show windows. Now loading document..."); try { log.debug("fileWrapperToLoad:"+fileWrapperToLoad); if (fileWrapperToLoad != null) { log.debug("posting loaddocumentdata notification..."); NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this, new NSDictionary(new Object[] {dataForFileWrapper(fileWrapperToLoad), doc}, new Object[] {"data", "doc"})); } // NSApplication.sharedApplication().beginSheet(taskProgressSheetWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); // // Thread.sleep(10000); // // NSApplication.sharedApplication().endSheet(taskProgressSheetWindow); // taskProgressSheetWindow.orderOut(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // called after the document finished loading the data or file wrapper for the document public void documentDidFinishLoading() { importData = null; fileWrapperToLoad = null; } public void windowControllerDidLoadNib(NSWindowController aController) { try { super.windowControllerDidLoadNib(aController); // Add any code here that need to be executed once the windowController has loaded the document's window. mainWindow = aController.window(); mainWindow.setToolbar(new MainToolbar()); log.debug("mainWindow:" + mainWindow); log.debug("indivEditWindow:" + individualEditWindow); //myAction(this); NSAttributedString text = individualButton.attributedTitle(); log.debug("indivButton attrTitle: " + text); // log.debug("indivButton attr at index 5:" + text.attributesAtIndex(5, null)); log.debug("individualList: " + individualsButtonMap.count() + "(" + individualsButtonMap + ")"); log.debug("individualList="+individualList); log.debug("individualList: " + individualList.size()); // + "(" + indiMap + ")"); individualList.document = this; familyList.document = this; // individualList.setIndividualMap(doc.getIndividualsMap()); // familyList.setFamilyMap(doc.getFamiliesMap()); if (individualList.size() > 0) { log.debug("individualList.size() > 0: "+individualList.size()); assignIndividualToButton( (Individual) individualList.getFirstIndividual(), individualButton); setIndividual(individualButton); } else { log.info("!!! Setting primary individual to UNKNOWN--No individuals in file:"+this); setPrimaryIndividual(Individual.UNKNOWN); } // add famMap to FamilyList // for (Iterator iter = famMap.values().iterator(); iter.hasNext(); ) { // Family fam = (Family) iter.next(); // familyList.add(fam); // } // NSImage testImage = new NSImage("/Users/logan/Pictures/iPhoto Library/Albums/Proposal/GQ.jpg", false); // testImage.setSize(new NSSize(50f, 50f)); // testImage.setScalesWhenResized(true); log.debug("indivButton cell type: " + individualButton.cell().type()); // individualButton.setImage(testImage); // save(); tabFamilyListController.setup(); tabFamilyListController.setDocument(this); tabIndividualListController.setup(); tabIndividualListController.setDocument(this); // register as an observer of the MAFDocumentJDOM doc.addObserver(this); NSNotificationCenter.defaultCenter().addObserver(importController, CocoaUtils.BEGIN_IMPORT_PROCESS_SELECTOR, CocoaUtils.BEGIN_IMPORT_PROCESS_NOTIFICATION, this); NSNotificationCenter.defaultCenter().addObserver(importController, CocoaUtils.IMPORT_DATA_SELECTOR, CocoaUtils.IMPORT_DATA_NOTIFICATION, this); NSNotificationCenter.defaultCenter().addObserver(importController, CocoaUtils.LOAD_DOCUMENT_SELECTOR, CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this); if (importData != null && importData.length() > 0) { NSRunLoop.currentRunLoop().performSelectorWithOrder(CocoaUtils.IMPORT_DATA_SELECTOR, importController, new NSNotification(CocoaUtils.IMPORT_DATA_NOTIFICATION, this, null), 0, new NSArray(NSRunLoop.DefaultRunLoopMode)); } if (false && fileWrapperToLoad != null) { // NSRunLoop.currentRunLoop().performSelectorWithOrder(CocoaUtils.LOAD_DOCUMENT_SELECTOR, importController, new NSNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this, null), 0, new NSArray(NSRunLoop.DefaultRunLoopMode)); log.debug("taskprogresswindow:"+taskProgressSheetWindow); NSApplication.sharedApplication().beginSheet(taskProgressSheetWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); NSFileWrapper nsFileWrapper = fileWrapperToLoad; log.debug("wrapper isDir:" + nsFileWrapper.isDirectory()); log.debug("attributes:" + nsFileWrapper.fileAttributes()); log.debug("filename: " + fileName() + " type:" + fileType()); log.debug("setFileAttr result=" + NSPathUtilities.setFileAttributes(fileName() + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer(NSHFSFileTypes.hfsTypeCodeFromFileType("TEXT")), NSPathUtilities.FileHFSTypeCode))); if (nsFileWrapper.isDirectory()) { log.debug("wrappers:" + nsFileWrapper.fileWrappers()); } // NSFileWrapper familiesPlist = (NSFileWrapper) // nsFileWrapper.fileWrappers().valueForKey("families.plist"); // log.error("start extract"); // families = (NSMutableDictionary) // NSPropertyListSerialization.propertyListFromData(familiesPlist.regularFileContents(), // NSPropertyListSerialization.PropertyListMutableContainersAndLeaves, // new int[]{NSPropertyListSerialization.PropertyListXMLFormat}, // errors); // log.error("end extract"); Enumeration en = nsFileWrapper.fileWrappers() .objectEnumerator(); while (en.hasMoreElements()) { NSFileWrapper wrapper = ((NSFileWrapper) en.nextElement()); log.debug(wrapper.filename() + " subattr:" + wrapper.fileAttributes()); if (NSPathUtilities.pathExtension(wrapper.filename()) .equalsIgnoreCase("ged")) { String fullPath = fileName() + "/" + wrapper.filename(); log.debug("..................Loading gedcom: " + fullPath); try { importGEDCOM(new File(fullPath)); } catch (RuntimeException e) { e.printStackTrace(); // return false; } // save individualList in a temporary so I can restore // it when the // Cocoa startup sequence calls the constructor twice // and clobbers it // startupIndividualList = individualList; } } } taskProgressSheetWindow.orderOut(this); //fileWrapperToLoad = null; // } } catch (Exception e) { log.error("Exception: ", e); //To change body of catch statement use Options | File Templates. } } // public boolean readFromFile(String filename, String aType) { // log.debug("********* readFromFile:" + filename + " ofType:"+aType); // // We will open GEDCOM file directly from Java File I/O, all others will pass up // // to readFileWrapper or loadDataRepresentation // // At some point, we may decide to have importGEDCOM just work on NSData as well // // instead of the File directly // try { // if (GEDCOM_DOCUMENT_TYPE.equals(aType)) { // // import GEDCOM into this file // boolean success = super.readFromFile(filename, aType); // if (success) { // importGEDCOM(new File(filename)); // setFileType(MACPAF_DOCUMENT_TYPE); // setFileName(null); // } // return success; // } else { // return super.readFromFile(filename, aType); // } // } // catch (Exception e) { // log.error("Exception: ", e); // return false; // } // } private NSData dataForFileWrapper(NSFileWrapper nsFileWrapper) { log.debug("MyDocument.dataForFileWrapper():"+nsFileWrapper); log.debug("wrapper isDir:" + nsFileWrapper.isDirectory()); log.debug("attributes:" + nsFileWrapper.fileAttributes()); log.debug("filename: " + fileName() + " type:" + fileType()); log.debug("setFileAttr result=" + NSPathUtilities.setFileAttributes(fileName() + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer(NSHFSFileTypes.hfsTypeCodeFromFileType("TEXT")), NSPathUtilities.FileHFSTypeCode))); if (nsFileWrapper.isDirectory()) { log.debug("wrappers:" + nsFileWrapper.fileWrappers()); } // NSFileWrapper familiesPlist = (NSFileWrapper) // nsFileWrapper.fileWrappers().valueForKey("families.plist"); // log.error("start extract"); // families = (NSMutableDictionary) // NSPropertyListSerialization.propertyListFromData(familiesPlist.regularFileContents(), // NSPropertyListSerialization.PropertyListMutableContainersAndLeaves, // new int[]{NSPropertyListSerialization.PropertyListXMLFormat}, // errors); // log.error("end extract"); Enumeration en = nsFileWrapper.fileWrappers().objectEnumerator(); while (en.hasMoreElements()) { NSFileWrapper wrapper = ((NSFileWrapper) en.nextElement()); log.debug(wrapper.filename() + " subattr:" + wrapper.fileAttributes()); if (NSPathUtilities.pathExtension(wrapper.filename()) .equalsIgnoreCase("ged")) { String fullPath = fileName() + "/" + wrapper.filename(); log.debug("..................Loading gedcom: " + fullPath); try { System.out.println("MyDocument.dataForFileWrapper() data:"+new NSData(new File(fullPath))); return new NSData(new File(fullPath)); } catch (RuntimeException e) { e.printStackTrace(); } // save individualList in a temporary so I can restore // it when the // Cocoa startup sequence calls the constructor twice // and clobbers it // startupIndividualList = individualList; } } return new NSData(); } public boolean loadFileWrapperRepresentation(NSFileWrapper nsFileWrapper, String aType) { log.info("MyDocument.loadFileWrapperRepresentation():" + nsFileWrapper + ":" + aType); try { // If this is not a MAF document, then pass it up to loadDataRepresentation for import. if (!MAF_DOCUMENT_TYPE.equals(aType)) { return super.loadFileWrapperRepresentation(nsFileWrapper, aType); } else { // Since MAF files are File Packages, we will load the various files here NDC.push(this.toString()); // NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this); fileWrapperToLoad = nsFileWrapper; if (true) return true; NSApplication.sharedApplication().beginSheet(taskProgressSheetWindow, mainWindow, this, CocoaUtils.SHEET_DID_END_SELECTOR, null); log.debug("wrapper isDir:" + nsFileWrapper.isDirectory()); log.debug("attributes:" + nsFileWrapper.fileAttributes()); log.debug("filename: " + fileName() + " type:" + fileType()); log.debug("setFileAttr result=" + NSPathUtilities.setFileAttributes(fileName() + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer(NSHFSFileTypes.hfsTypeCodeFromFileType("TEXT")), NSPathUtilities.FileHFSTypeCode))); if (nsFileWrapper.isDirectory()) { log.debug("wrappers:" + nsFileWrapper.fileWrappers()); } // NSFileWrapper familiesPlist = (NSFileWrapper) // nsFileWrapper.fileWrappers().valueForKey("families.plist"); // log.error("start extract"); // families = (NSMutableDictionary) // NSPropertyListSerialization.propertyListFromData(familiesPlist.regularFileContents(), // NSPropertyListSerialization.PropertyListMutableContainersAndLeaves, // new int[]{NSPropertyListSerialization.PropertyListXMLFormat}, // errors); // log.error("end extract"); Enumeration en = nsFileWrapper.fileWrappers() .objectEnumerator(); while (en.hasMoreElements()) { NSFileWrapper wrapper = ((NSFileWrapper) en.nextElement()); log.debug(wrapper.filename() + " subattr:" + wrapper.fileAttributes()); if (NSPathUtilities.pathExtension(wrapper.filename()) .equalsIgnoreCase("ged")) { String fullPath = fileName() + "/" + wrapper.filename(); log.debug("..................Loading gedcom: " + fullPath); try { importGEDCOM(new File(fullPath)); } catch (RuntimeException e) { e.printStackTrace(); return false; } // save individualList in a temporary so I can restore // it when the // Cocoa startup sequence calls the constructor twice // and clobbers it // startupIndividualList = individualList; } } } taskProgressSheetWindow.orderOut(this); return true; } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); } finally { NDC.pop(); } showUserErrorMessage( "There was a problem opening the file:\n" + nsFileWrapper.filename() + ".", "This is usually caused by a corrupt file. If the file is a GEDCOM file, it may not be the right version" + " or it may not conform to the GEDCOM 5.5 specification. If this is a MAF file, it is missing " + "some required data or the data has become corrupted. This can often be fixed by manually inspecting " + "the contents of the file. Please contact support to see if this can be fixed."); return false; } /* (non-Javadoc) * @see com.apple.cocoa.application.NSDocument#loadDataRepresentation(com.apple.cocoa.foundation.NSData, java.lang.String) */ public boolean loadDataRepresentation(NSData data, String aType) { log.info("MyDocument.loadDataRepresentation():<"+data.length() + " bytes>:"+aType); log.debug("MyDocument.loadDataRepresentation():filename:"+fileName()+" filetype:"+fileType()); try { if (GEDCOM_DOCUMENT_TYPE.equals(aType)) { // importGEDCOM(data); importData = data; } else if (PAF21_DOCUMENT_TYPE.equals(aType)) { // Insert code here to read your document from the given data. You can also choose to override -loadFileWrapperRepresentation:ofType: or -readFromFile:ofType: instead. log.debug(data.length()+", chunks "+(data.length()-512)/1024); // importPAF21(data); importData = data; } else if (TEMPLEREADY_UPDATE_DOCUMENT_TYPE.equals(aType)) { // importTempleReadyUpdate(data); importData = data; } else { // not sure what type of document this is, look at the data and see if we can find out // TODO look at the data to figure out the type showUserErrorMessage("Unable to load document", "Could not determine what type of document this is. Data may be corrupted or is a file that MAF cannot understand."); } // PAF21Data pafData = new PAF21Data(data); // [self setString: [[NSAttributedString alloc] initWithString:[pafData hexString:40] attributes:attrsDictionary]]; // pafData.importData(); // [textField setStringValue:[pafData hexString:40]]; // For applications targeted for Tiger or later systems, you should use the new Tiger API readFromData:ofType:error:. In this case you can also choose to override -readFromURL:ofType:error: or -readFromFileWrapper:ofType:error: instead. return true; } catch (RuntimeException e) { // TODO Auto-generated catch block log.error("Exception: ", e); e.printStackTrace(); } return super.loadDataRepresentation(data, aType); } public NSFileWrapper fileWrapperRepresentationOfType(String aType) { log.debug("MyDocument.fileWrapperRepresentationOfType:" + aType); try { if (MAF_DOCUMENT_TYPE.equals(aType)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baosGed = new ByteArrayOutputStream(); try { // out.output( // doc, // new FileWriter("/Projects/MAF/savetest.xml")); doc.outputToXML(baos); // doc.outputToXML(System.out); // XMLTest.outputWithKay( // doc, // new FileOutputStream("/Projects/MAF/savetest.ged")); doc.outputToGedcom(baosGed); // doc.outputToGedcom(System.out); } catch (IOException e) { log.error("Exception: ", e); } NSFileWrapper mainFile = new NSFileWrapper(new NSDictionary()); NSFileWrapper imagesFolder = new NSFileWrapper(new NSDictionary()); imagesFolder.setPreferredFilename("multimedia"); String images1 = mainFile.addFileWrapper(imagesFolder); // NSData data = new NSAttributedString("some data goes // here").RTFFromRange(new NSRange(0, 15), new NSDictionary()); // mainFile.addRegularFileWithContents(NSPropertyListSerialization.dataFromPropertyList(individuals), // "individuals.plist"); // for (int i=0; i< 10000; i++) { // families.takeValueForKey("familyvalue"+i, ""+i); // } // notes.takeValueForKey("notevalue", "notekey"); // log.debug("start serialize"); // String plist1 = // mainFile.addRegularFileWithContents(NSPropertyListSerialization.XMLDataFromPropertyList(families), // "families.plist"); // String plist2 = // mainFile.addRegularFileWithContents(NSPropertyListSerialization.XMLDataFromPropertyList(notes), // "notes.plist"); // log.debug("end serialize"); // String file1 = // imagesFolder.addFileWithPath( // "/Projects/MAF/macpaf-screenshot.png"); // String file2 = // imagesFolder.addFileWithPath( // "/Projects/MAF/macpaf-screenshot.tiff"); // String file3 = // imagesFolder.addFileWithPath( // "/Projects/MAF/macpaf-screenshot.jpg"); // String file4 = // imagesFolder.addFileWithPath( // "/Projects/Mcreenshot.gif"); String dataXmlFilename = DEFAULT_XML_FILENAME; String dataGedcomFilename = DEFAULT_GEDCOM_FILENAME; // if (fileName() != null && fileName().length() > 0) { // dataXmlFilename = fileName()+".xml"; // dataGedcomFilename = fileName()+".ged"; // } String xml1 = mainFile.addRegularFileWithContents( new NSData(baos.toByteArray()), dataXmlFilename); String ged1 = mainFile.addRegularFileWithContents( new NSData(baosGed.toByteArray()), dataGedcomFilename); log.debug("" // "file1=" // + file1 // + ", file2=" // + file2 // + ", file3=" // + file3 // + ", file4=" // + file4 + ", images1=" + images1 + ", xml1=" + xml1 + ", ged1=" + ged1); return mainFile; //super.fileWrapperRepresentationOfType(s); } // unknown file type log.error("fileWrapperRep unknown file type " + aType); return null; } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); return null; } } /** * @param string * @param string2 */ public static void showUserErrorMessage(String message, String details) { NSAlertPanel.runCriticalAlert(message, details, "OK", null, null); } /** * @param string * @param string2 */ public static boolean confirmCriticalActionMessage(String message, String details, String confirmActionText, String cancelActionText) { int result = NSAlertPanel.runCriticalAlert(message, details, confirmActionText, cancelActionText, null); return result == NSAlertPanel.DefaultReturn; } /* (non-Javadoc) * @see com.apple.cocoa.application.NSDocument#setFileName(java.lang.String) */ public void setFileName(String arg0) { try { super.setFileName(arg0); log.debug("super.setfilename() done." + arg0); log.debug("setfilename set file attrs result=" + NSPathUtilities.setFileAttributes(arg0 + "/" + DEFAULT_GEDCOM_FILENAME, new NSDictionary(new Integer( NSHFSFileTypes.hfsTypeCodeFromFileType("'TEXT'")), NSPathUtilities.FileHFSTypeCode))); // log.debug("setfilename " + arg0 + "/" + DEFAULT_GEDCOM_FILENAME + " attr aft:" + // NSPathUtilities.fileAttributes(arg0 + "/" + DEFAULT_GEDCOM_FILENAME, false)); } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); } } public void addFamily(Family newFamily) { try { doc.addFamily(newFamily); // TODO notification // if (familyListTableView != null) { // familyListTableView.reloadData(); // } } catch (Exception ex) { ex.printStackTrace(); } } public void addIndividual(Individual newIndividual) { try { doc.addIndividual(newIndividual); log.debug("added newIndividual with key: "+newIndividual.getId()+" newIndividual name: "+newIndividual.getFullName()); // TODO notification // if (individualListTableView != null) { // individualListTableView.reloadData(); // } } catch (Exception ex) { ex.printStackTrace(); /** @todo figure out what to do here */ } } // public NSData dataRepresentationOfType(String aType) { // // Insert code here to create and return the data for your document. // log.debug("MyDocument.dataRepresentationOfType():" + aType); // return new NSAttributedString("some data goes here").RTFFromRange(new NSRange(0, 15), new NSDictionary()); // } // public boolean loadDataRepresentation(NSData data, String aType) { // // Insert code here to read your document from the given data. // log.debug("MyDocument.loadDataRepresentation():" + aType); // log.debug("load data:" + aType + ":" + new NSStringReference(data, NSStringReference.ASCIIStringEncoding)); // return true; // } private void assignIndividualToButton(Individual indiv, NSButton button) { try { button.setObjectValue(indiv); NSAttributedString newLine = new NSAttributedString("\n"); NSMutableAttributedString nameText = new NSMutableAttributedString(indiv.getFullName()); button.setEnabled(true); if (indiv instanceof Individual.UnknownIndividual) { nameText = new NSMutableAttributedString("Unknown"); button.setEnabled(false); } NSMutableAttributedString birthdateText = new NSMutableAttributedString(""); NSMutableAttributedString birthplaceText = new NSMutableAttributedString(""); NSMutableAttributedString ordinancesText = makeOrdinanceString(indiv); if (indiv.getBirthEvent() != null) { birthdateText = new NSMutableAttributedString(indiv.getBirthEvent().getDateString()); if (indiv.getBirthEvent().getPlace() != null) { birthplaceText = new NSMutableAttributedString(indiv.getBirthEvent().getPlace().getFormatString()); } } NSMutableAttributedString text = nameText; text.appendAttributedString(newLine); text.appendAttributedString(birthdateText); text.appendAttributedString(newLine); text.appendAttributedString(birthplaceText); text.appendAttributedString(newLine); text.appendAttributedString(ordinancesText); button.setAttributedTitle(text); // URL imageURL = indiv.getImagePath(); // if (imageURL != null && imageURL.toString().length() > 0) { NSImage testImage = MultimediaUtils.makeImageFromMultimedia(indiv.getPreferredImage()); // log.debug("button image:"+testImage); if (!testImage.size().isEmpty()) { testImage.setSize(new NSSize(50f, 50f)); testImage.setScalesWhenResized(true); button.setImage(testImage); } // } individualsButtonMap.setObjectForKey(indiv, button.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private NSMutableAttributedString makeOrdinanceString(Individual individual) { NSMutableAttributedString ordinanceString = new NSMutableAttributedString("BEPSC"); if (individual.getLDSBaptism().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(0,1)); } if (individual.getLDSEndowment().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(1,1)); } if (individual.getLDSSealingToParents().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(2,1)); } if (individual.getPreferredFamilyAsSpouse().getPreferredSealingToSpouse().isCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(3,1)); } if (individual.childrensOrdinancesAreCompleted()) { ordinanceString.applyFontTraitsInRange(NSAttributedString.UnderlineStrikethroughMask, new NSRange(4,1)); } return ordinanceString; } public int numberOfRowsInTableView(NSTableView nsTableView) { try { log.debug("MyDocument.numberOfRowsInTableView():tag=" + nsTableView.tag()); if (nsTableView.tag() == 1) { if (getPrimaryIndividual().getPreferredFamilyAsSpouse() != null) { int numChildren = getCurrentFamily().getChildren().size(); log.debug("numberOfRowsInTableView children: " + numChildren); return numChildren; } } else if (nsTableView.tag() == 2) { int numSpouses = getPrimaryIndividual().getSpouseList().size(); log.debug("numberOfRowsInTableView spouses: " + numSpouses); return numSpouses; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } public Object tableViewObjectValueForLocation(NSTableView nsTableView, NSTableColumn nsTableColumn, int i) { try { // log.debug("nsTableColumn=" + nsTableColumn.identifier()+"; i="+i+"; tag="+nsTableView.tag()); if (nsTableView.tag() == 1) { if (nsTableColumn.identifier() != null && nsTableColumn.identifier().equals("num")) { nsTableColumn.setWidth(5.0f); return String.valueOf(i + 1); } Individual individual = (Individual) getCurrentFamily().getChildren().get(i); individualsButtonMap.setObjectForKey(individual, "child" + i); return individual.getFullName(); } else if (nsTableView.tag() == 2) { Individual individual = (Individual) getPrimaryIndividual().getSpouseList().get(i); individualsButtonMap.setObjectForKey(individual, "spouse" + i); return individual.getFullName(); } return "Unknown"; } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception: ", e); return "An Error Has Occurred"; } } // used to display row in bold if the child also has children public void tableViewWillDisplayCell(NSTableView aTableView, Object aCell, NSTableColumn aTableColumn, int rowIndex) { // log.debug("MyDocument.tableViewWillDisplayCell():"+aTableView.tag()+":"+aCell+":"+aTableColumn.headerCell().stringValue()+":"+rowIndex); // Thread.dumpStack(); try { if (aTableView.tag() == 1 ) { if (aCell instanceof NSCell) { NSCell cell = (NSCell) aCell; // log.debug("cell str val:"+cell.stringValue()); Individual child = (Individual) getCurrentFamily().getChildren().get(rowIndex); if (child.getPreferredFamilyAsSpouse().getChildren().size() > 0) { // log.debug("bolding child name:"+child.getFullName()); cell.setFont(NSFontManager.sharedFontManager().convertFontToHaveTrait(cell.font(), NSFontManager.BoldMask)); } else { // log.debug("unbolding child name:"+child.getFullName()); cell.setFont(NSFontManager.sharedFontManager().convertFontToNotHaveTrait(cell.font(), NSFontManager.BoldMask)); } } } } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Family getCurrentFamily() { Family result = getPrimaryIndividual().getPreferredFamilyAsSpouse(); List families = getPrimaryIndividual().getFamiliesAsSpouse(); if (getPrimaryIndividual().getSpouseList().size() > 0 && spouseTable.selectedRow() >= 0) { Individual selectedSpouse = (Individual) getPrimaryIndividual().getSpouseList().get(spouseTable.selectedRow()); for (Iterator iter = families.iterator(); iter.hasNext();) { Family family = (Family) iter.next(); if (family.getMother().getId().equals(selectedSpouse.getId()) || family.getFather().getId().equals(selectedSpouse.getId())) { result = family; } } } return result; } private void setCurrentSpouse(Individual spouse) { log.debug("MyDocument.setCurrentSpouse():"+spouse.getFullName()); assignIndividualToButton(spouse, spouseButton); familyAsSpouseButton.setTitle("Family: "+getCurrentFamily().getId()); childrenTable.reloadData(); } public void setCurrentFamily(Family family) { setPrimaryIndividual(family.getFather()); setCurrentSpouse(family.getMother()); } public void printShowingPrintPanel(boolean showPanels) { log.debug("printshowingprintpanel:" + showPanels); try { // Obtain a custom view that will be printed printInfo().setTopMargin(36); printInfo().setBottomMargin(36); printInfo().setLeftMargin(72); printInfo().setRightMargin(36); setPrintInfo(printInfo()); // NSView printView = printableView; // Construct the print operation and setup Print panel NSPrintOperation op = NSPrintOperation.printOperationWithView(printableView, printInfo()); log.debug("papersize: " + printInfo().paperSize()); log.debug("left margin: " + printInfo().leftMargin()); log.debug("right margin: " + printInfo().rightMargin()); log.debug("top margin: " + printInfo().topMargin()); log.debug("bottom margin: " + printInfo().bottomMargin()); op.setShowPanels(showPanels); if (showPanels) { // Add accessory view, if needed } // Run operation, which shows the Print panel if showPanels was YES runModalPrintOperation(op, null, null, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // private NSView printableView() { // return printableView; // return new PedigreeView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual(), 4); // return new FamilyGroupSheetView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); // return new IndividualSummaryView(new NSRect(0,0,printInfo().paperSize().width()-printInfo().leftMargin()-printInfo().rightMargin(),printInfo().paperSize().height()-printInfo().topMargin()-printInfo().bottomMargin()), getPrimaryIndividual()); // } /** * Saves this document to disk with all files in the file package */ public void save() { log.info("___||| save()"); long watch = System.currentTimeMillis(); // call the standard Cocoa save action saveDocument(this); log.debug("it took "+(System.currentTimeMillis()-watch)+" ms to save files"); // individualListWindowController.refreshData(); // familyListWindowController.refreshData(); log.debug("MyDocument.save() end ("+(System.currentTimeMillis()-watch)+" ms), filename=" + fileName()); } public void openImportSheet(Object sender) { /* IBAction */ log.debug("openImportSheet"); try { NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.BEGIN_IMPORT_PROCESS_NOTIFICATION, this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // public void importFile(Object sender) { /* IBAction */ // log.debug("importFile: " + sender); // try { // // NSApplication nsapp = NSApplication.sharedApplication(); // // nsapp.beginSheet(importSheet, mainWindow, this, null, null); // NSOpenPanel panel = NSOpenPanel.openPanel(); // //panther only? panel.setMessage("Please select a GEDCOM file to import into this MAF file."); // panel.beginSheetForDirectory(null, null, new NSArray(new Object[] {"GED"}), mainWindow, // this, // new NSSelector("openPanelDidEnd", new Class[] {NSOpenPanel.class, int.class, Object.class}), null); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } /** * @param sheet * @param returnCode * @param contextInfo */ // public void openPanelDidEnd(NSOpenPanel sheet, int returnCode, Object contextInfo) { // if (returnCode == NSPanel.OKButton) { // log.debug("import filenames:" + sheet.filenames()); // for (Enumeration enumerator = sheet.filenames().objectEnumerator(); enumerator.hasMoreElements();) { // String filename = (String) enumerator.nextElement(); // if (TEMPLEREADY_UPDATE_EXTENSION.equalsIgnoreCase(NSPathUtilities.pathExtension(sheet.filename()))) { // importTempleReadyUpdate(new NSData(new File(filename))); // } // importGEDCOM(new File(filename)); // } // } // } private void importMAF(NSFileWrapper importFile) { log.debug("MyDocument.importMAF():" + importFile); try { // doc.loadXMLFile(importFile); if (true) throw new RuntimeException("Importing from another MAF file not yet implemented"); if (getPrimaryIndividual().equals(Individual.UNKNOWN)) { // set first individual in imported file to primary individual setPrimaryIndividual(individualList.getSelectedIndividual()); } // individualListTableView.reloadData(); // familyListTableView.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); } } private void importTempleReadyUpdate(NSData data) { showUserErrorMessage("We're sorry, but we do not yet handle TempleReady Update Files", "This functionality will be added later. Look for a future update."); } // private void importGEDCOM(NSData data) { // log.debug("MyDocument.importGEDCOM():" + data.length()+" bytes"); // try { // doc.loadXMLData(data); // if (Individual.UNKNOWN.equals(getPrimaryIndividual()) && individualList != null) { // // set first individual in imported file to primary individual // setPrimaryIndividual(individualList.getSelectedIndividual()); // } //// individualListTableView.reloadData(); //// familyListTableView.reloadData(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); // } // } private void importGEDCOM(File importFile) { log.debug("MyDocument.importGEDCOM():" + importFile); try { doc.importGedcom(importFile, null); if (getPrimaryIndividual().equals(Individual.UNKNOWN)) { // set first individual in imported file to primary individual setPrimaryIndividual(individualList.getSelectedIndividual()); } // individualListTableView.reloadData(); // familyListTableView.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); } } private void importPAF21(NSData data) { log.debug("MyDocument.importPAF21():" + data); try { // invoke ObjC NSDictionary importParams = new NSDictionary(new Object[] {data, taskProgressSheetWindow}, new Object[] {"data", "progress"}); NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.IMPORT_DATA_NOTIFICATION, this, importParams); if (getPrimaryIndividual().equals(Individual.UNKNOWN)) { // set first individual in imported file to primary individual setPrimaryIndividual(individualList.getSelectedIndividual()); } // individualListTableView.reloadData(); // familyListTableView.reloadData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); showUserErrorMessage("There was an error importing the file.", "The file was not in a format that MAF could read. The file may be incorrect or corrupted. Please verify that the file is in the correct format, and then report this error to the developer if it persists."); } } public void exportFile(Object sender) { /* IBAction */ log.debug("exportFile: " + sender); try { // save(); NSSavePanel panel = NSSavePanel.savePanel(); // Jaguar-only code // panel.setCanSelectHiddenExtension(true); // panel.setExtensionHidden(false); //panther only? panel.setMessage("Choose the name and location for the exported GEDCOM file.\n\nThe file name should end with .ged"); // panel.setNameFieldLabel("Name Field Label:"); // panel.setPrompt("Prompt:"); panel.setRequiredFileType("ged"); // panel.setTitle("Title"); panel.beginSheetForDirectory(null, null, mainWindow, this, new NSSelector("savePanelDidEndReturnCode", new Class[] {NSSavePanel.class, int.class, Object.class}), null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void savePanelDidEndReturnCode(NSSavePanel sheet, int returnCode, Object contextInfo) { log.debug("MyDocument.savePanelDidEndReturnCode(sheet, returnCode, contextInfo):" + sheet + ":" + returnCode + ":" + contextInfo); if (returnCode == NSPanel.OKButton) { log.debug("export filename:" + sheet.filename()); try { // bring up selection window to choose what to export if (contextInfo.toString().indexOf("oup") > 0) { doc.outputToTempleReady(new FileOutputStream(sheet.filename())); } doc.outputToGedcom(new FileOutputStream(sheet.filename())); } catch (Exception e) { log.error("Exception: ", e); //To change body of catch statement use Options | File Templates. } } else if (returnCode == NSPanel.CancelButton) { log.debug("save panel cancelled, sheet filename=" + sheet.filename() + ", doc filename=" + fileName()); if (fileName() == null || fileName().length() == 0) { log.debug("cancel with null filename, should I close the document?"); // close(); } } } public void windowDidBecomeMain(NSNotification aNotification) { log.debug("MyDocument.windowDidBecomeMain()"); if (!isLoadingDocument()) { save(); } } private boolean isLoadingDocument() { // TODO Auto-generated method stub return fileWrapperToLoad != null || importData != null; } public Individual createAndInsertNewIndividual() { return doc.createAndInsertNewIndividual();//new IndividualJDOM(doc); } public Family createAndInsertNewFamily() { return doc.createAndInsertNewFamily();//new IndividualJDOM(doc); } public Note createAndInsertNewNote() { log.debug("MyDocument.createAndInsertNewNote()"); return doc.createAndInsertNewNote(); } /** * prepareSavePanel * * @param nSSavePanel NSSavePanel * @return boolean * @todo Implement this com.apple.cocoa.application.NSDocument method */ public boolean prepareSavePanel(NSSavePanel nSSavePanel) { log.debug("MyDocument.prepareSavePanel(nSSavePanel):" + nSSavePanel); nSSavePanel.setDelegate(this); return true; } public boolean panelIsValidFilename(Object sender, String filename) { log.debug("MyDocument.panelIsValidFilename(sender, filename):" + sender + ":" + filename); return true; } public void addNewIndividual(Object sender) { /* IBAction */ log.debug("addNewIndividual: " + sender); try { Individual newIndividual = createAndInsertNewIndividual(); // addIndividual(newIndividual); setPrimaryIndividual(newIndividual); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewChild(Object sender) { /* IBAction */ log.debug("addNewChild: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); Family familyAsSpouse = primaryIndividual.getPreferredFamilyAsSpouse(); if (familyAsSpouse instanceof Family.UnknownFamily) { familyAsSpouse = createAndInsertNewFamily(); if (Gender.MALE.equals(primaryIndividual.getGender())) { familyAsSpouse.setFather(primaryIndividual); } else { familyAsSpouse.setMother(primaryIndividual); } primaryIndividual.setFamilyAsSpouse(familyAsSpouse); } Individual newChild = createAndInsertNewIndividual(); familyAsSpouse.addChild(newChild); newChild.setFamilyAsChild(familyAsSpouse); setPrimaryIndividual(newChild); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewSpouse(Object sender) { /* IBAction */ log.debug("addNewSpouse: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); boolean isMale = Gender.MALE.equals(primaryIndividual.getGender()); Family familyAsSpouse = primaryIndividual.getPreferredFamilyAsSpouse(); if (familyAsSpouse instanceof Family.UnknownFamily) { familyAsSpouse = createAndInsertNewFamily(); if (isMale) { familyAsSpouse.setFather(primaryIndividual); } else { familyAsSpouse.setMother(primaryIndividual); } primaryIndividual.setFamilyAsSpouse(familyAsSpouse); } Individual newSpouse = createAndInsertNewIndividual(); primaryIndividual.addSpouse(newSpouse); newSpouse.addSpouse(primaryIndividual); setPrimaryIndividual(newSpouse); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFather(Object sender) { /* IBAction */ log.debug("addNewFather: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); Family familyAsChild = primaryIndividual.getFamilyAsChild(); if (familyAsChild instanceof Family.UnknownFamily) { familyAsChild = createAndInsertNewFamily(); familyAsChild.addChild(primaryIndividual); primaryIndividual.setFamilyAsChild(familyAsChild); } Individual newFather = createAndInsertNewIndividual(); newFather.setGender(Gender.MALE); newFather.setSurname(primaryIndividual.getSurname()); newFather.setFamilyAsSpouse(familyAsChild); familyAsChild.setFather(newFather); setPrimaryIndividual(newFather); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewMother(Object sender) { /* IBAction */ log.debug("addNewMother: " + sender); try { Individual primaryIndividual = getPrimaryIndividual(); Family familyAsChild = primaryIndividual.getFamilyAsChild(); if (familyAsChild instanceof Family.UnknownFamily) { familyAsChild = createAndInsertNewFamily(); familyAsChild.addChild(primaryIndividual); primaryIndividual.setFamilyAsChild(familyAsChild); } Individual newMother = createAndInsertNewIndividual(); newMother.setGender(Gender.FEMALE); newMother.setFamilyAsSpouse(familyAsChild); familyAsChild.setMother(newMother); setPrimaryIndividual(newMother); save(); openIndividualEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFamily(Object sender) { /* IBAction */ log.debug("addNewFamily: " + sender); try { // I think the family edit sheet takes care of creating a new family // Family newFamily = createAndInsertNewFamily(); // save(); openFamilyEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFamilyAsSpouse(Object sender) { /* IBAction */ log.debug("addNewFamilyAsSpouse: " + sender); try { Family newFamily = createAndInsertNewFamily(); Individual primaryIndividual = getPrimaryIndividual(); primaryIndividual.setFamilyAsSpouse(newFamily); if (Gender.MALE.equals(primaryIndividual.getGender())) { newFamily.setFather(primaryIndividual); } else { newFamily.setMother(primaryIndividual); } save(); openFamilyEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addNewFamilyAsChild(Object sender) { /* IBAction */ log.debug("addNewFamilyAsChild: " + sender); try { Family newFamily = createAndInsertNewFamily(); Individual primaryIndividual = getPrimaryIndividual(); primaryIndividual.setFamilyAsChild(newFamily); newFamily.addChild(primaryIndividual); save(); openFamilyEditSheet(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void displayFamilyView(Object sender) { /* IBAction */ mainTabView.selectFirstTabViewItem(sender); } public void displayPedigreeView(Object sender) { /* IBAction */ mainTabView.selectTabViewItemAtIndex(1); } public void displayIndividualListView(Object sender) { /* IBAction */ mainTabView.selectTabViewItemAtIndex(2); } public void displayFamilyListView(Object sender) { /* IBAction */ mainTabView.selectLastTabViewItem(sender); } public void showFamilyList(Object sender) { /* IBAction */ log.debug("showFamilyList: " + sender); try { if (familyListWindowController == null) { familyListWindowController = new FamilyListController(familyList); } addWindowController(familyListWindowController); familyListWindowController.showWindow(this); // log.debug(familyListWindowController.familyCountText.stringValue()); // log.debug(familyListWindowController.window()); // log.debug( familyListWindowController.owner()); // familyListWindowController.window().makeKeyAndOrderFront(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void showIndividualList(Object sender) { /* IBAction */ log.debug("showIndividualList: " + sender); try { if (individualListWindowController == null) { individualListWindowController = new IndividualListController(individualList); } addWindowController(individualListWindowController); individualListWindowController.showWindow(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void showBugReportWindow(Object sender) { /* IBAction */ log.debug("showBugReportWindow: " + sender); if (bugReportWindow != null) { bugReportText.setString(""); bugReportWindow.makeKeyAndOrderFront(sender); } } public void transmitBugReport(Object sender) { /* IBAction */ log.debug("transmitBugReport: " + sender); log.info(System.getProperties().toString()); // These are the files to include in the ZIP file NSMutableArray filePaths = new NSMutableArray(); NSArray searchPaths = NSPathUtilities.searchPathForDirectoriesInDomains(NSPathUtilities.LibraryDirectory, NSPathUtilities.UserDomainMask, true); if (searchPaths.count() > 0) { String logFileDirectoryPath = NSPathUtilities.stringByAppendingPathComponent((String) searchPaths.objectAtIndex(0), "Logs"); log.debug("logFileDirectoryPath:"+logFileDirectoryPath); String logFileBasePath = NSPathUtilities.stringByAppendingPathComponent(logFileDirectoryPath, "maf.log"); log.debug("logFileBasePath:"+logFileBasePath); NSArray logFileExtensions = new NSArray(new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}); log.debug("logFileExtensions:"+logFileExtensions); String logFilePath = NSPathUtilities.stringByStandardizingPath(logFileBasePath); log.debug("logFilePath:"+logFilePath); if (new File(logFilePath).exists()) { log.debug(logFilePath+" exists!"); filePaths.addObject(logFilePath); } Enumeration extensions = logFileExtensions.objectEnumerator(); while (extensions.hasMoreElements()) { String extension = (String) extensions.nextElement(); logFilePath = NSPathUtilities.stringByStandardizingPath(NSPathUtilities.stringByAppendingPathExtension(logFileBasePath, extension)); log.debug("logFilePath:"+logFilePath); if (new File(logFilePath).exists()) { log.debug(logFilePath+" exists!"); filePaths.addObject(logFilePath); } } } if (bugReportFileCheckbox.state() == NSCell.OnState) { filePaths.addObject(NSPathUtilities.stringByAppendingPathComponent(fileName(),DEFAULT_XML_FILENAME)); } log.debug("filePaths:"+filePaths); String targetURL = "http://www.macpaf.org/submitbug.php"; PostMethod filePost = new PostMethod(targetURL); try { List parts = new ArrayList(); parts.add(new StringPart("message", bugReportText.string())); if (filePaths.count() > 0) { File targetFile = createZipFile(null, CocoaUtils.arrayAsList(filePaths));//new File("/Users/logan/Library/Logs/maf.log"); FilePart filePart = new FilePart("fileatt", targetFile); log.debug("Uploading " + targetFile.getName() + " to " + targetURL); parts.add(filePart); } Object[] srcArray = parts.toArray(); Part[] targetArray = new Part[srcArray.length]; System.arraycopy(srcArray, 0, targetArray, 0, srcArray.length); filePost.setRequestEntity(new MultipartRequestEntity(targetArray, filePost.getParams())); // HttpClient client = new HttpClient(); // int status = client.executeMethod(filePost); // filePost.addParameter(targetFile.getName(), targetFile); HttpClient client = new HttpClient(); client.setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { log.debug( "Upload complete, response=" + filePost.getResponseBodyAsString() ); } else { log.debug( "Upload failed, response=" + HttpStatus.getStatusText(status) ); } } catch (Exception ex) { log.debug("Error trasmitting bug report: " + ex.getMessage()); ex.printStackTrace(); showUserErrorMessage("Could not submit feedback.", "If you are not connected to the internet, please try again after connecting."); } finally { filePost.releaseConnection(); } bugReportWindow.close(); } private File createZipFile(String outFilename, Collection filenames) throws IOException { // Create a buffer for reading the files byte[] buf = new byte[1024]; if (StringUtils.isEmpty(outFilename)) { outFilename = NSPathUtilities.stringByAppendingPathComponent(NSPathUtilities.temporaryDirectory(),"maf"+DateUtils.makeFileTimestampString()+".zip"); } // try { // Create the ZIP file ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); // Compress the files for (Iterator iter = filenames.iterator(); iter.hasNext();) { String filename = (String) iter.next(); File file = new File(filename); // } // for (int i=0; i<filenames.length; i++) { if (file.exists()) { FileInputStream in = new FileInputStream(file); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(NSPathUtilities.lastPathComponent(filename))); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } else { log.warn("createZipFile could not find file: "+filename); } } // Complete the ZIP file out.close(); // } catch (IOException e) { // } return new File(outFilename); } public void forgetIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.forgetIndividual():"+sender); historyController.forgetIndividual(getPrimaryIndividual()); } public void recallIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.recallIndividual():"+sender); historyController.recallIndividual(((NSMenuItem) sender).tag()); } public void recallLastFoundIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.recallLastFoundIndividual():"+sender); historyController.recallLastFoundIndividual(); } public void recallLastSavedIndividual(Object sender) { /* IBAction */ log.debug("MyDocument.recallLastSavedIndividual():"+sender); historyController.recallLastSavedIndividual(); } public void rememberIndividual(Individual individual) { /* IBAction */ log.debug("MyDocument.rememberIndividual():"+individual); historyController.rememberIndividual(getPrimaryIndividual()); } public boolean validateMenuItem(_NSObsoleteMenuItemProtocol menuItem) { if ("History".equals(menuItem.menu().title())) { log.debug("MyDocument.validateMenuItem():"+menuItem); log.debug("tag:"+menuItem.tag()); log.debug("action:"+menuItem.action().name()); log.debug("target:"+menuItem.target()); log.debug("representedObject:"+menuItem.representedObject()); log.debug("menu:"+menuItem.menu().title()); // log.debug("menu DELEGATE:"+menuItem.menu().delegate()); return historyController.validateMenuItem(menuItem); } else if (menuItemShouldBeInactiveWithUnknownIndividual(menuItem)) { // familyAsChildButton.setEnabled(false); return false; } else if (menuItemShouldBeInactiveWithUnknownFamily(menuItem)) { // familyAsChildButton.setEnabled(false); return false; } else { // familyAsChildButton.setEnabled(true); return super.validateMenuItem((NSMenuItem) menuItem); } } private boolean menuItemShouldBeInactiveWithUnknownIndividual(_NSObsoleteMenuItemProtocol menuItem) { NSArray menuItemsToDeactivate = new NSArray(new String[] { "Add Family As Spouse", "Add Family As Child", "Add Spouse", "Add Father", "Delete Individual" }); return menuItemsToDeactivate.containsObject(menuItem.title()) && getPrimaryIndividual() instanceof Individual.UnknownIndividual; } private boolean menuItemShouldBeInactiveWithUnknownFamily(_NSObsoleteMenuItemProtocol menuItem) { NSArray menuItemsToDeactivate = new NSArray(new String[] { "Delete Family", "Edit Family" }); return menuItemsToDeactivate.containsObject(menuItem.title()) && getCurrentFamily() instanceof Family.UnknownFamily; } /* (non-Javadoc) * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ public void update(Observable o, Object arg) { log.debug("MyDocument.update(): o="+o+" : arg="+arg); // The MAFDocumentJDOM has changed // @todo: do something here updateChangeCount(NSDocument.ChangeDone); if (familyListWindowController != null) { familyListWindowController.refreshData(); } if (individualListWindowController != null) { individualListWindowController.refreshData(); } refreshData(); } private void refreshData() { log.debug("MyDocument.refreshData() suppress:"+suppressUpdates); if (!suppressUpdates) { setPrimaryIndividual(getPrimaryIndividual()); childrenTable.reloadData(); spouseTable.reloadData(); tabFamilyListController.refreshData(); tabIndividualListController.refreshData(); } } public void startSuppressUpdates() { log.debug("MyDocument.startSuppressUpdates()"); NDC.push("suppressUpdates"); suppressUpdates = true; doc.startSuppressUpdates(); } public void endSuppressUpdates() { doc.endSuppressUpdates(); suppressUpdates = false; NDC.pop(); } public void cancelSheets(NSObject sender) { try { System.out.println("MyDocument.cancelSheets()"); NSSelector.invoke("cancel", NSObject.class, importController, sender); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * getMaf\Document */ public MafDocument getMafDocument() { return doc; } }
fix problem where not suppressing updates during initial file loading git-svn-id: 905cbd6d4c038cf348b718896e036a05930cc957@139 2a4b192d-170f-0410-9940-9fa4d9b264c7
MAF/src/MyDocument.java
fix problem where not suppressing updates during initial file loading
<ide><path>AF/src/MyDocument.java <ide> log.debug("fileWrapperToLoad:"+fileWrapperToLoad); <ide> if (fileWrapperToLoad != null) { <ide> log.debug("posting loaddocumentdata notification..."); <add> startSuppressUpdates(); <ide> NSNotificationCenter.defaultCenter().postNotification(CocoaUtils.LOAD_DOCUMENT_NOTIFICATION, this, new NSDictionary(new Object[] {dataForFileWrapper(fileWrapperToLoad), doc}, new Object[] {"data", "doc"})); <ide> } <ide> <ide> public void documentDidFinishLoading() { <ide> importData = null; <ide> fileWrapperToLoad = null; <add> endSuppressUpdates(); <ide> } <ide> <ide> public void windowControllerDidLoadNib(NSWindowController aController) {
Java
apache-2.0
error: pathspec 'src/test/java/com/googlesource/gerrit/plugins/x-docs/AsciidoctorFormatterTest.java' did not match any file(s) known to git
a9d392f12b93757f41afc84ee3c54a1a15698d32
1
GerritCodeReview/plugins_x-docs,GerritCodeReview/plugins_x-docs
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.xdocs.formatter; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; import com.googlesource.gerrit.plugins.xdocs.ConfigSection; import java.io.File; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.easymock.IAnswer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class AsciidoctorFormatterTest { private ConfigSection cfg; private AsciidoctorFormatter formatter; @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Before public void setUp() throws IOException { FormatterUtil util = createNiceMock(FormatterUtil.class); // To simplify things, make applyCss() a no-op and return the HTML code as-is. expect(util.applyCss(anyString(), anyString(), anyString())).andAnswer( new IAnswer<String>() { @Override public String answer() throws Throwable { // The first argument is the HTML code. return (String) getCurrentArguments()[0]; } } ); replay(util); cfg = createNiceMock(ConfigSection.class); // Do not expect any behavior from the ConfigSection itself. replay(cfg); Formatters formatters = createNiceMock(Formatters.class); // Avoid a NPE by just returning the ConfigSection mock object. expect(formatters.getFormatterConfig(anyString(), anyString())).andReturn(cfg); replay(formatters); formatter = new AsciidoctorFormatter(tmp.newFolder(), util, formatters); } @Test public void basicTextFormattingWorks() throws IOException { String raw = "_italic_ *bold* `monospace`"; String formatted = "<em>italic</em> <strong>bold</strong> <code>monospace</code>"; assertEquals(StringUtils.countMatches(formatter.format(null, null, null, null, cfg, raw), formatted), 1); } }
src/test/java/com/googlesource/gerrit/plugins/x-docs/AsciidoctorFormatterTest.java
Add a unit test for the AsciidoctorFormatter Change-Id: Iceff1d61512b9489e3a0a2bee9e3c5b208635853
src/test/java/com/googlesource/gerrit/plugins/x-docs/AsciidoctorFormatterTest.java
Add a unit test for the AsciidoctorFormatter
<ide><path>rc/test/java/com/googlesource/gerrit/plugins/x-docs/AsciidoctorFormatterTest.java <add>// Copyright (C) 2016 The Android Open Source Project <add>// <add>// Licensed under the Apache License, Version 2.0 (the "License"); <add>// you may not use this file except in compliance with the License. <add>// You may obtain a copy of the License at <add>// <add>// http://www.apache.org/licenses/LICENSE-2.0 <add>// <add>// Unless required by applicable law or agreed to in writing, software <add>// distributed under the License is distributed on an "AS IS" BASIS, <add>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add>// See the License for the specific language governing permissions and <add>// limitations under the License. <add> <add>package com.googlesource.gerrit.plugins.xdocs.formatter; <add> <add>import static org.easymock.EasyMock.*; <add>import static org.junit.Assert.assertEquals; <add> <add>import com.googlesource.gerrit.plugins.xdocs.ConfigSection; <add> <add>import java.io.File; <add>import java.io.IOException; <add> <add>import org.apache.commons.lang.StringUtils; <add>import org.easymock.IAnswer; <add>import org.junit.Before; <add>import org.junit.Rule; <add>import org.junit.Test; <add>import org.junit.rules.TemporaryFolder; <add> <add>public class AsciidoctorFormatterTest { <add> <add> private ConfigSection cfg; <add> private AsciidoctorFormatter formatter; <add> <add> @Rule <add> public TemporaryFolder tmp = new TemporaryFolder(); <add> <add> @Before <add> public void setUp() throws IOException { <add> FormatterUtil util = createNiceMock(FormatterUtil.class); <add> <add> // To simplify things, make applyCss() a no-op and return the HTML code as-is. <add> expect(util.applyCss(anyString(), anyString(), anyString())).andAnswer( <add> new IAnswer<String>() { <add> @Override <add> public String answer() throws Throwable { <add> // The first argument is the HTML code. <add> return (String) getCurrentArguments()[0]; <add> } <add> } <add> ); <add> <add> replay(util); <add> <add> cfg = createNiceMock(ConfigSection.class); <add> <add> // Do not expect any behavior from the ConfigSection itself. <add> replay(cfg); <add> <add> Formatters formatters = createNiceMock(Formatters.class); <add> <add> // Avoid a NPE by just returning the ConfigSection mock object. <add> expect(formatters.getFormatterConfig(anyString(), anyString())).andReturn(cfg); <add> <add> replay(formatters); <add> <add> formatter = new AsciidoctorFormatter(tmp.newFolder(), util, formatters); <add> } <add> <add> @Test <add> public void basicTextFormattingWorks() throws IOException { <add> String raw = "_italic_ *bold* `monospace`"; <add> String formatted = "<em>italic</em> <strong>bold</strong> <code>monospace</code>"; <add> assertEquals(StringUtils.countMatches(formatter.format(null, null, null, null, cfg, raw), formatted), 1); <add> } <add>}
Java
apache-2.0
d12db835288de323f00ef7010655aba3f81d3da4
0
zion64/spring-ldap,rwinch/spring-ldap,vitorgv/spring-ldap,fzilic/spring-ldap,zion64/spring-ldap,rwinch/spring-ldap,zion64/spring-ldap,eddumelendez/spring-ldap,ChunPIG/spring-ldap,eddumelendez/spring-ldap,spring-projects/spring-ldap,wilkinsona/spring-ldap,vitorgv/spring-ldap,jaune162/spring-ldap,wilkinsona/spring-ldap,rwinch/spring-ldap,wilkinsona/spring-ldap,likaiwalkman/spring-ldap,jaune162/spring-ldap,likaiwalkman/spring-ldap,n8rogers/spring-ldap,rwinch/spring-ldap,eddumelendez/spring-ldap,spring-projects/spring-ldap,wilkinsona/spring-ldap,likaiwalkman/spring-ldap,zion64/spring-ldap,ChunPIG/spring-ldap,thomasdarimont/spring-ldap,thomasdarimont/spring-ldap,ChunPIG/spring-ldap,zion64/spring-ldap,eddumelendez/spring-ldap,thomasdarimont/spring-ldap,jaune162/spring-ldap,spring-projects/spring-ldap,n8rogers/spring-ldap,likaiwalkman/spring-ldap,n8rogers/spring-ldap,jaune162/spring-ldap,vitorgv/spring-ldap,thomasdarimont/spring-ldap,wilkinsona/spring-ldap,fzilic/spring-ldap,rwinch/spring-ldap,n8rogers/spring-ldap,spring-projects/spring-ldap,ChunPIG/spring-ldap,jaune162/spring-ldap,ChunPIG/spring-ldap,fzilic/spring-ldap,likaiwalkman/spring-ldap,n8rogers/spring-ldap,likaiwalkman/spring-ldap,vitorgv/spring-ldap,n8rogers/spring-ldap,spring-projects/spring-ldap,eddumelendez/spring-ldap,fzilic/spring-ldap,fzilic/spring-ldap,fzilic/spring-ldap,thomasdarimont/spring-ldap,jaune162/spring-ldap,vitorgv/spring-ldap,rwinch/spring-ldap,thomasdarimont/spring-ldap,eddumelendez/spring-ldap,ChunPIG/spring-ldap
/* * Copyright 2005-2007 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.ldap.core; import java.util.ArrayList; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.ldap.support.LdapUtils; /** * Adapter that implements the interesting methods of the DirContext interface. * In particular it contains utility methods for getting and setting attributes. * Using the * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory} in your * <code>ContextSource</code> (which is the default) you will receive * instances of this class from searches and lookups. This can be particularly * useful when updating data, since this class implements * {@link AttributeModificationsAware}, providing a * {@link #getModificationItems()} method. When in update mode, an object of * this class keeps track of the changes made to its attributes, making them * available as an array of <code>ModificationItem</code> objects, suitable as * input to {@link LdapTemplate#modifyAttributes(DirContextOperations)}. * * @see #setAttributeValue(String, Object) * @see #setAttributeValues(String, Object[]) * @see #getStringAttribute(String) * @see #getStringAttributes(String) * @see #getObjectAttribute(String) * @see #addAttributeValue(String, Object) * @see #removeAttributeValue(String, Object) * @see #setUpdateMode(boolean) * @see #isUpdateMode() * * @author Magnus Robertsson * @author Andreas Ronge * @author Adam Skogman * @author Mattias Arthursson */ public class DirContextAdapter implements DirContextOperations { private static final boolean ORDER_DOESNT_MATTER = false; private static Log log = LogFactory.getLog(DirContextAdapter.class); private final Attributes originalAttrs; private DistinguishedName dn; private DistinguishedName base; private boolean updateMode = false; private Attributes updatedAttrs; /** * Default constructor. */ public DirContextAdapter() { this(null, null, null); } /** * Create a new adapter from the supplied dn. * * @param dn * the dn. */ public DirContextAdapter(Name dn) { this(null, dn); } /** * Create a new adapter from the supplied attributes and dn. * * @param originalAttrs * the attributes. * @param dn * the dn. */ public DirContextAdapter(Attributes attrs, Name dn) { this(attrs, dn, null); } /** * Create a new adapter from the supplied attributes, dn, and base. * * @param originalAttrs * the attributes. * @param dn * the dn. * @param base * the base name. */ public DirContextAdapter(Attributes attrs, Name dn, Name base) { if (attrs != null) { this.originalAttrs = attrs; } else { this.originalAttrs = new BasicAttributes(true); } if (dn != null) { this.dn = new DistinguishedName(dn.toString()); } else { this.dn = new DistinguishedName(); } if (base != null) { this.base = new DistinguishedName(base.toString()); } else { this.base = new DistinguishedName(); } } /** * Constructor for cloning an existing adapter. * * @param master * The adapter to be copied. */ protected DirContextAdapter(DirContextAdapter master) { this.originalAttrs = (Attributes) master.originalAttrs.clone(); this.dn = master.dn; this.updatedAttrs = (Attributes) master.updatedAttrs.clone(); this.updateMode = master.updateMode; } /** * Sets the update mode. The update mode should be <code>false</code> for * a new entry and <code>true</code> for an existing entry that is being * updated. * * @param mode * Update mode. */ public void setUpdateMode(boolean mode) { this.updateMode = mode; if (updateMode) { updatedAttrs = new BasicAttributes(true); } } /* * @see org.springframework.ldap.support.DirContextOperations#isUpdateMode() */ public boolean isUpdateMode() { return updateMode; } /* * @see org.springframework.ldap.support.DirContextOperations#getNamesOfModifiedAttributes() */ public String[] getNamesOfModifiedAttributes() { List tmpList = new ArrayList(); NamingEnumeration attributesEnumeration; if (isUpdateMode()) { attributesEnumeration = updatedAttrs.getAll(); } else { attributesEnumeration = originalAttrs.getAll(); } try { while (attributesEnumeration.hasMore()) { Attribute oneAttribute = (Attribute) attributesEnumeration .next(); tmpList.add(oneAttribute.getID()); } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } return (String[]) tmpList.toArray(new String[0]); } private void closeNamingEnumeration(NamingEnumeration enumeration) { try { if (enumeration != null) { enumeration.close(); } } catch (NamingException e) { // Never mind this } } /* * @see org.springframework.ldap.support.AttributeModificationsAware#getModificationItems() */ public ModificationItem[] getModificationItems() { if (!updateMode) { return new ModificationItem[0]; } List tmpList = new LinkedList(); NamingEnumeration attributesEnumeration = null; try { attributesEnumeration = updatedAttrs.getAll(); // find attributes that have been changed, removed or added while (attributesEnumeration.hasMore()) { Attribute oneAttr = (Attribute) attributesEnumeration.next(); collectModifications(oneAttr, tmpList); } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } if (log.isDebugEnabled()) { log.debug("Number of modifications:" + tmpList.size()); } return (ModificationItem[]) tmpList .toArray(new ModificationItem[tmpList.size()]); } /** * Collect all modifications for the changed attribute. If no changes have * been made, return immediately. If modifications have been made, and the * original size as well as the updated size of the attribute is 1, replace * the attribute. If the size of the updated attribute is 0, remove the * attribute. Otherwise, the attribute is a multi-value attribute, in which * case all modifications to the original value (removals and additions) * will be collected individually. * * @param changedAttr * the value of the changed attribute. * @param modificationList * the list in which to add the modifications. * @throws NamingException * if thrown by called Attribute methods. */ private void collectModifications(Attribute changedAttr, List modificationList) throws NamingException { Attribute currentAttribute = originalAttrs.get(changedAttr.getID()); if (changedAttr.equals(currentAttribute)) { // No changes return; } else if (currentAttribute != null && currentAttribute.size() == 1 && changedAttr.size() == 1) { // Replace single-vale attribute. modificationList.add(new ModificationItem( DirContext.REPLACE_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() == 0 && currentAttribute != null) { // Attribute has been removed. modificationList.add(new ModificationItem( DirContext.REMOVE_ATTRIBUTE, changedAttr)); } else if ((currentAttribute == null || currentAttribute.size() == 0) && changedAttr.size() > 0) { // Attribute has been added. modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() > 0) { // Change of multivalue Attribute. Collect additions and removals // individually. List myModifications = new LinkedList(); collectModifications(currentAttribute, changedAttr, myModifications); if (myModifications.isEmpty()) { // This means that the attributes are not equal, but the // actual values are the same - thus the order must have // changed. This should result in a REPLACE_ATTRIBUTE operation. myModifications.add(new ModificationItem( DirContext.REPLACE_ATTRIBUTE, changedAttr)); } modificationList.addAll(myModifications); } } private void collectModifications(Attribute originalAttr, Attribute changedAttr, List modificationList) throws NamingException { Attribute originalClone = (Attribute) originalAttr.clone(); Attribute addedValuesAttribute = new BasicAttribute(originalAttr .getID()); for (int i = 0; i < changedAttr.size(); i++) { Object attributeValue = changedAttr.get(i); if (!originalClone.remove(attributeValue)) { addedValuesAttribute.add(attributeValue); } } // We have now traversed and removed all values from the original that // were also present in the new values. The remaining values in the // original must be the ones that were removed. if (originalClone.size() > 0) { modificationList.add(new ModificationItem( DirContext.REMOVE_ATTRIBUTE, originalClone)); } if (addedValuesAttribute.size() > 0) { modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, addedValuesAttribute)); } } /** * returns true if the attribute is empty. It is empty if a == null, size == * 0 or get() == null or an exception if thrown when accessing the get * method */ private boolean isEmptyAttribute(Attribute a) { try { return (a == null || a.size() == 0 || a.get() == null); } catch (NamingException e) { return true; } } /** * Compare the existing attribute <code>name</code> with the values on the * array <code>values</code>. The order of the array must be the same * order as the existing multivalued attribute. * <p> * Also handles the case where the values have been reset to the original * values after a previous change. For example, changing * <code>[a,b,c]</code> to <code>[a,b]</code> and then back to * <code>[a,b,c]</code> again must result in this method returning * <code>true</code> so the first change can be overwritten with the * latest change. * * @param name * Name of the original multi-valued attribute. * @param values * Array of values to check if they have been changed. * @return true if there has been a change compared to original attribute, * or a previous update */ private boolean isChanged(String name, Object[] values, boolean orderMatters) { Attribute orig = originalAttrs.get(name); Attribute prev = updatedAttrs.get(name); // values == null and values.length == 0 is treated the same way boolean emptyNewValue = (values == null || values.length == 0); // Setting to empty --------------------- if (emptyNewValue) { // FALSE: if both are null, it is not changed (both don't exist) // TRUE: if new value is null and old value exists (should be // removed) // TODO Also include prev in null check // TODO Also check if there is a single null element if (orig != null) { return true; } return false; } // NOT setting to empty ------------------- // TRUE if existing value is null if (orig == null) { return true; } // TRUE if different length compared to original attributes if (orig.size() != values.length) { return true; } // TRUE if different length compared to previously updated attributes if (prev != null && prev.size() != values.length) { return true; } // Check contents of arrays // Order DOES matter, e.g. first names try { for (int i = 0; i < orig.size(); i++) { Object obj = orig.get(i); // TRUE if one value is not equal if (!(obj instanceof String)) { return true; } if (orderMatters) { // check only the string with same index if (!values[i].equals(obj)) { return true; } } else { // check all strings if (!ArrayUtils.contains(values, obj)) { return true; } } } } catch (NamingException e) { // TRUE if we can't access the value return true; } if (prev != null) { // Also check against updatedAttrs, since there might have been // a previous update try { for (int i = 0; i < prev.size(); i++) { Object obj = prev.get(i); // TRUE if one value is not equal if (!(obj instanceof String)) { return true; } if (orderMatters) { // check only the string with same index if (!values[i].equals(obj)) { return true; } } else { // check all strings if (!ArrayUtils.contains(values, obj)) { return true; } } } } catch (NamingException e) { // TRUE if we can't access the value return true; } } // FALSE since we have compared all values return false; } /** * Checks if an entry has a specific attribute. * * This method simply calls exists(String) with the attribute name. * * @param attr * the attribute to check. * @return true if attribute exists in entry. */ protected final boolean exists(Attribute attr) { return exists(attr.getID()); } /** * Checks if the attribute exists in this entry, either it was read or it * has been added and update() has been called. * * @param attrId * id of the attribute to check. * @return true if the attribute exists in the entry. */ protected final boolean exists(String attrId) { return originalAttrs.get(attrId) != null; } /* * @see org.springframework.ldap.support.DirContextOperations#getStringAttribute(java.lang.String) */ public String getStringAttribute(String name) { return (String) getObjectAttribute(name); } /* * @see org.springframework.ldap.support.DirContextOperations#getObjectAttribute(java.lang.String) */ public Object getObjectAttribute(String name) { Attribute oneAttr = originalAttrs.get(name); if (oneAttr == null) { return null; } try { return oneAttr.get(); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } } /* * @see org.springframework.ldap.support.DirContextOperations#setAttributeValue(java.lang.String, * java.lang.Object) */ public void setAttributeValue(String name, Object value) { // new entry if (!updateMode && value != null) { originalAttrs.put(name, value); } // updating entry if (updateMode) { BasicAttribute attribute = new BasicAttribute(name); if (value != null) { attribute.add(value); } updatedAttrs.put(attribute); } } /* * (non-Javadoc) * * @see org.springframework.ldap.core.DirContextOperations#addAttributeValue(java.lang.String, * java.lang.Object) */ public void addAttributeValue(String name, Object value) { if (!updateMode && value != null) { Attribute attr = originalAttrs.get(name); if (attr == null) { originalAttrs.put(name, value); } else { attr.add(value); } } else if (updateMode) { Attribute attr = updatedAttrs.get(name); if (attr == null) { if (originalAttrs.get(name) == null) { // No match in the original attributes - // add a new Attribute to updatedAttrs updatedAttrs.put(name, value); } else { // The attribute exists in the original attributes - clone // that and add the new entry to it attr = (Attribute) originalAttrs.get(name).clone(); attr.add(value); updatedAttrs.put(attr); } } else { attr.add(value); } } // Null values will not be added } /* * (non-Javadoc) * * @see org.springframework.ldap.core.DirContextOperations#removeAttributeValue(java.lang.String, * java.lang.Object) */ public void removeAttributeValue(String name, Object value) { if (!updateMode && value != null) { Attribute attr = originalAttrs.get(name); if (attr != null) { attr.remove(value); if (attr.size() == 0) { originalAttrs.remove(name); } } } else if (updateMode) { Attribute attr = updatedAttrs.get(name); if (attr == null) { if (originalAttrs.get(name) != null) { attr = (Attribute) originalAttrs.get(name).clone(); attr.remove(value); updatedAttrs.put(attr); } } else { attr.remove(value); } } } /* * @see org.springframework.ldap.support.DirContextOperations#setAttributeValues(java.lang.String, * java.lang.Object[]) */ public void setAttributeValues(String name, Object[] values) { setAttributeValues(name, values, ORDER_DOESNT_MATTER); } /* * @see org.springframework.ldap.support.DirContextOperations#setAttributeValues(java.lang.String, * java.lang.Object[], boolean) */ public void setAttributeValues(String name, Object[] values, boolean orderMatters) { Attribute a = new BasicAttribute(name, orderMatters); for (int i = 0; values != null && i < values.length; i++) { a.add(values[i]); } // only change the original attribute if not in update mode if (!updateMode && values != null && values.length > 0) { // don't save empty arrays originalAttrs.put(a); } // possible to set an already existing attribute to an empty array if (updateMode && isChanged(name, values, orderMatters)) { updatedAttrs.put(a); } } /* * @see org.springframework.ldap.support.DirContextOperations#update() */ public void update() { NamingEnumeration attributesEnumeration = null; try { attributesEnumeration = updatedAttrs.getAll(); // find what to update while (attributesEnumeration.hasMore()) { Attribute a = (Attribute) attributesEnumeration.next(); // if it does not exist it should be added if (isEmptyAttribute(a)) { originalAttrs.remove(a.getID()); } else { // Otherwise it should be set. originalAttrs.put(a); } } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } // Reset the attributes to be updated updatedAttrs = new BasicAttributes(true); } /* * @see org.springframework.ldap.support.DirContextOperations#getStringAttributes(java.lang.String) */ public String[] getStringAttributes(String name) { String[] attributes; Attribute attribute = originalAttrs.get(name); if (attribute != null && attribute.size() > 0) { attributes = new String[attribute.size()]; for (int i = 0; i < attribute.size(); i++) { try { attributes[i] = (String) attribute.get(i); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } } } else { return null; } return attributes; } /* * @see org.springframework.ldap.support.DirContextOperations#getAttributeSortedStringSet(java.lang.String) */ public SortedSet getAttributeSortedStringSet(String name) { TreeSet attrSet = new TreeSet(); Attribute attribute = originalAttrs.get(name); if (attribute != null) { for (int i = 0; i < attribute.size(); i++) { try { attrSet.add(attribute.get(i)); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } } } else { return null; } return attrSet; } /** * Set the supplied attribute. * * @param attribute * the attribute to set. */ public void setAttribute(Attribute attribute) { if (!updateMode) { originalAttrs.put(attribute); } else { updatedAttrs.put(attribute); } } /** * Get all attributes. * * @return all attributes. */ public Attributes getAttributes() { return originalAttrs; } /** * @see javax.naming.directory.DirContext#getAttributes(Name) */ public Attributes getAttributes(Name name) throws NamingException { return getAttributes(name.toString()); } /** * @see javax.naming.directory.DirContext#getAttributes(String) */ public Attributes getAttributes(String name) throws NamingException { if (!StringUtils.isEmpty(name)) { throw new NameNotFoundException(); } return (Attributes) originalAttrs.clone(); } /** * @see javax.naming.directory.DirContext#getAttributes(Name, String[]) */ public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { return getAttributes(name.toString(), attrIds); } /** * @see javax.naming.directory.DirContext#getAttributes(String, String[]) */ public Attributes getAttributes(String name, String[] attrIds) throws NamingException { if (!StringUtils.isEmpty(name)) { throw new NameNotFoundException(); } Attributes a = new BasicAttributes(true); Attribute target; for (int i = 0; i < attrIds.length; i++) { target = originalAttrs.get(attrIds[i]); if (target != null) { a.put(target); } } return a; } /** * @see javax.naming.directory.DirContext#modifyAttributes(javax.naming.Name, * int, javax.naming.directory.Attributes) */ public void modifyAttributes(Name name, int modOp, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#modifyAttributes(String, int, * Attributes) */ public void modifyAttributes(String name, int modOp, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#modifyAttributes(Name, * ModificationItem[]) */ public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#modifyAttributes(String, * ModificationItem[]) */ public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#bind(Name, Object, Attributes) */ public void bind(Name name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#bind(String, Object, Attributes) */ public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#rebind(Name, Object, Attributes) */ public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#rebind(String, Object, Attributes) */ public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#createSubcontext(Name, Attributes) */ public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#createSubcontext(String, * Attributes) */ public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchema(Name) */ public DirContext getSchema(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchema(String) */ public DirContext getSchema(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchemaClassDefinition(Name) */ public DirContext getSchemaClassDefinition(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchemaClassDefinition(String) */ public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, Attributes, String[]) */ public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, Attributes, * String[]) */ public NamingEnumeration search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, Attributes) */ public NamingEnumeration search(Name name, Attributes matchingAttributes) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, Attributes) */ public NamingEnumeration search(String name, Attributes matchingAttributes) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, String, * SearchControls) */ public NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, String, * SearchControls) */ public NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, String, Object[], * SearchControls) */ public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, String, Object[], * SearchControls) */ public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookup(Name) */ public Object lookup(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookup(String) */ public Object lookup(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#bind(Name, Object) */ public void bind(Name name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#bind(String, Object) */ public void bind(String name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rebind(Name, Object) */ public void rebind(Name name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rebind(String, Object) */ public void rebind(String name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#unbind(Name) */ public void unbind(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#unbind(String) */ public void unbind(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rename(Name, Name) */ public void rename(Name oldName, Name newName) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rename(String, String) */ public void rename(String oldName, String newName) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#list(Name) */ public NamingEnumeration list(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#list(String) */ public NamingEnumeration list(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#listBindings(Name) */ public NamingEnumeration listBindings(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#listBindings(String) */ public NamingEnumeration listBindings(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#destroySubcontext(Name) */ public void destroySubcontext(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#destroySubcontext(String) */ public void destroySubcontext(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#createSubcontext(Name) */ public Context createSubcontext(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#createSubcontext(String) */ public Context createSubcontext(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookupLink(Name) */ public Object lookupLink(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookupLink(String) */ public Object lookupLink(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getNameParser(Name) */ public NameParser getNameParser(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getNameParser(String) */ public NameParser getNameParser(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#composeName(Name, Name) */ public Name composeName(Name name, Name prefix) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#composeName(String, String) */ public String composeName(String name, String prefix) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#addToEnvironment(String, Object) */ public Object addToEnvironment(String propName, Object propVal) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#removeFromEnvironment(String) */ public Object removeFromEnvironment(String propName) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getEnvironment() */ public Hashtable getEnvironment() throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#close() */ public void close() throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getNameInNamespace() */ public String getNameInNamespace() { DistinguishedName result = new DistinguishedName(dn); result.prepend(base); return result.toString(); } /* * (non-Javadoc) * * @see org.springframework.ldap.support.DirContextOperations#getDn() */ public Name getDn() { return dn; } /* * (non-Javadoc) * * @see org.springframework.ldap.support.DirContextOperations#setDn(javax.naming.Name) */ public final void setDn(Name dn) { if (!updateMode) { this.dn = new DistinguishedName(dn.toString()); } } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { // A subclass with identical values should NOT be considered equal. // EqualsBuilder in commons-lang cannot handle subclasses correctly. if (obj == null || obj.getClass() != this.getClass()) { return false; } return EqualsBuilder.reflectionEquals(this, obj); } /** * @see Object#hashCode() */ public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getClass().getName()); buf.append(":"); if (dn != null) { buf.append(" dn=" + dn); } buf.append(" {"); try { for (NamingEnumeration i = originalAttrs.getAll(); i.hasMore();) { Attribute attribute = (Attribute) i.next(); if (attribute.size() == 1) { buf.append(attribute.getID()); buf.append('='); buf.append(attribute.get()); } else { for (int j = 0; j < attribute.size(); j++) { if (j > 0) { buf.append(", "); } buf.append(attribute.getID()); buf.append('['); buf.append(j); buf.append("]="); buf.append(attribute.get(j)); } } if (i.hasMore()) { buf.append(", "); } } } catch (NamingException e) { log.warn("Error in toString()"); } buf.append('}'); return buf.toString(); } }
spring-ldap/src/main/java/org/springframework/ldap/core/DirContextAdapter.java
/* * Copyright 2005-2007 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.ldap.core; import java.util.ArrayList; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.ldap.support.LdapUtils; /** * Adapter that implements the interesting methods of the DirContext interface. * In particular it contains utility methods for getting and setting attributes. * Using the * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory} in your * <code>ContextSource</code> (which is the default) you will receive * instances of this class from searches and lookups. This can be particularly * useful when updating data, since this class implements * {@link AttributeModificationsAware}, providing a * {@link #getModificationItems()} method. When in update mode, an object of * this class keeps track of the changes made to its attributes, making them * available as an array of <code>ModificationItem</code> objects, suitable as * input to {@link LdapTemplate#modifyAttributes(DirContextOperations)}. * * @see #setAttributeValue(String, Object) * @see #setAttributeValues(String, Object[]) * @see #getStringAttribute(String) * @see #getStringAttributes(String) * @see #getObjectAttribute(String) * @see #setUpdateMode(boolean) * @see #isUpdateMode() * * @author Magnus Robertsson * @author Andreas Ronge * @author Adam Skogman * @author Mattias Arthursson */ public class DirContextAdapter implements DirContextOperations { private static final boolean ORDER_DOESNT_MATTER = false; private static Log log = LogFactory.getLog(DirContextAdapter.class); private final Attributes originalAttrs; private DistinguishedName dn; private DistinguishedName base; private boolean updateMode = false; private Attributes updatedAttrs; /** * Default constructor. */ public DirContextAdapter() { this(null, null, null); } /** * Create a new adapter from the supplied dn. * * @param dn * the dn. */ public DirContextAdapter(Name dn) { this(null, dn); } /** * Create a new adapter from the supplied attributes and dn. * * @param originalAttrs * the attributes. * @param dn * the dn. */ public DirContextAdapter(Attributes attrs, Name dn) { this(attrs, dn, null); } /** * Create a new adapter from the supplied attributes, dn, and base. * * @param originalAttrs * the attributes. * @param dn * the dn. * @param base * the base name. */ public DirContextAdapter(Attributes attrs, Name dn, Name base) { if (attrs != null) { this.originalAttrs = attrs; } else { this.originalAttrs = new BasicAttributes(true); } if (dn != null) { this.dn = new DistinguishedName(dn.toString()); } else { this.dn = new DistinguishedName(); } if (base != null) { this.base = new DistinguishedName(base.toString()); } else { this.base = new DistinguishedName(); } } /** * Constructor for cloning an existing adapter. * * @param master * The adapter to be copied. */ protected DirContextAdapter(DirContextAdapter master) { this.originalAttrs = (Attributes) master.originalAttrs.clone(); this.dn = master.dn; this.updatedAttrs = (Attributes) master.updatedAttrs.clone(); this.updateMode = master.updateMode; } /** * Sets the update mode. The update mode should be <code>false</code> for * a new entry and <code>true</code> for an existing entry that is being * updated. * * @param mode * Update mode. */ public void setUpdateMode(boolean mode) { this.updateMode = mode; if (updateMode) { updatedAttrs = new BasicAttributes(true); } } /* * @see org.springframework.ldap.support.DirContextOperations#isUpdateMode() */ public boolean isUpdateMode() { return updateMode; } /* * @see org.springframework.ldap.support.DirContextOperations#getNamesOfModifiedAttributes() */ public String[] getNamesOfModifiedAttributes() { List tmpList = new ArrayList(); NamingEnumeration attributesEnumeration; if (isUpdateMode()) { attributesEnumeration = updatedAttrs.getAll(); } else { attributesEnumeration = originalAttrs.getAll(); } try { while (attributesEnumeration.hasMore()) { Attribute oneAttribute = (Attribute) attributesEnumeration .next(); tmpList.add(oneAttribute.getID()); } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } return (String[]) tmpList.toArray(new String[0]); } private void closeNamingEnumeration(NamingEnumeration enumeration) { try { if (enumeration != null) { enumeration.close(); } } catch (NamingException e) { // Never mind this } } /* * @see org.springframework.ldap.support.AttributeModificationsAware#getModificationItems() */ public ModificationItem[] getModificationItems() { if (!updateMode) { return new ModificationItem[0]; } List tmpList = new LinkedList(); NamingEnumeration attributesEnumeration = null; try { attributesEnumeration = updatedAttrs.getAll(); // find attributes that have been changed, removed or added while (attributesEnumeration.hasMore()) { Attribute oneAttr = (Attribute) attributesEnumeration.next(); collectModifications(oneAttr, tmpList); } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } if (log.isDebugEnabled()) { log.debug("Number of modifications:" + tmpList.size()); } return (ModificationItem[]) tmpList .toArray(new ModificationItem[tmpList.size()]); } /** * Collect all modifications for the changed attribute. If no changes have * been made, return immediately. If modifications have been made, and the * original size as well as the updated size of the attribute is 1, replace * the attribute. If the size of the updated attribute is 0, remove the * attribute. Otherwise, the attribute is a multi-value attribute, in which * case all modifications to the original value (removals and additions) * will be collected individually. * * @param changedAttr * the value of the changed attribute. * @param modificationList * the list in which to add the modifications. * @throws NamingException * if thrown by called Attribute methods. */ private void collectModifications(Attribute changedAttr, List modificationList) throws NamingException { Attribute currentAttribute = originalAttrs.get(changedAttr.getID()); if (changedAttr.equals(currentAttribute)) { // No changes return; } else if (currentAttribute != null && currentAttribute.size() == 1 && changedAttr.size() == 1) { // Replace single-vale attribute. modificationList.add(new ModificationItem( DirContext.REPLACE_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() == 0 && currentAttribute != null) { // Attribute has been removed. modificationList.add(new ModificationItem( DirContext.REMOVE_ATTRIBUTE, changedAttr)); } else if ((currentAttribute == null || currentAttribute.size() == 0) && changedAttr.size() > 0) { // Attribute has been added. modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() > 0) { // Change of multivalue Attribute. Collect additions and removals // individually. List myModifications = new LinkedList(); collectModifications(currentAttribute, changedAttr, myModifications); if (myModifications.isEmpty()) { // This means that the attributes are not equal, but the // actual values are the same - thus the order must have // changed. This should result in a REPLACE_ATTRIBUTE operation. myModifications.add(new ModificationItem( DirContext.REPLACE_ATTRIBUTE, changedAttr)); } modificationList.addAll(myModifications); } } private void collectModifications(Attribute originalAttr, Attribute changedAttr, List modificationList) throws NamingException { Attribute originalClone = (Attribute) originalAttr.clone(); Attribute addedValuesAttribute = new BasicAttribute(originalAttr .getID()); for (int i = 0; i < changedAttr.size(); i++) { Object attributeValue = changedAttr.get(i); if (!originalClone.remove(attributeValue)) { addedValuesAttribute.add(attributeValue); } } // We have now traversed and removed all values from the original that // were also present in the new values. The remaining values in the // original must be the ones that were removed. if (originalClone.size() > 0) { modificationList.add(new ModificationItem( DirContext.REMOVE_ATTRIBUTE, originalClone)); } if (addedValuesAttribute.size() > 0) { modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, addedValuesAttribute)); } } /** * returns true if the attribute is empty. It is empty if a == null, size == * 0 or get() == null or an exception if thrown when accessing the get * method */ private boolean isEmptyAttribute(Attribute a) { try { return (a == null || a.size() == 0 || a.get() == null); } catch (NamingException e) { return true; } } /** * Compare the existing attribute <code>name</code> with the values on the * array <code>values</code>. The order of the array must be the same * order as the existing multivalued attribute. * <p> * Also handles the case where the values have been reset to the original * values after a previous change. For example, changing * <code>[a,b,c]</code> to <code>[a,b]</code> and then back to * <code>[a,b,c]</code> again must result in this method returning * <code>true</code> so the first change can be overwritten with the * latest change. * * @param name * Name of the original multi-valued attribute. * @param values * Array of values to check if they have been changed. * @return true if there has been a change compared to original attribute, * or a previous update */ private boolean isChanged(String name, Object[] values, boolean orderMatters) { Attribute orig = originalAttrs.get(name); Attribute prev = updatedAttrs.get(name); // values == null and values.length == 0 is treated the same way boolean emptyNewValue = (values == null || values.length == 0); // Setting to empty --------------------- if (emptyNewValue) { // FALSE: if both are null, it is not changed (both don't exist) // TRUE: if new value is null and old value exists (should be // removed) // TODO Also include prev in null check // TODO Also check if there is a single null element if (orig != null) { return true; } return false; } // NOT setting to empty ------------------- // TRUE if existing value is null if (orig == null) { return true; } // TRUE if different length compared to original attributes if (orig.size() != values.length) { return true; } // TRUE if different length compared to previously updated attributes if (prev != null && prev.size() != values.length) { return true; } // Check contents of arrays // Order DOES matter, e.g. first names try { for (int i = 0; i < orig.size(); i++) { Object obj = orig.get(i); // TRUE if one value is not equal if (!(obj instanceof String)) { return true; } if (orderMatters) { // check only the string with same index if (!values[i].equals(obj)) { return true; } } else { // check all strings if (!ArrayUtils.contains(values, obj)) { return true; } } } } catch (NamingException e) { // TRUE if we can't access the value return true; } if (prev != null) { // Also check against updatedAttrs, since there might have been // a previous update try { for (int i = 0; i < prev.size(); i++) { Object obj = prev.get(i); // TRUE if one value is not equal if (!(obj instanceof String)) { return true; } if (orderMatters) { // check only the string with same index if (!values[i].equals(obj)) { return true; } } else { // check all strings if (!ArrayUtils.contains(values, obj)) { return true; } } } } catch (NamingException e) { // TRUE if we can't access the value return true; } } // FALSE since we have compared all values return false; } /** * Checks if an entry has a specific attribute. * * This method simply calls exists(String) with the attribute name. * * @param attr * the attribute to check. * @return true if attribute exists in entry. */ protected final boolean exists(Attribute attr) { return exists(attr.getID()); } /** * Checks if the attribute exists in this entry, either it was read or it * has been added and update() has been called. * * @param attrId * id of the attribute to check. * @return true if the attribute exists in the entry. */ protected final boolean exists(String attrId) { return originalAttrs.get(attrId) != null; } /* * @see org.springframework.ldap.support.DirContextOperations#getStringAttribute(java.lang.String) */ public String getStringAttribute(String name) { return (String) getObjectAttribute(name); } /* * @see org.springframework.ldap.support.DirContextOperations#getObjectAttribute(java.lang.String) */ public Object getObjectAttribute(String name) { Attribute oneAttr = originalAttrs.get(name); if (oneAttr == null) { return null; } try { return oneAttr.get(); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } } /* * @see org.springframework.ldap.support.DirContextOperations#setAttributeValue(java.lang.String, * java.lang.Object) */ public void setAttributeValue(String name, Object value) { // new entry if (!updateMode && value != null) { originalAttrs.put(name, value); } // updating entry if (updateMode) { BasicAttribute attribute = new BasicAttribute(name); if (value != null) { attribute.add(value); } updatedAttrs.put(attribute); } } /* * (non-Javadoc) * * @see org.springframework.ldap.core.DirContextOperations#addAttributeValue(java.lang.String, * java.lang.Object) */ public void addAttributeValue(String name, Object value) { if (!updateMode && value != null) { Attribute attr = originalAttrs.get(name); if (attr == null) { originalAttrs.put(name, value); } else { attr.add(value); } } else if (updateMode) { Attribute attr = updatedAttrs.get(name); if (attr == null) { if (originalAttrs.get(name) == null) { // No match in the original attributes - // add a new Attribute to updatedAttrs updatedAttrs.put(name, value); } else { // The attribute exists in the original attributes - clone // that and add the new entry to it attr = (Attribute) originalAttrs.get(name).clone(); attr.add(value); updatedAttrs.put(attr); } } else { attr.add(value); } } // Null values will not be added } /* * (non-Javadoc) * * @see org.springframework.ldap.core.DirContextOperations#removeAttributeValue(java.lang.String, * java.lang.Object) */ public void removeAttributeValue(String name, Object value) { if (!updateMode && value != null) { Attribute attr = originalAttrs.get(name); if (attr != null) { attr.remove(value); if (attr.size() == 0) { originalAttrs.remove(name); } } } else if (updateMode) { Attribute attr = updatedAttrs.get(name); if (attr == null) { if (originalAttrs.get(name) != null) { attr = (Attribute) originalAttrs.get(name).clone(); attr.remove(value); updatedAttrs.put(attr); } } else { attr.remove(value); } } } /* * @see org.springframework.ldap.support.DirContextOperations#setAttributeValues(java.lang.String, * java.lang.Object[]) */ public void setAttributeValues(String name, Object[] values) { setAttributeValues(name, values, ORDER_DOESNT_MATTER); } /* * @see org.springframework.ldap.support.DirContextOperations#setAttributeValues(java.lang.String, * java.lang.Object[], boolean) */ public void setAttributeValues(String name, Object[] values, boolean orderMatters) { Attribute a = new BasicAttribute(name, orderMatters); for (int i = 0; values != null && i < values.length; i++) { a.add(values[i]); } // only change the original attribute if not in update mode if (!updateMode && values != null && values.length > 0) { // don't save empty arrays originalAttrs.put(a); } // possible to set an already existing attribute to an empty array if (updateMode && isChanged(name, values, orderMatters)) { updatedAttrs.put(a); } } /* * @see org.springframework.ldap.support.DirContextOperations#update() */ public void update() { NamingEnumeration attributesEnumeration = null; try { attributesEnumeration = updatedAttrs.getAll(); // find what to update while (attributesEnumeration.hasMore()) { Attribute a = (Attribute) attributesEnumeration.next(); // if it does not exist it should be added if (isEmptyAttribute(a)) { originalAttrs.remove(a.getID()); } else { // Otherwise it should be set. originalAttrs.put(a); } } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } // Reset the attributes to be updated updatedAttrs = new BasicAttributes(true); } /* * @see org.springframework.ldap.support.DirContextOperations#getStringAttributes(java.lang.String) */ public String[] getStringAttributes(String name) { String[] attributes; Attribute attribute = originalAttrs.get(name); if (attribute != null && attribute.size() > 0) { attributes = new String[attribute.size()]; for (int i = 0; i < attribute.size(); i++) { try { attributes[i] = (String) attribute.get(i); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } } } else { return null; } return attributes; } /* * @see org.springframework.ldap.support.DirContextOperations#getAttributeSortedStringSet(java.lang.String) */ public SortedSet getAttributeSortedStringSet(String name) { TreeSet attrSet = new TreeSet(); Attribute attribute = originalAttrs.get(name); if (attribute != null) { for (int i = 0; i < attribute.size(); i++) { try { attrSet.add(attribute.get(i)); } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } } } else { return null; } return attrSet; } /** * Set the supplied attribute. * * @param attribute * the attribute to set. */ public void setAttribute(Attribute attribute) { if (!updateMode) { originalAttrs.put(attribute); } else { updatedAttrs.put(attribute); } } /** * Get all attributes. * * @return all attributes. */ public Attributes getAttributes() { return originalAttrs; } /** * @see javax.naming.directory.DirContext#getAttributes(Name) */ public Attributes getAttributes(Name name) throws NamingException { return getAttributes(name.toString()); } /** * @see javax.naming.directory.DirContext#getAttributes(String) */ public Attributes getAttributes(String name) throws NamingException { if (!StringUtils.isEmpty(name)) { throw new NameNotFoundException(); } return (Attributes) originalAttrs.clone(); } /** * @see javax.naming.directory.DirContext#getAttributes(Name, String[]) */ public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { return getAttributes(name.toString(), attrIds); } /** * @see javax.naming.directory.DirContext#getAttributes(String, String[]) */ public Attributes getAttributes(String name, String[] attrIds) throws NamingException { if (!StringUtils.isEmpty(name)) { throw new NameNotFoundException(); } Attributes a = new BasicAttributes(true); Attribute target; for (int i = 0; i < attrIds.length; i++) { target = originalAttrs.get(attrIds[i]); if (target != null) { a.put(target); } } return a; } /** * @see javax.naming.directory.DirContext#modifyAttributes(javax.naming.Name, * int, javax.naming.directory.Attributes) */ public void modifyAttributes(Name name, int modOp, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#modifyAttributes(String, int, * Attributes) */ public void modifyAttributes(String name, int modOp, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#modifyAttributes(Name, * ModificationItem[]) */ public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#modifyAttributes(String, * ModificationItem[]) */ public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#bind(Name, Object, Attributes) */ public void bind(Name name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#bind(String, Object, Attributes) */ public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#rebind(Name, Object, Attributes) */ public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#rebind(String, Object, Attributes) */ public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#createSubcontext(Name, Attributes) */ public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#createSubcontext(String, * Attributes) */ public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchema(Name) */ public DirContext getSchema(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchema(String) */ public DirContext getSchema(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchemaClassDefinition(Name) */ public DirContext getSchemaClassDefinition(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#getSchemaClassDefinition(String) */ public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, Attributes, String[]) */ public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, Attributes, * String[]) */ public NamingEnumeration search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, Attributes) */ public NamingEnumeration search(Name name, Attributes matchingAttributes) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, Attributes) */ public NamingEnumeration search(String name, Attributes matchingAttributes) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, String, * SearchControls) */ public NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, String, * SearchControls) */ public NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(Name, String, Object[], * SearchControls) */ public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.directory.DirContext#search(String, String, Object[], * SearchControls) */ public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookup(Name) */ public Object lookup(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookup(String) */ public Object lookup(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#bind(Name, Object) */ public void bind(Name name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#bind(String, Object) */ public void bind(String name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rebind(Name, Object) */ public void rebind(Name name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rebind(String, Object) */ public void rebind(String name, Object obj) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#unbind(Name) */ public void unbind(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#unbind(String) */ public void unbind(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rename(Name, Name) */ public void rename(Name oldName, Name newName) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#rename(String, String) */ public void rename(String oldName, String newName) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#list(Name) */ public NamingEnumeration list(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#list(String) */ public NamingEnumeration list(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#listBindings(Name) */ public NamingEnumeration listBindings(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#listBindings(String) */ public NamingEnumeration listBindings(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#destroySubcontext(Name) */ public void destroySubcontext(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#destroySubcontext(String) */ public void destroySubcontext(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#createSubcontext(Name) */ public Context createSubcontext(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#createSubcontext(String) */ public Context createSubcontext(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookupLink(Name) */ public Object lookupLink(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#lookupLink(String) */ public Object lookupLink(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getNameParser(Name) */ public NameParser getNameParser(Name name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getNameParser(String) */ public NameParser getNameParser(String name) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#composeName(Name, Name) */ public Name composeName(Name name, Name prefix) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#composeName(String, String) */ public String composeName(String name, String prefix) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#addToEnvironment(String, Object) */ public Object addToEnvironment(String propName, Object propVal) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#removeFromEnvironment(String) */ public Object removeFromEnvironment(String propName) throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getEnvironment() */ public Hashtable getEnvironment() throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#close() */ public void close() throws NamingException { throw new UnsupportedOperationException("Not implemented."); } /** * @see javax.naming.Context#getNameInNamespace() */ public String getNameInNamespace() { DistinguishedName result = new DistinguishedName(dn); result.prepend(base); return result.toString(); } /* * (non-Javadoc) * * @see org.springframework.ldap.support.DirContextOperations#getDn() */ public Name getDn() { return dn; } /* * (non-Javadoc) * * @see org.springframework.ldap.support.DirContextOperations#setDn(javax.naming.Name) */ public final void setDn(Name dn) { if (!updateMode) { this.dn = new DistinguishedName(dn.toString()); } } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { // A subclass with identical values should NOT be considered equal. // EqualsBuilder in commons-lang cannot handle subclasses correctly. if (obj == null || obj.getClass() != this.getClass()) { return false; } return EqualsBuilder.reflectionEquals(this, obj); } /** * @see Object#hashCode() */ public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getClass().getName()); buf.append(":"); if (dn != null) { buf.append(" dn=" + dn); } buf.append(" {"); try { for (NamingEnumeration i = originalAttrs.getAll(); i.hasMore();) { Attribute attribute = (Attribute) i.next(); if (attribute.size() == 1) { buf.append(attribute.getID()); buf.append('='); buf.append(attribute.get()); } else { for (int j = 0; j < attribute.size(); j++) { if (j > 0) { buf.append(", "); } buf.append(attribute.getID()); buf.append('['); buf.append(j); buf.append("]="); buf.append(attribute.get(j)); } } if (i.hasMore()) { buf.append(", "); } } } catch (NamingException e) { log.warn("Error in toString()"); } buf.append('}'); return buf.toString(); } }
Minor javadoc fix
spring-ldap/src/main/java/org/springframework/ldap/core/DirContextAdapter.java
Minor javadoc fix
<ide><path>pring-ldap/src/main/java/org/springframework/ldap/core/DirContextAdapter.java <ide> * @see #getStringAttribute(String) <ide> * @see #getStringAttributes(String) <ide> * @see #getObjectAttribute(String) <add> * @see #addAttributeValue(String, Object) <add> * @see #removeAttributeValue(String, Object) <ide> * @see #setUpdateMode(boolean) <ide> * @see #isUpdateMode() <ide> *
Java
bsd-3-clause
3617f45bc6c1fc3abb06159f43ea46b841489afa
0
tangentforks/piccolo2d.java
package edu.umd.cs.piccolo; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import junit.framework.TestCase; import edu.umd.cs.piccolo.event.PInputEvent; import edu.umd.cs.piccolo.util.PBounds; import edu.umd.cs.piccolo.util.PPickPath; public class PInputManagerTest extends TestCase { private PInputManager manager; private MockPInputEventListener mockListener; public void setUp() { manager = new PInputManager(); mockListener = new MockPInputEventListener(); } public void testGetKeyboardFocusNullByDefault() { assertNull(manager.getKeyboardFocus()); } public void testSetKeyboardFocusIsPersisted() { manager.setKeyboardFocus(mockListener); assertEquals(mockListener, manager.getKeyboardFocus()); } public void testSetKeyboardFocusDispatchesEventsAboutFocus() { MockPInputEventListener oldListener = new MockPInputEventListener(); manager.setKeyboardFocus(oldListener); assertEquals(1, oldListener.getNotificationCount()); assertEquals(FocusEvent.FOCUS_GAINED, oldListener.getNotification(0).type); MockPInputEventListener newListener = new MockPInputEventListener(); manager.setKeyboardFocus(newListener); assertEquals(1, newListener.getNotificationCount()); assertEquals(FocusEvent.FOCUS_GAINED, newListener.getNotification(0).type); assertEquals(2, oldListener.getNotificationCount()); assertEquals(FocusEvent.FOCUS_LOST, oldListener.getNotification(1).type); } public void testGetMouseFocusNullByDefault() { assertNull(manager.getMouseFocus()); } public void testSetMouseFocusPersists() { PCamera camera = new PCamera(); PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); manager.setMouseFocus(path); assertEquals(path, manager.getMouseFocus()); } public void testGetMouseOverNullByDefault() { assertNull(manager.getMouseOver()); } public void testSetMouseOverPersists() { PCamera camera = new PCamera(); PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); manager.setMouseOver(path); assertEquals(path, manager.getMouseOver()); } public void testGetCurrentCanvasPositionIsOriginByDefault() { assertEquals(new Point2D.Double(0, 0), manager .getCurrentCanvasPosition()); } public void testGetLastCanvasPositionIsOriginByDefault() { assertEquals(new Point2D.Double(0, 0), manager.getLastCanvasPosition()); } public void testKeyPressedDispatchesToCurrentFocus() { manager.setKeyboardFocus(mockListener); PInputEvent event = new PInputEvent(manager, null, null); manager.keyPressed(event); assertEquals(2, mockListener.getNotificationCount()); assertEquals(KeyEvent.KEY_PRESSED, mockListener.getNotification(1).type); } public void testKeyReleasedDispatchesToCurrentFocus() { manager.setKeyboardFocus(mockListener); PInputEvent event = new PInputEvent(manager, null, null); manager.keyReleased(event); assertEquals(2, mockListener.getNotificationCount()); assertEquals(KeyEvent.KEY_RELEASED, mockListener.getNotification(1).type); } public void testKeyTypedDispatchesToCurrentFocus() { manager.setKeyboardFocus(mockListener); PInputEvent event = new PInputEvent(manager, null, null); manager.keyTyped(event); assertEquals(2, mockListener.getNotificationCount()); assertEquals(KeyEvent.KEY_TYPED, mockListener.getNotification(1).type); } public void testProcessInputMayBeCalledOnFreshManager() { manager.processInput(); } }
core/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java
package edu.umd.cs.piccolo; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import junit.framework.TestCase; import edu.umd.cs.piccolo.event.PInputEvent; import edu.umd.cs.piccolo.event.PInputEventListener; import edu.umd.cs.piccolo.util.PBounds; import edu.umd.cs.piccolo.util.PPickPath; public class PInputManagerTest extends TestCase { private PInputManager manager; public void setUp() { manager = new PInputManager(); } public void testGetKeyboardFocusNullByDefault() { assertNull(manager.getKeyboardFocus()); } public void testSetKeyboardFocusIsPersisted() { PInputEventListener listener = new MockPInputEventListener(); manager.setKeyboardFocus(listener); assertEquals(listener, manager.getKeyboardFocus()); } public void testSetKeyboardFocusDispatchesEventsAboutFocus() { MockPInputEventListener oldListener = new MockPInputEventListener(); manager.setKeyboardFocus(oldListener); assertEquals(1, oldListener.getNotificationCount()); assertEquals(FocusEvent.FOCUS_GAINED, oldListener.getNotification(0).type); MockPInputEventListener newListener = new MockPInputEventListener(); manager.setKeyboardFocus(newListener); assertEquals(1, newListener.getNotificationCount()); assertEquals(FocusEvent.FOCUS_GAINED, newListener.getNotification(0).type); assertEquals(2, oldListener.getNotificationCount()); assertEquals(FocusEvent.FOCUS_LOST, oldListener.getNotification(1).type); } public void testGetMouseFocusNullByDefault() { assertNull(manager.getMouseFocus()); } public void testSetMouseFocusPersists() { PCamera camera = new PCamera(); PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); manager.setMouseFocus(path); assertEquals(path, manager.getMouseFocus()); } public void testGetMouseOverNullByDefault() { assertNull(manager.getMouseOver()); } public void testSetMouseOverPersists() { PCamera camera = new PCamera(); PPickPath path = new PPickPath(camera, new PBounds(0, 0, 10, 10)); manager.setMouseOver(path); assertEquals(path, manager.getMouseOver()); } public void testGetCurrentCanvasPositionIsOriginByDefault() { assertEquals(new Point2D.Double(0, 0), manager .getCurrentCanvasPosition()); } public void testGetLastCanvasPositionIsOriginByDefault() { assertEquals(new Point2D.Double(0, 0), manager.getLastCanvasPosition()); } public void testKeyPressedDispatchesToCurrentFocus() { MockPInputEventListener mockListener = new MockPInputEventListener(); manager.setKeyboardFocus(mockListener); PInputEvent event = new PInputEvent(manager, null, null); manager.keyPressed(event); assertEquals(2, mockListener.getNotificationCount()); assertEquals(KeyEvent.KEY_PRESSED, mockListener.getNotification(1).type); } public void testKeyReleasedDispatchesToCurrentFocus() { MockPInputEventListener mockListener = new MockPInputEventListener(); manager.setKeyboardFocus(mockListener); PInputEvent event = new PInputEvent(manager, null, null); manager.keyReleased(event); assertEquals(2, mockListener.getNotificationCount()); assertEquals(KeyEvent.KEY_RELEASED, mockListener.getNotification(1).type); } public void testKeyTypedDispatchesToCurrentFocus() { MockPInputEventListener mockListener = new MockPInputEventListener(); manager.setKeyboardFocus(mockListener); PInputEvent event = new PInputEvent(manager, null, null); manager.keyTyped(event); assertEquals(2, mockListener.getNotificationCount()); assertEquals(KeyEvent.KEY_TYPED, mockListener.getNotification(1).type); } public void testProcessInputMayBeCalledOnFreshManager() { manager.processInput(); } }
Moved mockListener out of methods and into the setUp. it's common enough to warrant it. git-svn-id: d976a3fa9fd96fa05fb374ae920b691bf85e82cb@466 aadc08cf-1350-0410-9b51-cf97fce99a1b
core/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java
Moved mockListener out of methods and into the setUp. it's common enough to warrant it.
<ide><path>ore/src/test/java/edu/umd/cs/piccolo/PInputManagerTest.java <ide> <ide> import junit.framework.TestCase; <ide> import edu.umd.cs.piccolo.event.PInputEvent; <del>import edu.umd.cs.piccolo.event.PInputEventListener; <ide> import edu.umd.cs.piccolo.util.PBounds; <ide> import edu.umd.cs.piccolo.util.PPickPath; <ide> <ide> public class PInputManagerTest extends TestCase { <ide> private PInputManager manager; <add> private MockPInputEventListener mockListener; <ide> <ide> public void setUp() { <ide> manager = new PInputManager(); <add> mockListener = new MockPInputEventListener(); <ide> } <ide> <ide> public void testGetKeyboardFocusNullByDefault() { <ide> assertNull(manager.getKeyboardFocus()); <ide> } <ide> <del> public void testSetKeyboardFocusIsPersisted() { <del> PInputEventListener listener = new MockPInputEventListener(); <del> manager.setKeyboardFocus(listener); <del> assertEquals(listener, manager.getKeyboardFocus()); <add> public void testSetKeyboardFocusIsPersisted() { <add> manager.setKeyboardFocus(mockListener); <add> assertEquals(mockListener, manager.getKeyboardFocus()); <ide> } <ide> <ide> public void testSetKeyboardFocusDispatchesEventsAboutFocus() { <ide> assertEquals(new Point2D.Double(0, 0), manager.getLastCanvasPosition()); <ide> } <ide> <del> public void testKeyPressedDispatchesToCurrentFocus() { <del> MockPInputEventListener mockListener = new MockPInputEventListener(); <add> public void testKeyPressedDispatchesToCurrentFocus() { <ide> manager.setKeyboardFocus(mockListener); <ide> PInputEvent event = new PInputEvent(manager, null, null); <ide> manager.keyPressed(event); <ide> assertEquals(2, mockListener.getNotificationCount()); <ide> assertEquals(KeyEvent.KEY_PRESSED, mockListener.getNotification(1).type); <ide> } <del> public void testKeyReleasedDispatchesToCurrentFocus() { <del> MockPInputEventListener mockListener = new MockPInputEventListener(); <add> public void testKeyReleasedDispatchesToCurrentFocus() { <ide> manager.setKeyboardFocus(mockListener); <ide> PInputEvent event = new PInputEvent(manager, null, null); <ide> manager.keyReleased(event); <ide> assertEquals(KeyEvent.KEY_RELEASED, mockListener.getNotification(1).type); <ide> } <ide> <del> public void testKeyTypedDispatchesToCurrentFocus() { <del> MockPInputEventListener mockListener = new MockPInputEventListener(); <add> public void testKeyTypedDispatchesToCurrentFocus() { <ide> manager.setKeyboardFocus(mockListener); <ide> PInputEvent event = new PInputEvent(manager, null, null); <ide> manager.keyTyped(event); <ide> <ide> public void testProcessInputMayBeCalledOnFreshManager() { <ide> manager.processInput(); <del> } <add> } <add> <ide> }
Java
apache-2.0
62311fcd2fae6f6d34f210d068809daeaded2431
0
JCTools/JCTools
/* * 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.jctools.util; import static org.jctools.util.UnsafeAccess.UNSAFE; @InternalAPI public final class UnsafeRefArrayAccess { public static final long REF_ARRAY_BASE; public static final int REF_ELEMENT_SHIFT; static { final int scale = UnsafeAccess.UNSAFE.arrayIndexScale(Object[].class); if (4 == scale) { REF_ELEMENT_SHIFT = 2; } else if (8 == scale) { REF_ELEMENT_SHIFT = 3; } else { throw new IllegalStateException("Unknown pointer size: " + scale); } REF_ARRAY_BASE = UnsafeAccess.UNSAFE.arrayBaseOffset(Object[].class); } /** * A plain store (no ordering/fences) of an element to a given offset * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} * @param e an orderly kitty */ public static <E> void spElement(E[] buffer, long offset, E e) { UNSAFE.putObject(buffer, offset, e); } /** * An ordered store of an element to a given offset * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcCircularElementOffset} * @param e an orderly kitty */ public static <E> void soElement(E[] buffer, long offset, E e) { UNSAFE.putOrderedObject(buffer, offset, e); } /** * A plain load (no ordering/fences) of an element from a given offset. * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} * @return the element at the offset */ @SuppressWarnings("unchecked") public static <E> E lpElement(E[] buffer, long offset) { return (E) UNSAFE.getObject(buffer, offset); } /** * A volatile load of an element from a given offset. * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} * @return the element at the offset */ @SuppressWarnings("unchecked") public static <E> E lvElement(E[] buffer, long offset) { return (E) UNSAFE.getObjectVolatile(buffer, offset); } /** * @param index desirable element index * @return the offset in bytes within the array for a given index */ public static long calcElementOffset(long index) { return REF_ARRAY_BASE + (index << REF_ELEMENT_SHIFT); } /** * Note: circular arrays are assumed a power of 2 in length and the `mask` is (length - 1). * * @param index desirable element index * @param mask (length - 1) * @return the offset in bytes within the circular array for a given index */ public static long calcCircularElementOffset(long index, long mask) { return REF_ARRAY_BASE + ((index & mask) << REF_ELEMENT_SHIFT); } /** * This makes for an easier time generating the atomic queues, and removes some warnings. */ @SuppressWarnings("unchecked") public static <E> E[] allocate(int capacity) { return (E[]) new Object[capacity]; } }
jctools-core/src/main/java/org/jctools/util/UnsafeRefArrayAccess.java
/* * 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.jctools.util; import static org.jctools.util.UnsafeAccess.UNSAFE; /** * A concurrent access enabling class used by circular array based queues this class exposes an offset computation * method along with differently memory fenced load/store methods into the underlying array. The class is pre-padded and * the array is padded on either side to help with False sharing prvention. It is expected theat subclasses handle post * padding. * <p> * Offset calculation is separate from access to enable the reuse of a give compute offset. * <p> * Load/Store methods using a <i>buffer</i> parameter are provided to allow the prevention of final field reload after a * LoadLoad barrier. * <p> * * @author nitsanw */ @InternalAPI public final class UnsafeRefArrayAccess { public static final long REF_ARRAY_BASE; public static final int REF_ELEMENT_SHIFT; static { final int scale = UnsafeAccess.UNSAFE.arrayIndexScale(Object[].class); if (4 == scale) { REF_ELEMENT_SHIFT = 2; } else if (8 == scale) { REF_ELEMENT_SHIFT = 3; } else { throw new IllegalStateException("Unknown pointer size: " + scale); } REF_ARRAY_BASE = UnsafeAccess.UNSAFE.arrayBaseOffset(Object[].class); } /** * A plain store (no ordering/fences) of an element to a given offset * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} * @param e an orderly kitty */ public static <E> void spElement(E[] buffer, long offset, E e) { UNSAFE.putObject(buffer, offset, e); } /** * An ordered store(store + StoreStore barrier) of an element to a given offset * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcCircularElementOffset} * @param e an orderly kitty */ public static <E> void soElement(E[] buffer, long offset, E e) { UNSAFE.putOrderedObject(buffer, offset, e); } /** * A plain load (no ordering/fences) of an element from a given offset. * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} * @return the element at the offset */ @SuppressWarnings("unchecked") public static <E> E lpElement(E[] buffer, long offset) { return (E) UNSAFE.getObject(buffer, offset); } /** * A volatile load (load + LoadLoad barrier) of an element from a given offset. * * @param buffer this.buffer * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} * @return the element at the offset */ @SuppressWarnings("unchecked") public static <E> E lvElement(E[] buffer, long offset) { return (E) UNSAFE.getObjectVolatile(buffer, offset); } /** * @param index desirable element index * @return the offset in bytes within the array for a given index. */ public static long calcElementOffset(long index) { return REF_ARRAY_BASE + (index << REF_ELEMENT_SHIFT); } /** * @param index desirable element index * @param mask (length - 1) * @return the offset in bytes within the array for a given index. */ public static long calcCircularElementOffset(long index, long mask) { return REF_ARRAY_BASE + ((index & mask) << REF_ELEMENT_SHIFT); } /** * This makes for an easier time generating the atomic queues, and removes some warnings. */ @SuppressWarnings("unchecked") public static <E> E[] allocate(int capacity) { return (E[]) new Object[capacity]; } }
Javadoc cleanup
jctools-core/src/main/java/org/jctools/util/UnsafeRefArrayAccess.java
Javadoc cleanup
<ide><path>ctools-core/src/main/java/org/jctools/util/UnsafeRefArrayAccess.java <ide> <ide> import static org.jctools.util.UnsafeAccess.UNSAFE; <ide> <del>/** <del> * A concurrent access enabling class used by circular array based queues this class exposes an offset computation <del> * method along with differently memory fenced load/store methods into the underlying array. The class is pre-padded and <del> * the array is padded on either side to help with False sharing prvention. It is expected theat subclasses handle post <del> * padding. <del> * <p> <del> * Offset calculation is separate from access to enable the reuse of a give compute offset. <del> * <p> <del> * Load/Store methods using a <i>buffer</i> parameter are provided to allow the prevention of final field reload after a <del> * LoadLoad barrier. <del> * <p> <del> * <del> * @author nitsanw <del> */ <ide> @InternalAPI <ide> public final class UnsafeRefArrayAccess <ide> { <ide> } <ide> <ide> /** <del> * An ordered store(store + StoreStore barrier) of an element to a given offset <add> * An ordered store of an element to a given offset <ide> * <ide> * @param buffer this.buffer <ide> * @param offset computed via {@link UnsafeRefArrayAccess#calcCircularElementOffset} <ide> } <ide> <ide> /** <del> * A volatile load (load + LoadLoad barrier) of an element from a given offset. <add> * A volatile load of an element from a given offset. <ide> * <ide> * @param buffer this.buffer <ide> * @param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)} <ide> <ide> /** <ide> * @param index desirable element index <del> * @return the offset in bytes within the array for a given index. <add> * @return the offset in bytes within the array for a given index <ide> */ <ide> public static long calcElementOffset(long index) <ide> { <ide> } <ide> <ide> /** <add> * Note: circular arrays are assumed a power of 2 in length and the `mask` is (length - 1). <add> * <ide> * @param index desirable element index <ide> * @param mask (length - 1) <del> * @return the offset in bytes within the array for a given index. <add> * @return the offset in bytes within the circular array for a given index <ide> */ <ide> public static long calcCircularElementOffset(long index, long mask) <ide> {
Java
mit
3405d180ce7453fd56c16daaed20f37ca9b02801
0
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
package org.micromanager.asidispim; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.process.ImageProcessor; import java.awt.Cursor; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.SwingWorker; import net.miginfocom.swing.MigLayout; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.MMWindow; import org.micromanager.api.ScriptInterface; import org.micromanager.asidispim.Data.Prefs; import org.micromanager.asidispim.Data.Properties; import org.micromanager.asidispim.Utils.ListeningJPanel; import org.micromanager.asidispim.Utils.PanelUtils; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; /** * Panel in ASIdiSPIM plugin specifically for data analysis/processing * For now, we provide a way to export Micro-Manager datasets into * a mipav compatible format * mipav likes data in a folder as follows: * folder - SPIMA - name_SPIMA-0.tif, name_SPIMA-x.tif, name_SPIMA-n.tif * - SPIMB - name_SPIMB-0.tif, name_SPIMB-x.tif, name_SPIMB-n.tif * @author Nico */ @SuppressWarnings("serial") public class DataAnalysisPanel extends ListeningJPanel { private final ScriptInterface gui_; private final JPanel mipavPanel_; private final JTextField saveDestinationField_; private Prefs prefs_; /** * * @param gui - implementation of the Micro-Manager ScriptInterface api * @param prefs - Plugin wide preferences */ public DataAnalysisPanel(ScriptInterface gui, Prefs prefs) { super("Data Analysis", new MigLayout( "", "[right]", "[]16[]")); gui_ = gui; prefs_ = prefs; int textFieldWidth = 20; // start volume sub-panel mipavPanel_ = new JPanel(new MigLayout( "", "[right]4[center]4[left]", "[]8[]")); mipavPanel_.setBorder(PanelUtils.makeTitledBorder("Export to mipav")); JLabel instructions = new JLabel("Exports selected data set to a format \n" + "compatible with the mipav GenerateFusion Plugin"); mipavPanel_.add(instructions, "span 3, wrap"); mipavPanel_.add(new JLabel("Target directory:"), ""); saveDestinationField_ = new JTextField(); saveDestinationField_.setText(prefs_.getString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, "")); saveDestinationField_.setColumns(textFieldWidth); mipavPanel_.add(saveDestinationField_); JButton browseToSaveDestinationButton = new JButton(); browseToSaveDestinationButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setSaveDestinationDirectory(saveDestinationField_); prefs_.putString(panelName_, Properties.Keys.PLUGIN_EXPORT_MIPAV_DATA_DIR, saveDestinationField_.getText()); } }); browseToSaveDestinationButton.setMargin(new Insets(2, 5, 2, 5)); browseToSaveDestinationButton.setText("..."); mipavPanel_.add(browseToSaveDestinationButton, "wrap"); final JProgressBar progBar = new JProgressBar(); progBar.setStringPainted(true); JButton exportButton = new JButton("Export"); exportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); SaveTask task = new SaveTask(saveDestinationField_.getText()); task.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { int progress = (Integer) evt.getNewValue(); progBar.setValue(progress); if (progress == 100) { progBar.setString("Done!"); } } } }); task.execute(); } }); mipavPanel_.add(exportButton, "span 3, center, wrap"); mipavPanel_.add(progBar, "span3, center, wrap"); this.add(mipavPanel_); } class SaveTask extends SwingWorker<Void, Void> { final String targetDirectory_; SaveTask (String targetDirectory) { targetDirectory_ = targetDirectory; } @Override protected Void doInBackground() throws Exception { setProgress(0); boolean rotateRight = true; ImagePlus ip = IJ.getImage(); MMWindow mmW = new MMWindow(ip); try { if (!mmW.isMMWindow()) { gui_.message("Can only convert Micro-Manager data set "); return null; } String spimADir = targetDirectory_ + "\\" + "SPIMA"; String spimBDir = targetDirectory_ + "\\" + "SPIMB"; if (new File(spimADir).exists() || new File(spimBDir).exists()) { gui_.message("Output directory already exists"); return null; } new File(spimADir).mkdirs(); new File(spimBDir).mkdir(); String acqName = ip.getShortTitle(); acqName = acqName.replace("/", "-"); ImageProcessor iProc = ip.getProcessor(); int totalNr = 2 * mmW.getNumberOfFrames() * mmW.getNumberOfSlices(); int counter = 0; for (int c = 0; c < 2; c++) { for (int t = 0; t < mmW.getNumberOfFrames(); t++) { ImageStack stack = new ImageStack(iProc.getWidth(), iProc.getHeight()); for (int i = 0; i < mmW.getNumberOfSlices(); i++) { ImageProcessor iProc2; iProc2 = mmW.getImageProcessor(c, i, t, 1); if (rotateRight) { iProc2 = iProc2.rotateRight(); } stack.addSlice(iProc2); counter++; setProgress(counter / totalNr * 100); } ImagePlus ipN = new ImagePlus("tmp", stack); if (c == 0) { ij.IJ.save(ipN, spimADir + "\\" + acqName + "_" + "SPIMA-" + t + ".tif"); } else if (c == 1) { ij.IJ.save(ipN, spimBDir + "\\" + acqName + "_" + "SPIMB-" + t + ".tif"); } } } } catch (MMScriptException ex) { ReportingUtils.showError(ex, "Problem saving data"); } return null; } @Override public void done() { setProgress(100); setCursor(null); } } private void setSaveDestinationDirectory(JTextField rootField) { File result = FileDialogs.openDir(null, "Please choose a directory root for image data", MMStudioMainFrame.MM_DATA_SET); if (result != null) { rootField.setText(result.getAbsolutePath()); } } // needs to be put on its own thread, untested code private void exportMipav(String targetDirectory) { boolean rotateRight = true; ImagePlus ip = IJ.getImage(); MMWindow mmW = new MMWindow(ip); try { if (!mmW.isMMWindow()) { gui_.message("Can only convert Micro-Manager data set "); return; } String spimADir = targetDirectory + "\\" + "SPIMA"; String spimBDir = targetDirectory + "\\" + "SPIMB"; if (new File(spimADir).exists() || new File(spimBDir).exists()) { gui_.message("Output directory already exists"); return; } new File(spimADir).mkdirs(); new File(spimBDir).mkdir(); String acqName = ip.getShortTitle(); acqName = acqName.replace("/", "-"); ImageProcessor iProc = ip.getProcessor(); //gui.message("NrSlices: " + mmW.getNumberOfSlices()); for (int c = 0; c < 2; c++) { for (int t = 0; t < mmW.getNumberOfFrames(); t++) { ImageStack stack = new ImageStack(iProc.getWidth(), iProc.getHeight()); for (int i = 0; i < mmW.getNumberOfSlices(); i++) { ImageProcessor iProc2; iProc2 = mmW.getImageProcessor(c, i, t, 1); if (rotateRight) { iProc2 = iProc2.rotateRight(); } stack.addSlice(iProc2); } ImagePlus ipN = new ImagePlus("tmp", stack); if (c == 0) { ij.IJ.save(ipN, spimADir + "\\" + acqName + "_" + "SPIMA-" + t + ".tif"); } else if (c == 1) { ij.IJ.save(ipN, spimBDir + "\\" + acqName + "_" + "SPIMB-" + t + ".tif"); } } } } catch (MMScriptException ex) { ReportingUtils.showError(ex, "Problem saving data"); } } }
plugins/ASIdiSPIM/src/org/micromanager/asidispim/DataAnalysisPanel.java
package org.micromanager.asidispim; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.process.ImageProcessor; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.MMWindow; import org.micromanager.api.ScriptInterface; import org.micromanager.asidispim.Data.Prefs; import org.micromanager.asidispim.Data.Properties; import org.micromanager.asidispim.Utils.ListeningJPanel; import org.micromanager.asidispim.Utils.PanelUtils; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; /** * Panel in ASIdiSPIM plugin specifically for data analysis/processing * For now, we provide a way to export Micro-Manager datasets into * a mipav compatible format * mipav likes data in a folder as follows: * folder - SPIMA - name_SPIMA-0.tif, name_SPIMA-x.tif, name_SPIMA-n.tif * - SPIMB - name_SPIMB-0.tif, name_SPIMB-x.tif, name_SPIMB-n.tif * @author Nico */ @SuppressWarnings("serial") public class DataAnalysisPanel extends ListeningJPanel { private final ScriptInterface gui_; private final JPanel mipavPanel_; private final JTextField saveDestinationField_; private Prefs prefs_; /** * * @param gui -implementation of the Micro-Manager ScriptInterface api */ public DataAnalysisPanel(ScriptInterface gui, Prefs prefs) { super("Data Analysis", new MigLayout( "", "[right]", "[]16[]")); gui_ = gui; prefs_ = prefs; int textFieldWidth = 20; // start volume sub-panel mipavPanel_ = new JPanel(new MigLayout( "", "[right]4[center]4[left]", "[]8[]")); mipavPanel_.setBorder(PanelUtils.makeTitledBorder("Export to mipav")); JLabel instructions = new JLabel("Exports selected data set to a format \n" + "compatible with the mipav GenerateFusion Plugin"); mipavPanel_.add(instructions, "span 3, wrap"); mipavPanel_.add(new JLabel("Target directory:"), ""); saveDestinationField_ = new JTextField(); saveDestinationField_.setText(prefs_.getString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, "")); saveDestinationField_.setColumns(textFieldWidth); mipavPanel_.add(saveDestinationField_); JButton browseToSaveDestinationButton = new JButton(); browseToSaveDestinationButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setSaveDestinationDirectory(saveDestinationField_); prefs_.putString(panelName_, Properties.Keys.PLUGIN_EXPORT_MIPAV_DATA_DIR, saveDestinationField_.getText()); } }); browseToSaveDestinationButton.setMargin(new Insets(2, 5, 2, 5)); browseToSaveDestinationButton.setText("..."); mipavPanel_.add(browseToSaveDestinationButton, "wrap"); JButton exportButton = new JButton("Export"); exportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exportMipav(saveDestinationField_.getText()); } }); mipavPanel_.add(exportButton, "span 3, center, wrap"); this.add(mipavPanel_); } private void setSaveDestinationDirectory(JTextField rootField) { File result = FileDialogs.openDir(null, "Please choose a directory root for image data", MMStudioMainFrame.MM_DATA_SET); if (result != null) { rootField.setText(result.getAbsolutePath()); } } // needs to be put on its own thread, untested code private void exportMipav(String targetDirectory) { boolean rotateRight = true; ImagePlus ip = IJ.getImage(); MMWindow mmW = new MMWindow(ip); try { if (!mmW.isMMWindow()) { gui_.message("Can only convert Micro-Manager data set "); return; } String spimADir = targetDirectory + "\\" + "SPIMA"; String spimBDir = targetDirectory + "\\" + "SPIMB"; if (new File(spimADir).exists() || new File(spimBDir).exists()) { gui_.message("Output directory already exists"); return; } new File(spimADir).mkdirs(); new File(spimBDir).mkdir(); String acqName = ip.getShortTitle(); acqName = acqName.replace("/", "-"); ImageProcessor iProc = ip.getProcessor(); //gui.message("NrSlices: " + mmW.getNumberOfSlices()); for (int c = 0; c < 2; c++) { for (int t = 0; t < mmW.getNumberOfFrames(); t++) { ImageStack stack = new ImageStack(iProc.getWidth(), iProc.getHeight()); for (int i = 0; i < mmW.getNumberOfSlices(); i++) { ImageProcessor iProc2; iProc2 = mmW.getImageProcessor(c, i, t, 1); if (rotateRight) { iProc2 = iProc2.rotateRight(); } stack.addSlice(iProc2); } ImagePlus ipN = new ImagePlus("tmp", stack); if (c == 0) { ij.IJ.save(ipN, spimADir + "\\" + acqName + "_" + "SPIMA-" + t + ".tif"); } else if (c == 1) { ij.IJ.save(ipN, spimBDir + "\\" + acqName + "_" + "SPIMB-" + t + ".tif"); } } } } catch (MMScriptException ex) { ReportingUtils.showError(ex, "Problem saving data"); } } }
Added a progress bar to file saving git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@13361 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
plugins/ASIdiSPIM/src/org/micromanager/asidispim/DataAnalysisPanel.java
Added a progress bar to file saving
<ide><path>lugins/ASIdiSPIM/src/org/micromanager/asidispim/DataAnalysisPanel.java <ide> import ij.ImagePlus; <ide> import ij.ImageStack; <ide> import ij.process.ImageProcessor; <add>import java.awt.Cursor; <ide> import java.awt.Insets; <ide> import java.awt.event.ActionEvent; <ide> import java.awt.event.ActionListener; <add>import java.beans.PropertyChangeEvent; <add>import java.beans.PropertyChangeListener; <ide> import java.io.File; <del>import java.util.logging.Level; <del>import java.util.logging.Logger; <ide> import javax.swing.JButton; <add>import javax.swing.JComponent; <ide> import javax.swing.JLabel; <ide> import javax.swing.JPanel; <add>import javax.swing.JProgressBar; <ide> import javax.swing.JTextField; <add>import javax.swing.SwingWorker; <ide> import net.miginfocom.swing.MigLayout; <ide> import org.micromanager.MMStudioMainFrame; <ide> import org.micromanager.api.MMWindow; <ide> <ide> /** <ide> * <del> * @param gui -implementation of the Micro-Manager ScriptInterface api <add> * @param gui - implementation of the Micro-Manager ScriptInterface api <add> * @param prefs - Plugin wide preferences <ide> */ <ide> public DataAnalysisPanel(ScriptInterface gui, Prefs prefs) { <ide> super("Data Analysis", <ide> browseToSaveDestinationButton.setText("..."); <ide> mipavPanel_.add(browseToSaveDestinationButton, "wrap"); <ide> <add> final JProgressBar progBar = new JProgressBar(); <add> progBar.setStringPainted(true); <add> <ide> JButton exportButton = new JButton("Export"); <ide> exportButton.addActionListener(new ActionListener() { <add> @Override <ide> public void actionPerformed(ActionEvent e) { <del> exportMipav(saveDestinationField_.getText()); <add> setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); <add> SaveTask task = new SaveTask(saveDestinationField_.getText()); <add> task.addPropertyChangeListener(new PropertyChangeListener() { <add> <add> @Override <add> public void propertyChange(PropertyChangeEvent evt) { <add> if ("progress".equals(evt.getPropertyName())) { <add> int progress = (Integer) evt.getNewValue(); <add> progBar.setValue(progress); <add> if (progress == 100) { <add> progBar.setString("Done!"); <add> } <add> } <add> } <add> }); <add> task.execute(); <ide> } <ide> }); <ide> mipavPanel_.add(exportButton, "span 3, center, wrap"); <del> <del> <add> mipavPanel_.add(progBar, "span3, center, wrap"); <add> <add> <add> <add> <ide> this.add(mipavPanel_); <ide> } <ide> <add> class SaveTask extends SwingWorker<Void, Void> { <add> final String targetDirectory_; <add> SaveTask (String targetDirectory) { <add> targetDirectory_ = targetDirectory; <add> } <add> <add> @Override <add> protected Void doInBackground() throws Exception { <add> setProgress(0); <add> boolean rotateRight = true; <add> ImagePlus ip = IJ.getImage(); <add> MMWindow mmW = new MMWindow(ip); <add> try { <add> if (!mmW.isMMWindow()) { <add> gui_.message("Can only convert Micro-Manager data set "); <add> return null; <add> } <add> <add> String spimADir = targetDirectory_ + "\\" + "SPIMA"; <add> String spimBDir = targetDirectory_ + "\\" + "SPIMB"; <add> <add> if (new File(spimADir).exists() <add> || new File(spimBDir).exists()) { <add> gui_.message("Output directory already exists"); <add> return null; <add> } <add> <add> new File(spimADir).mkdirs(); <add> new File(spimBDir).mkdir(); <add> <add> String acqName = ip.getShortTitle(); <add> acqName = acqName.replace("/", "-"); <add> <add> ImageProcessor iProc = ip.getProcessor(); <add> int totalNr = 2 * mmW.getNumberOfFrames() * mmW.getNumberOfSlices(); <add> int counter = 0; <add> <add> for (int c = 0; c < 2; c++) { <add> for (int t = 0; t < mmW.getNumberOfFrames(); t++) { <add> ImageStack stack = new ImageStack(iProc.getWidth(), iProc.getHeight()); <add> for (int i = 0; i < mmW.getNumberOfSlices(); i++) { <add> ImageProcessor iProc2; <add> <add> iProc2 = mmW.getImageProcessor(c, i, t, 1); <add> <add> if (rotateRight) { <add> iProc2 = iProc2.rotateRight(); <add> } <add> stack.addSlice(iProc2); <add> counter++; <add> setProgress(counter / totalNr * 100); <add> } <add> ImagePlus ipN = new ImagePlus("tmp", stack); <add> if (c == 0) { <add> ij.IJ.save(ipN, spimADir + "\\" + acqName + "_" + "SPIMA-" + t + ".tif"); <add> } else if (c == 1) { <add> ij.IJ.save(ipN, spimBDir + "\\" + acqName + "_" + "SPIMB-" + t + ".tif"); <add> } <add> <add> } <add> } <add> } catch (MMScriptException ex) { <add> ReportingUtils.showError(ex, "Problem saving data"); <add> } <add> <add> return null; <add> } <add> <add> @Override <add> public void done() { <add> setProgress(100); <add> setCursor(null); <add> } <add> } <add> <ide> private void setSaveDestinationDirectory(JTextField rootField) { <ide> File result = FileDialogs.openDir(null, <ide> "Please choose a directory root for image data", <ide> rootField.setText(result.getAbsolutePath()); <ide> } <ide> } <del> <add> <ide> // needs to be put on its own thread, untested code <ide> private void exportMipav(String targetDirectory) { <ide> boolean rotateRight = true; <ide> gui_.message("Can only convert Micro-Manager data set "); <ide> return; <ide> } <del> <add> <ide> String spimADir = targetDirectory + "\\" + "SPIMA"; <ide> String spimBDir = targetDirectory + "\\" + "SPIMB"; <del> <add> <ide> if (new File(spimADir).exists() <ide> || new File(spimBDir).exists()) { <ide> gui_.message("Output directory already exists"); <ide> return; <ide> } <del> <add> <ide> new File(spimADir).mkdirs(); <ide> new File(spimBDir).mkdir(); <del> <add> <ide> String acqName = ip.getShortTitle(); <ide> acqName = acqName.replace("/", "-"); <del> <add> <ide> ImageProcessor iProc = ip.getProcessor(); <ide> //gui.message("NrSlices: " + mmW.getNumberOfSlices()); <ide> <del> <ide> for (int c = 0; c < 2; c++) { <ide> for (int t = 0; t < mmW.getNumberOfFrames(); t++) { <ide> ImageStack stack = new ImageStack(iProc.getWidth(), iProc.getHeight()); <ide> for (int i = 0; i < mmW.getNumberOfSlices(); i++) { <ide> ImageProcessor iProc2; <del> <add> <ide> iProc2 = mmW.getImageProcessor(c, i, t, 1); <del> <add> <ide> if (rotateRight) { <ide> iProc2 = iProc2.rotateRight(); <ide> }
Java
apache-2.0
be8f0d0879e2b9df1cd7773bc2fe88cde26c707d
0
real-logic/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,real-logic/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,mikeb01/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron
/* * Copyright 2014-2019 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.cluster; import io.aeron.Aeron; import io.aeron.CommonContext; import io.aeron.Counter; import io.aeron.archive.Archive; import io.aeron.archive.client.AeronArchive; import io.aeron.cluster.client.AeronCluster; import io.aeron.cluster.client.ClusterClock; import io.aeron.cluster.client.ClusterException; import io.aeron.cluster.codecs.mark.ClusterComponentType; import io.aeron.cluster.service.*; import io.aeron.exceptions.ConcurrentConcludeException; import io.aeron.security.Authenticator; import io.aeron.security.AuthenticatorSupplier; import org.agrona.*; import org.agrona.concurrent.*; import org.agrona.concurrent.errors.DistinctErrorLog; import org.agrona.concurrent.errors.LoggingErrorHandler; import org.agrona.concurrent.status.AtomicCounter; import java.io.File; import java.util.Random; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.function.Supplier; import static io.aeron.cluster.ConsensusModule.Configuration.*; import static io.aeron.cluster.service.ClusteredServiceContainer.Configuration.SNAPSHOT_CHANNEL_PROP_NAME; import static io.aeron.cluster.service.ClusteredServiceContainer.Configuration.SNAPSHOT_STREAM_ID_PROP_NAME; import static java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater; import static org.agrona.SystemUtil.*; import static org.agrona.concurrent.status.CountersReader.METADATA_LENGTH; /** * Component which resides on each node and is responsible for coordinating consensus within a cluster in concert * with the lifecycle of clustered services. */ @SuppressWarnings("unused") public class ConsensusModule implements AutoCloseable { /** * Possible states for the {@link ConsensusModule}. * These will be reflected in the {@link Context#moduleStateCounter()} counter. */ public enum State { /** * Starting up and recovering state. */ INIT(0), /** * Active state with ingress and expired timers appended to the log. */ ACTIVE(1), /** * Suspended processing of ingress and expired timers. */ SUSPENDED(2), /** * In the process of taking a snapshot. */ SNAPSHOT(3), /** * Leaving cluster and shutting down as soon as services ack without taking a snapshot. */ LEAVING(4), /** * In the process of terminating the node. */ TERMINATING(5), /** * Terminal state. */ CLOSED(6); static final State[] STATES; static { final State[] states = values(); STATES = new State[states.length]; for (final State state : states) { final int code = state.code(); if (null != STATES[code]) { throw new ClusterException("code already in use: " + code); } STATES[code] = state; } } private final int code; State(final int code) { this.code = code; } public final int code() { return code; } /** * Get the {@link State} encoded in an {@link AtomicCounter}. * * @param counter to get the current state for. * @return the state for the {@link ConsensusModule}. * @throws ClusterException if the counter is not one of the valid values. */ public static State get(final AtomicCounter counter) { final long code = counter.get(); return get((int)code); } /** * Get the {@link State} corresponding to a particular code. * * @param code representing a {@link State}. * @return the {@link State} corresponding to the provided code. * @throws ClusterException if the code does not correspond to a valid State. */ public static State get(final int code) { if (code < 0 || code > (STATES.length - 1)) { throw new ClusterException("invalid state counter code: " + code); } return STATES[code]; } } /** * Launch an {@link ConsensusModule} with that communicates with an out of process {@link io.aeron.archive.Archive} * and {@link io.aeron.driver.MediaDriver} then awaits shutdown signal. * * @param args command line argument which is a list for properties files as URLs or filenames. */ public static void main(final String[] args) { loadPropertiesFiles(args); try (ConsensusModule consensusModule = launch()) { consensusModule.context().shutdownSignalBarrier().await(); System.out.println("Shutdown ConsensusModule..."); } } private final Context ctx; private final AgentRunner conductorRunner; ConsensusModule(final Context ctx) { this.ctx = ctx; try { ctx.conclude(); } catch (final Throwable ex) { if (null != ctx.markFile) { ctx.markFile.signalFailedStart(); } ctx.close(); throw ex; } final ConsensusModuleAgent conductor = new ConsensusModuleAgent(ctx); conductorRunner = new AgentRunner(ctx.idleStrategy(), ctx.errorHandler(), ctx.errorCounter(), conductor); } private ConsensusModule start() { AgentRunner.startOnThread(conductorRunner, ctx.threadFactory()); return this; } /** * Launch an {@link ConsensusModule} using a default configuration. * * @return a new instance of an {@link ConsensusModule}. */ public static ConsensusModule launch() { return launch(new Context()); } /** * Launch an {@link ConsensusModule} by providing a configuration context. * * @param ctx for the configuration parameters. * @return a new instance of an {@link ConsensusModule}. */ public static ConsensusModule launch(final Context ctx) { return new ConsensusModule(ctx).start(); } /** * Get the {@link ConsensusModule.Context} that is used by this {@link ConsensusModule}. * * @return the {@link ConsensusModule.Context} that is used by this {@link ConsensusModule}. */ public Context context() { return ctx; } public void close() { CloseHelper.close(conductorRunner); } /** * Configuration options for cluster. */ public static class Configuration { /** * Property name for the limit for fragments to be consumed on each poll of ingress. */ public static final String CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME = "aeron.cluster.ingress.fragment.limit"; /** * Default for the limit for fragments to be consumed on each poll of ingress. */ public static final int CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT = 50; /** * Type of snapshot for this component. */ public static final long SNAPSHOT_TYPE_ID = 1; /** * Service ID to identify a snapshot in the {@link RecordingLog}. */ public static final int SERVICE_ID = Aeron.NULL_VALUE; /** * Property name for the identity of the cluster member. */ public static final String CLUSTER_MEMBER_ID_PROP_NAME = "aeron.cluster.member.id"; /** * Default property for the cluster member identity. */ public static final int CLUSTER_MEMBER_ID_DEFAULT = 0; /** * Property name for the identity of the appointed leader. This is when automated leader elections are * not employed. */ public static final String APPOINTED_LEADER_ID_PROP_NAME = "aeron.cluster.appointed.leader.id"; /** * Default property for the appointed cluster leader id. A value of {@link Aeron#NULL_VALUE} means no leader * has been appointed and thus an automated leader election should occur. */ public static final int APPOINTED_LEADER_ID_DEFAULT = Aeron.NULL_VALUE; /** * Property name for the comma separated list of cluster member endpoints. * <p> * <code> * 0,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| \ * 1,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| ... * </code> * <p> * The client facing endpoints will be used as the endpoint substituted into the * {@link io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_CHANNEL_PROP_NAME} if the endpoint * is not provided when unicast. */ public static final String CLUSTER_MEMBERS_PROP_NAME = "aeron.cluster.members"; /** * Default property for the list of cluster member endpoints. */ public static final String CLUSTER_MEMBERS_DEFAULT = "0,localhost:10000,localhost:20000,localhost:30000,localhost:40000,localhost:8010"; /** * Property name for the comma separated list of cluster member status endpoints used for adding passive * followers as well as dynamic join of a cluster. */ public static final String CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME = "aeron.cluster.members.status.endpoints"; /** * Default property for the list of cluster member status endpoints. */ public static final String CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT = ""; /** * Property name for whether cluster member information in snapshots should be ignored on load or not. */ public static final String CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME = "aeron.cluster.members.ignore.snapshot"; /** * Default property for whether cluster member information in snapshots should be ignored or not. */ public static final String CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT = "false"; /** * Channel for the clustered log. */ public static final String LOG_CHANNEL_PROP_NAME = "aeron.cluster.log.channel"; /** * Channel for the clustered log. */ public static final String LOG_CHANNEL_DEFAULT = "aeron:udp?endpoint=localhost:9030|group=true"; /** * Property name for the comma separated list of member endpoints. * <p> * <code> * client-facing:port,member-facing:port,log:port,transfer:port,archive:port * </code> * @see #CLUSTER_MEMBERS_PROP_NAME */ public static final String MEMBER_ENDPOINTS_PROP_NAME = "aeron.cluster.member.endpoints"; /** * Default property for member endpoints. */ public static final String MEMBER_ENDPOINTS_DEFAULT = ""; /** * Stream id within a channel for the clustered log. */ public static final String LOG_STREAM_ID_PROP_NAME = "aeron.cluster.log.stream.id"; /** * Stream id within a channel for the clustered log. */ public static final int LOG_STREAM_ID_DEFAULT = 100; /** * Channel to be used for archiving snapshots. */ public static final String SNAPSHOT_CHANNEL_DEFAULT = CommonContext.IPC_CHANNEL + "?alias=snapshot"; /** * Stream id for the archived snapshots within a channel. */ public static final int SNAPSHOT_STREAM_ID_DEFAULT = 107; /** * Message detail to be sent when max concurrent session limit is reached. */ public static final String SESSION_LIMIT_MSG = "concurrent session limit"; /** * Message detail to be sent when a session timeout occurs. */ public static final String SESSION_TIMEOUT_MSG = "session inactive"; /** * Message detail to be sent when a session is terminated by a service. */ public static final String SESSION_TERMINATED_MSG = "session terminated"; /** * Message detail to be sent when a session is rejected due to authentication. */ public static final String SESSION_REJECTED_MSG = "session failed authentication"; /** * Message detail to be sent when a session has an invalid client version. */ public static final String SESSION_INVALID_VERSION_MSG = "invalid client version"; /** * Channel to be used communicating cluster member status to each other. This can be used for default * configuration with the endpoints replaced with those provided by {@link #CLUSTER_MEMBERS_PROP_NAME}. */ public static final String MEMBER_STATUS_CHANNEL_PROP_NAME = "aeron.cluster.member.status.channel"; /** * Channel to be used for communicating cluster member status to each other. This can be used for default * configuration with the endpoints replaced with those provided by {@link #CLUSTER_MEMBERS_PROP_NAME}. */ public static final String MEMBER_STATUS_CHANNEL_DEFAULT = "aeron:udp?term-length=64k"; /** * Stream id within a channel for communicating cluster member status. */ public static final String MEMBER_STATUS_STREAM_ID_PROP_NAME = "aeron.cluster.member.status.stream.id"; /** * Stream id for the archived snapshots within a channel. */ public static final int MEMBER_STATUS_STREAM_ID_DEFAULT = 108; /** * Counter type id for the consensus module state. */ public static final int CONSENSUS_MODULE_STATE_TYPE_ID = 200; /** * Counter type id for the consensus module error count. */ public static final int CONSENSUS_MODULE_ERROR_COUNT_TYPE_ID = 212; /** * Counter type id for the number of cluster clients which have been timed out. */ public static final int CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID = 213; /** * Counter type id for the number of invalid requests which the cluster has received. */ public static final int CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID = 214; /** * Counter type id for the cluster node role. */ public static final int CLUSTER_NODE_ROLE_TYPE_ID = ClusterNodeRole.CLUSTER_NODE_ROLE_TYPE_ID; /** * Counter type id for the control toggle. */ public static final int CONTROL_TOGGLE_TYPE_ID = ClusterControl.CONTROL_TOGGLE_TYPE_ID; /** * Type id of a commit position counter. */ public static final int COMMIT_POSITION_TYPE_ID = CommitPos.COMMIT_POSITION_TYPE_ID; /** * Type id of a recovery state counter. */ public static final int RECOVERY_STATE_TYPE_ID = RecoveryState.RECOVERY_STATE_TYPE_ID; /** * Counter type id for count of snapshots taken. */ public static final int SNAPSHOT_COUNTER_TYPE_ID = 205; /** * Type id for election state counter. */ public static final int ELECTION_STATE_TYPE_ID = Election.ELECTION_STATE_TYPE_ID; /** * The number of services in this cluster instance. */ public static final String SERVICE_COUNT_PROP_NAME = "aeron.cluster.service.count"; /** * The number of services in this cluster instance. */ public static final int SERVICE_COUNT_DEFAULT = 1; /** * Maximum number of cluster sessions that can be active concurrently. */ public static final String MAX_CONCURRENT_SESSIONS_PROP_NAME = "aeron.cluster.max.sessions"; /** * Maximum number of cluster sessions that can be active concurrently. */ public static final int MAX_CONCURRENT_SESSIONS_DEFAULT = 10; /** * Timeout for a session if no activity is observed. */ public static final String SESSION_TIMEOUT_PROP_NAME = "aeron.cluster.session.timeout"; /** * Timeout for a session if no activity is observed. */ public static final long SESSION_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(5); /** * Timeout for a leader if no heartbeat is received by an other member. */ public static final String LEADER_HEARTBEAT_TIMEOUT_PROP_NAME = "aeron.cluster.leader.heartbeat.timeout"; /** * Timeout for a leader if no heartbeat is received by an other member. */ public static final long LEADER_HEARTBEAT_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(10); /** * Interval at which a leader will send heartbeats if the log is not progressing. */ public static final String LEADER_HEARTBEAT_INTERVAL_PROP_NAME = "aeron.cluster.leader.heartbeat.interval"; /** * Interval at which a leader will send heartbeats if the log is not progressing. */ public static final long LEADER_HEARTBEAT_INTERVAL_DEFAULT_NS = TimeUnit.MILLISECONDS.toNanos(200); /** * Timeout after which an election vote will be attempted after startup while waiting to canvass the status * of members if a majority has been heard from. */ public static final String STARTUP_CANVASS_TIMEOUT_PROP_NAME = "aeron.cluster.startup.canvass.timeout"; /** * Default timeout after which an election vote will be attempted on startup when waiting to canvass the * status of all members before going for a majority if possible. */ public static final long STARTUP_CANVASS_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(60); /** * Timeout after which an election fails if the candidate does not get a majority of votes. */ public static final String ELECTION_TIMEOUT_PROP_NAME = "aeron.cluster.election.timeout"; /** * Default timeout after which an election fails if the candidate does not get a majority of votes. */ public static final long ELECTION_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(1); /** * Interval at which a member will send out status updates during election phases. */ public static final String ELECTION_STATUS_INTERVAL_PROP_NAME = "aeron.cluster.election.status.interval"; /** * Default interval at which a member will send out status updates during election phases. */ public static final long ELECTION_STATUS_INTERVAL_DEFAULT_NS = TimeUnit.MILLISECONDS.toNanos(20); /** * Interval at which a dynamic joining member will send add cluster member and snapshot recording * queries. */ public static final String DYNAMIC_JOIN_INTERVAL_PROP_NAME = "aeron.cluster.dynamic.join.interval"; /** * Default interval at which a dynamic joining member will send add cluster member and snapshot recording * queries. */ public static final long DYNAMIC_JOIN_INTERVAL_DEFAULT_NS = TimeUnit.SECONDS.toNanos(1); /** * Name of class to use as a supplier of {@link Authenticator} for the cluster. */ public static final String AUTHENTICATOR_SUPPLIER_PROP_NAME = "aeron.cluster.authenticator.supplier"; /** * Name of the class to use as a supplier of {@link Authenticator} for the cluster. Default is * a non-authenticating option. */ public static final String AUTHENTICATOR_SUPPLIER_DEFAULT = "io.aeron.security.DefaultAuthenticatorSupplier"; /** * Size in bytes of the error buffer for the cluster. */ public static final String ERROR_BUFFER_LENGTH_PROP_NAME = "aeron.cluster.error.buffer.length"; /** * Size in bytes of the error buffer for the cluster. */ public static final int ERROR_BUFFER_LENGTH_DEFAULT = 1024 * 1024; /** * Timeout waiting for follower termination by leader. */ public static final String TERMINATION_TIMEOUT_PROP_NAME = "aeron.cluster.termination.timeout"; /** * Timeout waiting for follower termination by leader default value. */ public static final long TERMINATION_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(5); /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. */ public static final String WHEEL_TICK_RESOLUTION_PROP_NAME = "aeron.cluster.wheel.tick.resolution"; /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. Defaults to 8ms. */ public static final long WHEEL_TICK_RESOLUTION_DEFAULT_NS = TimeUnit.MILLISECONDS.toNanos(8); /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. */ public static final String TICKS_PER_WHEEL_PROP_NAME = "aeron.cluster.ticks.per.wheel"; /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. Defaults to 128 per wheel. */ public static final int TICKS_PER_WHEEL_DEFAULT = 128; /** * The level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> */ public static final String FILE_SYNC_LEVEL_PROP_NAME = "aeron.cluster.file.sync.level"; /** * Default file sync level of normal writes. */ public static final int FILE_SYNC_LEVEL_DEFAULT = 0; /** * The value {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT} or system property * {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME} if set. * * @return {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT} or system property * {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME} if set. */ public static int ingressFragmentLimit() { return Integer.getInteger(CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME, CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT); } /** * The value {@link #CLUSTER_MEMBER_ID_DEFAULT} or system property * {@link #CLUSTER_MEMBER_ID_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBER_ID_DEFAULT} or system property * {@link #CLUSTER_MEMBER_ID_PROP_NAME} if set. */ public static int clusterMemberId() { return Integer.getInteger(CLUSTER_MEMBER_ID_PROP_NAME, CLUSTER_MEMBER_ID_DEFAULT); } /** * The value {@link #APPOINTED_LEADER_ID_DEFAULT} or system property * {@link #APPOINTED_LEADER_ID_PROP_NAME} if set. * * @return {@link #APPOINTED_LEADER_ID_DEFAULT} or system property * {@link #APPOINTED_LEADER_ID_PROP_NAME} if set. */ public static int appointedLeaderId() { return Integer.getInteger(APPOINTED_LEADER_ID_PROP_NAME, APPOINTED_LEADER_ID_DEFAULT); } /** * The value {@link #CLUSTER_MEMBERS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBERS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_PROP_NAME} if set. */ public static String clusterMembers() { return System.getProperty(CLUSTER_MEMBERS_PROP_NAME, CLUSTER_MEMBERS_DEFAULT); } /** * The value {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME} it set. */ public static String clusterMembersStatusEndpoints() { return System.getProperty( CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME, CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT); } /** * The value {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME} it set. */ public static boolean clusterMembersIgnoreSnapshot() { return "true".equalsIgnoreCase(System.getProperty( CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME, CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT)); } /** * The value {@link #LOG_CHANNEL_DEFAULT} or system property {@link #LOG_CHANNEL_PROP_NAME} if set. * * @return {@link #LOG_CHANNEL_DEFAULT} or system property {@link #LOG_CHANNEL_PROP_NAME} if set. */ public static String logChannel() { return System.getProperty(LOG_CHANNEL_PROP_NAME, LOG_CHANNEL_DEFAULT); } /** * The value {@link #LOG_STREAM_ID_DEFAULT} or system property {@link #LOG_STREAM_ID_PROP_NAME} if set. * * @return {@link #LOG_STREAM_ID_DEFAULT} or system property {@link #LOG_STREAM_ID_PROP_NAME} if set. */ public static int logStreamId() { return Integer.getInteger(LOG_STREAM_ID_PROP_NAME, LOG_STREAM_ID_DEFAULT); } /** * The value {@link #MEMBER_ENDPOINTS_DEFAULT} or system property {@link #MEMBER_ENDPOINTS_PROP_NAME} if set. * * @return {@link #MEMBER_ENDPOINTS_DEFAULT} or system property {@link #MEMBER_ENDPOINTS_PROP_NAME} if set. */ public static String memberEndpoints() { return System.getProperty(MEMBER_ENDPOINTS_PROP_NAME, MEMBER_ENDPOINTS_DEFAULT); } /** * The value {@link #SNAPSHOT_CHANNEL_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME} if set. * * @return {@link #SNAPSHOT_CHANNEL_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME} if set. */ public static String snapshotChannel() { return System.getProperty(SNAPSHOT_CHANNEL_PROP_NAME, SNAPSHOT_CHANNEL_DEFAULT); } /** * The value {@link #SNAPSHOT_STREAM_ID_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME} if set. * * @return {@link #SNAPSHOT_STREAM_ID_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME} if set. */ public static int snapshotStreamId() { return Integer.getInteger(SNAPSHOT_STREAM_ID_PROP_NAME, SNAPSHOT_STREAM_ID_DEFAULT); } /** * The value {@link #SERVICE_COUNT_DEFAULT} or system property * {@link #SERVICE_COUNT_PROP_NAME} if set. * * @return {@link #SERVICE_COUNT_DEFAULT} or system property * {@link #SERVICE_COUNT_PROP_NAME} if set. */ public static int serviceCount() { return Integer.getInteger(SERVICE_COUNT_PROP_NAME, SERVICE_COUNT_DEFAULT); } /** * The value {@link #MAX_CONCURRENT_SESSIONS_DEFAULT} or system property * {@link #MAX_CONCURRENT_SESSIONS_PROP_NAME} if set. * * @return {@link #MAX_CONCURRENT_SESSIONS_DEFAULT} or system property * {@link #MAX_CONCURRENT_SESSIONS_PROP_NAME} if set. */ public static int maxConcurrentSessions() { return Integer.getInteger(MAX_CONCURRENT_SESSIONS_PROP_NAME, MAX_CONCURRENT_SESSIONS_DEFAULT); } /** * Timeout for a session if no activity is observed. * * @return timeout in nanoseconds to wait for activity * @see #SESSION_TIMEOUT_PROP_NAME */ public static long sessionTimeoutNs() { return getDurationInNanos(SESSION_TIMEOUT_PROP_NAME, SESSION_TIMEOUT_DEFAULT_NS); } /** * Timeout for a leader if no heartbeat is received by an other member. * * @return timeout in nanoseconds to wait for heartbeat from a leader. * @see #LEADER_HEARTBEAT_TIMEOUT_PROP_NAME */ public static long leaderHeartbeatTimeoutNs() { return getDurationInNanos(LEADER_HEARTBEAT_TIMEOUT_PROP_NAME, LEADER_HEARTBEAT_TIMEOUT_DEFAULT_NS); } /** * Interval at which a leader will send a heartbeat if the log is not progressing. * * @return timeout in nanoseconds to for leader heartbeats when no log being appended. * @see #LEADER_HEARTBEAT_INTERVAL_PROP_NAME */ public static long leaderHeartbeatIntervalNs() { return getDurationInNanos(LEADER_HEARTBEAT_INTERVAL_PROP_NAME, LEADER_HEARTBEAT_INTERVAL_DEFAULT_NS); } /** * Timeout waiting to canvass the status of cluster members before voting if a majority have been heard from. * * @return timeout in nanoseconds to wait for the status of other cluster members before voting. * @see #STARTUP_CANVASS_TIMEOUT_PROP_NAME */ public static long startupCanvassTimeoutNs() { return getDurationInNanos(STARTUP_CANVASS_TIMEOUT_PROP_NAME, STARTUP_CANVASS_TIMEOUT_DEFAULT_NS); } /** * Timeout waiting for votes to become leader in an election. * * @return timeout in nanoseconds to wait for votes to become leader in an election. * @see #ELECTION_TIMEOUT_PROP_NAME */ public static long electionTimeoutNs() { return getDurationInNanos(ELECTION_TIMEOUT_PROP_NAME, ELECTION_TIMEOUT_DEFAULT_NS); } /** * Interval at which a member will send out status messages during the election phases. * * @return interval at which a member will send out status messages during the election phases. * @see #ELECTION_STATUS_INTERVAL_PROP_NAME */ public static long electionStatusIntervalNs() { return getDurationInNanos(ELECTION_STATUS_INTERVAL_PROP_NAME, ELECTION_STATUS_INTERVAL_DEFAULT_NS); } /** * Interval at which a dynamic joining member will send out add cluster members and snapshot recording * queries. * * @return Interval at which a dynamic joining member will send out add cluster members and snapshot recording * queries. * @see #DYNAMIC_JOIN_INTERVAL_PROP_NAME */ public static long dynamicJoinIntervalNs() { return getDurationInNanos(DYNAMIC_JOIN_INTERVAL_PROP_NAME, DYNAMIC_JOIN_INTERVAL_DEFAULT_NS); } /** * Timeout waiting for follower termination by leader. * * @return timeout in nanoseconds to wait followers to terminate. * @see #TERMINATION_TIMEOUT_PROP_NAME */ public static long terminationTimeoutNs() { return getDurationInNanos(TERMINATION_TIMEOUT_PROP_NAME, TERMINATION_TIMEOUT_DEFAULT_NS); } /** * Size in bytes of the error buffer in the mark file. * * @return length of error buffer in bytes. * @see #ERROR_BUFFER_LENGTH_PROP_NAME */ public static int errorBufferLength() { return getSizeAsInt(ERROR_BUFFER_LENGTH_PROP_NAME, ERROR_BUFFER_LENGTH_DEFAULT); } /** * The value {@link #AUTHENTICATOR_SUPPLIER_DEFAULT} or system property * {@link #AUTHENTICATOR_SUPPLIER_PROP_NAME} if set. * * @return {@link #AUTHENTICATOR_SUPPLIER_DEFAULT} or system property * {@link #AUTHENTICATOR_SUPPLIER_PROP_NAME} if set. */ public static AuthenticatorSupplier authenticatorSupplier() { final String supplierClassName = System.getProperty( AUTHENTICATOR_SUPPLIER_PROP_NAME, AUTHENTICATOR_SUPPLIER_DEFAULT); AuthenticatorSupplier supplier = null; try { supplier = (AuthenticatorSupplier)Class.forName(supplierClassName).getConstructor().newInstance(); } catch (final Exception ex) { LangUtil.rethrowUnchecked(ex); } return supplier; } /** * The value {@link #MEMBER_STATUS_CHANNEL_DEFAULT} or system property * {@link #MEMBER_STATUS_CHANNEL_PROP_NAME} if set. * * @return {@link #MEMBER_STATUS_CHANNEL_DEFAULT} or system property * {@link #MEMBER_STATUS_CHANNEL_PROP_NAME} if set. */ public static String memberStatusChannel() { return System.getProperty(MEMBER_STATUS_CHANNEL_PROP_NAME, MEMBER_STATUS_CHANNEL_DEFAULT); } /** * The value {@link #MEMBER_STATUS_STREAM_ID_DEFAULT} or system property * {@link #MEMBER_STATUS_STREAM_ID_PROP_NAME} if set. * * @return {@link #MEMBER_STATUS_STREAM_ID_DEFAULT} or system property * {@link #MEMBER_STATUS_STREAM_ID_PROP_NAME} if set. */ public static int memberStatusStreamId() { return Integer.getInteger(MEMBER_STATUS_STREAM_ID_PROP_NAME, MEMBER_STATUS_STREAM_ID_DEFAULT); } /** * The value {@link #WHEEL_TICK_RESOLUTION_DEFAULT_NS} or system property * {@link #WHEEL_TICK_RESOLUTION_PROP_NAME} if set. * * @return {@link #WHEEL_TICK_RESOLUTION_DEFAULT_NS} or system property * {@link #WHEEL_TICK_RESOLUTION_PROP_NAME} if set. */ public static long wheelTickResolutionNs() { return getDurationInNanos(WHEEL_TICK_RESOLUTION_PROP_NAME, WHEEL_TICK_RESOLUTION_DEFAULT_NS); } /** * The value {@link #TICKS_PER_WHEEL_DEFAULT} or system property * {@link #CLUSTER_MEMBER_ID_PROP_NAME} if set. * * @return {@link #TICKS_PER_WHEEL_DEFAULT} or system property * {@link #TICKS_PER_WHEEL_PROP_NAME} if set. */ public static int ticksPerWheel() { return Integer.getInteger(TICKS_PER_WHEEL_PROP_NAME, TICKS_PER_WHEEL_DEFAULT); } /** * The level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> * * @return level at which files should be sync'ed to disk. */ public static int fileSyncLevel() { return Integer.getInteger(FILE_SYNC_LEVEL_PROP_NAME, FILE_SYNC_LEVEL_DEFAULT); } } /** * Programmable overrides for configuring the {@link ConsensusModule} in a cluster. * <p> * The context will be owned by {@link ConsensusModuleAgent} after a successful * {@link ConsensusModule#launch(Context)} and closed via {@link ConsensusModule#close()}. */ public static class Context implements Cloneable { /** * Using an integer because there is no support for boolean. 1 is concluded, 0 is not concluded. */ private static final AtomicIntegerFieldUpdater<Context> IS_CONCLUDED_UPDATER = newUpdater( Context.class, "isConcluded"); private volatile int isConcluded; private boolean ownsAeronClient = false; private String aeronDirectoryName = CommonContext.getAeronDirectoryName(); private Aeron aeron; private boolean deleteDirOnStart = false; private String clusterDirectoryName = ClusteredServiceContainer.Configuration.clusterDirName(); private File clusterDir; private RecordingLog recordingLog; private ClusterMarkFile markFile; private MutableDirectBuffer tempBuffer; private int fileSyncLevel = Archive.Configuration.fileSyncLevel(); private int appVersion = SemanticVersion.compose(0, 0, 1); private int clusterMemberId = Configuration.clusterMemberId(); private int appointedLeaderId = Configuration.appointedLeaderId(); private String clusterMembers = Configuration.clusterMembers(); private String clusterMembersStatusEndpoints = Configuration.clusterMembersStatusEndpoints(); private boolean clusterMembersIgnoreSnapshot = Configuration.clusterMembersIgnoreSnapshot(); private String ingressChannel = AeronCluster.Configuration.ingressChannel(); private int ingressStreamId = AeronCluster.Configuration.ingressStreamId(); private int ingressFragmentLimit = Configuration.ingressFragmentLimit(); private String logChannel = Configuration.logChannel(); private int logStreamId = Configuration.logStreamId(); private String memberEndpoints = Configuration.memberEndpoints(); private String replayChannel = ClusteredServiceContainer.Configuration.replayChannel(); private int replayStreamId = ClusteredServiceContainer.Configuration.replayStreamId(); private String serviceControlChannel = ClusteredServiceContainer.Configuration.serviceControlChannel(); private int consensusModuleStreamId = ClusteredServiceContainer.Configuration.consensusModuleStreamId(); private int serviceStreamId = ClusteredServiceContainer.Configuration.serviceStreamId(); private String snapshotChannel = Configuration.snapshotChannel(); private int snapshotStreamId = Configuration.snapshotStreamId(); private String memberStatusChannel = Configuration.memberStatusChannel(); private int memberStatusStreamId = Configuration.memberStatusStreamId(); private int serviceCount = Configuration.serviceCount(); private int errorBufferLength = Configuration.errorBufferLength(); private int maxConcurrentSessions = Configuration.maxConcurrentSessions(); private int ticksPerWheel = Configuration.ticksPerWheel(); private long wheelTickResolutionNs = Configuration.wheelTickResolutionNs(); private long sessionTimeoutNs = Configuration.sessionTimeoutNs(); private long leaderHeartbeatTimeoutNs = Configuration.leaderHeartbeatTimeoutNs(); private long leaderHeartbeatIntervalNs = Configuration.leaderHeartbeatIntervalNs(); private long startupCanvassTimeoutNs = Configuration.startupCanvassTimeoutNs(); private long electionTimeoutNs = Configuration.electionTimeoutNs(); private long electionStatusIntervalNs = Configuration.electionStatusIntervalNs(); private long dynamicJoinIntervalNs = Configuration.dynamicJoinIntervalNs(); private long terminationTimeoutNs = Configuration.terminationTimeoutNs(); private ThreadFactory threadFactory; private Supplier<IdleStrategy> idleStrategySupplier; private ClusterClock clusterClock; private EpochClock epochClock; private Random random; private DistinctErrorLog errorLog; private ErrorHandler errorHandler; private AtomicCounter errorCounter; private CountedErrorHandler countedErrorHandler; private Counter moduleState; private Counter clusterNodeRole; private Counter commitPosition; private Counter controlToggle; private Counter snapshotCounter; private Counter invalidRequestCounter; private Counter timedOutClientCounter; private ShutdownSignalBarrier shutdownSignalBarrier; private Runnable terminationHook; private AeronArchive.Context archiveContext; private AuthenticatorSupplier authenticatorSupplier; private LogPublisher logPublisher; private EgressPublisher egressPublisher; /** * Perform a shallow copy of the object. * * @return a shallow copy of the object. */ public Context clone() { try { return (Context)super.clone(); } catch (final CloneNotSupportedException ex) { throw new RuntimeException(ex); } } @SuppressWarnings("MethodLength") public void conclude() { if (0 != IS_CONCLUDED_UPDATER.getAndSet(this, 1)) { throw new ConcurrentConcludeException(); } if (null == clusterDir) { clusterDir = new File(clusterDirectoryName); } if (deleteDirOnStart && clusterDir.exists()) { IoUtil.delete(clusterDir, false); } if (!clusterDir.exists() && !clusterDir.mkdirs()) { throw new ClusterException("failed to create cluster dir: " + clusterDir.getAbsolutePath()); } if (null == tempBuffer) { tempBuffer = new UnsafeBuffer(new byte[METADATA_LENGTH]); } if (null == clusterClock) { clusterClock = new MillisecondClusterClock(); } if (null == epochClock) { epochClock = new SystemEpochClock(); } if (null == markFile) { markFile = new ClusterMarkFile( new File(clusterDir, ClusterMarkFile.FILENAME), ClusterComponentType.CONSENSUS_MODULE, errorBufferLength, epochClock, 0); } if (null == errorLog) { errorLog = new DistinctErrorLog(markFile.errorBuffer(), epochClock); } if (null == errorHandler) { errorHandler = new LoggingErrorHandler(errorLog); } if (null == recordingLog) { recordingLog = new RecordingLog(clusterDir); } if (null == aeron) { ownsAeronClient = true; aeron = Aeron.connect( new Aeron.Context() .aeronDirectoryName(aeronDirectoryName) .errorHandler(errorHandler) .epochClock(epochClock) .useConductorAgentInvoker(true) .awaitingIdleStrategy(YieldingIdleStrategy.INSTANCE) .clientLock(NoOpLock.INSTANCE)); if (null == errorCounter) { errorCounter = aeron.addCounter(CONSENSUS_MODULE_ERROR_COUNT_TYPE_ID, "Cluster errors"); } } if (null == aeron.conductorAgentInvoker()) { throw new ClusterException("Aeron client must use conductor agent invoker"); } if (null == errorCounter) { throw new ClusterException("error counter must be supplied if aeron client is"); } if (null == countedErrorHandler) { countedErrorHandler = new CountedErrorHandler(errorHandler, errorCounter); if (ownsAeronClient) { aeron.context().errorHandler(countedErrorHandler); } } if (null == moduleState) { moduleState = aeron.addCounter(CONSENSUS_MODULE_STATE_TYPE_ID, "Consensus module state"); } if (null == commitPosition) { commitPosition = CommitPos.allocate(aeron); } if (null == controlToggle) { controlToggle = aeron.addCounter(CONTROL_TOGGLE_TYPE_ID, "Cluster control toggle"); } if (null == snapshotCounter) { snapshotCounter = aeron.addCounter(SNAPSHOT_COUNTER_TYPE_ID, "Snapshot count"); } if (null == invalidRequestCounter) { invalidRequestCounter = aeron.addCounter( CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID, "Invalid cluster request count"); } if (null == timedOutClientCounter) { timedOutClientCounter = aeron.addCounter( CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID, "Timed out cluster client count"); } if (null == clusterNodeRole) { clusterNodeRole = aeron.addCounter(Configuration.CLUSTER_NODE_ROLE_TYPE_ID, "Cluster node role"); } if (null == threadFactory) { threadFactory = Thread::new; } if (null == idleStrategySupplier) { idleStrategySupplier = ClusteredServiceContainer.Configuration.idleStrategySupplier(null); } if (null == archiveContext) { archiveContext = new AeronArchive.Context() .controlRequestChannel(AeronArchive.Configuration.localControlChannel()) .controlResponseChannel(AeronArchive.Configuration.localControlChannel()) .controlRequestStreamId(AeronArchive.Configuration.localControlStreamId()); } archiveContext .aeron(aeron) .errorHandler(countedErrorHandler) .ownsAeronClient(false) .lock(NoOpLock.INSTANCE); if (null == shutdownSignalBarrier) { shutdownSignalBarrier = new ShutdownSignalBarrier(); } if (null == terminationHook) { terminationHook = () -> shutdownSignalBarrier.signal(); } if (null == authenticatorSupplier) { authenticatorSupplier = Configuration.authenticatorSupplier(); } if (null == random) { random = new Random(); } if (null == logPublisher) { logPublisher = new LogPublisher(); } if (null == egressPublisher) { egressPublisher = new EgressPublisher(); } concludeMarkFile(); } /** * The temporary buffer than can be used to build up counter labels to avoid allocation. * * @return the temporary buffer than can be used to build up counter labels to avoid allocation. */ public MutableDirectBuffer tempBuffer() { return tempBuffer; } /** * Set the temporary buffer than can be used to build up counter labels to avoid allocation. * * @param tempBuffer to be used to avoid allocation. * @return the temporary buffer than can be used to build up counter labels to avoid allocation. */ public Context tempBuffer(final MutableDirectBuffer tempBuffer) { this.tempBuffer = tempBuffer; return this; } /** * Should the consensus module attempt to immediately delete {@link #clusterDir()} on startup. * * @param deleteDirOnStart Attempt deletion. * @return this for a fluent API. */ public Context deleteDirOnStart(final boolean deleteDirOnStart) { this.deleteDirOnStart = deleteDirOnStart; return this; } /** * Will the consensus module attempt to immediately delete {@link #clusterDir()} on startup. * * @return true when directory will be deleted, otherwise false. */ public boolean deleteDirOnStart() { return deleteDirOnStart; } /** * Set the directory name to use for the consensus module directory. * * @param clusterDirectoryName to use. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public Context clusterDirectoryName(final String clusterDirectoryName) { this.clusterDirectoryName = clusterDirectoryName; return this; } /** * The directory name to use for the consensus module directory. * * @return directory name for the consensus module directory. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public String clusterDirectoryName() { return clusterDirectoryName; } /** * Set the directory to use for the consensus module directory. * * @param clusterDir to use. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public Context clusterDir(final File clusterDir) { this.clusterDir = clusterDir; return this; } /** * The directory used for for the consensus module directory. * * @return directory for for the consensus module directory. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public File clusterDir() { return clusterDir; } /** * Set the {@link RecordingLog} for the log terms and snapshots. * * @param recordingLog to use. * @return this for a fluent API. */ public Context recordingLog(final RecordingLog recordingLog) { this.recordingLog = recordingLog; return this; } /** * The {@link RecordingLog} for the log terms and snapshots. * * @return {@link RecordingLog} for the log terms and snapshots. */ public RecordingLog recordingLog() { return recordingLog; } /** * User assigned application version which appended to the log as the appVersion in new leadership events. * <p> * This can be validated using {@link org.agrona.SemanticVersion} to ensure only application nodes of the same * major version communicate with each other. * * @param appVersion for user application. * @return this for a fluent API. */ public Context appVersion(final int appVersion) { this.appVersion = appVersion; return this; } /** * User assigned application version which appended to the log as the appVersion in new leadership events. * <p> * This can be validated using {@link org.agrona.SemanticVersion} to ensure only application nodes of the same * major version communicate with each other. * * @return appVersion for user application. */ public int appVersion() { return appVersion; } /** * Get level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> * * @return the level to be applied for file write. * @see Configuration#FILE_SYNC_LEVEL_PROP_NAME */ int fileSyncLevel() { return fileSyncLevel; } /** * Set level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> * * @param syncLevel to be applied for file writes. * @return this for a fluent API. * @see Configuration#FILE_SYNC_LEVEL_PROP_NAME */ public Context fileSyncLevel(final int syncLevel) { this.fileSyncLevel = syncLevel; return this; } /** * This cluster member identity. * * @param clusterMemberId for this member. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBER_ID_PROP_NAME */ public Context clusterMemberId(final int clusterMemberId) { this.clusterMemberId = clusterMemberId; return this; } /** * This cluster member identity. * * @return this cluster member identity. * @see Configuration#CLUSTER_MEMBER_ID_PROP_NAME */ public int clusterMemberId() { return clusterMemberId; } /** * The cluster member id of the appointed cluster leader. * <p> * -1 means no leader has been appointed and an automated leader election should occur. * * @param appointedLeaderId for the cluster. * @return this for a fluent API. * @see Configuration#APPOINTED_LEADER_ID_PROP_NAME */ public Context appointedLeaderId(final int appointedLeaderId) { this.appointedLeaderId = appointedLeaderId; return this; } /** * The cluster member id of the appointed cluster leader. * <p> * -1 means no leader has been appointed and an automated leader election should occur. * * @return cluster member id of the appointed cluster leader. * @see Configuration#APPOINTED_LEADER_ID_PROP_NAME */ public int appointedLeaderId() { return appointedLeaderId; } /** * String representing the cluster members. * <p> * <code> * 0,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| \ * 1,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| ... * </code> * <p> * The client facing endpoints will be used as the endpoint substituted into the {@link #ingressChannel()} * if the endpoint is not provided unless it is multicast. * * @param clusterMembers which are all candidates to be leader. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBERS_PROP_NAME */ public Context clusterMembers(final String clusterMembers) { this.clusterMembers = clusterMembers; return this; } /** * The endpoints representing members of the cluster which are all candidates to be leader. * <p> * The client facing endpoints will be used as the endpoint in {@link #ingressChannel()} if the endpoint is * not provided in that when it is not multicast. * * @return members of the cluster which are all candidates to be leader. * @see Configuration#CLUSTER_MEMBERS_PROP_NAME */ public String clusterMembers() { return clusterMembers; } /** * String representing the cluster members member status endpoints used to request to join the cluster. * <p> * {@code "endpoint,endpoint,endpoint"} * <p> * * @param endpoints which are to be contacted for joining the cluster. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME */ public Context clusterMembersStatusEndpoints(final String endpoints) { this.clusterMembersStatusEndpoints = endpoints; return this; } /** * The endpoints representing cluster members of the cluster to attempt to contact to join the cluster. * * @return members of the cluster to attempt to request to join from. * @see Configuration#CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME */ public String clusterMembersStatusEndpoints() { return clusterMembersStatusEndpoints; } /** * Whether the cluster members in the snapshot should be ignored or not. * * @param ignore or not the cluster members in the snapshot. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME */ public Context clusterMembersIgnoreSnapshot(final boolean ignore) { this.clusterMembersIgnoreSnapshot = ignore; return this; } /** * Whether the cluster members in the snapshot should be ignored or not. * * @return ignore or not the cluster members in the snapshot. * @see Configuration#CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME */ public boolean clusterMembersIgnoreSnapshot() { return clusterMembersIgnoreSnapshot; } /** * Set the channel parameter for the ingress channel. * * @param channel parameter for the ingress channel. * @return this for a fluent API. * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_CHANNEL_PROP_NAME */ public Context ingressChannel(final String channel) { ingressChannel = channel; return this; } /** * Get the channel parameter for the ingress channel. * * @return the channel parameter for the ingress channel. * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_CHANNEL_PROP_NAME */ public String ingressChannel() { return ingressChannel; } /** * Set the stream id for the ingress channel. * * @param streamId for the ingress channel. * @return this for a fluent API * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_STREAM_ID_PROP_NAME */ public Context ingressStreamId(final int streamId) { ingressStreamId = streamId; return this; } /** * Get the stream id for the ingress channel. * * @return the stream id for the ingress channel. * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_STREAM_ID_PROP_NAME */ public int ingressStreamId() { return ingressStreamId; } /** * Set limit for fragments to be consumed on each poll of ingress. * * @param ingressFragmentLimit for the ingress channel. * @return this for a fluent API * @see Configuration#CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME */ public Context ingressFragmentLimit(final int ingressFragmentLimit) { this.ingressFragmentLimit = ingressFragmentLimit; return this; } /** * The limit for fragments to be consumed on each poll of ingress. * * @return the limit for fragments to be consumed on each poll of ingress. * @see Configuration#CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME */ public int ingressFragmentLimit() { return ingressFragmentLimit; } /** * Set the channel parameter for the cluster log channel. * * @param channel parameter for the cluster log channel. * @return this for a fluent API. * @see Configuration#LOG_CHANNEL_PROP_NAME */ public Context logChannel(final String channel) { logChannel = channel; return this; } /** * Get the channel parameter for the cluster log channel. * * @return the channel parameter for the cluster channel. * @see Configuration#LOG_CHANNEL_PROP_NAME */ public String logChannel() { return logChannel; } /** * Set the stream id for the cluster log channel. * * @param streamId for the cluster log channel. * @return this for a fluent API * @see Configuration#LOG_STREAM_ID_PROP_NAME */ public Context logStreamId(final int streamId) { logStreamId = streamId; return this; } /** * Get the stream id for the cluster log channel. * * @return the stream id for the cluster log channel. * @see Configuration#LOG_STREAM_ID_PROP_NAME */ public int logStreamId() { return logStreamId; } /** * Set the endpoints for this cluster node. * * @param endpoints for the cluster node. * @return this for a fluent API. * @see Configuration#MEMBER_ENDPOINTS_PROP_NAME */ public Context memberEndpoints(final String endpoints) { memberEndpoints = endpoints; return this; } /** * Get the endpoints for this cluster node. * * @return the endpoints for the cluster node. * @see Configuration#MEMBER_ENDPOINTS_PROP_NAME */ public String memberEndpoints() { return memberEndpoints; } /** * Set the channel parameter for the cluster log and snapshot replay channel. * * @param channel parameter for the cluster log replay channel. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_CHANNEL_PROP_NAME */ public Context replayChannel(final String channel) { replayChannel = channel; return this; } /** * Get the channel parameter for the cluster log and snapshot replay channel. * * @return the channel parameter for the cluster replay channel. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_CHANNEL_PROP_NAME */ public String replayChannel() { return replayChannel; } /** * Set the stream id for the cluster log and snapshot replay channel. * * @param streamId for the cluster log replay channel. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_STREAM_ID_PROP_NAME */ public Context replayStreamId(final int streamId) { replayStreamId = streamId; return this; } /** * Get the stream id for the cluster log and snapshot replay channel. * * @return the stream id for the cluster log replay channel. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_STREAM_ID_PROP_NAME */ public int replayStreamId() { return replayStreamId; } /** * Set the channel parameter for bi-directional communications between the consensus module and services. * * @param channel parameter for bi-directional communications between the consensus module and services. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_CONTROL_CHANNEL_PROP_NAME */ public Context serviceControlChannel(final String channel) { serviceControlChannel = channel; return this; } /** * Get the channel parameter for bi-directional communications between the consensus module and services. * * @return the channel parameter for bi-directional communications between the consensus module and services. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_CONTROL_CHANNEL_PROP_NAME */ public String serviceControlChannel() { return serviceControlChannel; } /** * Set the stream id for communications from the consensus module and to the services. * * @param streamId for communications from the consensus module and to the services. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_STREAM_ID_PROP_NAME */ public Context serviceStreamId(final int streamId) { serviceStreamId = streamId; return this; } /** * Get the stream id for communications from the consensus module and to the services. * * @return the stream id for communications from the consensus module and to the services. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_STREAM_ID_PROP_NAME */ public int serviceStreamId() { return serviceStreamId; } /** * Set the stream id for communications from the services to the consensus module. * * @param streamId for communications from the services to the consensus module. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CONSENSUS_MODULE_STREAM_ID_PROP_NAME */ public Context consensusModuleStreamId(final int streamId) { consensusModuleStreamId = streamId; return this; } /** * Get the stream id for communications from the services to the consensus module. * * @return the stream id for communications from the services to the consensus module. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CONSENSUS_MODULE_STREAM_ID_PROP_NAME */ public int consensusModuleStreamId() { return consensusModuleStreamId; } /** * Set the channel parameter for snapshot recordings. * * @param channel parameter for snapshot recordings * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME */ public Context snapshotChannel(final String channel) { snapshotChannel = channel; return this; } /** * Get the channel parameter for snapshot recordings. * * @return the channel parameter for snapshot recordings. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME */ public String snapshotChannel() { return snapshotChannel; } /** * Set the stream id for snapshot recordings. * * @param streamId for snapshot recordings. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME */ public Context snapshotStreamId(final int streamId) { snapshotStreamId = streamId; return this; } /** * Get the stream id for snapshot recordings. * * @return the stream id for snapshot recordings. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME */ public int snapshotStreamId() { return snapshotStreamId; } /** * Set the channel parameter for the member status communication channel. * * @param channel parameter for the member status communication channel. * @return this for a fluent API. * @see Configuration#MEMBER_STATUS_CHANNEL_PROP_NAME */ public Context memberStatusChannel(final String channel) { memberStatusChannel = channel; return this; } /** * Get the channel parameter for the member status communication channel. * * @return the channel parameter for the member status communication channel. * @see Configuration#MEMBER_STATUS_CHANNEL_PROP_NAME */ public String memberStatusChannel() { return memberStatusChannel; } /** * Set the stream id for the member status channel. * * @param streamId for the ingress channel. * @return this for a fluent API * @see Configuration#MEMBER_STATUS_STREAM_ID_PROP_NAME */ public Context memberStatusStreamId(final int streamId) { memberStatusStreamId = streamId; return this; } /** * Get the stream id for the member status channel. * * @return the stream id for the member status channel. * @see Configuration#MEMBER_STATUS_STREAM_ID_PROP_NAME */ public int memberStatusStreamId() { return memberStatusStreamId; } /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. * * @param wheelTickResolutionNs the resolution in nanoseconds of each tick on the timer wheel. * @return this for a fluent API * @see Configuration#WHEEL_TICK_RESOLUTION_PROP_NAME */ public Context wheelTickResolutionNs(final long wheelTickResolutionNs) { this.wheelTickResolutionNs = wheelTickResolutionNs; return this; } /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. * * @return the resolution in nanoseconds for each tick on the timer wheel. * @see Configuration#WHEEL_TICK_RESOLUTION_PROP_NAME */ public long wheelTickResolutionNs() { return wheelTickResolutionNs; } /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. * * @param ticksPerWheel the number of ticks on the timer wheel. * @return this for a fluent API * @see Configuration#TICKS_PER_WHEEL_PROP_NAME */ public Context ticksPerWheel(final int ticksPerWheel) { this.ticksPerWheel = ticksPerWheel; return this; } /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. * * @return the number of ticks on the timer wheel. * @see Configuration#TICKS_PER_WHEEL_PROP_NAME */ public int ticksPerWheel() { return ticksPerWheel; } /** * Set the number of clustered services in this cluster instance. * * @param serviceCount the number of clustered services in this cluster instance. * @return this for a fluent API * @see Configuration#SERVICE_COUNT_PROP_NAME */ public Context serviceCount(final int serviceCount) { this.serviceCount = serviceCount; return this; } /** * Get the number of clustered services in this cluster instance. * * @return the number of clustered services in this cluster instance. * @see Configuration#SERVICE_COUNT_PROP_NAME */ public int serviceCount() { return serviceCount; } /** * Set the limit for the maximum number of concurrent cluster sessions. * * @param maxSessions after which new sessions will be rejected. * @return this for a fluent API * @see Configuration#MAX_CONCURRENT_SESSIONS_PROP_NAME */ public Context maxConcurrentSessions(final int maxSessions) { this.maxConcurrentSessions = maxSessions; return this; } /** * Get the limit for the maximum number of concurrent cluster sessions. * * @return the limit for the maximum number of concurrent cluster sessions. * @see Configuration#MAX_CONCURRENT_SESSIONS_PROP_NAME */ public int maxConcurrentSessions() { return maxConcurrentSessions; } /** * Timeout for a session if no activity is observed. * * @param sessionTimeoutNs to wait for activity on a session. * @return this for a fluent API. * @see Configuration#SESSION_TIMEOUT_PROP_NAME */ public Context sessionTimeoutNs(final long sessionTimeoutNs) { this.sessionTimeoutNs = sessionTimeoutNs; return this; } /** * Timeout for a session if no activity is observed. * * @return the timeout for a session if no activity is observed. * @see Configuration#SESSION_TIMEOUT_PROP_NAME */ public long sessionTimeoutNs() { return sessionTimeoutNs; } /** * Timeout for a leader if no heartbeat is received by an other member. * * @param heartbeatTimeoutNs to wait for heartbeat from a leader. * @return this for a fluent API. * @see Configuration#LEADER_HEARTBEAT_TIMEOUT_PROP_NAME */ public Context leaderHeartbeatTimeoutNs(final long heartbeatTimeoutNs) { this.leaderHeartbeatTimeoutNs = heartbeatTimeoutNs; return this; } /** * Timeout for a leader if no heartbeat is received by an other member. * * @return the timeout for a leader if no heartbeat is received by an other member. * @see Configuration#LEADER_HEARTBEAT_TIMEOUT_PROP_NAME */ public long leaderHeartbeatTimeoutNs() { return leaderHeartbeatTimeoutNs; } /** * Interval at which a leader will send heartbeats if the log is not progressing. * * @param heartbeatIntervalNs between leader heartbeats. * @return this for a fluent API. * @see Configuration#LEADER_HEARTBEAT_INTERVAL_PROP_NAME */ public Context leaderHeartbeatIntervalNs(final long heartbeatIntervalNs) { this.leaderHeartbeatIntervalNs = heartbeatIntervalNs; return this; } /** * Interval at which a leader will send heartbeats if the log is not progressing. * * @return the interval at which a leader will send heartbeats if the log is not progressing. * @see Configuration#LEADER_HEARTBEAT_INTERVAL_PROP_NAME */ public long leaderHeartbeatIntervalNs() { return leaderHeartbeatIntervalNs; } /** * Timeout to wait for hearing the status of all cluster members on startup after recovery before commencing * an election if a majority of members has been heard from. * * @param timeoutNs to wait on startup after recovery before commencing an election. * @return this for a fluent API. * @see Configuration#STARTUP_CANVASS_TIMEOUT_PROP_NAME */ public Context startupCanvassTimeoutNs(final long timeoutNs) { this.startupCanvassTimeoutNs = timeoutNs; return this; } /** * Timeout to wait for hearing the status of all cluster members on startup after recovery before commencing * an election if a majority of members has been heard from. * * @return the timeout to wait on startup after recovery before commencing an election. * @see Configuration#STARTUP_CANVASS_TIMEOUT_PROP_NAME */ public long startupCanvassTimeoutNs() { return startupCanvassTimeoutNs; } /** * Timeout to wait for votes in an election before declaring the election void and starting over. * * @param timeoutNs to wait for votes in an elections. * @return this for a fluent API. * @see Configuration#ELECTION_TIMEOUT_PROP_NAME */ public Context electionTimeoutNs(final long timeoutNs) { this.electionTimeoutNs = timeoutNs; return this; } /** * Timeout to wait for votes in an election before declaring the election void and starting over. * * @return the timeout to wait for votes in an elections. * @see Configuration#ELECTION_TIMEOUT_PROP_NAME */ public long electionTimeoutNs() { return electionTimeoutNs; } /** * Interval at which a member will send out status messages during the election phases. * * @param electionStatusIntervalNs between status message updates. * @return this for a fluent API. * @see Configuration#ELECTION_STATUS_INTERVAL_PROP_NAME * @see Configuration#ELECTION_STATUS_INTERVAL_DEFAULT_NS */ public Context electionStatusIntervalNs(final long electionStatusIntervalNs) { this.electionStatusIntervalNs = electionStatusIntervalNs; return this; } /** * Interval at which a member will send out status messages during the election phases. * * @return the interval at which a member will send out status messages during the election phases. * @see Configuration#ELECTION_STATUS_INTERVAL_PROP_NAME * @see Configuration#ELECTION_STATUS_INTERVAL_DEFAULT_NS */ public long electionStatusIntervalNs() { return electionStatusIntervalNs; } /** * Interval at which a dynamic joining member will send add cluster member and snapshot recording queries. * * @param dynamicJoinIntervalNs between add cluster members and snapshot recording queries. * @return this for a fluent API. * @see Configuration#DYNAMIC_JOIN_INTERVAL_PROP_NAME * @see Configuration#DYNAMIC_JOIN_INTERVAL_DEFAULT_NS */ public Context dynamicJoinIntervalNs(final long dynamicJoinIntervalNs) { this.dynamicJoinIntervalNs = dynamicJoinIntervalNs; return this; } /** * Interval at which a dynamic joining member will send add cluster member and snapshot recording queries. * * @return the interval at which a dynamic joining member will send add cluster member and snapshot recording * queries. * @see Configuration#DYNAMIC_JOIN_INTERVAL_PROP_NAME * @see Configuration#DYNAMIC_JOIN_INTERVAL_DEFAULT_NS */ public long dynamicJoinIntervalNs() { return dynamicJoinIntervalNs; } /** * Timeout to wait for follower termination by leader. * * @param terminationTimeoutNs to wait for follower termination. * @return this for a fluent API. * @see Configuration#TERMINATION_TIMEOUT_PROP_NAME * @see Configuration#TERMINATION_TIMEOUT_DEFAULT_NS */ public Context terminationTimeoutNs(final long terminationTimeoutNs) { this.terminationTimeoutNs = terminationTimeoutNs; return this; } /** * Timeout to wait for follower termination by leader. * * @return timeout to wait for follower termination by leader. * @see Configuration#TERMINATION_TIMEOUT_PROP_NAME * @see Configuration#TERMINATION_TIMEOUT_DEFAULT_NS */ public long terminationTimeoutNs() { return terminationTimeoutNs; } /** * Get the thread factory used for creating threads. * * @return thread factory used for creating threads. */ public ThreadFactory threadFactory() { return threadFactory; } /** * Set the thread factory used for creating threads. * * @param threadFactory used for creating threads * @return this for a fluent API. */ public Context threadFactory(final ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } /** * Provides an {@link IdleStrategy} supplier for the idle strategy for the agent duty cycle. * * @param idleStrategySupplier supplier for the idle strategy for the agent duty cycle. * @return this for a fluent API. */ public Context idleStrategySupplier(final Supplier<IdleStrategy> idleStrategySupplier) { this.idleStrategySupplier = idleStrategySupplier; return this; } /** * Get a new {@link IdleStrategy} based on configured supplier. * * @return a new {@link IdleStrategy} based on configured supplier. */ public IdleStrategy idleStrategy() { return idleStrategySupplier.get(); } /** * Set the {@link ClusterClock} to be used for timestamping messages. * * @param clock {@link ClusterClock} to be used for timestamping message * @return this for a fluent API. */ public Context clusterClock(final ClusterClock clock) { this.clusterClock = clock; return this; } /** * Get the {@link ClusterClock} to used for timestamping message * * @return the {@link ClusterClock} to used for timestamping message */ public ClusterClock clusterClock() { return clusterClock; } /** * Set the {@link EpochClock} to be used for tracking wall clock time. * * @param clock {@link EpochClock} to be used for tracking wall clock time. * @return this for a fluent API. */ public Context epochClock(final EpochClock clock) { this.epochClock = clock; return this; } /** * Get the {@link EpochClock} to used for tracking wall clock time. * * @return the {@link EpochClock} to used for tracking wall clock time. */ public EpochClock epochClock() { return epochClock; } /** * Get the {@link ErrorHandler} to be used by the Consensus Module. * * @return the {@link ErrorHandler} to be used by the Consensus Module. */ public ErrorHandler errorHandler() { return errorHandler; } /** * Set the {@link ErrorHandler} to be used by the Consensus Module. * * @param errorHandler the error handler to be used by the Consensus Module. * @return this for a fluent API */ public Context errorHandler(final ErrorHandler errorHandler) { this.errorHandler = errorHandler; return this; } /** * Get the error counter that will record the number of errors observed. * * @return the error counter that will record the number of errors observed. */ public AtomicCounter errorCounter() { return errorCounter; } /** * Set the error counter that will record the number of errors observed. * * @param errorCounter the error counter that will record the number of errors observed. * @return this for a fluent API. */ public Context errorCounter(final AtomicCounter errorCounter) { this.errorCounter = errorCounter; return this; } /** * Non-default for context. * * @param countedErrorHandler to override the default. * @return this for a fluent API. */ public Context countedErrorHandler(final CountedErrorHandler countedErrorHandler) { this.countedErrorHandler = countedErrorHandler; return this; } /** * The {@link #errorHandler()} that will increment {@link #errorCounter()} by default. * * @return {@link #errorHandler()} that will increment {@link #errorCounter()} by default. */ public CountedErrorHandler countedErrorHandler() { return countedErrorHandler; } /** * Get the counter for the current state of the consensus module. * * @return the counter for the current state of the consensus module. * @see ConsensusModule.State */ public Counter moduleStateCounter() { return moduleState; } /** * Set the counter for the current state of the consensus module. * * @param moduleState the counter for the current state of the consensus module. * @return this for a fluent API. * @see ConsensusModule.State */ public Context moduleStateCounter(final Counter moduleState) { this.moduleState = moduleState; return this; } /** * Get the counter for the commit position the cluster has reached for consensus. * * @return the counter for the commit position the cluster has reached for consensus. * @see CommitPos */ public Counter commitPositionCounter() { return commitPosition; } /** * Set the counter for the commit position the cluster has reached for consensus. * * @param commitPosition counter for the commit position the cluster has reached for consensus. * @return this for a fluent API. * @see CommitPos */ public Context commitPositionCounter(final Counter commitPosition) { this.commitPosition = commitPosition; return this; } /** * Get the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} of the * consensus module node. * * @return the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} of the * cluster node. * @see io.aeron.cluster.service.Cluster.Role */ public Counter clusterNodeCounter() { return clusterNodeRole; } /** * Set the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} of the * cluster node. * * @param moduleRole the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} * of the cluster node. * @return this for a fluent API. * @see io.aeron.cluster.service.Cluster.Role */ public Context clusterNodeCounter(final Counter moduleRole) { this.clusterNodeRole = moduleRole; return this; } /** * Get the counter for the control toggle for triggering actions on the cluster node. * * @return the counter for triggering cluster node actions. * @see ClusterControl */ public Counter controlToggleCounter() { return controlToggle; } /** * Set the counter for the control toggle for triggering actions on the cluster node. * * @param controlToggle the counter for triggering cluster node actions. * @return this for a fluent API. * @see ClusterControl */ public Context controlToggleCounter(final Counter controlToggle) { this.controlToggle = controlToggle; return this; } /** * Get the counter for the count of snapshots taken. * * @return the counter for the count of snapshots taken. */ public Counter snapshotCounter() { return snapshotCounter; } /** * Set the counter for the count of snapshots taken. * * @param snapshotCounter the count of snapshots taken. * @return this for a fluent API. */ public Context snapshotCounter(final Counter snapshotCounter) { this.snapshotCounter = snapshotCounter; return this; } /** * Get the counter for the count of invalid client requests. * * @return the counter for the count of invalid client requests. */ public Counter invalidRequestCounter() { return invalidRequestCounter; } /** * Set the counter for the count of invalid client requests. * * @param invalidRequestCounter the count of invalid client requests. * @return this for a fluent API. */ public Context invalidRequestCounter(final Counter invalidRequestCounter) { this.invalidRequestCounter = invalidRequestCounter; return this; } /** * Get the counter for the count of clients that have been timed out and disconnected. * * @return the counter for the count of clients that have been timed out and disconnected. */ public Counter timedOutClientCounter() { return timedOutClientCounter; } /** * Set the counter for the count of clients that have been timed out and disconnected. * * @param timedOutClientCounter the count of clients that have been timed out and disconnected. * @return this for a fluent API. */ public Context timedOutClientCounter(final Counter timedOutClientCounter) { this.timedOutClientCounter = timedOutClientCounter; return this; } /** * {@link Aeron} client for communicating with the local Media Driver. * <p> * This client will be closed when the {@link ConsensusModule#close()} or {@link #close()} methods are called * if {@link #ownsAeronClient()} is true. * * @param aeron client for communicating with the local Media Driver. * @return this for a fluent API. * @see Aeron#connect() */ public Context aeron(final Aeron aeron) { this.aeron = aeron; return this; } /** * {@link Aeron} client for communicating with the local Media Driver. * <p> * If not provided then a default will be established during {@link #conclude()} by calling * {@link Aeron#connect()}. * * @return client for communicating with the local Media Driver. */ public Aeron aeron() { return aeron; } /** * Set the top level Aeron directory used for communication between the Aeron client and Media Driver. * * @param aeronDirectoryName the top level Aeron directory. * @return this for a fluent API. */ public Context aeronDirectoryName(final String aeronDirectoryName) { this.aeronDirectoryName = aeronDirectoryName; return this; } /** * Get the top level Aeron directory used for communication between the Aeron client and Media Driver. * * @return The top level Aeron directory. */ public String aeronDirectoryName() { return aeronDirectoryName; } /** * Does this context own the {@link #aeron()} client and this takes responsibility for closing it? * * @param ownsAeronClient does this context own the {@link #aeron()} client. * @return this for a fluent API. */ public Context ownsAeronClient(final boolean ownsAeronClient) { this.ownsAeronClient = ownsAeronClient; return this; } /** * Does this context own the {@link #aeron()} client and this takes responsibility for closing it? * * @return does this context own the {@link #aeron()} client and this takes responsibility for closing it? */ public boolean ownsAeronClient() { return ownsAeronClient; } /** * Set the {@link io.aeron.archive.client.AeronArchive.Context} that should be used for communicating with the * local Archive. * * @param archiveContext that should be used for communicating with the local Archive. * @return this for a fluent API. */ public Context archiveContext(final AeronArchive.Context archiveContext) { this.archiveContext = archiveContext; return this; } /** * Get the {@link io.aeron.archive.client.AeronArchive.Context} that should be used for communicating with * the local Archive. * * @return the {@link io.aeron.archive.client.AeronArchive.Context} that should be used for communicating * with the local Archive. */ public AeronArchive.Context archiveContext() { return archiveContext; } /** * Get the {@link AuthenticatorSupplier} that should be used for the consensus module. * * @return the {@link AuthenticatorSupplier} to be used for the consensus module. */ public AuthenticatorSupplier authenticatorSupplier() { return authenticatorSupplier; } /** * Set the {@link AuthenticatorSupplier} that will be used for the consensus module. * * @param authenticatorSupplier {@link AuthenticatorSupplier} to use for the consensus module. * @return this for a fluent API. */ public Context authenticatorSupplier(final AuthenticatorSupplier authenticatorSupplier) { this.authenticatorSupplier = authenticatorSupplier; return this; } /** * Set the {@link ShutdownSignalBarrier} that can be used to shutdown a consensus module. * * @param barrier that can be used to shutdown a consensus module. * @return this for a fluent API. */ public Context shutdownSignalBarrier(final ShutdownSignalBarrier barrier) { shutdownSignalBarrier = barrier; return this; } /** * Get the {@link ShutdownSignalBarrier} that can be used to shutdown a consensus module. * * @return the {@link ShutdownSignalBarrier} that can be used to shutdown a consensus module. */ public ShutdownSignalBarrier shutdownSignalBarrier() { return shutdownSignalBarrier; } /** * Set the {@link Runnable} that is called when the {@link ConsensusModule} processes a termination action. * * @param terminationHook that can be used to terminate a consensus module. * @return this for a fluent API. */ public Context terminationHook(final Runnable terminationHook) { this.terminationHook = terminationHook; return this; } /** * Get the {@link Runnable} that is called when the {@link ConsensusModule} processes a termination action. * <p> * The default action is to call signal on the {@link #shutdownSignalBarrier()}. * * @return the {@link Runnable} that can be used to terminate a consensus module. */ public Runnable terminationHook() { return terminationHook; } /** * Set the {@link ClusterMarkFile} in use. * * @param markFile to use. * @return this for a fluent API. */ public Context clusterMarkFile(final ClusterMarkFile markFile) { this.markFile = markFile; return this; } /** * The {@link ClusterMarkFile} in use. * * @return {@link ClusterMarkFile} in use. */ public ClusterMarkFile clusterMarkFile() { return markFile; } /** * Set the error buffer length in bytes to use. * * @param errorBufferLength in bytes to use. * @return this for a fluent API. */ public Context errorBufferLength(final int errorBufferLength) { this.errorBufferLength = errorBufferLength; return this; } /** * The error buffer length in bytes. * * @return error buffer length in bytes. */ public int errorBufferLength() { return errorBufferLength; } /** * Set the {@link DistinctErrorLog} in use. * * @param errorLog to use. * @return this for a fluent API. */ public Context errorLog(final DistinctErrorLog errorLog) { this.errorLog = errorLog; return this; } /** * The {@link DistinctErrorLog} in use. * * @return {@link DistinctErrorLog} in use. */ public DistinctErrorLog errorLog() { return errorLog; } /** * The source of random values for timeouts used in elections. * * @param random source of random values for timeouts used in elections. * @return this for a fluent API. */ public Context random(final Random random) { this.random = random; return this; } /** * The source of random values for timeouts used in elections. * * @return source of random values for timeouts used in elections. */ public Random random() { return random; } /** * Delete the cluster directory. */ public void deleteDirectory() { if (null != clusterDir) { IoUtil.delete(clusterDir, false); } } /** * Close the context and free applicable resources. * <p> * If {@link #ownsAeronClient()} is true then the {@link #aeron()} client will be closed. */ public void close() { CloseHelper.close(recordingLog); CloseHelper.close(markFile); if (errorHandler instanceof AutoCloseable) { CloseHelper.close((AutoCloseable)errorHandler); } if (ownsAeronClient) { CloseHelper.close(aeron); } else if (!aeron.isClosed()) { CloseHelper.close(moduleState); CloseHelper.close(commitPosition); CloseHelper.close(clusterNodeRole); CloseHelper.close(controlToggle); CloseHelper.close(snapshotCounter); } } Context logPublisher(final LogPublisher logPublisher) { this.logPublisher = logPublisher; return this; } LogPublisher logPublisher() { return logPublisher; } Context egressPublisher(final EgressPublisher egressPublisher) { this.egressPublisher = egressPublisher; return this; } EgressPublisher egressPublisher() { return egressPublisher; } private void concludeMarkFile() { ClusterMarkFile.checkHeaderLength( aeron.context().aeronDirectoryName(), archiveContext.controlRequestChannel(), serviceControlChannel(), ingressChannel, null, authenticatorSupplier.getClass().toString()); markFile.encoder() .archiveStreamId(archiveContext.controlRequestStreamId()) .serviceStreamId(serviceStreamId) .consensusModuleStreamId(consensusModuleStreamId) .ingressStreamId(ingressStreamId) .memberId(clusterMemberId) .serviceId(SERVICE_ID) .aeronDirectory(aeron.context().aeronDirectoryName()) .archiveChannel(archiveContext.controlRequestChannel()) .serviceControlChannel(serviceControlChannel) .ingressChannel(ingressChannel) .serviceName("") .authenticator(authenticatorSupplier.getClass().toString()); markFile.updateActivityTimestamp(epochClock.time()); markFile.signalReady(); } } }
aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModule.java
/* * Copyright 2014-2019 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.cluster; import io.aeron.Aeron; import io.aeron.CommonContext; import io.aeron.Counter; import io.aeron.archive.Archive; import io.aeron.archive.client.AeronArchive; import io.aeron.cluster.client.AeronCluster; import io.aeron.cluster.client.ClusterClock; import io.aeron.cluster.client.ClusterException; import io.aeron.cluster.codecs.mark.ClusterComponentType; import io.aeron.cluster.service.*; import io.aeron.exceptions.ConcurrentConcludeException; import io.aeron.security.Authenticator; import io.aeron.security.AuthenticatorSupplier; import org.agrona.*; import org.agrona.concurrent.*; import org.agrona.concurrent.errors.DistinctErrorLog; import org.agrona.concurrent.errors.LoggingErrorHandler; import org.agrona.concurrent.status.AtomicCounter; import java.io.File; import java.util.Random; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.function.Supplier; import static io.aeron.cluster.ConsensusModule.Configuration.*; import static io.aeron.cluster.service.ClusteredServiceContainer.Configuration.SNAPSHOT_CHANNEL_PROP_NAME; import static io.aeron.cluster.service.ClusteredServiceContainer.Configuration.SNAPSHOT_STREAM_ID_PROP_NAME; import static java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater; import static org.agrona.SystemUtil.*; import static org.agrona.concurrent.status.CountersReader.METADATA_LENGTH; /** * Component which resides on each node and is responsible for coordinating consensus within a cluster in concert * with the lifecycle of clustered services. */ @SuppressWarnings("unused") public class ConsensusModule implements AutoCloseable { /** * Possible states for the {@link ConsensusModule}. * These will be reflected in the {@link Context#moduleStateCounter()} counter. */ public enum State { /** * Starting up and recovering state. */ INIT(0), /** * Active state with ingress and expired timers appended to the log. */ ACTIVE(1), /** * Suspended processing of ingress and expired timers. */ SUSPENDED(2), /** * In the process of taking a snapshot. */ SNAPSHOT(3), /** * Leaving cluster and shutting down as soon as services ack without taking a snapshot. */ LEAVING(4), /** * In the process of terminating the node. */ TERMINATING(5), /** * Terminal state. */ CLOSED(6); static final State[] STATES; static { final State[] states = values(); STATES = new State[states.length]; for (final State state : states) { final int code = state.code(); if (null != STATES[code]) { throw new ClusterException("code already in use: " + code); } STATES[code] = state; } } private final int code; State(final int code) { this.code = code; } public final int code() { return code; } /** * Get the {@link State} encoded in an {@link AtomicCounter}. * * @param counter to get the current state for. * @return the state for the {@link ConsensusModule}. * @throws ClusterException if the counter is not one of the valid values. */ public static State get(final AtomicCounter counter) { final long code = counter.get(); return get((int)code); } /** * Get the {@link State} corresponding to a particular code. * * @param code representing a {@link State}. * @return the {@link State} corresponding to the provided code. * @throws ClusterException if the code does not correspond to a valid State. */ public static State get(final int code) { if (code < 0 || code > (STATES.length - 1)) { throw new ClusterException("invalid state counter code: " + code); } return STATES[code]; } } /** * Launch an {@link ConsensusModule} with that communicates with an out of process {@link io.aeron.archive.Archive} * and {@link io.aeron.driver.MediaDriver} then awaits shutdown signal. * * @param args command line argument which is a list for properties files as URLs or filenames. */ public static void main(final String[] args) { loadPropertiesFiles(args); try (ConsensusModule consensusModule = launch()) { consensusModule.context().shutdownSignalBarrier().await(); System.out.println("Shutdown ConsensusModule..."); } } private final Context ctx; private final AgentRunner conductorRunner; ConsensusModule(final Context ctx) { this.ctx = ctx; try { ctx.conclude(); } catch (final Throwable ex) { if (null != ctx.markFile) { ctx.markFile.signalFailedStart(); } ctx.close(); throw ex; } final ConsensusModuleAgent conductor = new ConsensusModuleAgent(ctx); conductorRunner = new AgentRunner(ctx.idleStrategy(), ctx.errorHandler(), ctx.errorCounter(), conductor); } private ConsensusModule start() { AgentRunner.startOnThread(conductorRunner, ctx.threadFactory()); return this; } /** * Launch an {@link ConsensusModule} using a default configuration. * * @return a new instance of an {@link ConsensusModule}. */ public static ConsensusModule launch() { return launch(new Context()); } /** * Launch an {@link ConsensusModule} by providing a configuration context. * * @param ctx for the configuration parameters. * @return a new instance of an {@link ConsensusModule}. */ public static ConsensusModule launch(final Context ctx) { return new ConsensusModule(ctx).start(); } /** * Get the {@link ConsensusModule.Context} that is used by this {@link ConsensusModule}. * * @return the {@link ConsensusModule.Context} that is used by this {@link ConsensusModule}. */ public Context context() { return ctx; } public void close() { CloseHelper.close(conductorRunner); } /** * Configuration options for cluster. */ public static class Configuration { /** * Property name for the limit for fragments to be consumed on each poll of ingress. */ public static final String CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME = "aeron.cluster.ingress.fragment.limit"; /** * Default for the limit for fragments to be consumed on each poll of ingress. */ public static final int CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT = 50; /** * Type of snapshot for this component. */ public static final long SNAPSHOT_TYPE_ID = 1; /** * Service ID to identify a snapshot in the {@link RecordingLog}. */ public static final int SERVICE_ID = Aeron.NULL_VALUE; /** * Property name for the identity of the cluster member. */ public static final String CLUSTER_MEMBER_ID_PROP_NAME = "aeron.cluster.member.id"; /** * Default property for the cluster member identity. */ public static final int CLUSTER_MEMBER_ID_DEFAULT = 0; /** * Property name for the identity of the appointed leader. This is when automated leader elections are * not employed. */ public static final String APPOINTED_LEADER_ID_PROP_NAME = "aeron.cluster.appointed.leader.id"; /** * Default property for the appointed cluster leader id. A value of {@link Aeron#NULL_VALUE} means no leader * has been appointed and thus an automated leader election should occur. */ public static final int APPOINTED_LEADER_ID_DEFAULT = Aeron.NULL_VALUE; /** * Property name for the comma separated list of cluster member endpoints. * <p> * <code> * 0,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| \ * 1,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| ... * </code> * <p> * The client facing endpoints will be used as the endpoint substituted into the * {@link io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_CHANNEL_PROP_NAME} if the endpoint * is not provided when unicast. */ public static final String CLUSTER_MEMBERS_PROP_NAME = "aeron.cluster.members"; /** * Default property for the list of cluster member endpoints. */ public static final String CLUSTER_MEMBERS_DEFAULT = "0,localhost:10000,localhost:20000,localhost:30000,localhost:40000,localhost:8010"; /** * Property name for the comma separated list of cluster member status endpoints used for adding passive * followers as well as dynamic join of a cluster. */ public static final String CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME = "aeron.cluster.members.status.endpoints"; /** * Default property for the list of cluster member status endpoints. */ public static final String CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT = ""; /** * Property name for whether cluster member information in snapshots should be ignored on load or not. */ public static final String CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME = "aeron.cluster.members.ignore.snapshot"; /** * Default property for whether cluster member information in snapshots should be ignored or not. */ public static final String CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT = "false"; /** * Channel for the clustered log. */ public static final String LOG_CHANNEL_PROP_NAME = "aeron.cluster.log.channel"; /** * Channel for the clustered log. */ public static final String LOG_CHANNEL_DEFAULT = "aeron:udp?endpoint=localhost:9030|group=true"; /** * Property name for the comma separated list of member endpoints. * <p> * <code> * client-facing:port,member-facing:port,log:port,transfer:port,archive:port * </code> * @see #CLUSTER_MEMBERS_PROP_NAME */ public static final String MEMBER_ENDPOINTS_PROP_NAME = "aeron.cluster.member.endpoints"; /** * Default property for member endpoints. */ public static final String MEMBER_ENDPOINTS_DEFAULT = ""; /** * Stream id within a channel for the clustered log. */ public static final String LOG_STREAM_ID_PROP_NAME = "aeron.cluster.log.stream.id"; /** * Stream id within a channel for the clustered log. */ public static final int LOG_STREAM_ID_DEFAULT = 100; /** * Channel to be used for archiving snapshots. */ public static final String SNAPSHOT_CHANNEL_DEFAULT = CommonContext.IPC_CHANNEL + "?alias=snapshot"; /** * Stream id for the archived snapshots within a channel. */ public static final int SNAPSHOT_STREAM_ID_DEFAULT = 107; /** * Message detail to be sent when max concurrent session limit is reached. */ public static final String SESSION_LIMIT_MSG = "concurrent session limit"; /** * Message detail to be sent when a session timeout occurs. */ public static final String SESSION_TIMEOUT_MSG = "session inactive"; /** * Message detail to be sent when a session is terminated by a service. */ public static final String SESSION_TERMINATED_MSG = "session terminated"; /** * Message detail to be sent when a session is rejected due to authentication. */ public static final String SESSION_REJECTED_MSG = "session failed authentication"; /** * Message detail to be sent when a session has an invalid client version. */ public static final String SESSION_INVALID_VERSION_MSG = "invalid client version"; /** * Channel to be used communicating cluster member status to each other. This can be used for default * configuration with the endpoints replaced with those provided by {@link #CLUSTER_MEMBERS_PROP_NAME}. */ public static final String MEMBER_STATUS_CHANNEL_PROP_NAME = "aeron.cluster.member.status.channel"; /** * Channel to be used for communicating cluster member status to each other. This can be used for default * configuration with the endpoints replaced with those provided by {@link #CLUSTER_MEMBERS_PROP_NAME}. */ public static final String MEMBER_STATUS_CHANNEL_DEFAULT = "aeron:udp?term-length=64k"; /** * Stream id within a channel for communicating cluster member status. */ public static final String MEMBER_STATUS_STREAM_ID_PROP_NAME = "aeron.cluster.member.status.stream.id"; /** * Stream id for the archived snapshots within a channel. */ public static final int MEMBER_STATUS_STREAM_ID_DEFAULT = 108; /** * Counter type id for the consensus module state. */ public static final int CONSENSUS_MODULE_STATE_TYPE_ID = 200; /** * Counter type id for the consensus module error count. */ public static final int CONSENSUS_MODULE_ERROR_COUNT_TYPE_ID = 212; /** * Counter type id for the number of cluster clients which have been timed out. */ public static final int CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID = 213; /** * Counter type id for the number of invalid requests which the cluster has received. */ public static final int CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID = 214; /** * Counter type id for the cluster node role. */ public static final int CLUSTER_NODE_ROLE_TYPE_ID = ClusterNodeRole.CLUSTER_NODE_ROLE_TYPE_ID; /** * Counter type id for the control toggle. */ public static final int CONTROL_TOGGLE_TYPE_ID = ClusterControl.CONTROL_TOGGLE_TYPE_ID; /** * Type id of a commit position counter. */ public static final int COMMIT_POSITION_TYPE_ID = CommitPos.COMMIT_POSITION_TYPE_ID; /** * Type id of a recovery state counter. */ public static final int RECOVERY_STATE_TYPE_ID = RecoveryState.RECOVERY_STATE_TYPE_ID; /** * Counter type id for count of snapshots taken. */ public static final int SNAPSHOT_COUNTER_TYPE_ID = 205; /** * Type id for election state counter. */ public static final int ELECTION_STATE_TYPE_ID = Election.ELECTION_STATE_TYPE_ID; /** * The number of services in this cluster instance. */ public static final String SERVICE_COUNT_PROP_NAME = "aeron.cluster.service.count"; /** * The number of services in this cluster instance. */ public static final int SERVICE_COUNT_DEFAULT = 1; /** * Maximum number of cluster sessions that can be active concurrently. */ public static final String MAX_CONCURRENT_SESSIONS_PROP_NAME = "aeron.cluster.max.sessions"; /** * Maximum number of cluster sessions that can be active concurrently. */ public static final int MAX_CONCURRENT_SESSIONS_DEFAULT = 10; /** * Timeout for a session if no activity is observed. */ public static final String SESSION_TIMEOUT_PROP_NAME = "aeron.cluster.session.timeout"; /** * Timeout for a session if no activity is observed. */ public static final long SESSION_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(5); /** * Timeout for a leader if no heartbeat is received by an other member. */ public static final String LEADER_HEARTBEAT_TIMEOUT_PROP_NAME = "aeron.cluster.leader.heartbeat.timeout"; /** * Timeout for a leader if no heartbeat is received by an other member. */ public static final long LEADER_HEARTBEAT_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(10); /** * Interval at which a leader will send heartbeats if the log is not progressing. */ public static final String LEADER_HEARTBEAT_INTERVAL_PROP_NAME = "aeron.cluster.leader.heartbeat.interval"; /** * Interval at which a leader will send heartbeats if the log is not progressing. */ public static final long LEADER_HEARTBEAT_INTERVAL_DEFAULT_NS = TimeUnit.MILLISECONDS.toNanos(200); /** * Timeout after which an election vote will be attempted after startup while waiting to canvass the status * of members if a majority has been heard from. */ public static final String STARTUP_CANVASS_TIMEOUT_PROP_NAME = "aeron.cluster.startup.canvass.timeout"; /** * Default timeout after which an election vote will be attempted on startup when waiting to canvass the * status of all members before going for a majority if possible. */ public static final long STARTUP_CANVASS_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(60); /** * Timeout after which an election fails if the candidate does not get a majority of votes. */ public static final String ELECTION_TIMEOUT_PROP_NAME = "aeron.cluster.election.timeout"; /** * Default timeout after which an election fails if the candidate does not get a majority of votes. */ public static final long ELECTION_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(1); /** * Interval at which a member will send out status updates during election phases. */ public static final String ELECTION_STATUS_INTERVAL_PROP_NAME = "aeron.cluster.election.status.interval"; /** * Default interval at which a member will send out status updates during election phases. */ public static final long ELECTION_STATUS_INTERVAL_DEFAULT_NS = TimeUnit.MILLISECONDS.toNanos(20); /** * Interval at which a dynamic joining member will send add cluster member and snapshot recording * queries. */ public static final String DYNAMIC_JOIN_INTERVAL_PROP_NAME = "aeron.cluster.dynamic.join.interval"; /** * Default interval at which a dynamic joining member will send add cluster member and snapshot recording * queries. */ public static final long DYNAMIC_JOIN_INTERVAL_DEFAULT_NS = TimeUnit.SECONDS.toNanos(1); /** * Name of class to use as a supplier of {@link Authenticator} for the cluster. */ public static final String AUTHENTICATOR_SUPPLIER_PROP_NAME = "aeron.cluster.authenticator.supplier"; /** * Name of the class to use as a supplier of {@link Authenticator} for the cluster. Default is * a non-authenticating option. */ public static final String AUTHENTICATOR_SUPPLIER_DEFAULT = "io.aeron.security.DefaultAuthenticatorSupplier"; /** * Size in bytes of the error buffer for the cluster. */ public static final String ERROR_BUFFER_LENGTH_PROP_NAME = "aeron.cluster.error.buffer.length"; /** * Size in bytes of the error buffer for the cluster. */ public static final int ERROR_BUFFER_LENGTH_DEFAULT = 1024 * 1024; /** * Timeout waiting for follower termination by leader. */ public static final String TERMINATION_TIMEOUT_PROP_NAME = "aeron.cluster.termination.timeout"; /** * Timeout waiting for follower termination by leader default value. */ public static final long TERMINATION_TIMEOUT_DEFAULT_NS = TimeUnit.SECONDS.toNanos(5); /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. */ public static final String WHEEL_TICK_RESOLUTION_PROP_NAME = "aeron.cluster.wheel.tick.resolution"; /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. Defaults to 8ms. */ public static final long WHEEL_TICK_RESOLUTION_DEFAULT_NS = TimeUnit.MILLISECONDS.toNanos(8); /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. */ public static final String TICKS_PER_WHEEL_PROP_NAME = "aeron.cluster.ticks.per.wheel"; /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. Defaults to 128 per wheel. */ public static final int TICKS_PER_WHEEL_DEFAULT = 128; /** * The level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> */ public static final String FILE_SYNC_LEVEL_PROP_NAME = "aeron.cluster.file.sync.level"; /** * Default file sync level of normal writes. */ public static final int FILE_SYNC_LEVEL_DEFAULT = 0; /** * The value {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT} or system property * {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME} if set. * * @return {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT} or system property * {@link #CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME} if set. */ public static int ingressFragmentLimit() { return Integer.getInteger(CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME, CLUSTER_INGRESS_FRAGMENT_LIMIT_DEFAULT); } /** * The value {@link #CLUSTER_MEMBER_ID_DEFAULT} or system property * {@link #CLUSTER_MEMBER_ID_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBER_ID_DEFAULT} or system property * {@link #CLUSTER_MEMBER_ID_PROP_NAME} if set. */ public static int clusterMemberId() { return Integer.getInteger(CLUSTER_MEMBER_ID_PROP_NAME, CLUSTER_MEMBER_ID_DEFAULT); } /** * The value {@link #APPOINTED_LEADER_ID_DEFAULT} or system property * {@link #APPOINTED_LEADER_ID_PROP_NAME} if set. * * @return {@link #APPOINTED_LEADER_ID_DEFAULT} or system property * {@link #APPOINTED_LEADER_ID_PROP_NAME} if set. */ public static int appointedLeaderId() { return Integer.getInteger(APPOINTED_LEADER_ID_PROP_NAME, APPOINTED_LEADER_ID_DEFAULT); } /** * The value {@link #CLUSTER_MEMBERS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBERS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_PROP_NAME} if set. */ public static String clusterMembers() { return System.getProperty(CLUSTER_MEMBERS_PROP_NAME, CLUSTER_MEMBERS_DEFAULT); } /** * The value {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME} it set. */ public static String clusterMembersStatusEndpoints() { return System.getProperty( CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME, CLUSTER_MEMBERS_STATUS_ENDPOINTS_DEFAULT); } /** * The value {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME} if set. * * @return {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT} or system property * {@link #CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME} it set. */ public static boolean clusterMembersIgnoreSnapshot() { return "true".equalsIgnoreCase(System.getProperty( CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME, CLUSTER_MEMBERS_IGNORE_SNAPSHOT_DEFAULT)); } /** * The value {@link #LOG_CHANNEL_DEFAULT} or system property {@link #LOG_CHANNEL_PROP_NAME} if set. * * @return {@link #LOG_CHANNEL_DEFAULT} or system property {@link #LOG_CHANNEL_PROP_NAME} if set. */ public static String logChannel() { return System.getProperty(LOG_CHANNEL_PROP_NAME, LOG_CHANNEL_DEFAULT); } /** * The value {@link #LOG_STREAM_ID_DEFAULT} or system property {@link #LOG_STREAM_ID_PROP_NAME} if set. * * @return {@link #LOG_STREAM_ID_DEFAULT} or system property {@link #LOG_STREAM_ID_PROP_NAME} if set. */ public static int logStreamId() { return Integer.getInteger(LOG_STREAM_ID_PROP_NAME, LOG_STREAM_ID_DEFAULT); } /** * The value {@link #MEMBER_ENDPOINTS_DEFAULT} or system property {@link #MEMBER_ENDPOINTS_PROP_NAME} if set. * * @return {@link #MEMBER_ENDPOINTS_DEFAULT} or system property {@link #MEMBER_ENDPOINTS_PROP_NAME} if set. */ public static String memberEndpoints() { return System.getProperty(MEMBER_ENDPOINTS_PROP_NAME, MEMBER_ENDPOINTS_DEFAULT); } /** * The value {@link #SNAPSHOT_CHANNEL_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME} if set. * * @return {@link #SNAPSHOT_CHANNEL_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME} if set. */ public static String snapshotChannel() { return System.getProperty(SNAPSHOT_CHANNEL_PROP_NAME, SNAPSHOT_CHANNEL_DEFAULT); } /** * The value {@link #SNAPSHOT_STREAM_ID_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME} if set. * * @return {@link #SNAPSHOT_STREAM_ID_DEFAULT} or system property * {@link io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME} if set. */ public static int snapshotStreamId() { return Integer.getInteger(SNAPSHOT_STREAM_ID_PROP_NAME, SNAPSHOT_STREAM_ID_DEFAULT); } /** * The value {@link #SERVICE_COUNT_DEFAULT} or system property * {@link #SERVICE_COUNT_PROP_NAME} if set. * * @return {@link #SERVICE_COUNT_DEFAULT} or system property * {@link #SERVICE_COUNT_PROP_NAME} if set. */ public static int serviceCount() { return Integer.getInteger(SERVICE_COUNT_PROP_NAME, SERVICE_COUNT_DEFAULT); } /** * The value {@link #MAX_CONCURRENT_SESSIONS_DEFAULT} or system property * {@link #MAX_CONCURRENT_SESSIONS_PROP_NAME} if set. * * @return {@link #MAX_CONCURRENT_SESSIONS_DEFAULT} or system property * {@link #MAX_CONCURRENT_SESSIONS_PROP_NAME} if set. */ public static int maxConcurrentSessions() { return Integer.getInteger(MAX_CONCURRENT_SESSIONS_PROP_NAME, MAX_CONCURRENT_SESSIONS_DEFAULT); } /** * Timeout for a session if no activity is observed. * * @return timeout in nanoseconds to wait for activity * @see #SESSION_TIMEOUT_PROP_NAME */ public static long sessionTimeoutNs() { return getDurationInNanos(SESSION_TIMEOUT_PROP_NAME, SESSION_TIMEOUT_DEFAULT_NS); } /** * Timeout for a leader if no heartbeat is received by an other member. * * @return timeout in nanoseconds to wait for heartbeat from a leader. * @see #LEADER_HEARTBEAT_TIMEOUT_PROP_NAME */ public static long leaderHeartbeatTimeoutNs() { return getDurationInNanos(LEADER_HEARTBEAT_TIMEOUT_PROP_NAME, LEADER_HEARTBEAT_TIMEOUT_DEFAULT_NS); } /** * Interval at which a leader will send a heartbeat if the log is not progressing. * * @return timeout in nanoseconds to for leader heartbeats when no log being appended. * @see #LEADER_HEARTBEAT_INTERVAL_PROP_NAME */ public static long leaderHeartbeatIntervalNs() { return getDurationInNanos(LEADER_HEARTBEAT_INTERVAL_PROP_NAME, LEADER_HEARTBEAT_INTERVAL_DEFAULT_NS); } /** * Timeout waiting to canvass the status of cluster members before voting if a majority have been heard from. * * @return timeout in nanoseconds to wait for the status of other cluster members before voting. * @see #STARTUP_CANVASS_TIMEOUT_PROP_NAME */ public static long startupCanvassTimeoutNs() { return getDurationInNanos(STARTUP_CANVASS_TIMEOUT_PROP_NAME, STARTUP_CANVASS_TIMEOUT_DEFAULT_NS); } /** * Timeout waiting for votes to become leader in an election. * * @return timeout in nanoseconds to wait for votes to become leader in an election. * @see #ELECTION_TIMEOUT_PROP_NAME */ public static long electionTimeoutNs() { return getDurationInNanos(ELECTION_TIMEOUT_PROP_NAME, ELECTION_TIMEOUT_DEFAULT_NS); } /** * Interval at which a member will send out status messages during the election phases. * * @return interval at which a member will send out status messages during the election phases. * @see #ELECTION_STATUS_INTERVAL_PROP_NAME */ public static long electionStatusIntervalNs() { return getDurationInNanos(ELECTION_STATUS_INTERVAL_PROP_NAME, ELECTION_STATUS_INTERVAL_DEFAULT_NS); } /** * Interval at which a dynamic joining member will send out add cluster members and snapshot recording * queries. * * @return Interval at which a dynamic joining member will send out add cluster members and snapshot recording * queries. * @see #DYNAMIC_JOIN_INTERVAL_PROP_NAME */ public static long dynamicJoinIntervalNs() { return getDurationInNanos(DYNAMIC_JOIN_INTERVAL_PROP_NAME, DYNAMIC_JOIN_INTERVAL_DEFAULT_NS); } /** * Timeout waiting for follower termination by leader. * * @return timeout in nanoseconds to wait followers to terminate. * @see #TERMINATION_TIMEOUT_PROP_NAME */ public static long terminationTimeoutNs() { return getDurationInNanos(TERMINATION_TIMEOUT_PROP_NAME, TERMINATION_TIMEOUT_DEFAULT_NS); } /** * Size in bytes of the error buffer in the mark file. * * @return length of error buffer in bytes. * @see #ERROR_BUFFER_LENGTH_PROP_NAME */ public static int errorBufferLength() { return getSizeAsInt(ERROR_BUFFER_LENGTH_PROP_NAME, ERROR_BUFFER_LENGTH_DEFAULT); } /** * The value {@link #AUTHENTICATOR_SUPPLIER_DEFAULT} or system property * {@link #AUTHENTICATOR_SUPPLIER_PROP_NAME} if set. * * @return {@link #AUTHENTICATOR_SUPPLIER_DEFAULT} or system property * {@link #AUTHENTICATOR_SUPPLIER_PROP_NAME} if set. */ public static AuthenticatorSupplier authenticatorSupplier() { final String supplierClassName = System.getProperty( AUTHENTICATOR_SUPPLIER_PROP_NAME, AUTHENTICATOR_SUPPLIER_DEFAULT); AuthenticatorSupplier supplier = null; try { supplier = (AuthenticatorSupplier)Class.forName(supplierClassName).getConstructor().newInstance(); } catch (final Exception ex) { LangUtil.rethrowUnchecked(ex); } return supplier; } /** * The value {@link #MEMBER_STATUS_CHANNEL_DEFAULT} or system property * {@link #MEMBER_STATUS_CHANNEL_PROP_NAME} if set. * * @return {@link #MEMBER_STATUS_CHANNEL_DEFAULT} or system property * {@link #MEMBER_STATUS_CHANNEL_PROP_NAME} if set. */ public static String memberStatusChannel() { return System.getProperty(MEMBER_STATUS_CHANNEL_PROP_NAME, MEMBER_STATUS_CHANNEL_DEFAULT); } /** * The value {@link #MEMBER_STATUS_STREAM_ID_DEFAULT} or system property * {@link #MEMBER_STATUS_STREAM_ID_PROP_NAME} if set. * * @return {@link #MEMBER_STATUS_STREAM_ID_DEFAULT} or system property * {@link #MEMBER_STATUS_STREAM_ID_PROP_NAME} if set. */ public static int memberStatusStreamId() { return Integer.getInteger(MEMBER_STATUS_STREAM_ID_PROP_NAME, MEMBER_STATUS_STREAM_ID_DEFAULT); } /** * The value {@link #WHEEL_TICK_RESOLUTION_DEFAULT_NS} or system property * {@link #WHEEL_TICK_RESOLUTION_PROP_NAME} if set. * * @return {@link #WHEEL_TICK_RESOLUTION_DEFAULT_NS} or system property * {@link #WHEEL_TICK_RESOLUTION_PROP_NAME} if set. */ public static long wheelTickResolutionNs() { return getDurationInNanos(WHEEL_TICK_RESOLUTION_PROP_NAME, WHEEL_TICK_RESOLUTION_DEFAULT_NS); } /** * The value {@link #TICKS_PER_WHEEL_DEFAULT} or system property * {@link #CLUSTER_MEMBER_ID_PROP_NAME} if set. * * @return {@link #TICKS_PER_WHEEL_DEFAULT} or system property * {@link #TICKS_PER_WHEEL_PROP_NAME} if set. */ public static int ticksPerWheel() { return Integer.getInteger(TICKS_PER_WHEEL_PROP_NAME, TICKS_PER_WHEEL_DEFAULT); } /** * The level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> * * @return level at which files should be sync'ed to disk. */ public static int fileSyncLevel() { return Integer.getInteger(FILE_SYNC_LEVEL_PROP_NAME, FILE_SYNC_LEVEL_DEFAULT); } } /** * Programmable overrides for configuring the {@link ConsensusModule} in a cluster. * <p> * The context will be owned by {@link ConsensusModuleAgent} after a successful * {@link ConsensusModule#launch(Context)} and closed via {@link ConsensusModule#close()}. */ public static class Context implements Cloneable { /** * Using an integer because there is no support for boolean. 1 is concluded, 0 is not concluded. */ private static final AtomicIntegerFieldUpdater<Context> IS_CONCLUDED_UPDATER = newUpdater( Context.class, "isConcluded"); private volatile int isConcluded; private boolean ownsAeronClient = false; private String aeronDirectoryName = CommonContext.getAeronDirectoryName(); private Aeron aeron; private boolean deleteDirOnStart = false; private String clusterDirectoryName = ClusteredServiceContainer.Configuration.clusterDirName(); private File clusterDir; private RecordingLog recordingLog; private ClusterMarkFile markFile; private MutableDirectBuffer tempBuffer; private int fileSyncLevel = Archive.Configuration.fileSyncLevel(); private int appVersion = SemanticVersion.compose(0, 0, 1); private int clusterMemberId = Configuration.clusterMemberId(); private int appointedLeaderId = Configuration.appointedLeaderId(); private String clusterMembers = Configuration.clusterMembers(); private String clusterMembersStatusEndpoints = Configuration.clusterMembersStatusEndpoints(); private boolean clusterMembersIgnoreSnapshot = Configuration.clusterMembersIgnoreSnapshot(); private String ingressChannel = AeronCluster.Configuration.ingressChannel(); private int ingressStreamId = AeronCluster.Configuration.ingressStreamId(); private int ingressFragmentLimit = Configuration.ingressFragmentLimit(); private String logChannel = Configuration.logChannel(); private int logStreamId = Configuration.logStreamId(); private String memberEndpoints = Configuration.memberEndpoints(); private String replayChannel = ClusteredServiceContainer.Configuration.replayChannel(); private int replayStreamId = ClusteredServiceContainer.Configuration.replayStreamId(); private String serviceControlChannel = ClusteredServiceContainer.Configuration.serviceControlChannel(); private int consensusModuleStreamId = ClusteredServiceContainer.Configuration.consensusModuleStreamId(); private int serviceStreamId = ClusteredServiceContainer.Configuration.serviceStreamId(); private String snapshotChannel = Configuration.snapshotChannel(); private int snapshotStreamId = Configuration.snapshotStreamId(); private String memberStatusChannel = Configuration.memberStatusChannel(); private int memberStatusStreamId = Configuration.memberStatusStreamId(); private int serviceCount = Configuration.serviceCount(); private int errorBufferLength = Configuration.errorBufferLength(); private int maxConcurrentSessions = Configuration.maxConcurrentSessions(); private int ticksPerWheel = Configuration.ticksPerWheel(); private long wheelTickResolutionNs = Configuration.wheelTickResolutionNs(); private long sessionTimeoutNs = Configuration.sessionTimeoutNs(); private long leaderHeartbeatTimeoutNs = Configuration.leaderHeartbeatTimeoutNs(); private long leaderHeartbeatIntervalNs = Configuration.leaderHeartbeatIntervalNs(); private long startupCanvassTimeoutNs = Configuration.startupCanvassTimeoutNs(); private long electionTimeoutNs = Configuration.electionTimeoutNs(); private long electionStatusIntervalNs = Configuration.electionStatusIntervalNs(); private long dynamicJoinIntervalNs = Configuration.dynamicJoinIntervalNs(); private long terminationTimeoutNs = Configuration.terminationTimeoutNs(); private ThreadFactory threadFactory; private Supplier<IdleStrategy> idleStrategySupplier; private ClusterClock clusterClock; private EpochClock epochClock; private Random random; private DistinctErrorLog errorLog; private ErrorHandler errorHandler; private AtomicCounter errorCounter; private CountedErrorHandler countedErrorHandler; private Counter moduleState; private Counter clusterNodeRole; private Counter commitPosition; private Counter controlToggle; private Counter snapshotCounter; private Counter invalidRequestCounter; private Counter timedOutClientCounter; private ShutdownSignalBarrier shutdownSignalBarrier; private Runnable terminationHook; private AeronArchive.Context archiveContext; private AuthenticatorSupplier authenticatorSupplier; private LogPublisher logPublisher; private EgressPublisher egressPublisher; /** * Perform a shallow copy of the object. * * @return a shallow copy of the object. */ public Context clone() { try { return (Context)super.clone(); } catch (final CloneNotSupportedException ex) { throw new RuntimeException(ex); } } @SuppressWarnings("MethodLength") public void conclude() { if (0 != IS_CONCLUDED_UPDATER.getAndSet(this, 1)) { throw new ConcurrentConcludeException(); } if (null == clusterDir) { clusterDir = new File(clusterDirectoryName); } if (deleteDirOnStart && clusterDir.exists()) { IoUtil.delete(clusterDir, false); } if (!clusterDir.exists() && !clusterDir.mkdirs()) { throw new ClusterException("failed to create cluster dir: " + clusterDir.getAbsolutePath()); } if (null == tempBuffer) { tempBuffer = new UnsafeBuffer(new byte[METADATA_LENGTH]); } if (null == clusterClock) { clusterClock = new MillisecondClusterClock(); } if (null == epochClock) { epochClock = new SystemEpochClock(); } if (null == markFile) { markFile = new ClusterMarkFile( new File(clusterDir, ClusterMarkFile.FILENAME), ClusterComponentType.CONSENSUS_MODULE, errorBufferLength, epochClock, 0); } if (null == errorLog) { errorLog = new DistinctErrorLog(markFile.errorBuffer(), epochClock); } if (null == errorHandler) { errorHandler = new LoggingErrorHandler(errorLog); } if (null == recordingLog) { recordingLog = new RecordingLog(clusterDir); } if (null == aeron) { ownsAeronClient = true; aeron = Aeron.connect( new Aeron.Context() .aeronDirectoryName(aeronDirectoryName) .errorHandler(errorHandler) .epochClock(epochClock) .useConductorAgentInvoker(true) .awaitingIdleStrategy(YieldingIdleStrategy.INSTANCE) .clientLock(NoOpLock.INSTANCE)); if (null == errorCounter) { errorCounter = aeron.addCounter(CONSENSUS_MODULE_ERROR_COUNT_TYPE_ID, "Cluster errors"); } } if (null == aeron.conductorAgentInvoker()) { throw new ClusterException("Aeron client must use conductor agent invoker"); } if (null == errorCounter) { throw new ClusterException("error counter must be supplied if aeron client is"); } if (null == countedErrorHandler) { countedErrorHandler = new CountedErrorHandler(errorHandler, errorCounter); if (ownsAeronClient) { aeron.context().errorHandler(countedErrorHandler); } } if (null == moduleState) { moduleState = aeron.addCounter(CONSENSUS_MODULE_STATE_TYPE_ID, "Consensus module state"); } if (null == commitPosition) { commitPosition = CommitPos.allocate(aeron); } if (null == controlToggle) { controlToggle = aeron.addCounter(CONTROL_TOGGLE_TYPE_ID, "Cluster control toggle"); } if (null == snapshotCounter) { snapshotCounter = aeron.addCounter(SNAPSHOT_COUNTER_TYPE_ID, "Snapshot count"); } if (null == invalidRequestCounter) { invalidRequestCounter = aeron.addCounter(CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID, "Invalid cluster request count"); } if (null == timedOutClientCounter) { timedOutClientCounter = aeron.addCounter(CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID, "Timed out cluster client count"); } if (null == clusterNodeRole) { clusterNodeRole = aeron.addCounter(Configuration.CLUSTER_NODE_ROLE_TYPE_ID, "Cluster node role"); } if (null == threadFactory) { threadFactory = Thread::new; } if (null == idleStrategySupplier) { idleStrategySupplier = ClusteredServiceContainer.Configuration.idleStrategySupplier(null); } if (null == archiveContext) { archiveContext = new AeronArchive.Context() .controlRequestChannel(AeronArchive.Configuration.localControlChannel()) .controlResponseChannel(AeronArchive.Configuration.localControlChannel()) .controlRequestStreamId(AeronArchive.Configuration.localControlStreamId()); } archiveContext .aeron(aeron) .errorHandler(countedErrorHandler) .ownsAeronClient(false) .lock(NoOpLock.INSTANCE); if (null == shutdownSignalBarrier) { shutdownSignalBarrier = new ShutdownSignalBarrier(); } if (null == terminationHook) { terminationHook = () -> shutdownSignalBarrier.signal(); } if (null == authenticatorSupplier) { authenticatorSupplier = Configuration.authenticatorSupplier(); } if (null == random) { random = new Random(); } if (null == logPublisher) { logPublisher = new LogPublisher(); } if (null == egressPublisher) { egressPublisher = new EgressPublisher(); } concludeMarkFile(); } /** * The temporary buffer than can be used to build up counter labels to avoid allocation. * * @return the temporary buffer than can be used to build up counter labels to avoid allocation. */ public MutableDirectBuffer tempBuffer() { return tempBuffer; } /** * Set the temporary buffer than can be used to build up counter labels to avoid allocation. * * @param tempBuffer to be used to avoid allocation. * @return the temporary buffer than can be used to build up counter labels to avoid allocation. */ public Context tempBuffer(final MutableDirectBuffer tempBuffer) { this.tempBuffer = tempBuffer; return this; } /** * Should the consensus module attempt to immediately delete {@link #clusterDir()} on startup. * * @param deleteDirOnStart Attempt deletion. * @return this for a fluent API. */ public Context deleteDirOnStart(final boolean deleteDirOnStart) { this.deleteDirOnStart = deleteDirOnStart; return this; } /** * Will the consensus module attempt to immediately delete {@link #clusterDir()} on startup. * * @return true when directory will be deleted, otherwise false. */ public boolean deleteDirOnStart() { return deleteDirOnStart; } /** * Set the directory name to use for the consensus module directory. * * @param clusterDirectoryName to use. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public Context clusterDirectoryName(final String clusterDirectoryName) { this.clusterDirectoryName = clusterDirectoryName; return this; } /** * The directory name to use for the consensus module directory. * * @return directory name for the consensus module directory. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public String clusterDirectoryName() { return clusterDirectoryName; } /** * Set the directory to use for the consensus module directory. * * @param clusterDir to use. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public Context clusterDir(final File clusterDir) { this.clusterDir = clusterDir; return this; } /** * The directory used for for the consensus module directory. * * @return directory for for the consensus module directory. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CLUSTER_DIR_PROP_NAME */ public File clusterDir() { return clusterDir; } /** * Set the {@link RecordingLog} for the log terms and snapshots. * * @param recordingLog to use. * @return this for a fluent API. */ public Context recordingLog(final RecordingLog recordingLog) { this.recordingLog = recordingLog; return this; } /** * The {@link RecordingLog} for the log terms and snapshots. * * @return {@link RecordingLog} for the log terms and snapshots. */ public RecordingLog recordingLog() { return recordingLog; } /** * User assigned application version which appended to the log as the appVersion in new leadership events. * <p> * This can be validated using {@link org.agrona.SemanticVersion} to ensure only application nodes of the same * major version communicate with each other. * * @param appVersion for user application. * @return this for a fluent API. */ public Context appVersion(final int appVersion) { this.appVersion = appVersion; return this; } /** * User assigned application version which appended to the log as the appVersion in new leadership events. * <p> * This can be validated using {@link org.agrona.SemanticVersion} to ensure only application nodes of the same * major version communicate with each other. * * @return appVersion for user application. */ public int appVersion() { return appVersion; } /** * Get level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> * * @return the level to be applied for file write. * @see Configuration#FILE_SYNC_LEVEL_PROP_NAME */ int fileSyncLevel() { return fileSyncLevel; } /** * Set level at which files should be sync'ed to disk. * <ul> * <li>0 - normal writes.</li> * <li>1 - sync file data.</li> * <li>2 - sync file data + metadata.</li> * </ul> * * @param syncLevel to be applied for file writes. * @return this for a fluent API. * @see Configuration#FILE_SYNC_LEVEL_PROP_NAME */ public Context fileSyncLevel(final int syncLevel) { this.fileSyncLevel = syncLevel; return this; } /** * This cluster member identity. * * @param clusterMemberId for this member. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBER_ID_PROP_NAME */ public Context clusterMemberId(final int clusterMemberId) { this.clusterMemberId = clusterMemberId; return this; } /** * This cluster member identity. * * @return this cluster member identity. * @see Configuration#CLUSTER_MEMBER_ID_PROP_NAME */ public int clusterMemberId() { return clusterMemberId; } /** * The cluster member id of the appointed cluster leader. * <p> * -1 means no leader has been appointed and an automated leader election should occur. * * @param appointedLeaderId for the cluster. * @return this for a fluent API. * @see Configuration#APPOINTED_LEADER_ID_PROP_NAME */ public Context appointedLeaderId(final int appointedLeaderId) { this.appointedLeaderId = appointedLeaderId; return this; } /** * The cluster member id of the appointed cluster leader. * <p> * -1 means no leader has been appointed and an automated leader election should occur. * * @return cluster member id of the appointed cluster leader. * @see Configuration#APPOINTED_LEADER_ID_PROP_NAME */ public int appointedLeaderId() { return appointedLeaderId; } /** * String representing the cluster members. * <p> * <code> * 0,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| \ * 1,client-facing:port,member-facing:port,log:port,transfer:port,archive:port| ... * </code> * <p> * The client facing endpoints will be used as the endpoint substituted into the {@link #ingressChannel()} * if the endpoint is not provided unless it is multicast. * * @param clusterMembers which are all candidates to be leader. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBERS_PROP_NAME */ public Context clusterMembers(final String clusterMembers) { this.clusterMembers = clusterMembers; return this; } /** * The endpoints representing members of the cluster which are all candidates to be leader. * <p> * The client facing endpoints will be used as the endpoint in {@link #ingressChannel()} if the endpoint is * not provided in that when it is not multicast. * * @return members of the cluster which are all candidates to be leader. * @see Configuration#CLUSTER_MEMBERS_PROP_NAME */ public String clusterMembers() { return clusterMembers; } /** * String representing the cluster members member status endpoints used to request to join the cluster. * <p> * {@code "endpoint,endpoint,endpoint"} * <p> * * @param endpoints which are to be contacted for joining the cluster. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME */ public Context clusterMembersStatusEndpoints(final String endpoints) { this.clusterMembersStatusEndpoints = endpoints; return this; } /** * The endpoints representing cluster members of the cluster to attempt to contact to join the cluster. * * @return members of the cluster to attempt to request to join from. * @see Configuration#CLUSTER_MEMBERS_STATUS_ENDPOINTS_PROP_NAME */ public String clusterMembersStatusEndpoints() { return clusterMembersStatusEndpoints; } /** * Whether the cluster members in the snapshot should be ignored or not. * * @param ignore or not the cluster members in the snapshot. * @return this for a fluent API. * @see Configuration#CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME */ public Context clusterMembersIgnoreSnapshot(final boolean ignore) { this.clusterMembersIgnoreSnapshot = ignore; return this; } /** * Whether the cluster members in the snapshot should be ignored or not. * * @return ignore or not the cluster members in the snapshot. * @see Configuration#CLUSTER_MEMBERS_IGNORE_SNAPSHOT_PROP_NAME */ public boolean clusterMembersIgnoreSnapshot() { return clusterMembersIgnoreSnapshot; } /** * Set the channel parameter for the ingress channel. * * @param channel parameter for the ingress channel. * @return this for a fluent API. * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_CHANNEL_PROP_NAME */ public Context ingressChannel(final String channel) { ingressChannel = channel; return this; } /** * Get the channel parameter for the ingress channel. * * @return the channel parameter for the ingress channel. * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_CHANNEL_PROP_NAME */ public String ingressChannel() { return ingressChannel; } /** * Set the stream id for the ingress channel. * * @param streamId for the ingress channel. * @return this for a fluent API * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_STREAM_ID_PROP_NAME */ public Context ingressStreamId(final int streamId) { ingressStreamId = streamId; return this; } /** * Get the stream id for the ingress channel. * * @return the stream id for the ingress channel. * @see io.aeron.cluster.client.AeronCluster.Configuration#INGRESS_STREAM_ID_PROP_NAME */ public int ingressStreamId() { return ingressStreamId; } /** * Set limit for fragments to be consumed on each poll of ingress. * * @param ingressFragmentLimit for the ingress channel. * @return this for a fluent API * @see Configuration#CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME */ public Context ingressFragmentLimit(final int ingressFragmentLimit) { this.ingressFragmentLimit = ingressFragmentLimit; return this; } /** * The limit for fragments to be consumed on each poll of ingress. * * @return the limit for fragments to be consumed on each poll of ingress. * @see Configuration#CLUSTER_INGRESS_FRAGMENT_LIMIT_PROP_NAME */ public int ingressFragmentLimit() { return ingressFragmentLimit; } /** * Set the channel parameter for the cluster log channel. * * @param channel parameter for the cluster log channel. * @return this for a fluent API. * @see Configuration#LOG_CHANNEL_PROP_NAME */ public Context logChannel(final String channel) { logChannel = channel; return this; } /** * Get the channel parameter for the cluster log channel. * * @return the channel parameter for the cluster channel. * @see Configuration#LOG_CHANNEL_PROP_NAME */ public String logChannel() { return logChannel; } /** * Set the stream id for the cluster log channel. * * @param streamId for the cluster log channel. * @return this for a fluent API * @see Configuration#LOG_STREAM_ID_PROP_NAME */ public Context logStreamId(final int streamId) { logStreamId = streamId; return this; } /** * Get the stream id for the cluster log channel. * * @return the stream id for the cluster log channel. * @see Configuration#LOG_STREAM_ID_PROP_NAME */ public int logStreamId() { return logStreamId; } /** * Set the endpoints for this cluster node. * * @param endpoints for the cluster node. * @return this for a fluent API. * @see Configuration#MEMBER_ENDPOINTS_PROP_NAME */ public Context memberEndpoints(final String endpoints) { memberEndpoints = endpoints; return this; } /** * Get the endpoints for this cluster node. * * @return the endpoints for the cluster node. * @see Configuration#MEMBER_ENDPOINTS_PROP_NAME */ public String memberEndpoints() { return memberEndpoints; } /** * Set the channel parameter for the cluster log and snapshot replay channel. * * @param channel parameter for the cluster log replay channel. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_CHANNEL_PROP_NAME */ public Context replayChannel(final String channel) { replayChannel = channel; return this; } /** * Get the channel parameter for the cluster log and snapshot replay channel. * * @return the channel parameter for the cluster replay channel. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_CHANNEL_PROP_NAME */ public String replayChannel() { return replayChannel; } /** * Set the stream id for the cluster log and snapshot replay channel. * * @param streamId for the cluster log replay channel. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_STREAM_ID_PROP_NAME */ public Context replayStreamId(final int streamId) { replayStreamId = streamId; return this; } /** * Get the stream id for the cluster log and snapshot replay channel. * * @return the stream id for the cluster log replay channel. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#REPLAY_STREAM_ID_PROP_NAME */ public int replayStreamId() { return replayStreamId; } /** * Set the channel parameter for bi-directional communications between the consensus module and services. * * @param channel parameter for bi-directional communications between the consensus module and services. * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_CONTROL_CHANNEL_PROP_NAME */ public Context serviceControlChannel(final String channel) { serviceControlChannel = channel; return this; } /** * Get the channel parameter for bi-directional communications between the consensus module and services. * * @return the channel parameter for bi-directional communications between the consensus module and services. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_CONTROL_CHANNEL_PROP_NAME */ public String serviceControlChannel() { return serviceControlChannel; } /** * Set the stream id for communications from the consensus module and to the services. * * @param streamId for communications from the consensus module and to the services. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_STREAM_ID_PROP_NAME */ public Context serviceStreamId(final int streamId) { serviceStreamId = streamId; return this; } /** * Get the stream id for communications from the consensus module and to the services. * * @return the stream id for communications from the consensus module and to the services. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SERVICE_STREAM_ID_PROP_NAME */ public int serviceStreamId() { return serviceStreamId; } /** * Set the stream id for communications from the services to the consensus module. * * @param streamId for communications from the services to the consensus module. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CONSENSUS_MODULE_STREAM_ID_PROP_NAME */ public Context consensusModuleStreamId(final int streamId) { consensusModuleStreamId = streamId; return this; } /** * Get the stream id for communications from the services to the consensus module. * * @return the stream id for communications from the services to the consensus module. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#CONSENSUS_MODULE_STREAM_ID_PROP_NAME */ public int consensusModuleStreamId() { return consensusModuleStreamId; } /** * Set the channel parameter for snapshot recordings. * * @param channel parameter for snapshot recordings * @return this for a fluent API. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME */ public Context snapshotChannel(final String channel) { snapshotChannel = channel; return this; } /** * Get the channel parameter for snapshot recordings. * * @return the channel parameter for snapshot recordings. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_CHANNEL_PROP_NAME */ public String snapshotChannel() { return snapshotChannel; } /** * Set the stream id for snapshot recordings. * * @param streamId for snapshot recordings. * @return this for a fluent API * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME */ public Context snapshotStreamId(final int streamId) { snapshotStreamId = streamId; return this; } /** * Get the stream id for snapshot recordings. * * @return the stream id for snapshot recordings. * @see io.aeron.cluster.service.ClusteredServiceContainer.Configuration#SNAPSHOT_STREAM_ID_PROP_NAME */ public int snapshotStreamId() { return snapshotStreamId; } /** * Set the channel parameter for the member status communication channel. * * @param channel parameter for the member status communication channel. * @return this for a fluent API. * @see Configuration#MEMBER_STATUS_CHANNEL_PROP_NAME */ public Context memberStatusChannel(final String channel) { memberStatusChannel = channel; return this; } /** * Get the channel parameter for the member status communication channel. * * @return the channel parameter for the member status communication channel. * @see Configuration#MEMBER_STATUS_CHANNEL_PROP_NAME */ public String memberStatusChannel() { return memberStatusChannel; } /** * Set the stream id for the member status channel. * * @param streamId for the ingress channel. * @return this for a fluent API * @see Configuration#MEMBER_STATUS_STREAM_ID_PROP_NAME */ public Context memberStatusStreamId(final int streamId) { memberStatusStreamId = streamId; return this; } /** * Get the stream id for the member status channel. * * @return the stream id for the member status channel. * @see Configuration#MEMBER_STATUS_STREAM_ID_PROP_NAME */ public int memberStatusStreamId() { return memberStatusStreamId; } /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. * * @param wheelTickResolutionNs the resolution in nanoseconds of each tick on the timer wheel. * @return this for a fluent API * @see Configuration#WHEEL_TICK_RESOLUTION_PROP_NAME */ public Context wheelTickResolutionNs(final long wheelTickResolutionNs) { this.wheelTickResolutionNs = wheelTickResolutionNs; return this; } /** * Resolution in nanoseconds for each tick of the timer wheel for scheduling deadlines. * * @return the resolution in nanoseconds for each tick on the timer wheel. * @see Configuration#WHEEL_TICK_RESOLUTION_PROP_NAME */ public long wheelTickResolutionNs() { return wheelTickResolutionNs; } /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. * * @param ticksPerWheel the number of ticks on the timer wheel. * @return this for a fluent API * @see Configuration#TICKS_PER_WHEEL_PROP_NAME */ public Context ticksPerWheel(final int ticksPerWheel) { this.ticksPerWheel = ticksPerWheel; return this; } /** * Number of ticks, or spokes, on the timer wheel. Higher number of ticks reduces potential conflicts * traded off against memory usage. * * @return the number of ticks on the timer wheel. * @see Configuration#TICKS_PER_WHEEL_PROP_NAME */ public int ticksPerWheel() { return ticksPerWheel; } /** * Set the number of clustered services in this cluster instance. * * @param serviceCount the number of clustered services in this cluster instance. * @return this for a fluent API * @see Configuration#SERVICE_COUNT_PROP_NAME */ public Context serviceCount(final int serviceCount) { this.serviceCount = serviceCount; return this; } /** * Get the number of clustered services in this cluster instance. * * @return the number of clustered services in this cluster instance. * @see Configuration#SERVICE_COUNT_PROP_NAME */ public int serviceCount() { return serviceCount; } /** * Set the limit for the maximum number of concurrent cluster sessions. * * @param maxSessions after which new sessions will be rejected. * @return this for a fluent API * @see Configuration#MAX_CONCURRENT_SESSIONS_PROP_NAME */ public Context maxConcurrentSessions(final int maxSessions) { this.maxConcurrentSessions = maxSessions; return this; } /** * Get the limit for the maximum number of concurrent cluster sessions. * * @return the limit for the maximum number of concurrent cluster sessions. * @see Configuration#MAX_CONCURRENT_SESSIONS_PROP_NAME */ public int maxConcurrentSessions() { return maxConcurrentSessions; } /** * Timeout for a session if no activity is observed. * * @param sessionTimeoutNs to wait for activity on a session. * @return this for a fluent API. * @see Configuration#SESSION_TIMEOUT_PROP_NAME */ public Context sessionTimeoutNs(final long sessionTimeoutNs) { this.sessionTimeoutNs = sessionTimeoutNs; return this; } /** * Timeout for a session if no activity is observed. * * @return the timeout for a session if no activity is observed. * @see Configuration#SESSION_TIMEOUT_PROP_NAME */ public long sessionTimeoutNs() { return sessionTimeoutNs; } /** * Timeout for a leader if no heartbeat is received by an other member. * * @param heartbeatTimeoutNs to wait for heartbeat from a leader. * @return this for a fluent API. * @see Configuration#LEADER_HEARTBEAT_TIMEOUT_PROP_NAME */ public Context leaderHeartbeatTimeoutNs(final long heartbeatTimeoutNs) { this.leaderHeartbeatTimeoutNs = heartbeatTimeoutNs; return this; } /** * Timeout for a leader if no heartbeat is received by an other member. * * @return the timeout for a leader if no heartbeat is received by an other member. * @see Configuration#LEADER_HEARTBEAT_TIMEOUT_PROP_NAME */ public long leaderHeartbeatTimeoutNs() { return leaderHeartbeatTimeoutNs; } /** * Interval at which a leader will send heartbeats if the log is not progressing. * * @param heartbeatIntervalNs between leader heartbeats. * @return this for a fluent API. * @see Configuration#LEADER_HEARTBEAT_INTERVAL_PROP_NAME */ public Context leaderHeartbeatIntervalNs(final long heartbeatIntervalNs) { this.leaderHeartbeatIntervalNs = heartbeatIntervalNs; return this; } /** * Interval at which a leader will send heartbeats if the log is not progressing. * * @return the interval at which a leader will send heartbeats if the log is not progressing. * @see Configuration#LEADER_HEARTBEAT_INTERVAL_PROP_NAME */ public long leaderHeartbeatIntervalNs() { return leaderHeartbeatIntervalNs; } /** * Timeout to wait for hearing the status of all cluster members on startup after recovery before commencing * an election if a majority of members has been heard from. * * @param timeoutNs to wait on startup after recovery before commencing an election. * @return this for a fluent API. * @see Configuration#STARTUP_CANVASS_TIMEOUT_PROP_NAME */ public Context startupCanvassTimeoutNs(final long timeoutNs) { this.startupCanvassTimeoutNs = timeoutNs; return this; } /** * Timeout to wait for hearing the status of all cluster members on startup after recovery before commencing * an election if a majority of members has been heard from. * * @return the timeout to wait on startup after recovery before commencing an election. * @see Configuration#STARTUP_CANVASS_TIMEOUT_PROP_NAME */ public long startupCanvassTimeoutNs() { return startupCanvassTimeoutNs; } /** * Timeout to wait for votes in an election before declaring the election void and starting over. * * @param timeoutNs to wait for votes in an elections. * @return this for a fluent API. * @see Configuration#ELECTION_TIMEOUT_PROP_NAME */ public Context electionTimeoutNs(final long timeoutNs) { this.electionTimeoutNs = timeoutNs; return this; } /** * Timeout to wait for votes in an election before declaring the election void and starting over. * * @return the timeout to wait for votes in an elections. * @see Configuration#ELECTION_TIMEOUT_PROP_NAME */ public long electionTimeoutNs() { return electionTimeoutNs; } /** * Interval at which a member will send out status messages during the election phases. * * @param electionStatusIntervalNs between status message updates. * @return this for a fluent API. * @see Configuration#ELECTION_STATUS_INTERVAL_PROP_NAME * @see Configuration#ELECTION_STATUS_INTERVAL_DEFAULT_NS */ public Context electionStatusIntervalNs(final long electionStatusIntervalNs) { this.electionStatusIntervalNs = electionStatusIntervalNs; return this; } /** * Interval at which a member will send out status messages during the election phases. * * @return the interval at which a member will send out status messages during the election phases. * @see Configuration#ELECTION_STATUS_INTERVAL_PROP_NAME * @see Configuration#ELECTION_STATUS_INTERVAL_DEFAULT_NS */ public long electionStatusIntervalNs() { return electionStatusIntervalNs; } /** * Interval at which a dynamic joining member will send add cluster member and snapshot recording queries. * * @param dynamicJoinIntervalNs between add cluster members and snapshot recording queries. * @return this for a fluent API. * @see Configuration#DYNAMIC_JOIN_INTERVAL_PROP_NAME * @see Configuration#DYNAMIC_JOIN_INTERVAL_DEFAULT_NS */ public Context dynamicJoinIntervalNs(final long dynamicJoinIntervalNs) { this.dynamicJoinIntervalNs = dynamicJoinIntervalNs; return this; } /** * Interval at which a dynamic joining member will send add cluster member and snapshot recording queries. * * @return the interval at which a dynamic joining member will send add cluster member and snapshot recording * queries. * @see Configuration#DYNAMIC_JOIN_INTERVAL_PROP_NAME * @see Configuration#DYNAMIC_JOIN_INTERVAL_DEFAULT_NS */ public long dynamicJoinIntervalNs() { return dynamicJoinIntervalNs; } /** * Timeout to wait for follower termination by leader. * * @param terminationTimeoutNs to wait for follower termination. * @return this for a fluent API. * @see Configuration#TERMINATION_TIMEOUT_PROP_NAME * @see Configuration#TERMINATION_TIMEOUT_DEFAULT_NS */ public Context terminationTimeoutNs(final long terminationTimeoutNs) { this.terminationTimeoutNs = terminationTimeoutNs; return this; } /** * Timeout to wait for follower termination by leader. * * @return timeout to wait for follower termination by leader. * @see Configuration#TERMINATION_TIMEOUT_PROP_NAME * @see Configuration#TERMINATION_TIMEOUT_DEFAULT_NS */ public long terminationTimeoutNs() { return terminationTimeoutNs; } /** * Get the thread factory used for creating threads. * * @return thread factory used for creating threads. */ public ThreadFactory threadFactory() { return threadFactory; } /** * Set the thread factory used for creating threads. * * @param threadFactory used for creating threads * @return this for a fluent API. */ public Context threadFactory(final ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } /** * Provides an {@link IdleStrategy} supplier for the idle strategy for the agent duty cycle. * * @param idleStrategySupplier supplier for the idle strategy for the agent duty cycle. * @return this for a fluent API. */ public Context idleStrategySupplier(final Supplier<IdleStrategy> idleStrategySupplier) { this.idleStrategySupplier = idleStrategySupplier; return this; } /** * Get a new {@link IdleStrategy} based on configured supplier. * * @return a new {@link IdleStrategy} based on configured supplier. */ public IdleStrategy idleStrategy() { return idleStrategySupplier.get(); } /** * Set the {@link ClusterClock} to be used for timestamping messages. * * @param clock {@link ClusterClock} to be used for timestamping message * @return this for a fluent API. */ public Context clusterClock(final ClusterClock clock) { this.clusterClock = clock; return this; } /** * Get the {@link ClusterClock} to used for timestamping message * * @return the {@link ClusterClock} to used for timestamping message */ public ClusterClock clusterClock() { return clusterClock; } /** * Set the {@link EpochClock} to be used for tracking wall clock time. * * @param clock {@link EpochClock} to be used for tracking wall clock time. * @return this for a fluent API. */ public Context epochClock(final EpochClock clock) { this.epochClock = clock; return this; } /** * Get the {@link EpochClock} to used for tracking wall clock time. * * @return the {@link EpochClock} to used for tracking wall clock time. */ public EpochClock epochClock() { return epochClock; } /** * Get the {@link ErrorHandler} to be used by the Consensus Module. * * @return the {@link ErrorHandler} to be used by the Consensus Module. */ public ErrorHandler errorHandler() { return errorHandler; } /** * Set the {@link ErrorHandler} to be used by the Consensus Module. * * @param errorHandler the error handler to be used by the Consensus Module. * @return this for a fluent API */ public Context errorHandler(final ErrorHandler errorHandler) { this.errorHandler = errorHandler; return this; } /** * Get the error counter that will record the number of errors observed. * * @return the error counter that will record the number of errors observed. */ public AtomicCounter errorCounter() { return errorCounter; } /** * Set the error counter that will record the number of errors observed. * * @param errorCounter the error counter that will record the number of errors observed. * @return this for a fluent API. */ public Context errorCounter(final AtomicCounter errorCounter) { this.errorCounter = errorCounter; return this; } /** * Non-default for context. * * @param countedErrorHandler to override the default. * @return this for a fluent API. */ public Context countedErrorHandler(final CountedErrorHandler countedErrorHandler) { this.countedErrorHandler = countedErrorHandler; return this; } /** * The {@link #errorHandler()} that will increment {@link #errorCounter()} by default. * * @return {@link #errorHandler()} that will increment {@link #errorCounter()} by default. */ public CountedErrorHandler countedErrorHandler() { return countedErrorHandler; } /** * Get the counter for the current state of the consensus module. * * @return the counter for the current state of the consensus module. * @see ConsensusModule.State */ public Counter moduleStateCounter() { return moduleState; } /** * Set the counter for the current state of the consensus module. * * @param moduleState the counter for the current state of the consensus module. * @return this for a fluent API. * @see ConsensusModule.State */ public Context moduleStateCounter(final Counter moduleState) { this.moduleState = moduleState; return this; } /** * Get the counter for the commit position the cluster has reached for consensus. * * @return the counter for the commit position the cluster has reached for consensus. * @see CommitPos */ public Counter commitPositionCounter() { return commitPosition; } /** * Set the counter for the commit position the cluster has reached for consensus. * * @param commitPosition counter for the commit position the cluster has reached for consensus. * @return this for a fluent API. * @see CommitPos */ public Context commitPositionCounter(final Counter commitPosition) { this.commitPosition = commitPosition; return this; } /** * Get the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} of the * consensus module node. * * @return the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} of the * cluster node. * @see io.aeron.cluster.service.Cluster.Role */ public Counter clusterNodeCounter() { return clusterNodeRole; } /** * Set the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} of the * cluster node. * * @param moduleRole the counter for representing the current {@link io.aeron.cluster.service.Cluster.Role} * of the cluster node. * @return this for a fluent API. * @see io.aeron.cluster.service.Cluster.Role */ public Context clusterNodeCounter(final Counter moduleRole) { this.clusterNodeRole = moduleRole; return this; } /** * Get the counter for the control toggle for triggering actions on the cluster node. * * @return the counter for triggering cluster node actions. * @see ClusterControl */ public Counter controlToggleCounter() { return controlToggle; } /** * Set the counter for the control toggle for triggering actions on the cluster node. * * @param controlToggle the counter for triggering cluster node actions. * @return this for a fluent API. * @see ClusterControl */ public Context controlToggleCounter(final Counter controlToggle) { this.controlToggle = controlToggle; return this; } /** * Get the counter for the count of snapshots taken. * * @return the counter for the count of snapshots taken. */ public Counter snapshotCounter() { return snapshotCounter; } /** * Set the counter for the count of snapshots taken. * * @param snapshotCounter the count of snapshots taken. * @return this for a fluent API. */ public Context snapshotCounter(final Counter snapshotCounter) { this.snapshotCounter = snapshotCounter; return this; } /** * Get the counter for the count of invalid client requests. * * @return the counter for the count of invalid client requests. */ public Counter invalidRequestCounter() { return invalidRequestCounter; } /** * Set the counter for the count of invalid client requests. * * @param invalidRequestCounter the count of invalid client requests. * @return this for a fluent API. */ public Context invalidRequestCounter(final Counter invalidRequestCounter) { this.invalidRequestCounter = invalidRequestCounter; return this; } /** * Get the counter for the count of clients that have been timed out and disconnected. * * @return the counter for the count of clients that have been timed out and disconnected. */ public Counter timedOutClientCounter() { return timedOutClientCounter; } /** * Set the counter for the count of clients that have been timed out and disconnected. * * @param timedOutClientCounter the count of clients that have been timed out and disconnected. * @return this for a fluent API. */ public Context timedOutClientCounter(final Counter timedOutClientCounter) { this.timedOutClientCounter = timedOutClientCounter; return this; } /** * {@link Aeron} client for communicating with the local Media Driver. * <p> * This client will be closed when the {@link ConsensusModule#close()} or {@link #close()} methods are called * if {@link #ownsAeronClient()} is true. * * @param aeron client for communicating with the local Media Driver. * @return this for a fluent API. * @see Aeron#connect() */ public Context aeron(final Aeron aeron) { this.aeron = aeron; return this; } /** * {@link Aeron} client for communicating with the local Media Driver. * <p> * If not provided then a default will be established during {@link #conclude()} by calling * {@link Aeron#connect()}. * * @return client for communicating with the local Media Driver. */ public Aeron aeron() { return aeron; } /** * Set the top level Aeron directory used for communication between the Aeron client and Media Driver. * * @param aeronDirectoryName the top level Aeron directory. * @return this for a fluent API. */ public Context aeronDirectoryName(final String aeronDirectoryName) { this.aeronDirectoryName = aeronDirectoryName; return this; } /** * Get the top level Aeron directory used for communication between the Aeron client and Media Driver. * * @return The top level Aeron directory. */ public String aeronDirectoryName() { return aeronDirectoryName; } /** * Does this context own the {@link #aeron()} client and this takes responsibility for closing it? * * @param ownsAeronClient does this context own the {@link #aeron()} client. * @return this for a fluent API. */ public Context ownsAeronClient(final boolean ownsAeronClient) { this.ownsAeronClient = ownsAeronClient; return this; } /** * Does this context own the {@link #aeron()} client and this takes responsibility for closing it? * * @return does this context own the {@link #aeron()} client and this takes responsibility for closing it? */ public boolean ownsAeronClient() { return ownsAeronClient; } /** * Set the {@link io.aeron.archive.client.AeronArchive.Context} that should be used for communicating with the * local Archive. * * @param archiveContext that should be used for communicating with the local Archive. * @return this for a fluent API. */ public Context archiveContext(final AeronArchive.Context archiveContext) { this.archiveContext = archiveContext; return this; } /** * Get the {@link io.aeron.archive.client.AeronArchive.Context} that should be used for communicating with * the local Archive. * * @return the {@link io.aeron.archive.client.AeronArchive.Context} that should be used for communicating * with the local Archive. */ public AeronArchive.Context archiveContext() { return archiveContext; } /** * Get the {@link AuthenticatorSupplier} that should be used for the consensus module. * * @return the {@link AuthenticatorSupplier} to be used for the consensus module. */ public AuthenticatorSupplier authenticatorSupplier() { return authenticatorSupplier; } /** * Set the {@link AuthenticatorSupplier} that will be used for the consensus module. * * @param authenticatorSupplier {@link AuthenticatorSupplier} to use for the consensus module. * @return this for a fluent API. */ public Context authenticatorSupplier(final AuthenticatorSupplier authenticatorSupplier) { this.authenticatorSupplier = authenticatorSupplier; return this; } /** * Set the {@link ShutdownSignalBarrier} that can be used to shutdown a consensus module. * * @param barrier that can be used to shutdown a consensus module. * @return this for a fluent API. */ public Context shutdownSignalBarrier(final ShutdownSignalBarrier barrier) { shutdownSignalBarrier = barrier; return this; } /** * Get the {@link ShutdownSignalBarrier} that can be used to shutdown a consensus module. * * @return the {@link ShutdownSignalBarrier} that can be used to shutdown a consensus module. */ public ShutdownSignalBarrier shutdownSignalBarrier() { return shutdownSignalBarrier; } /** * Set the {@link Runnable} that is called when the {@link ConsensusModule} processes a termination action. * * @param terminationHook that can be used to terminate a consensus module. * @return this for a fluent API. */ public Context terminationHook(final Runnable terminationHook) { this.terminationHook = terminationHook; return this; } /** * Get the {@link Runnable} that is called when the {@link ConsensusModule} processes a termination action. * <p> * The default action is to call signal on the {@link #shutdownSignalBarrier()}. * * @return the {@link Runnable} that can be used to terminate a consensus module. */ public Runnable terminationHook() { return terminationHook; } /** * Set the {@link ClusterMarkFile} in use. * * @param markFile to use. * @return this for a fluent API. */ public Context clusterMarkFile(final ClusterMarkFile markFile) { this.markFile = markFile; return this; } /** * The {@link ClusterMarkFile} in use. * * @return {@link ClusterMarkFile} in use. */ public ClusterMarkFile clusterMarkFile() { return markFile; } /** * Set the error buffer length in bytes to use. * * @param errorBufferLength in bytes to use. * @return this for a fluent API. */ public Context errorBufferLength(final int errorBufferLength) { this.errorBufferLength = errorBufferLength; return this; } /** * The error buffer length in bytes. * * @return error buffer length in bytes. */ public int errorBufferLength() { return errorBufferLength; } /** * Set the {@link DistinctErrorLog} in use. * * @param errorLog to use. * @return this for a fluent API. */ public Context errorLog(final DistinctErrorLog errorLog) { this.errorLog = errorLog; return this; } /** * The {@link DistinctErrorLog} in use. * * @return {@link DistinctErrorLog} in use. */ public DistinctErrorLog errorLog() { return errorLog; } /** * The source of random values for timeouts used in elections. * * @param random source of random values for timeouts used in elections. * @return this for a fluent API. */ public Context random(final Random random) { this.random = random; return this; } /** * The source of random values for timeouts used in elections. * * @return source of random values for timeouts used in elections. */ public Random random() { return random; } /** * Delete the cluster directory. */ public void deleteDirectory() { if (null != clusterDir) { IoUtil.delete(clusterDir, false); } } /** * Close the context and free applicable resources. * <p> * If {@link #ownsAeronClient()} is true then the {@link #aeron()} client will be closed. */ public void close() { CloseHelper.close(recordingLog); CloseHelper.close(markFile); if (errorHandler instanceof AutoCloseable) { CloseHelper.close((AutoCloseable)errorHandler); } if (ownsAeronClient) { CloseHelper.close(aeron); } else if (!aeron.isClosed()) { CloseHelper.close(moduleState); CloseHelper.close(commitPosition); CloseHelper.close(clusterNodeRole); CloseHelper.close(controlToggle); CloseHelper.close(snapshotCounter); } } Context logPublisher(final LogPublisher logPublisher) { this.logPublisher = logPublisher; return this; } LogPublisher logPublisher() { return logPublisher; } Context egressPublisher(final EgressPublisher egressPublisher) { this.egressPublisher = egressPublisher; return this; } EgressPublisher egressPublisher() { return egressPublisher; } private void concludeMarkFile() { ClusterMarkFile.checkHeaderLength( aeron.context().aeronDirectoryName(), archiveContext.controlRequestChannel(), serviceControlChannel(), ingressChannel, null, authenticatorSupplier.getClass().toString()); markFile.encoder() .archiveStreamId(archiveContext.controlRequestStreamId()) .serviceStreamId(serviceStreamId) .consensusModuleStreamId(consensusModuleStreamId) .ingressStreamId(ingressStreamId) .memberId(clusterMemberId) .serviceId(SERVICE_ID) .aeronDirectory(aeron.context().aeronDirectoryName()) .archiveChannel(archiveContext.controlRequestChannel()) .serviceControlChannel(serviceControlChannel) .ingressChannel(ingressChannel) .serviceName("") .authenticator(authenticatorSupplier.getClass().toString()); markFile.updateActivityTimestamp(epochClock.time()); markFile.signalReady(); } } }
[Java] Formatting.
aeron-cluster/src/main/java/io/aeron/cluster/ConsensusModule.java
[Java] Formatting.
<ide><path>eron-cluster/src/main/java/io/aeron/cluster/ConsensusModule.java <ide> <ide> if (null == invalidRequestCounter) <ide> { <del> invalidRequestCounter = <del> aeron.addCounter(CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID, "Invalid cluster request count"); <add> invalidRequestCounter = aeron.addCounter( <add> CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID, "Invalid cluster request count"); <ide> } <ide> <ide> if (null == timedOutClientCounter) <ide> { <del> timedOutClientCounter = <del> aeron.addCounter(CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID, "Timed out cluster client count"); <add> timedOutClientCounter = aeron.addCounter( <add> CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID, "Timed out cluster client count"); <ide> } <ide> <ide> if (null == clusterNodeRole)
Java
agpl-3.0
44998769b6e919140728cf06f52f6b93785c42d7
0
mkl-public/testarea-itext5,mkl-public/testarea-itext5,mkl-public/testarea-itext5
package mkl.testarea.signature.analyze; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.ocsp.OCSPResponse; import org.bouncycastle.asn1.ocsp.ResponderID; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.DigestInfo; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.TBSCertificate; import org.bouncycastle.cert.CertException; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.bouncycastle.cert.ocsp.OCSPException; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cert.ocsp.SingleResp; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSVerifierCertificateNotValidException; import org.bouncycastle.cms.SignerId; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil; import org.bouncycastle.operator.DigestCalculator; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.RuntimeOperatorException; import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; import org.bouncycastle.tsp.TSPException; import org.bouncycastle.tsp.TimeStampToken; import org.bouncycastle.tsp.TimeStampTokenInfo; import org.bouncycastle.util.Selector; import org.bouncycastle.util.Store; /** * This class is meant to eventually become a tool for analyzing signatures. * More and more tests shall be added to indicate the issues of the upcoming * test signatures. * * @author mklink */ public class SignatureAnalyzer { private DigestCalculatorProvider digCalcProvider = new BcDigestCalculatorProvider(); public static void main(String[] args) throws Exception { for (String arg : args) { System.out.printf("\nAnalyzing %s\n", arg); byte[] bytes = Files.readAllBytes(FileSystems.getDefault().getPath(arg)); System.out.print("=========\n"); new SignatureAnalyzer(bytes); } } public SignatureAnalyzer(byte[] signatureData) throws CMSException, IOException, TSPException, OperatorCreationException, GeneralSecurityException { signedData = new CMSSignedData(signatureData); Store certificateStore = signedData.getCertificates(); if (certificateStore == null || certificateStore.getMatches(selectAny).isEmpty()) System.out.println("\nCertificates: none"); else { System.out.println("\nCertificates:"); for (X509CertificateHolder certificate : (Collection<X509CertificateHolder>) certificateStore.getMatches(selectAny)) { System.out.printf("- Subject: %s\n Issuer: %s\n Serial: %s\n", certificate.getSubject(), certificate.getIssuer(), certificate.getSerialNumber()); } } Store attributeCertificateStore = signedData.getAttributeCertificates(); if (attributeCertificateStore == null || attributeCertificateStore.getMatches(selectAny).isEmpty()) System.out.println("\nAttribute Certificates: none"); else { System.out.println("\nAttribute Certificates: TODO!!!"); } Store crls = signedData.getCRLs(); if (crls == null || crls.getMatches(selectAny).isEmpty()) System.out.println("\nCRLs: none"); else { System.out.println("\nCRLs: TODO!!!"); } for (SignerInformation signerInfo : (Collection<SignerInformation>)signedData.getSignerInfos().getSigners()) { System.out.printf("\nSignerInfo: %s / %s\n", signerInfo.getSID().getIssuer(), signerInfo.getSID().getSerialNumber()); Store certificates = signedData.getCertificates(); Collection certs = certificates.getMatches(signerInfo.getSID()); System.out.print("Certificate: "); X509CertificateHolder cert = null; if (certs.size() != 1) { System.out.printf("Could not identify, %s candidates\n", certs.size()); } else { cert = (X509CertificateHolder) certs.iterator().next(); System.out.printf("%s\n", cert.getSubject()); } if (signerInfo.getSignedAttributes() == null) { System.out.println("!!! No signed attributes"); analyzeSignatureBytes(signerInfo.getSignature(), cert, null); continue; } Map<ASN1ObjectIdentifier, ?> attributes = signerInfo.getSignedAttributes().toHashtable(); for (Map.Entry<ASN1ObjectIdentifier, ?> attributeEntry : attributes.entrySet()) { System.out.printf("Signed attribute %s", attributeEntry.getKey()); if (attributeEntry.getKey().equals(ADBE_REVOCATION_INFO_ARCHIVAL)) { System.out.println(" (Adobe Revocation Information Archival)"); Attribute attribute = (Attribute) attributeEntry.getValue(); for (ASN1Encodable encodable : attribute.getAttrValues().toArray()) { ASN1Sequence asn1Sequence = (ASN1Sequence) encodable; for (ASN1Encodable taggedEncodable : asn1Sequence.toArray()) { ASN1TaggedObject asn1TaggedObject = (ASN1TaggedObject) taggedEncodable; switch (asn1TaggedObject.getTagNo()) { case 0: { ASN1Sequence crlSeq = (ASN1Sequence) asn1TaggedObject.getObject(); for (ASN1Encodable crlEncodable : crlSeq.toArray()) { System.out.println(" CRL " + crlEncodable.getClass()); } break; } case 1: { ASN1Sequence ocspSeq = (ASN1Sequence) asn1TaggedObject.getObject(); for (ASN1Encodable ocspEncodable : ocspSeq.toArray()) { OCSPResponse ocspResponse = OCSPResponse.getInstance(ocspEncodable); OCSPResp ocspResp = new OCSPResp(ocspResponse); int status = ocspResp.getStatus(); BasicOCSPResp basicOCSPResp; try { basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); System.out.printf(" OCSP Response status %s - %s - %s\n", status, basicOCSPResp.getProducedAt(), ((ResponderID)basicOCSPResp.getResponderId().toASN1Primitive()).getName()); for (X509CertificateHolder certificate : basicOCSPResp.getCerts()) { System.out.printf(" Cert w/ Subject: %s\n Issuer: %s\n Serial: %s\n", certificate.getSubject(), certificate.getIssuer(), certificate.getSerialNumber()); } for (SingleResp singleResp : basicOCSPResp.getResponses()) { System.out.printf(" Response %s for ", singleResp.getCertStatus()); X509CertificateHolder issuer = null; for (X509CertificateHolder certificate : basicOCSPResp.getCerts()) { if (singleResp.getCertID().matchesIssuer(certificate, digCalcProvider)) issuer = certificate; } if (issuer == null) { System.out.printf("Serial %s and (hash algorithm %s) name %s / key %s\n", singleResp.getCertID().getSerialNumber(), singleResp.getCertID().getHashAlgOID(), toHex(singleResp.getCertID().getIssuerNameHash()), toHex(singleResp.getCertID().getIssuerKeyHash())); } else { System.out.printf("Issuer: %s Serial: %s\n", issuer.getSubject(), singleResp.getCertID().getSerialNumber()); } } } catch (OCSPException e) { System.out.printf(" !! Failure parsing OCSP response object: %s\n", e.getMessage()); } } break; } case 2: { ASN1Sequence otherSeq = (ASN1Sequence) asn1TaggedObject.getObject(); for (ASN1Encodable otherEncodable : otherSeq.toArray()) { System.out.println(" Other " + otherEncodable.getClass()); } break; } default: break; } } } } else if (attributeEntry.getKey().equals(PKCSObjectIdentifiers.pkcs_9_at_contentType)) { System.out.println(" (PKCS 9 - Content Type)"); } else if (attributeEntry.getKey().equals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest)) { System.out.println(" (PKCS 9 - Message Digest)"); Attribute attribute = (Attribute) attributeEntry.getValue(); ASN1Encodable[] values = attribute.getAttributeValues(); if (values == null || values.length == 0) System.out.println("!!! No Message Digest value"); else { if (values.length > 1) System.out.println("!!! Multiple Message Digest values"); for (ASN1Encodable value : values) { if (value instanceof ASN1OctetString) { byte[] octets = ((ASN1OctetString)value).getOctets(); System.out.printf("Digest: %s\n", toHex(octets)); try { Field resultDigestField = signerInfo.getClass().getDeclaredField("resultDigest"); resultDigestField.setAccessible(true); resultDigestField.set(signerInfo, octets); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { System.out.println("## Introspection failure: " + e.getMessage()); } } else System.out.println("!!! Invalid Message Digest value type " + value.getClass()); } } } else if (attributeEntry.getKey().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2)) { System.out.println(" (Signing certificate v2)"); } else { System.out.println(); } System.out.println(); } byte[] signedAttributeBytes = signerInfo.getEncodedSignedAttributes(); MessageDigest md = MessageDigest.getInstance(signerInfo.getDigestAlgOID()); byte[] signedAttributeHash = md.digest(signedAttributeBytes); String signedAttributeHashString = toHex(signedAttributeHash); System.out.printf("Signed Attributes Hash: %s\n", signedAttributeHashString); md.reset(); byte[] signedAttributeHashHash = md.digest(signedAttributeHash); String signedAttributeHashHashString = toHex(signedAttributeHashHash); System.out.printf("Signed Attributes Hash Hash: %s\n", signedAttributeHashHashString); byte[] derSignedAttributeBytes = new DERSet(ASN1Set.getInstance(signedAttributeBytes).toArray()).getEncoded(ASN1Encoding.DER); if (!Arrays.equals(derSignedAttributeBytes, signedAttributeBytes)) { System.out.println("!!! Signed attribute bytes not DER encoded"); md.reset(); byte[] derSignedAttributeHash = md.digest(derSignedAttributeBytes); String derSignedAttributeHashString = toHex(derSignedAttributeHash); System.out.printf("DER Signed Attributes Hash: %s\n", derSignedAttributeHashString); Files.write(Paths.get("C:\\Temp\\1.ber"), signedAttributeBytes); Files.write(Paths.get("C:\\Temp\\1.der"), derSignedAttributeBytes); } if (cert != null) { byte[] digestBytes = analyzeSignatureBytes(signerInfo.getSignature(), cert, derSignedAttributeBytes); if (digestBytes != null) { String digestString = toHex(digestBytes); if (!digestString.equals(signedAttributeHashString)) { System.out.println("!!! Decrypted RSA signature with PKCS1 1.5 padding does not contain signed attributes hash"); if (digestString.equals(signedAttributeHashHashString)) System.out.println("!!! but it contains the hash of the signed attributes hash"); } } System.out.println(); try { if(signerInfo.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))) System.out.println("Signature validates with certificate"); else System.out.println("!!! Signature does not validate with certificate"); } catch(CMSVerifierCertificateNotValidException e) { System.out.println("!!! Certificate not valid at claimed signing time: " + e.getMessage()); } catch(CertificateException e) { System.out.println("!!! Verification failure (Certificate): " + e.getMessage()); } catch(IllegalArgumentException e) { System.out.println("!!! Verification failure (Illegal argument): " + e.getMessage()); } catch(RuntimeOperatorException e) { System.out.println("!!! Verification failure (Runtime Operator): " + e.getMessage()); } catch(CMSException e2) { System.out.println("!!! Verification failure: " + e2.getMessage()); } System.out.println("\nCertificate path from accompanying certificates"); X509CertificateHolder c = cert; JcaContentVerifierProviderBuilder jcaContentVerifierProviderBuilder = new JcaContentVerifierProviderBuilder(); while (c != null) { System.out.printf("- %s ", c.getSubject()); X500Name issuer = c.getIssuer(); Collection cs = certificates.getMatches(new Selector() { @Override public boolean match(Object obj) { return (obj instanceof X509CertificateHolder) && ((X509CertificateHolder)obj).getSubject().equals(issuer); } @Override public Object clone() { return this; } }); if (cs.size() != 1) { System.out.printf("(no unique match - %d)", cs.size()); break; } X509CertificateHolder cc = (X509CertificateHolder) cs.iterator().next(); try { boolean isValid = c.isSignatureValid(jcaContentVerifierProviderBuilder.build(cc)); System.out.print(isValid ? "(valid signature)" : "(invalid signature)"); TBSCertificate tbsCert = c.toASN1Structure().getTBSCertificate(); try ( ByteArrayOutputStream sOut = new ByteArrayOutputStream() ) { ASN1OutputStream dOut = ASN1OutputStream.create(sOut, ASN1Encoding.DER); dOut.writeObject(tbsCert); byte[] tbsDerBytes = sOut.toByteArray(); boolean isDer = Arrays.equals(tbsDerBytes, tbsCert.getEncoded()); if (!isDer) System.out.print(" (TBSCertificate not DER encoded)"); } if (!isValid) { System.out.println("\nHashes of the TBSCertificate:"); for (Map.Entry<String, MessageDigest> entry : SignatureAnalyzer.digestByName.entrySet()) { String digestName = entry.getKey(); MessageDigest digest = entry.getValue(); digest.reset(); byte[] digestValue = digest.digest(tbsCert.getEncoded()); System.out.printf(" * %s: %s\n", digestName, SignatureAnalyzer.toHex(digestValue)); } analyzeSignatureBytes(c.getSignature(), cc, null); } } catch (CertException | CertificateException e) { System.out.printf("(inappropriate signature - %s)", e.getMessage()); } if (c == cc) { System.out.print(" (self-signed)"); c = null; } else c = cc; System.out.println(); } } System.out.println(); if (certificates != null) { for (Object certObject : certificates.getMatches(selectAny)) { X509CertificateHolder certHolder = (X509CertificateHolder) certObject; try { boolean verify = signerInfo.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder)); System.out.printf("Verify %s with '%s'.\n", verify ? "succeeds" : "fails", certHolder.getSubject()); } catch(Exception ex) { System.out.printf("Verify throws exception with '%s': '%s'.\n", certHolder.getSubject(), ex.getMessage()); } } } System.out.println(); AttributeTable attributeTable = signerInfo.getUnsignedAttributes(); if (attributeTable != null) { attributes = attributeTable.toHashtable(); for (Map.Entry<ASN1ObjectIdentifier, ?> attributeEntry : attributes.entrySet()) { System.out.printf("Unsigned attribute %s", attributeEntry.getKey()); if (attributeEntry.getKey().equals(/*SIGNATURE_TIME_STAMP_OID*/PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)) { System.out.println(" (Signature Time Stamp)"); Attribute attribute = (Attribute) attributeEntry.getValue(); for (ASN1Encodable encodable : attribute.getAttrValues().toArray()) { ContentInfo contentInfo = ContentInfo.getInstance(encodable); TimeStampToken timeStampToken = new TimeStampToken(contentInfo); TimeStampTokenInfo tstInfo = timeStampToken.getTimeStampInfo(); System.out.printf("Authority/SN %s / %s\n", tstInfo.getTsa(), tstInfo.getSerialNumber()); DigestCalculator digCalc = digCalcProvider .get(tstInfo.getHashAlgorithm()); OutputStream dOut = digCalc.getOutputStream(); dOut.write(signerInfo.getSignature()); dOut.close(); byte[] expectedDigest = digCalc.getDigest(); boolean matches = Arrays.equals(expectedDigest, tstInfo.getMessageImprintDigest()); System.out.printf("Digest match? %s\n", matches); System.out.printf("Signer %s / %s\n", timeStampToken.getSID().getIssuer(), timeStampToken.getSID().getSerialNumber()); Store tstCertificates = timeStampToken.getCertificates(); Collection tstCerts = tstCertificates.getMatches(new SignerId(timeStampToken.getSID().getIssuer(), timeStampToken.getSID().getSerialNumber())); System.out.print("Certificate: "); if (tstCerts.size() != 1) { System.out.printf("Could not identify, %s candidates\n", tstCerts.size()); } else { X509CertificateHolder tstCert = (X509CertificateHolder) tstCerts.iterator().next(); System.out.printf("%s\n", tstCert.getSubject()); int version = tstCert.toASN1Structure().getVersionNumber(); System.out.printf("Version: %s\n", version); if (version != 3) System.out.println("Error: Certificate must be version 3 to have an ExtendedKeyUsage extension."); Extension ext = tstCert.getExtension(Extension.extendedKeyUsage); if (ext == null) System.out.println("Error: Certificate must have an ExtendedKeyUsage extension."); else { if (!ext.isCritical()) { System.out.println("Error: Certificate must have an ExtendedKeyUsage extension marked as critical."); } ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(ext.getParsedValue()); if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) { System.out.println("Error: ExtendedKeyUsage not solely time stamping."); } } } } } else System.out.println(); } } } } public static byte[] analyzeSignatureBytes(byte[] signatureBytes, X509CertificateHolder cert, byte[] signedData) throws GeneralSecurityException, IOException { if (RSAUtil.isRsaOid(cert.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm())) { KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(cert.getSubjectPublicKeyInfo().getEncoded())); try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] bytes = cipher.doFinal(signatureBytes); System.out.printf("Decrypted signature bytes: %s\n", toHex(bytes)); try { DigestInfo digestInfo = DigestInfo.getInstance(bytes); String digestString = toHex(digestInfo.getDigest()); System.out.printf("Decrypted signature digest algorithm: %s\n", digestInfo.getAlgorithmId().getAlgorithm()); System.out.printf("Decrypted signature digest: %s\n", digestString); if (signedData != null) { MessageDigest digest = MessageDigest.getInstance(digestInfo.getAlgorithmId().getAlgorithm().toString()); byte[] actualDigest = digest.digest(signedData); if (!Arrays.equals(actualDigest, digestInfo.getDigest())) { String actualDigestString = toHex(actualDigest); System.out.printf("Actual signed data digest: %s\n", actualDigestString); } else { System.out.println("Decrypted signature digest matches signed data digest."); } } return digestInfo.getDigest(); } catch (IllegalArgumentException bpe) { System.out.println("!!! Decrypted, PKCS1 padded RSA signature is not well-formed: " + bpe.getMessage()); } } catch (BadPaddingException bpe) { System.out.println("!!! Decrypted RSA signature is not PKCS1 padded: " + bpe.getMessage()); try { Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding"); cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey); byte[] bytes = cipherNoPadding.doFinal(signatureBytes); System.out.printf("Decrypted signature bytes: %s\n", toHex(bytes)); if (bytes[bytes.length - 1] != (byte) 0xbc) System.out.println("!!! Decrypted RSA signature does not end with the PSS 0xbc byte either"); else { System.out.println("Decrypted RSA signature does end with the PSS 0xbc byte"); } } catch(BadPaddingException bpe2) { System.out.println("!!! Failure decrypted RSA signature: " + bpe2.getMessage()); } } } return null; } public static String toHex(byte[] bytes) { if (bytes == null) return "null"; final char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } final Selector selectAny = new Selector() { @Override public boolean match(Object obj) { return true; } @Override public Object clone() { return this; } }; final static List<String> digestNames = Arrays.asList("SHA-512", "SHA-384", "SHA-256", "SHA-224", "SHA1"); public final static Map<String, MessageDigest> digestByName = new LinkedHashMap<>(); static { for (String name : digestNames) { try { MessageDigest digest = MessageDigest.getInstance(name); digestByName.put(name, digest); } catch (NoSuchAlgorithmException e) { System.err.printf("Unknown digest algorithm '%s'. Skipping.\n", name); } } System.err.println(); } static final ASN1ObjectIdentifier adobe = new ASN1ObjectIdentifier("1.2.840.113583"); static final ASN1ObjectIdentifier acrobat = adobe.branch("1"); static final ASN1ObjectIdentifier security = acrobat.branch("1"); static final ASN1ObjectIdentifier ADBE_REVOCATION_INFO_ARCHIVAL = security.branch("8"); final CMSSignedData signedData; final static ASN1ObjectIdentifier SIGNATURE_TIME_STAMP_OID = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.2.14"); }
src/main/java/mkl/testarea/signature/analyze/SignatureAnalyzer.java
package mkl.testarea.signature.analyze; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.ocsp.OCSPResponse; import org.bouncycastle.asn1.ocsp.ResponderID; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.DigestInfo; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.TBSCertificate; import org.bouncycastle.cert.CertException; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.bouncycastle.cert.ocsp.OCSPException; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cert.ocsp.SingleResp; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSVerifierCertificateNotValidException; import org.bouncycastle.cms.SignerId; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil; import org.bouncycastle.operator.DigestCalculator; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.RuntimeOperatorException; import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; import org.bouncycastle.tsp.TSPException; import org.bouncycastle.tsp.TimeStampToken; import org.bouncycastle.tsp.TimeStampTokenInfo; import org.bouncycastle.util.Selector; import org.bouncycastle.util.Store; /** * This class is meant to eventually become a tool for analyzing signatures. * More and more tests shall be added to indicate the issues of the upcoming * test signatures. * * @author mklink */ public class SignatureAnalyzer { private DigestCalculatorProvider digCalcProvider = new BcDigestCalculatorProvider(); public static void main(String[] args) throws Exception { for (String arg : args) { System.out.printf("\nAnalyzing %s\n", arg); byte[] bytes = Files.readAllBytes(FileSystems.getDefault().getPath(arg)); System.out.print("=========\n"); new SignatureAnalyzer(bytes); } } public SignatureAnalyzer(byte[] signatureData) throws CMSException, IOException, TSPException, OperatorCreationException, GeneralSecurityException { signedData = new CMSSignedData(signatureData); Store certificateStore = signedData.getCertificates(); if (certificateStore == null || certificateStore.getMatches(selectAny).isEmpty()) System.out.println("\nCertificates: none"); else { System.out.println("\nCertificates:"); for (X509CertificateHolder certificate : (Collection<X509CertificateHolder>) certificateStore.getMatches(selectAny)) { System.out.printf("- Subject: %s\n Issuer: %s\n Serial: %s\n", certificate.getSubject(), certificate.getIssuer(), certificate.getSerialNumber()); } } Store attributeCertificateStore = signedData.getAttributeCertificates(); if (attributeCertificateStore == null || attributeCertificateStore.getMatches(selectAny).isEmpty()) System.out.println("\nAttribute Certificates: none"); else { System.out.println("\nAttribute Certificates: TODO!!!"); } Store crls = signedData.getCRLs(); if (crls == null || crls.getMatches(selectAny).isEmpty()) System.out.println("\nCRLs: none"); else { System.out.println("\nCRLs: TODO!!!"); } for (SignerInformation signerInfo : (Collection<SignerInformation>)signedData.getSignerInfos().getSigners()) { System.out.printf("\nSignerInfo: %s / %s\n", signerInfo.getSID().getIssuer(), signerInfo.getSID().getSerialNumber()); Store certificates = signedData.getCertificates(); Collection certs = certificates.getMatches(signerInfo.getSID()); System.out.print("Certificate: "); X509CertificateHolder cert = null; if (certs.size() != 1) { System.out.printf("Could not identify, %s candidates\n", certs.size()); } else { cert = (X509CertificateHolder) certs.iterator().next(); System.out.printf("%s\n", cert.getSubject()); } if (signerInfo.getSignedAttributes() == null) { System.out.println("!!! No signed attributes"); continue; } Map<ASN1ObjectIdentifier, ?> attributes = signerInfo.getSignedAttributes().toHashtable(); for (Map.Entry<ASN1ObjectIdentifier, ?> attributeEntry : attributes.entrySet()) { System.out.printf("Signed attribute %s", attributeEntry.getKey()); if (attributeEntry.getKey().equals(ADBE_REVOCATION_INFO_ARCHIVAL)) { System.out.println(" (Adobe Revocation Information Archival)"); Attribute attribute = (Attribute) attributeEntry.getValue(); for (ASN1Encodable encodable : attribute.getAttrValues().toArray()) { ASN1Sequence asn1Sequence = (ASN1Sequence) encodable; for (ASN1Encodable taggedEncodable : asn1Sequence.toArray()) { ASN1TaggedObject asn1TaggedObject = (ASN1TaggedObject) taggedEncodable; switch (asn1TaggedObject.getTagNo()) { case 0: { ASN1Sequence crlSeq = (ASN1Sequence) asn1TaggedObject.getObject(); for (ASN1Encodable crlEncodable : crlSeq.toArray()) { System.out.println(" CRL " + crlEncodable.getClass()); } break; } case 1: { ASN1Sequence ocspSeq = (ASN1Sequence) asn1TaggedObject.getObject(); for (ASN1Encodable ocspEncodable : ocspSeq.toArray()) { OCSPResponse ocspResponse = OCSPResponse.getInstance(ocspEncodable); OCSPResp ocspResp = new OCSPResp(ocspResponse); int status = ocspResp.getStatus(); BasicOCSPResp basicOCSPResp; try { basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); System.out.printf(" OCSP Response status %s - %s - %s\n", status, basicOCSPResp.getProducedAt(), ((ResponderID)basicOCSPResp.getResponderId().toASN1Primitive()).getName()); for (X509CertificateHolder certificate : basicOCSPResp.getCerts()) { System.out.printf(" Cert w/ Subject: %s\n Issuer: %s\n Serial: %s\n", certificate.getSubject(), certificate.getIssuer(), certificate.getSerialNumber()); } for (SingleResp singleResp : basicOCSPResp.getResponses()) { System.out.printf(" Response %s for ", singleResp.getCertStatus()); X509CertificateHolder issuer = null; for (X509CertificateHolder certificate : basicOCSPResp.getCerts()) { if (singleResp.getCertID().matchesIssuer(certificate, digCalcProvider)) issuer = certificate; } if (issuer == null) { System.out.printf("Serial %s and (hash algorithm %s) name %s / key %s\n", singleResp.getCertID().getSerialNumber(), singleResp.getCertID().getHashAlgOID(), toHex(singleResp.getCertID().getIssuerNameHash()), toHex(singleResp.getCertID().getIssuerKeyHash())); } else { System.out.printf("Issuer: %s Serial: %s\n", issuer.getSubject(), singleResp.getCertID().getSerialNumber()); } } } catch (OCSPException e) { System.out.printf(" !! Failure parsing OCSP response object: %s\n", e.getMessage()); } } break; } case 2: { ASN1Sequence otherSeq = (ASN1Sequence) asn1TaggedObject.getObject(); for (ASN1Encodable otherEncodable : otherSeq.toArray()) { System.out.println(" Other " + otherEncodable.getClass()); } break; } default: break; } } } } else if (attributeEntry.getKey().equals(PKCSObjectIdentifiers.pkcs_9_at_contentType)) { System.out.println(" (PKCS 9 - Content Type)"); } else if (attributeEntry.getKey().equals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest)) { System.out.println(" (PKCS 9 - Message Digest)"); Attribute attribute = (Attribute) attributeEntry.getValue(); ASN1Encodable[] values = attribute.getAttributeValues(); if (values == null || values.length == 0) System.out.println("!!! No Message Digest value"); else { if (values.length > 1) System.out.println("!!! Multiple Message Digest values"); for (ASN1Encodable value : values) { if (value instanceof ASN1OctetString) { byte[] octets = ((ASN1OctetString)value).getOctets(); System.out.printf("Digest: %s\n", toHex(octets)); try { Field resultDigestField = signerInfo.getClass().getDeclaredField("resultDigest"); resultDigestField.setAccessible(true); resultDigestField.set(signerInfo, octets); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { System.out.println("## Introspection failure: " + e.getMessage()); } } else System.out.println("!!! Invalid Message Digest value type " + value.getClass()); } } } else if (attributeEntry.getKey().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2)) { System.out.println(" (Signing certificate v2)"); } else { System.out.println(); } System.out.println(); } byte[] signedAttributeBytes = signerInfo.getEncodedSignedAttributes(); MessageDigest md = MessageDigest.getInstance(signerInfo.getDigestAlgOID()); byte[] signedAttributeHash = md.digest(signedAttributeBytes); String signedAttributeHashString = toHex(signedAttributeHash); System.out.printf("Signed Attributes Hash: %s\n", signedAttributeHashString); md.reset(); byte[] signedAttributeHashHash = md.digest(signedAttributeHash); String signedAttributeHashHashString = toHex(signedAttributeHashHash); System.out.printf("Signed Attributes Hash Hash: %s\n", signedAttributeHashHashString); byte[] derSignedAttributeBytes = new DERSet(ASN1Set.getInstance(signedAttributeBytes).toArray()).getEncoded(ASN1Encoding.DER); if (!Arrays.equals(derSignedAttributeBytes, signedAttributeBytes)) { System.out.println("!!! Signed attribute bytes not DER encoded"); md.reset(); byte[] derSignedAttributeHash = md.digest(derSignedAttributeBytes); String derSignedAttributeHashString = toHex(derSignedAttributeHash); System.out.printf("DER Signed Attributes Hash: %s\n", derSignedAttributeHashString); Files.write(Paths.get("C:\\Temp\\1.ber"), signedAttributeBytes); Files.write(Paths.get("C:\\Temp\\1.der"), derSignedAttributeBytes); } if (cert != null) { byte[] digestBytes = analyzeSignatureBytes(signerInfo.getSignature(), cert, derSignedAttributeBytes); if (digestBytes != null) { String digestString = toHex(digestBytes); if (!digestString.equals(signedAttributeHashString)) { System.out.println("!!! Decrypted RSA signature with PKCS1 1.5 padding does not contain signed attributes hash"); if (digestString.equals(signedAttributeHashHashString)) System.out.println("!!! but it contains the hash of the signed attributes hash"); } } System.out.println(); try { if(signerInfo.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))) System.out.println("Signature validates with certificate"); else System.out.println("!!! Signature does not validate with certificate"); } catch(CMSVerifierCertificateNotValidException e) { System.out.println("!!! Certificate not valid at claimed signing time: " + e.getMessage()); } catch(CertificateException e) { System.out.println("!!! Verification failure (Certificate): " + e.getMessage()); } catch(IllegalArgumentException e) { System.out.println("!!! Verification failure (Illegal argument): " + e.getMessage()); } catch(RuntimeOperatorException e) { System.out.println("!!! Verification failure (Runtime Operator): " + e.getMessage()); } catch(CMSException e2) { System.out.println("!!! Verification failure: " + e2.getMessage()); } System.out.println("\nCertificate path from accompanying certificates"); X509CertificateHolder c = cert; JcaContentVerifierProviderBuilder jcaContentVerifierProviderBuilder = new JcaContentVerifierProviderBuilder(); while (c != null) { System.out.printf("- %s ", c.getSubject()); X500Name issuer = c.getIssuer(); Collection cs = certificates.getMatches(new Selector() { @Override public boolean match(Object obj) { return (obj instanceof X509CertificateHolder) && ((X509CertificateHolder)obj).getSubject().equals(issuer); } @Override public Object clone() { return this; } }); if (cs.size() != 1) { System.out.printf("(no unique match - %d)", cs.size()); break; } X509CertificateHolder cc = (X509CertificateHolder) cs.iterator().next(); try { boolean isValid = c.isSignatureValid(jcaContentVerifierProviderBuilder.build(cc)); System.out.print(isValid ? "(valid signature)" : "(invalid signature)"); TBSCertificate tbsCert = c.toASN1Structure().getTBSCertificate(); try ( ByteArrayOutputStream sOut = new ByteArrayOutputStream() ) { DEROutputStream dOut = new DEROutputStream(sOut); dOut.writeObject(tbsCert); byte[] tbsDerBytes = sOut.toByteArray(); boolean isDer = Arrays.equals(tbsDerBytes, tbsCert.getEncoded()); if (!isDer) System.out.print(" (TBSCertificate not DER encoded)"); } if (!isValid) { System.out.println("\nHashes of the TBSCertificate:"); for (Map.Entry<String, MessageDigest> entry : SignatureAnalyzer.digestByName.entrySet()) { String digestName = entry.getKey(); MessageDigest digest = entry.getValue(); digest.reset(); byte[] digestValue = digest.digest(tbsCert.getEncoded()); System.out.printf(" * %s: %s\n", digestName, SignatureAnalyzer.toHex(digestValue)); } analyzeSignatureBytes(c.getSignature(), cc, null); } } catch (CertException | CertificateException e) { System.out.printf("(inappropriate signature - %s)", e.getMessage()); } if (c == cc) { System.out.print(" (self-signed)"); c = null; } else c = cc; System.out.println(); } } System.out.println(); if (certificates != null) { for (Object certObject : certificates.getMatches(selectAny)) { X509CertificateHolder certHolder = (X509CertificateHolder) certObject; try { boolean verify = signerInfo.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder)); System.out.printf("Verify %s with '%s'.\n", verify ? "succeeds" : "fails", certHolder.getSubject()); } catch(Exception ex) { System.out.printf("Verify throws exception with '%s': '%s'.\n", certHolder.getSubject(), ex.getMessage()); } } } System.out.println(); AttributeTable attributeTable = signerInfo.getUnsignedAttributes(); if (attributeTable != null) { attributes = attributeTable.toHashtable(); for (Map.Entry<ASN1ObjectIdentifier, ?> attributeEntry : attributes.entrySet()) { System.out.printf("Unsigned attribute %s", attributeEntry.getKey()); if (attributeEntry.getKey().equals(/*SIGNATURE_TIME_STAMP_OID*/PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)) { System.out.println(" (Signature Time Stamp)"); Attribute attribute = (Attribute) attributeEntry.getValue(); for (ASN1Encodable encodable : attribute.getAttrValues().toArray()) { ContentInfo contentInfo = ContentInfo.getInstance(encodable); TimeStampToken timeStampToken = new TimeStampToken(contentInfo); TimeStampTokenInfo tstInfo = timeStampToken.getTimeStampInfo(); System.out.printf("Authority/SN %s / %s\n", tstInfo.getTsa(), tstInfo.getSerialNumber()); DigestCalculator digCalc = digCalcProvider .get(tstInfo.getHashAlgorithm()); OutputStream dOut = digCalc.getOutputStream(); dOut.write(signerInfo.getSignature()); dOut.close(); byte[] expectedDigest = digCalc.getDigest(); boolean matches = Arrays.equals(expectedDigest, tstInfo.getMessageImprintDigest()); System.out.printf("Digest match? %s\n", matches); System.out.printf("Signer %s / %s\n", timeStampToken.getSID().getIssuer(), timeStampToken.getSID().getSerialNumber()); Store tstCertificates = timeStampToken.getCertificates(); Collection tstCerts = tstCertificates.getMatches(new SignerId(timeStampToken.getSID().getIssuer(), timeStampToken.getSID().getSerialNumber())); System.out.print("Certificate: "); if (tstCerts.size() != 1) { System.out.printf("Could not identify, %s candidates\n", tstCerts.size()); } else { X509CertificateHolder tstCert = (X509CertificateHolder) tstCerts.iterator().next(); System.out.printf("%s\n", tstCert.getSubject()); int version = tstCert.toASN1Structure().getVersionNumber(); System.out.printf("Version: %s\n", version); if (version != 3) System.out.println("Error: Certificate must be version 3 to have an ExtendedKeyUsage extension."); Extension ext = tstCert.getExtension(Extension.extendedKeyUsage); if (ext == null) System.out.println("Error: Certificate must have an ExtendedKeyUsage extension."); else { if (!ext.isCritical()) { System.out.println("Error: Certificate must have an ExtendedKeyUsage extension marked as critical."); } ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(ext.getParsedValue()); if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) { System.out.println("Error: ExtendedKeyUsage not solely time stamping."); } } } } } else System.out.println(); } } } } public static byte[] analyzeSignatureBytes(byte[] signatureBytes, X509CertificateHolder cert, byte[] signedData) throws GeneralSecurityException, IOException { if (RSAUtil.isRsaOid(cert.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm())) { KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(cert.getSubjectPublicKeyInfo().getEncoded())); try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] bytes = cipher.doFinal(signatureBytes); System.out.printf("Decrypted signature bytes: %s\n", toHex(bytes)); try { DigestInfo digestInfo = DigestInfo.getInstance(bytes); String digestString = toHex(digestInfo.getDigest()); System.out.printf("Decrypted signature digest algorithm: %s\n", digestInfo.getAlgorithmId().getAlgorithm()); System.out.printf("Decrypted signature digest: %s\n", digestString); if (signedData != null) { MessageDigest digest = MessageDigest.getInstance(digestInfo.getAlgorithmId().getAlgorithm().toString()); byte[] actualDigest = digest.digest(signedData); if (!Arrays.equals(actualDigest, digestInfo.getDigest())) { String actualDigestString = toHex(actualDigest); System.out.printf("Actual signed data digest: %s\n", actualDigestString); } else { System.out.println("Decrypted signature digest matches signed data digest."); } } return digestInfo.getDigest(); } catch (IllegalArgumentException bpe) { System.out.println("!!! Decrypted, PKCS1 padded RSA signature is not well-formed: " + bpe.getMessage()); } } catch (BadPaddingException bpe) { System.out.println("!!! Decrypted RSA signature is not PKCS1 padded: " + bpe.getMessage()); try { Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding"); cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey); byte[] bytes = cipherNoPadding.doFinal(signatureBytes); System.out.printf("Decrypted signature bytes: %s\n", toHex(bytes)); if (bytes[bytes.length - 1] != (byte) 0xbc) System.out.println("!!! Decrypted RSA signature does not end with the PSS 0xbc byte either"); else { System.out.println("Decrypted RSA signature does end with the PSS 0xbc byte"); } } catch(BadPaddingException bpe2) { System.out.println("!!! Failure decrypted RSA signature: " + bpe2.getMessage()); } } } return null; } public static String toHex(byte[] bytes) { if (bytes == null) return "null"; final char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } final Selector selectAny = new Selector() { @Override public boolean match(Object obj) { return true; } @Override public Object clone() { return this; } }; final static List<String> digestNames = Arrays.asList("SHA-512", "SHA-384", "SHA-256", "SHA-224", "SHA1"); public final static Map<String, MessageDigest> digestByName = new LinkedHashMap<>(); static { for (String name : digestNames) { try { MessageDigest digest = MessageDigest.getInstance(name); digestByName.put(name, digest); } catch (NoSuchAlgorithmException e) { System.err.printf("Unknown digest algorithm '%s'. Skipping.\n", name); } } System.err.println(); } static final ASN1ObjectIdentifier adobe = new ASN1ObjectIdentifier("1.2.840.113583"); static final ASN1ObjectIdentifier acrobat = adobe.branch("1"); static final ASN1ObjectIdentifier security = acrobat.branch("1"); static final ASN1ObjectIdentifier ADBE_REVOCATION_INFO_ARCHIVAL = security.branch("8"); final CMSSignedData signedData; final static ASN1ObjectIdentifier SIGNATURE_TIME_STAMP_OID = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.2.14"); }
Analyze signature bytes even without signed attributes Even in case of primitive signature SignerInfos without signed attributes the analysis of the signature bytes is of interest; thus, they are now analyzed in that case, too. Furthermore, DEROutputStream has been deprecated. Now ASN1OutputStream with ASN1Encoding.DER is used instead.
src/main/java/mkl/testarea/signature/analyze/SignatureAnalyzer.java
Analyze signature bytes even without signed attributes
<ide><path>rc/main/java/mkl/testarea/signature/analyze/SignatureAnalyzer.java <ide> import org.bouncycastle.asn1.ASN1Encoding; <ide> import org.bouncycastle.asn1.ASN1ObjectIdentifier; <ide> import org.bouncycastle.asn1.ASN1OctetString; <add>import org.bouncycastle.asn1.ASN1OutputStream; <ide> import org.bouncycastle.asn1.ASN1Sequence; <ide> import org.bouncycastle.asn1.ASN1Set; <ide> import org.bouncycastle.asn1.ASN1TaggedObject; <del>import org.bouncycastle.asn1.DEROutputStream; <ide> import org.bouncycastle.asn1.DERSet; <ide> import org.bouncycastle.asn1.cms.Attribute; <ide> import org.bouncycastle.asn1.cms.AttributeTable; <ide> <ide> if (signerInfo.getSignedAttributes() == null) { <ide> System.out.println("!!! No signed attributes"); <add> analyzeSignatureBytes(signerInfo.getSignature(), cert, null); <ide> continue; <ide> } <ide> <ide> System.out.print(isValid ? "(valid signature)" : "(invalid signature)"); <ide> TBSCertificate tbsCert = c.toASN1Structure().getTBSCertificate(); <ide> try ( ByteArrayOutputStream sOut = new ByteArrayOutputStream() ) { <del> DEROutputStream dOut = new DEROutputStream(sOut); <add> ASN1OutputStream dOut = ASN1OutputStream.create(sOut, ASN1Encoding.DER); <ide> dOut.writeObject(tbsCert); <ide> byte[] tbsDerBytes = sOut.toByteArray(); <ide> boolean isDer = Arrays.equals(tbsDerBytes, tbsCert.getEncoded());
Java
apache-2.0
b3e4b690d80fa4ad706d7e28f60126cb174eda3a
0
square/sqlbrite,square/sqlbrite,square/sqlbrite,gabrielittner/sqlbrite,gabrielittner/sqlbrite,gabrielittner/sqlbrite
/* * Copyright (C) 2015 Square, 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.squareup.sqlbrite; import android.annotation.TargetApi; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteTransactionListener; import android.support.annotation.CheckResult; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import com.squareup.sqlbrite.SqlBrite.Query; import java.io.Closeable; import java.lang.annotation.Retention; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Func1; import rx.subjects.PublishSubject; import static android.database.sqlite.SQLiteDatabase.CONFLICT_ABORT; import static android.database.sqlite.SQLiteDatabase.CONFLICT_FAIL; import static android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE; import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static android.database.sqlite.SQLiteDatabase.CONFLICT_ROLLBACK; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static java.lang.System.nanoTime; import static java.lang.annotation.RetentionPolicy.SOURCE; import static java.util.concurrent.TimeUnit.NANOSECONDS; /** * A lightweight wrapper around {@link SQLiteOpenHelper} which allows for continuously observing * the result of a query. Create using a {@link SqlBrite} instance. */ public final class BriteDatabase implements Closeable { private final SQLiteOpenHelper helper; private final SqlBrite.Logger logger; // Package-private to avoid synthetic accessor method for 'transaction' instance. final ThreadLocal<SqliteTransaction> transactions = new ThreadLocal<>(); /** Publishes sets of tables which have changed. */ private final PublishSubject<Set<String>> triggers = PublishSubject.create(); private final Transaction transaction = new Transaction() { @Override public void markSuccessful() { if (logging) log("TXN SUCCESS %s", transactions.get()); getWriteableDatabase().setTransactionSuccessful(); } @Override public boolean yieldIfContendedSafely() { return getWriteableDatabase().yieldIfContendedSafely(); } @Override public boolean yieldIfContendedSafely(long sleepAmount, TimeUnit sleepUnit) { return getWriteableDatabase().yieldIfContendedSafely(sleepUnit.toMillis(sleepAmount)); } @Override public void end() { SqliteTransaction transaction = transactions.get(); if (transaction == null) { throw new IllegalStateException("Not in transaction."); } SqliteTransaction newTransaction = transaction.parent; transactions.set(newTransaction); if (logging) log("TXN END %s", transaction); getWriteableDatabase().endTransaction(); // Send the triggers after ending the transaction in the DB. if (transaction.commit) { sendTableTrigger(transaction); } } @Override public void close() { end(); } }; private final Action0 ensureNotInTransaction = new Action0() { @Override public void call() { if (transactions.get() != null) { throw new IllegalStateException("Cannot subscribe to observable query in a transaction."); } } }; // Read and write guarded by 'databaseLock'. Lazily initialized. Use methods to access. private volatile SQLiteDatabase readableDatabase; private volatile SQLiteDatabase writeableDatabase; private final Object databaseLock = new Object(); private final Scheduler scheduler; // Package-private to avoid synthetic accessor method for 'transaction' instance. volatile boolean logging; BriteDatabase(SQLiteOpenHelper helper, SqlBrite.Logger logger, Scheduler scheduler) { this.helper = helper; this.logger = logger; this.scheduler = scheduler; } /** * Control whether debug logging is enabled. */ public void setLoggingEnabled(boolean enabled) { logging = enabled; } SQLiteDatabase getReadableDatabase() { SQLiteDatabase db = readableDatabase; if (db == null) { synchronized (databaseLock) { db = readableDatabase; if (db == null) { if (logging) log("Creating readable database"); db = readableDatabase = helper.getReadableDatabase(); } } } return db; } // Package-private to avoid synthetic accessor method for 'transaction' instance. SQLiteDatabase getWriteableDatabase() { SQLiteDatabase db = writeableDatabase; if (db == null) { synchronized (databaseLock) { db = writeableDatabase; if (db == null) { if (logging) log("Creating writeable database"); db = writeableDatabase = helper.getWritableDatabase(); } } } return db; } void sendTableTrigger(Set<String> tables) { SqliteTransaction transaction = transactions.get(); if (transaction != null) { transaction.addAll(tables); } else { if (logging) log("TRIGGER %s", tables); triggers.onNext(tables); } } /** * Begin a transaction for this thread. * <p> * Transactions may nest. If the transaction is not in progress, then a database connection is * obtained and a new transaction is started. Otherwise, a nested transaction is started. * <p> * Each call to {@code newTransaction} must be matched exactly by a call to * {@link Transaction#end()}. To mark a transaction as successful, call * {@link Transaction#markSuccessful()} before calling {@link Transaction#end()}. If the * transaction is not successful, or if any of its nested transactions were not successful, then * the entire transaction will be rolled back when the outermost transaction is ended. * <p> * Transactions queue up all query notifications until they have been applied. * <p> * Here is the standard idiom for transactions: * * <pre>{@code * try (Transaction transaction = db.newTransaction()) { * ... * transaction.markSuccessful(); * } * }</pre> * * Manually call {@link Transaction#end()} when try-with-resources is not available: * <pre>{@code * Transaction transaction = db.newTransaction(); * try { * ... * transaction.markSuccessful(); * } finally { * transaction.end(); * } * }</pre> * * * @see SQLiteDatabase#beginTransaction() */ @CheckResult @NonNull public Transaction newTransaction() { SqliteTransaction transaction = new SqliteTransaction(transactions.get()); transactions.set(transaction); if (logging) log("TXN BEGIN %s", transaction); getWriteableDatabase().beginTransactionWithListener(transaction); return this.transaction; } /** * Begins a transaction in IMMEDIATE mode for this thread. * <p> * Transactions may nest. If the transaction is not in progress, then a database connection is * obtained and a new transaction is started. Otherwise, a nested transaction is started. * <p> * Each call to {@code newNonExclusiveTransaction} must be matched exactly by a call to * {@link Transaction#end()}. To mark a transaction as successful, call * {@link Transaction#markSuccessful()} before calling {@link Transaction#end()}. If the * transaction is not successful, or if any of its nested transactions were not successful, then * the entire transaction will be rolled back when the outermost transaction is ended. * <p> * Transactions queue up all query notifications until they have been applied. * <p> * Here is the standard idiom for transactions: * * <pre>{@code * try (Transaction transaction = db.newNonExclusiveTransaction()) { * ... * transaction.markSuccessful(); * } * }</pre> * * Manually call {@link Transaction#end()} when try-with-resources is not available: * <pre>{@code * Transaction transaction = db.newNonExclusiveTransaction(); * try { * ... * transaction.markSuccessful(); * } finally { * transaction.end(); * } * }</pre> * * * @see SQLiteDatabase#beginTransactionNonExclusive() */ @TargetApi(HONEYCOMB) @RequiresApi(HONEYCOMB) @CheckResult @NonNull public Transaction newNonExclusiveTransaction() { SqliteTransaction transaction = new SqliteTransaction(transactions.get()); transactions.set(transaction); if (logging) log("TXN BEGIN %s", transaction); getWriteableDatabase().beginTransactionWithListenerNonExclusive(transaction); return this.transaction; } /** * Close the underlying {@link SQLiteOpenHelper} and remove cached readable and writeable * databases. This does not prevent existing observables from retaining existing references as * well as attempting to create new ones for new subscriptions. */ @Override public void close() { synchronized (databaseLock) { readableDatabase = null; writeableDatabase = null; helper.close(); } } /** * Create an observable which will notify subscribers with a {@linkplain Query query} for * execution. Subscribers are responsible for <b>always</b> closing {@link Cursor} instance * returned from the {@link Query}. * <p> * Subscribers will receive an immediate notification for initial data as well as subsequent * notifications for when the supplied {@code table}'s data changes through the {@code insert}, * {@code update}, and {@code delete} methods of this class. Unsubscribe when you no longer want * updates to a query. * <p> * Since database triggers are inherently asynchronous, items emitted from the returned * observable use the {@link Scheduler} supplied to {@link SqlBrite#wrapDatabaseHelper}. For * consistency, the immediate notification sent on subscribe also uses this scheduler. As such, * calling {@link Observable#subscribeOn subscribeOn} on the returned observable has no effect. * <p> * Note: To skip the immediate notification and only receive subsequent notifications when data * has changed call {@code skip(1)} on the returned observable. * <p> * <b>Warning:</b> this method does not perform the query! Only by subscribing to the returned * {@link Observable} will the operation occur. * * @see SQLiteDatabase#rawQuery(String, String[]) */ @CheckResult @NonNull public QueryObservable createQuery(@NonNull final String table, @NonNull String sql, @NonNull String... args) { Func1<Set<String>, Boolean> tableFilter = new Func1<Set<String>, Boolean>() { @Override public Boolean call(Set<String> triggers) { return triggers.contains(table); } @Override public String toString() { return table; } }; return createQuery(tableFilter, sql, args); } /** * See {@link #createQuery(String, String, String...)} for usage. This overload allows for * monitoring multiple tables for changes. * * @see SQLiteDatabase#rawQuery(String, String[]) */ @CheckResult @NonNull public QueryObservable createQuery(@NonNull final Iterable<String> tables, @NonNull String sql, @NonNull String... args) { Func1<Set<String>, Boolean> tableFilter = new Func1<Set<String>, Boolean>() { @Override public Boolean call(Set<String> triggers) { for (String table : tables) { if (triggers.contains(table)) { return true; } } return false; } @Override public String toString() { return tables.toString(); } }; return createQuery(tableFilter, sql, args); } @CheckResult @NonNull private QueryObservable createQuery(Func1<Set<String>, Boolean> tableFilter, String sql, String... args) { if (transactions.get() != null) { throw new IllegalStateException("Cannot create observable query in transaction. " + "Use query() for a query inside a transaction."); } DatabaseQuery query = new DatabaseQuery(tableFilter, sql, args); final Observable<Query> queryObservable = triggers // .filter(tableFilter) // Only trigger on tables we care about. .map(query) // DatabaseQuery maps to itself to save an allocation. .onBackpressureLatest() // Guard against uncontrollable frequency of upstream emissions. .startWith(query) // .observeOn(scheduler) // .onBackpressureLatest() // Guard against uncontrollable frequency of scheduler executions. .doOnSubscribe(ensureNotInTransaction); // TODO switch to .extend when non-@Experimental return new QueryObservable(new Observable.OnSubscribe<Query>() { @Override public void call(Subscriber<? super Query> subscriber) { queryObservable.unsafeSubscribe(subscriber); } }); } /** * Runs the provided SQL and returns a {@link Cursor} over the result set. * * @see SQLiteDatabase#rawQuery(String, String[]) */ @CheckResult // TODO @WorkerThread public Cursor query(@NonNull String sql, @NonNull String... args) { long startNanos = nanoTime(); Cursor cursor = getReadableDatabase().rawQuery(sql, args); long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos); if (logging) { log("QUERY (%sms)\n sql: %s\n args: %s", tookMillis, indentSql(sql), Arrays.toString(args)); } return cursor; } /** * Insert a row into the specified {@code table} and notify any subscribed queries. * * @see SQLiteDatabase#insert(String, String, ContentValues) */ // TODO @WorkerThread public long insert(@NonNull String table, @NonNull ContentValues values) { return insert(table, values, CONFLICT_NONE); } /** * Insert a row into the specified {@code table} and notify any subscribed queries. * * @see SQLiteDatabase#insertWithOnConflict(String, String, ContentValues, int) */ // TODO @WorkerThread public long insert(@NonNull String table, @NonNull ContentValues values, @ConflictAlgorithm int conflictAlgorithm) { SQLiteDatabase db = getWriteableDatabase(); if (logging) { log("INSERT\n table: %s\n values: %s\n conflictAlgorithm: %s", table, values, conflictString(conflictAlgorithm)); } long rowId = db.insertWithOnConflict(table, null, values, conflictAlgorithm); if (logging) log("INSERT id: %s", rowId); if (rowId != -1) { // Only send a table trigger if the insert was successful. sendTableTrigger(Collections.singleton(table)); } return rowId; } /** * Delete rows from the specified {@code table} and notify any subscribed queries. This method * will not trigger a notification if no rows were deleted. * * @see SQLiteDatabase#delete(String, String, String[]) */ // TODO @WorkerThread public int delete(@NonNull String table, @Nullable String whereClause, @Nullable String... whereArgs) { SQLiteDatabase db = getWriteableDatabase(); if (logging) { log("DELETE\n table: %s\n whereClause: %s\n whereArgs: %s", table, whereClause, Arrays.toString(whereArgs)); } int rows = db.delete(table, whereClause, whereArgs); if (logging) log("DELETE affected %s %s", rows, rows != 1 ? "rows" : "row"); if (rows > 0) { // Only send a table trigger if rows were affected. sendTableTrigger(Collections.singleton(table)); } return rows; } /** * Update rows in the specified {@code table} and notify any subscribed queries. This method * will not trigger a notification if no rows were updated. * * @see SQLiteDatabase#update(String, ContentValues, String, String[]) */ // TODO @WorkerThread public int update(@NonNull String table, @NonNull ContentValues values, @Nullable String whereClause, @Nullable String... whereArgs) { return update(table, values, CONFLICT_NONE, whereClause, whereArgs); } /** * Update rows in the specified {@code table} and notify any subscribed queries. This method * will not trigger a notification if no rows were updated. * * @see SQLiteDatabase#updateWithOnConflict(String, ContentValues, String, String[], int) */ // TODO @WorkerThread public int update(@NonNull String table, @NonNull ContentValues values, @ConflictAlgorithm int conflictAlgorithm, @Nullable String whereClause, @Nullable String... whereArgs) { SQLiteDatabase db = getWriteableDatabase(); if (logging) { log("UPDATE\n table: %s\n values: %s\n whereClause: %s\n whereArgs: %s\n conflictAlgorithm: %s", table, values, whereClause, Arrays.toString(whereArgs), conflictString(conflictAlgorithm)); } int rows = db.updateWithOnConflict(table, values, whereClause, whereArgs, conflictAlgorithm); if (logging) log("UPDATE affected %s %s", rows, rows != 1 ? "rows" : "row"); if (rows > 0) { // Only send a table trigger if rows were affected. sendTableTrigger(Collections.singleton(table)); } return rows; } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * No notifications will be sent to queries if {@code sql} affects the data of a table. * * @see SQLiteDatabase#execSQL(String) */ public void execute(String sql) { if (logging) log("EXECUTE\n sql: %s", sql); SQLiteDatabase db = getWriteableDatabase(); db.execSQL(sql); } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * No notifications will be sent to queries if {@code sql} affects the data of a table. * * @see SQLiteDatabase#execSQL(String, Object[]) */ public void execute(String sql, Object... args) { if (logging) log("EXECUTE\n sql: %s\n args: %s", sql, Arrays.toString(args)); SQLiteDatabase db = getWriteableDatabase(); db.execSQL(sql, args); } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * A notification to queries for {@code table} will be sent after the statement is executed. * * @see SQLiteDatabase#execSQL(String) */ public void executeAndTrigger(String table, String sql) { execute(sql); sendTableTrigger(Collections.singleton(table)); } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * A notification to queries for {@code table} will be sent after the statement is executed. * * @see SQLiteDatabase#execSQL(String, Object[]) */ public void executeAndTrigger(String table, String sql, Object... args) { execute(sql, args); sendTableTrigger(Collections.singleton(table)); } /** An in-progress database transaction. */ public interface Transaction extends Closeable { /** * End a transaction. See {@link #newTransaction()} for notes about how to use this and when * transactions are committed and rolled back. * * @see SQLiteDatabase#endTransaction() */ // TODO @WorkerThread void end(); /** * Marks the current transaction as successful. Do not do any more database work between * calling this and calling {@link #end()}. Do as little non-database work as possible in that * situation too. If any errors are encountered between this and {@link #end()} the transaction * will still be committed. * * @see SQLiteDatabase#setTransactionSuccessful() */ // TODO @WorkerThread void markSuccessful(); /** * Temporarily end the transaction to let other threads run. The transaction is assumed to be * successful so far. Do not call {@link #markSuccessful()} before calling this. When this * returns a new transaction will have been created but not marked as successful. This assumes * that there are no nested transactions (newTransaction has only been called once) and will * throw an exception if that is not the case. * * @return true if the transaction was yielded * * @see SQLiteDatabase#yieldIfContendedSafely() */ // TODO @WorkerThread boolean yieldIfContendedSafely(); /** * Temporarily end the transaction to let other threads run. The transaction is assumed to be * successful so far. Do not call {@link #markSuccessful()} before calling this. When this * returns a new transaction will have been created but not marked as successful. This assumes * that there are no nested transactions (newTransaction has only been called once) and will * throw an exception if that is not the case. * * @param sleepAmount if > 0, sleep this long before starting a new transaction if * the lock was actually yielded. This will allow other background threads to make some * more progress than they would if we started the transaction immediately. * @return true if the transaction was yielded * * @see SQLiteDatabase#yieldIfContendedSafely(long) */ // TODO @WorkerThread boolean yieldIfContendedSafely(long sleepAmount, TimeUnit sleepUnit); /** * Equivalent to calling {@link #end()} */ // TODO @WorkerThread @Override void close(); } @IntDef({ CONFLICT_ABORT, CONFLICT_FAIL, CONFLICT_IGNORE, CONFLICT_NONE, CONFLICT_REPLACE, CONFLICT_ROLLBACK }) @Retention(SOURCE) public @interface ConflictAlgorithm { } static String indentSql(String sql) { return sql.replace("\n", "\n "); } void log(String message, Object... args) { if (args.length > 0) message = String.format(message, args); logger.log(message); } private static String conflictString(@ConflictAlgorithm int conflictAlgorithm) { switch (conflictAlgorithm) { case CONFLICT_ABORT: return "abort"; case CONFLICT_FAIL: return "fail"; case CONFLICT_IGNORE: return "ignore"; case CONFLICT_NONE: return "none"; case CONFLICT_REPLACE: return "replace"; case CONFLICT_ROLLBACK: return "rollback"; default: return "unknown (" + conflictAlgorithm + ')'; } } static final class SqliteTransaction extends LinkedHashSet<String> implements SQLiteTransactionListener { final SqliteTransaction parent; boolean commit; SqliteTransaction(SqliteTransaction parent) { this.parent = parent; } @Override public void onBegin() { } @Override public void onCommit() { commit = true; } @Override public void onRollback() { } @Override public String toString() { String name = String.format("%08x", System.identityHashCode(this)); return parent == null ? name : name + " [" + parent.toString() + ']'; } } final class DatabaseQuery extends Query implements Func1<Set<String>, Query> { private final Func1<Set<String>, Boolean> tableFilter; private final String sql; private final String[] args; DatabaseQuery(Func1<Set<String>, Boolean> tableFilter, String sql, String... args) { this.tableFilter = tableFilter; this.sql = sql; this.args = args; } @Override public Cursor run() { if (transactions.get() != null) { throw new IllegalStateException("Cannot execute observable query in a transaction."); } long startNanos = nanoTime(); Cursor cursor = getReadableDatabase().rawQuery(sql, args); if (logging) { long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos); log("QUERY (%sms)\n tables: %s\n sql: %s\n args: %s", tookMillis, tableFilter, indentSql(sql), Arrays.toString(args)); } return cursor; } @Override public String toString() { return sql; } @Override public Query call(Set<String> ignored) { return this; } } }
sqlbrite/src/main/java/com/squareup/sqlbrite/BriteDatabase.java
/* * Copyright (C) 2015 Square, 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.squareup.sqlbrite; import android.annotation.TargetApi; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteTransactionListener; import android.support.annotation.CheckResult; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import com.squareup.sqlbrite.SqlBrite.Query; import java.io.Closeable; import java.lang.annotation.Retention; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Func1; import rx.subjects.PublishSubject; import static android.database.sqlite.SQLiteDatabase.CONFLICT_ABORT; import static android.database.sqlite.SQLiteDatabase.CONFLICT_FAIL; import static android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE; import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static android.database.sqlite.SQLiteDatabase.CONFLICT_ROLLBACK; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static java.lang.System.nanoTime; import static java.lang.annotation.RetentionPolicy.SOURCE; import static java.util.concurrent.TimeUnit.NANOSECONDS; /** * A lightweight wrapper around {@link SQLiteOpenHelper} which allows for continuously observing * the result of a query. Create using a {@link SqlBrite} instance. */ public final class BriteDatabase implements Closeable { private final SQLiteOpenHelper helper; private final SqlBrite.Logger logger; // Package-private to avoid synthetic accessor method for 'transaction' instance. final ThreadLocal<SqliteTransaction> transactions = new ThreadLocal<>(); /** Publishes sets of tables which have changed. */ private final PublishSubject<Set<String>> triggers = PublishSubject.create(); private final Transaction transaction = new Transaction() { @Override public void markSuccessful() { if (logging) log("TXN SUCCESS %s", transactions.get()); getWriteableDatabase().setTransactionSuccessful(); } @Override public boolean yieldIfContendedSafely() { return getWriteableDatabase().yieldIfContendedSafely(); } @Override public boolean yieldIfContendedSafely(long sleepAmount, TimeUnit sleepUnit) { return getWriteableDatabase().yieldIfContendedSafely(sleepUnit.toMillis(sleepAmount)); } @Override public void end() { SqliteTransaction transaction = transactions.get(); if (transaction == null) { throw new IllegalStateException("Not in transaction."); } SqliteTransaction newTransaction = transaction.parent; transactions.set(newTransaction); if (logging) log("TXN END %s", transaction); getWriteableDatabase().endTransaction(); // Send the triggers after ending the transaction in the DB. if (transaction.commit) { sendTableTrigger(transaction); } } @Override public void close() { end(); } }; private final Action0 ensureNotInTransaction = new Action0() { @Override public void call() { if (transactions.get() != null) { throw new IllegalStateException("Cannot subscribe to observable query in a transaction."); } } }; // Read and write guarded by 'databaseLock'. Lazily initialized. Use methods to access. private volatile SQLiteDatabase readableDatabase; private volatile SQLiteDatabase writeableDatabase; private final Object databaseLock = new Object(); private final Scheduler scheduler; // Package-private to avoid synthetic accessor method for 'transaction' instance. volatile boolean logging; BriteDatabase(SQLiteOpenHelper helper, SqlBrite.Logger logger, Scheduler scheduler) { this.helper = helper; this.logger = logger; this.scheduler = scheduler; } /** * Control whether debug logging is enabled. */ public void setLoggingEnabled(boolean enabled) { logging = enabled; } SQLiteDatabase getReadableDatabase() { SQLiteDatabase db = readableDatabase; if (db == null) { synchronized (databaseLock) { db = readableDatabase; if (db == null) { if (logging) log("Creating readable database"); db = readableDatabase = helper.getReadableDatabase(); } } } return db; } // Package-private to avoid synthetic accessor method for 'transaction' instance. SQLiteDatabase getWriteableDatabase() { SQLiteDatabase db = writeableDatabase; if (db == null) { synchronized (databaseLock) { db = writeableDatabase; if (db == null) { if (logging) log("Creating writeable database"); db = writeableDatabase = helper.getWritableDatabase(); } } } return db; } void sendTableTrigger(Set<String> tables) { SqliteTransaction transaction = transactions.get(); if (transaction != null) { transaction.addAll(tables); } else { if (logging) log("TRIGGER %s", tables); triggers.onNext(tables); } } /** * Begin a transaction for this thread. * <p> * Transactions may nest. If the transaction is not in progress, then a database connection is * obtained and a new transaction is started. Otherwise, a nested transaction is started. * <p> * Each call to {@code newTransaction} must be matched exactly by a call to * {@link Transaction#end()}. To mark a transaction as successful, call * {@link Transaction#markSuccessful()} before calling {@link Transaction#end()}. If the * transaction is not successful, or if any of its nested transactions were not successful, then * the entire transaction will be rolled back when the outermost transaction is ended. * <p> * Transactions queue up all query notifications until they have been applied. * <p> * Here is the standard idiom for transactions: * * <pre>{@code * try (Transaction transaction = db.newTransaction()) { * ... * transaction.markSuccessful(); * } * }</pre> * * Manually call {@link Transaction#end()} when try-with-resources is not available: * <pre>{@code * Transaction transaction = db.newTransaction(); * try { * ... * transaction.markSuccessful(); * } finally { * transaction.end(); * } * }</pre> * * * @see SQLiteDatabase#beginTransaction() */ @CheckResult @NonNull public Transaction newTransaction() { SqliteTransaction transaction = new SqliteTransaction(transactions.get()); transactions.set(transaction); if (logging) log("TXN BEGIN %s", transaction); getWriteableDatabase().beginTransactionWithListener(transaction); return this.transaction; } /** * Begins a transaction in IMMEDIATE mode for this thread. * <p> * Transactions may nest. If the transaction is not in progress, then a database connection is * obtained and a new transaction is started. Otherwise, a nested transaction is started. * <p> * Each call to {@code newNonExclusiveTransaction} must be matched exactly by a call to * {@link Transaction#end()}. To mark a transaction as successful, call * {@link Transaction#markSuccessful()} before calling {@link Transaction#end()}. If the * transaction is not successful, or if any of its nested transactions were not successful, then * the entire transaction will be rolled back when the outermost transaction is ended. * <p> * Transactions queue up all query notifications until they have been applied. * <p> * Here is the standard idiom for transactions: * * <pre>{@code * try (Transaction transaction = db.newNonExclusiveTransaction()) { * ... * transaction.markSuccessful(); * } * }</pre> * * Manually call {@link Transaction#end()} when try-with-resources is not available: * <pre>{@code * Transaction transaction = db.newNonExclusiveTransaction(); * try { * ... * transaction.markSuccessful(); * } finally { * transaction.end(); * } * }</pre> * * * @see SQLiteDatabase#beginTransactionNonExclusive() */ @TargetApi(HONEYCOMB) @RequiresApi(HONEYCOMB) @CheckResult @NonNull public Transaction newNonExclusiveTransaction() { SqliteTransaction transaction = new SqliteTransaction(transactions.get()); transactions.set(transaction); if (logging) log("TXN BEGIN %s", transaction); getWriteableDatabase().beginTransactionWithListenerNonExclusive(transaction); return this.transaction; } /** * Close the underlying {@link SQLiteOpenHelper} and remove cached readable and writeable * databases. This does not prevent existing observables from retaining existing references as * well as attempting to create new ones for new subscriptions. */ @Override public void close() { synchronized (databaseLock) { readableDatabase = null; writeableDatabase = null; helper.close(); } } /** * Create an observable which will notify subscribers with a {@linkplain Query query} for * execution. Subscribers are responsible for <b>always</b> closing {@link Cursor} instance * returned from the {@link Query}. * <p> * Subscribers will receive an immediate notification for initial data as well as subsequent * notifications for when the supplied {@code table}'s data changes through the {@code insert}, * {@code update}, and {@code delete} methods of this class. Unsubscribe when you no longer want * updates to a query. * <p> * Since database triggers are inherently asynchronous, items emitted from the returned * observable use the {@link Scheduler} supplied to {@link SqlBrite#wrapDatabaseHelper}. For * consistency, the immediate notification sent on subscribe also uses this scheduler. As such, * calling {@link Observable#subscribeOn subscribeOn} on the returned observable has no effect. * <p> * Note: To skip the immediate notification and only receive subsequent notifications when data * has changed call {@code skip(1)} on the returned observable. * <p> * <b>Warning:</b> this method does not perform the query! Only by subscribing to the returned * {@link Observable} will the operation occur. * * @see SQLiteDatabase#rawQuery(String, String[]) */ @CheckResult @NonNull public QueryObservable createQuery(@NonNull final String table, @NonNull String sql, @NonNull String... args) { Func1<Set<String>, Boolean> tableFilter = new Func1<Set<String>, Boolean>() { @Override public Boolean call(Set<String> triggers) { return triggers.contains(table); } @Override public String toString() { return table; } }; return createQuery(tableFilter, sql, args); } /** * See {@link #createQuery(String, String, String...)} for usage. This overload allows for * monitoring multiple tables for changes. * * @see SQLiteDatabase#rawQuery(String, String[]) */ @CheckResult @NonNull public QueryObservable createQuery(@NonNull final Iterable<String> tables, @NonNull String sql, @NonNull String... args) { Func1<Set<String>, Boolean> tableFilter = new Func1<Set<String>, Boolean>() { @Override public Boolean call(Set<String> triggers) { for (String table : tables) { if (triggers.contains(table)) { return true; } } return false; } @Override public String toString() { return tables.toString(); } }; return createQuery(tableFilter, sql, args); } @CheckResult @NonNull private QueryObservable createQuery(Func1<Set<String>, Boolean> tableFilter, String sql, String... args) { if (transactions.get() != null) { throw new IllegalStateException("Cannot create observable query in transaction. " + "Use query() for a query inside a transaction."); } DatabaseQuery query = new DatabaseQuery(tableFilter, sql, args); final Observable<Query> queryObservable = triggers // .filter(tableFilter) // Only trigger on tables we care about. .map(query) // DatabaseQuery maps to itself to save an allocation. .onBackpressureLatest() // Guard against uncontrollable frequency of upstream emissions. .startWith(query) // .observeOn(scheduler) // .onBackpressureLatest() // Guard against uncontrollable frequency of scheduler executions. .doOnSubscribe(ensureNotInTransaction); // TODO switch to .extend when non-@Experimental return new QueryObservable(new Observable.OnSubscribe<Query>() { @Override public void call(Subscriber<? super Query> subscriber) { queryObservable.unsafeSubscribe(subscriber); } }); } /** * Runs the provided SQL and returns a {@link Cursor} over the result set. * * @see SQLiteDatabase#rawQuery(String, String[]) */ @CheckResult // TODO @WorkerThread public Cursor query(@NonNull String sql, @NonNull String... args) { long startNanos = nanoTime(); Cursor cursor = getReadableDatabase().rawQuery(sql, args); long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos); if (logging) { log("QUERY (%sms)\n sql: %s\n args: %s", tookMillis, indentSql(sql), Arrays.toString(args)); } return cursor; } /** * Insert a row into the specified {@code table} and notify any subscribed queries. * * @see SQLiteDatabase#insert(String, String, ContentValues) */ // TODO @WorkerThread public long insert(@NonNull String table, @NonNull ContentValues values) { return insert(table, values, CONFLICT_NONE); } /** * Insert a row into the specified {@code table} and notify any subscribed queries. * * @see SQLiteDatabase#insertWithOnConflict(String, String, ContentValues, int) */ // TODO @WorkerThread public long insert(@NonNull String table, @NonNull ContentValues values, @ConflictAlgorithm int conflictAlgorithm) { SQLiteDatabase db = getWriteableDatabase(); if (logging) { log("INSERT\n table: %s\n values: %s\n conflictAlgorithm: %s", table, values, conflictString(conflictAlgorithm)); } long rowId = db.insertWithOnConflict(table, null, values, conflictAlgorithm); if (logging) log("INSERT id: %s", rowId); if (rowId != -1) { // Only send a table trigger if the insert was successful. sendTableTrigger(Collections.singleton(table)); } return rowId; } /** * Delete rows from the specified {@code table} and notify any subscribed queries. This method * will not trigger a notification if no rows were deleted. * * @see SQLiteDatabase#delete(String, String, String[]) */ // TODO @WorkerThread public int delete(@NonNull String table, @Nullable String whereClause, @Nullable String... whereArgs) { SQLiteDatabase db = getWriteableDatabase(); if (logging) { log("DELETE\n table: %s\n whereClause: %s\n whereArgs: %s", table, whereClause, Arrays.toString(whereArgs)); } int rows = db.delete(table, whereClause, whereArgs); if (logging) log("DELETE affected %s %s", rows, rows != 1 ? "rows" : "row"); if (rows > 0) { // Only send a table trigger if rows were affected. sendTableTrigger(Collections.singleton(table)); } return rows; } /** * Update rows in the specified {@code table} and notify any subscribed queries. This method * will not trigger a notification if no rows were updated. * * @see SQLiteDatabase#update(String, ContentValues, String, String[]) */ // TODO @WorkerThread public int update(@NonNull String table, @NonNull ContentValues values, @Nullable String whereClause, @Nullable String... whereArgs) { return update(table, values, CONFLICT_NONE, whereClause, whereArgs); } /** * Update rows in the specified {@code table} and notify any subscribed queries. This method * will not trigger a notification if no rows were updated. * * @see SQLiteDatabase#updateWithOnConflict(String, ContentValues, String, String[], int) */ // TODO @WorkerThread public int update(@NonNull String table, @NonNull ContentValues values, @ConflictAlgorithm int conflictAlgorithm, @Nullable String whereClause, @Nullable String... whereArgs) { SQLiteDatabase db = getWriteableDatabase(); if (logging) { log("UPDATE\n table: %s\n values: %s\n whereClause: %s\n whereArgs: %s\n conflictAlgorithm: %s", table, values, whereClause, Arrays.toString(whereArgs), conflictString(conflictAlgorithm)); } int rows = db.updateWithOnConflict(table, values, whereClause, whereArgs, conflictAlgorithm); if (logging) log("UPDATE affected %s %s", rows, rows != 1 ? "rows" : "row"); if (rows > 0) { // Only send a table trigger if rows were affected. sendTableTrigger(Collections.singleton(table)); } return rows; } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * No notifications will be sent to queries if {@code sql} affects the data of a table. * * @see SQLiteDatabase#execSQL(String) */ public void execute(String sql) { if (logging) log("EXECUTE\n sql: %s", sql); SQLiteDatabase db = getWriteableDatabase(); db.execSQL(sql); } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * No notifications will be sent to queries if {@code sql} affects the data of a table. * * @see SQLiteDatabase#execSQL(String, Object[]) */ public void execute(String sql, Object... args) { if (logging) log("EXECUTE\n sql: %s\n args: %s", sql, Arrays.toString(args)); SQLiteDatabase db = getWriteableDatabase(); db.execSQL(sql, args); } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * A notification to queries for {@code table} will be sent after the statement is executed. * * @see SQLiteDatabase#execSQL(String) */ public void executeAndTrigger(String table, String sql) { execute(sql); sendTableTrigger(Collections.singleton(table)); } /** * Execute {@code sql} provided it is NOT a {@code SELECT} or any other SQL statement that * returns data. No data can be returned (such as the number of affected rows). Instead, use * {@link #insert}, {@link #update}, et al, when possible. * <p> * A notification to queries for {@code table} will be sent after the statement is executed. * * @see SQLiteDatabase#execSQL(String, Object[]) */ public void executeAndTrigger(String table, String sql, Object... args) { execute(sql, args); sendTableTrigger(Collections.singleton(table)); } /** An in-progress database transaction. */ public interface Transaction extends Closeable { /** * End a transaction. See {@link #newTransaction()} for notes about how to use this and when * transactions are committed and rolled back. * * @see SQLiteDatabase#endTransaction() */ // TODO @WorkerThread void end(); /** * Marks the current transaction as successful. Do not do any more database work between * calling this and calling {@link #end()}. Do as little non-database work as possible in that * situation too. If any errors are encountered between this and {@link #end()} the transaction * will still be committed. * * @see SQLiteDatabase#setTransactionSuccessful() */ // TODO @WorkerThread void markSuccessful(); /** * Temporarily end the transaction to let other threads run. The transaction is assumed to be * successful so far. Do not call {@link #markSuccessful()} before calling this. When this * returns a new transaction will have been created but not marked as successful. This assumes * that there are no nested transactions (newTransaction has only been called once) and will * throw an exception if that is not the case. * * @return true if the transaction was yielded * * @see SQLiteDatabase#yieldIfContendedSafely() */ // TODO @WorkerThread boolean yieldIfContendedSafely(); /** * Temporarily end the transaction to let other threads run. The transaction is assumed to be * successful so far. Do not call {@link #markSuccessful()} before calling this. When this * returns a new transaction will have been created but not marked as successful. This assumes * that there are no nested transactions (newTransaction has only been called once) and will * throw an exception if that is not the case. * * @param sleepAmount if > 0, sleep this long before starting a new transaction if * the lock was actually yielded. This will allow other background threads to make some * more progress than they would if we started the transaction immediately. * @return true if the transaction was yielded * * @see SQLiteDatabase#yieldIfContendedSafely(long) */ // TODO @WorkerThread boolean yieldIfContendedSafely(long sleepAmount, TimeUnit sleepUnit); /** * Equivalent to calling {@link #end()} */ // TODO @WorkerThread @Override void close(); } @IntDef({ CONFLICT_ABORT, CONFLICT_FAIL, CONFLICT_IGNORE, CONFLICT_NONE, CONFLICT_REPLACE, CONFLICT_ROLLBACK }) @Retention(SOURCE) public @interface ConflictAlgorithm { } private static String indentSql(String sql) { return sql.replace("\n", "\n "); } void log(String message, Object... args) { if (args.length > 0) message = String.format(message, args); logger.log(message); } private static String conflictString(@ConflictAlgorithm int conflictAlgorithm) { switch (conflictAlgorithm) { case CONFLICT_ABORT: return "abort"; case CONFLICT_FAIL: return "fail"; case CONFLICT_IGNORE: return "ignore"; case CONFLICT_NONE: return "none"; case CONFLICT_REPLACE: return "replace"; case CONFLICT_ROLLBACK: return "rollback"; default: return "unknown (" + conflictAlgorithm + ')'; } } static final class SqliteTransaction extends LinkedHashSet<String> implements SQLiteTransactionListener { final SqliteTransaction parent; boolean commit; SqliteTransaction(SqliteTransaction parent) { this.parent = parent; } @Override public void onBegin() { } @Override public void onCommit() { commit = true; } @Override public void onRollback() { } @Override public String toString() { String name = String.format("%08x", System.identityHashCode(this)); return parent == null ? name : name + " [" + parent.toString() + ']'; } } final class DatabaseQuery extends Query implements Func1<Set<String>, Query> { private final Func1<Set<String>, Boolean> tableFilter; private final String sql; private final String[] args; DatabaseQuery(Func1<Set<String>, Boolean> tableFilter, String sql, String... args) { this.tableFilter = tableFilter; this.sql = sql; this.args = args; } @Override public Cursor run() { if (transactions.get() != null) { throw new IllegalStateException("Cannot execute observable query in a transaction."); } long startNanos = nanoTime(); Cursor cursor = getReadableDatabase().rawQuery(sql, args); if (logging) { long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos); log("QUERY (%sms)\n tables: %s\n sql: %s\n args: %s", tookMillis, tableFilter, indentSql(sql), Arrays.toString(args)); } return cursor; } @Override public String toString() { return sql; } @Override public Query call(Set<String> ignored) { return this; } } }
Remove creation of synthetic accessor method.
sqlbrite/src/main/java/com/squareup/sqlbrite/BriteDatabase.java
Remove creation of synthetic accessor method.
<ide><path>qlbrite/src/main/java/com/squareup/sqlbrite/BriteDatabase.java <ide> public @interface ConflictAlgorithm { <ide> } <ide> <del> private static String indentSql(String sql) { <add> static String indentSql(String sql) { <ide> return sql.replace("\n", "\n "); <ide> } <ide>
Java
apache-2.0
c96c8f97a8828ec344cfa5ae43e8df24e8f4f76a
0
pyamsoft/power-manager,pyamsoft/power-manager
/* * Copyright 2016 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.app.manager.backend; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import com.birbit.android.jobqueue.TagConstraint; import com.pyamsoft.powermanager.PowerManager; import com.pyamsoft.powermanager.app.base.SchedulerPresenter; import com.pyamsoft.powermanager.dagger.manager.backend.DozeJob; import com.pyamsoft.powermanager.dagger.manager.backend.ManagerDozeInteractor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.subscriptions.Subscriptions; import timber.log.Timber; public class ManagerDoze extends SchedulerPresenter<ManagerDoze.DozeView> implements Manager { //@NonNull public static final String GRANT_PERMISSION_COMMAND = // "adb -d shell pm grant com.pyamsoft.powermanager android.permission.DUMP"; @NonNull public static final String DUMPSYS_DOZE_START = "deviceidle force-idle deep"; @NonNull public static final String DUMPSYS_DOZE_END = "deviceidle step"; @NonNull public static final String DUMPSYS_SENSOR_ENABLE = "sensorservice enable"; @NonNull public static final String DUMPSYS_SENSOR_RESTRICT = "sensorservice restrict com.pyamsoft.powermanager"; @NonNull private static final String DUMPSYS_COMMAND = "dumpsys"; @NonNull private final ManagerDozeInteractor interactor; @NonNull private Subscription subscription = Subscriptions.empty(); @Inject public ManagerDoze(@NonNull ManagerDozeInteractor interactor, @NonNull @Named("io") Scheduler ioScheduler, @NonNull @Named("main") Scheduler mainScheduler) { super(mainScheduler, ioScheduler); this.interactor = interactor; } @CheckResult public static boolean isDozeAvailable() { return Build.VERSION.SDK_INT == Build.VERSION_CODES.M; } @CheckResult public static boolean checkDumpsysPermission(@NonNull Context context) { return context.getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.DUMP) == PackageManager.PERMISSION_GRANTED; } @SuppressLint("NewApi") public static void executeDumpsys(@NonNull Context context, @NonNull String cmd) { if (!(checkDumpsysPermission(context) && isDozeAvailable())) { Timber.e("Does not have permission to call dumpsys"); return; } final Process process; boolean caughtPermissionDenial = false; try { final String command = "dumpsys " + cmd; process = Runtime.getRuntime().exec(command); try (final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream()))) { Timber.d("Read results of exec: '%s'", command); String line = bufferedReader.readLine(); while (line != null && !line.isEmpty()) { if (line.startsWith("Permission Denial")) { Timber.e("Command resulted in permission denial"); caughtPermissionDenial = true; break; } Timber.d("%s", line); line = bufferedReader.readLine(); } } if (caughtPermissionDenial) { throw new IllegalStateException("Error running command: " + command); } // Will always be 0 } catch (IOException e) { Timber.e(e, "Error running shell command"); } } @Override public void enable() { unsubSubscription(); subscription = interactor.isDozeEnabled().map(aBoolean -> { Timber.d("Cancel old doze jobs"); PowerManager.getInstance().getJobManager().cancelJobs(TagConstraint.ANY, DozeJob.DOZE_TAG); return aBoolean; }).filter(aBoolean -> { Timber.d("filter Doze not enabled"); return aBoolean; }).flatMap(aBoolean -> { if (!isDozeAvailable()) { Timber.e("Doze is not available on this platform"); return Observable.empty(); } return Observable.just(0L); }).subscribeOn(getSubscribeScheduler()).observeOn(getObserveScheduler()).subscribe(delay -> { PowerManager.getInstance().getJobManager().addJobInBackground(new DozeJob.EnableJob()); }, throwable -> { Timber.e(throwable, "onError"); }, this::unsubSubscription); } private void unsubSubscription() { if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); } } @Override public void disable(boolean charging) { unsubSubscription(); subscription = interactor.isDozeEnabled().map(aBoolean -> { Timber.d("Cancel old doze jobs"); PowerManager.getInstance().getJobManager().cancelJobs(TagConstraint.ANY, DozeJob.DOZE_TAG); return aBoolean; }).filter(aBoolean -> { Timber.d("filter Doze not enabled"); return aBoolean; }).flatMap(aBoolean -> interactor.isIgnoreCharging()).filter(ignore -> { Timber.d("Filter out if ignore doze and device is charging"); return !(ignore && charging); }).flatMap(aBoolean -> { if (!isDozeAvailable()) { Timber.e("Doze is not available on this platform"); return Observable.empty(); } return interactor.getDozeDelay(); }).subscribeOn(getSubscribeScheduler()).observeOn(getObserveScheduler()).subscribe(delay -> { PowerManager.getInstance().getJobManager().addJobInBackground(new DozeJob.DisableJob(delay)); }, throwable -> { Timber.e(throwable, "onError"); }, this::unsubSubscription); } @Override public void cleanup() { unsubSubscription(); } public interface DozeView { void onDumpSysPermissionSuccess(); void onDumpSysPermissionError(); } }
src/main/java/com/pyamsoft/powermanager/app/manager/backend/ManagerDoze.java
/* * Copyright 2016 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.app.manager.backend; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import com.birbit.android.jobqueue.TagConstraint; import com.pyamsoft.powermanager.PowerManager; import com.pyamsoft.powermanager.app.base.SchedulerPresenter; import com.pyamsoft.powermanager.dagger.manager.backend.DozeJob; import com.pyamsoft.powermanager.dagger.manager.backend.ManagerDozeInteractor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.inject.Inject; import javax.inject.Named; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.subscriptions.Subscriptions; import timber.log.Timber; public class ManagerDoze extends SchedulerPresenter<ManagerDoze.DozeView> implements Manager { //@NonNull public static final String GRANT_PERMISSION_COMMAND = // "adb -d shell pm grant com.pyamsoft.powermanager android.permission.DUMP"; @NonNull public static final String DUMPSYS_DOZE_START = "deviceidle force-idle deep"; @NonNull public static final String DUMPSYS_DOZE_END = "deviceidle step"; @NonNull public static final String DUMPSYS_SENSOR_ENABLE = "sensorservice enable"; @NonNull public static final String DUMPSYS_SENSOR_RESTRICT = "sensorservice restrict com.pyamsoft.powermanager"; @NonNull private static final String DUMPSYS_COMMAND = "dumpsys"; @NonNull private final ManagerDozeInteractor interactor; @NonNull private Subscription subscription = Subscriptions.empty(); @Inject public ManagerDoze(@NonNull ManagerDozeInteractor interactor, @NonNull @Named("io") Scheduler ioScheduler, @NonNull @Named("main") Scheduler mainScheduler) { super(mainScheduler, ioScheduler); this.interactor = interactor; } @CheckResult public static boolean isDozeAvailable() { return Build.VERSION.SDK_INT == Build.VERSION_CODES.M; } @CheckResult public static boolean checkDumpsysPermission(@NonNull Context context) { return context.getApplicationContext().checkCallingOrSelfPermission(Manifest.permission.DUMP) == PackageManager.PERMISSION_GRANTED; } @SuppressLint("NewApi") public static void executeDumpsys(@NonNull Context context, @NonNull String command) { if (!(checkDumpsysPermission(context) && isDozeAvailable())) { Timber.e("Does not have permission to call dumpsys"); return; } final Process process; boolean caughtPermissionDenial = false; try { process = Runtime.getRuntime().exec("dumpsys " + command); try (final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream()))) { Timber.d("Read results of exec: '%s'", command); String line = bufferedReader.readLine(); while (line != null && !line.isEmpty()) { if (line.startsWith("Permission Denial")) { Timber.e("Command resulted in permission denial"); caughtPermissionDenial = true; break; } Timber.d("%s", line); line = bufferedReader.readLine(); } } if (caughtPermissionDenial) { throw new IllegalStateException("Error running command: " + command); } // Will always be 0 } catch (IOException e) { Timber.e(e, "Error running shell command"); } } @Override public void enable() { unsubSubscription(); subscription = interactor.isDozeEnabled().map(aBoolean -> { Timber.d("Cancel old doze jobs"); PowerManager.getInstance().getJobManager().cancelJobs(TagConstraint.ANY, DozeJob.DOZE_TAG); return aBoolean; }).filter(aBoolean -> { Timber.d("filter Doze not enabled"); return aBoolean; }).flatMap(aBoolean -> { if (!isDozeAvailable()) { Timber.e("Doze is not available on this platform"); return Observable.empty(); } return Observable.just(0L); }).subscribeOn(getSubscribeScheduler()).observeOn(getObserveScheduler()).subscribe(delay -> { PowerManager.getInstance().getJobManager().addJobInBackground(new DozeJob.EnableJob()); }, throwable -> { Timber.e(throwable, "onError"); }, this::unsubSubscription); } private void unsubSubscription() { if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); } } @Override public void disable(boolean charging) { unsubSubscription(); subscription = interactor.isDozeEnabled().map(aBoolean -> { Timber.d("Cancel old doze jobs"); PowerManager.getInstance().getJobManager().cancelJobs(TagConstraint.ANY, DozeJob.DOZE_TAG); return aBoolean; }).filter(aBoolean -> { Timber.d("filter Doze not enabled"); return aBoolean; }).flatMap(aBoolean -> interactor.isIgnoreCharging()).filter(ignore -> { Timber.d("Filter out if ignore doze and device is charging"); return !(ignore && charging); }).flatMap(aBoolean -> { if (!isDozeAvailable()) { Timber.e("Doze is not available on this platform"); return Observable.empty(); } return interactor.getDozeDelay(); }).subscribeOn(getSubscribeScheduler()).observeOn(getObserveScheduler()).subscribe(delay -> { PowerManager.getInstance().getJobManager().addJobInBackground(new DozeJob.DisableJob(delay)); }, throwable -> { Timber.e(throwable, "onError"); }, this::unsubSubscription); } @Override public void cleanup() { unsubSubscription(); } public interface DozeView { void onDumpSysPermissionSuccess(); void onDumpSysPermissionError(); } }
Log full command
src/main/java/com/pyamsoft/powermanager/app/manager/backend/ManagerDoze.java
Log full command
<ide><path>rc/main/java/com/pyamsoft/powermanager/app/manager/backend/ManagerDoze.java <ide> } <ide> <ide> @SuppressLint("NewApi") <del> public static void executeDumpsys(@NonNull Context context, @NonNull String command) { <add> public static void executeDumpsys(@NonNull Context context, @NonNull String cmd) { <ide> if (!(checkDumpsysPermission(context) && isDozeAvailable())) { <ide> Timber.e("Does not have permission to call dumpsys"); <ide> return; <ide> final Process process; <ide> boolean caughtPermissionDenial = false; <ide> try { <del> process = Runtime.getRuntime().exec("dumpsys " + command); <add> final String command = "dumpsys " + cmd; <add> process = Runtime.getRuntime().exec(command); <ide> try (final BufferedReader bufferedReader = new BufferedReader( <ide> new InputStreamReader(process.getInputStream()))) { <ide> Timber.d("Read results of exec: '%s'", command);
Java
apache-2.0
2defc41268237ee7be58167064fbb8e7bee593c3
0
AmeBel/relex,opencog/relex,leungmanhin/relex,williampma/relex,opencog/relex,linas/relex,virneo/relex,williampma/relex,rodsol/relex,virneo/relex,ainishdave/relex,ainishdave/relex,ainishdave/relex,AmeBel/relex,linas/relex,williampma/relex,linas/relex,williampma/relex,opencog/relex,rodsol/relex,ainishdave/relex,virneo/relex,leungmanhin/relex,leungmanhin/relex,virneo/relex,rodsol/relex,rodsol/relex,AmeBel/relex
/* * Copyright 2009 Linas Vepstas * * 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 relex.test; import java.util.ArrayList; import java.util.Collections; import relex.ParsedSentence; import relex.RelationExtractor; import relex.Sentence; import relex.output.SimpleView; public class TestRelEx { private static RelationExtractor re; private int pass; private int fail; private int subpass; private int subfail; private static ArrayList<String> sentfail= new ArrayList<String>(); // @BeforeClass public static void setUpClass() { re = new RelationExtractor(); } public TestRelEx() { pass = 0; fail = 0; subpass = 0; subfail = 0; } public ArrayList<String> split(String a) { String[] sa = a.split("\n"); ArrayList<String> saa = new ArrayList<String>(); for (String s : sa) { saa.add(s); } Collections.sort (saa); return saa; } /** * First argument is the sentence. * Second argument is a list of the relations that RelEx * should be generating. * Return true if RelEx generates the same dependencies * as the second argument. */ public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); // Add number of binary relations from parser-output, // to total number of relationships gotten int sizeOfGotRelations = brgot.size(); // Check expected binary and unary relations. // The below for-loop checks whether all expected binary relations are // contained in the parser-binary-relation-output arrayList "brgot". // If any unary relations are expected in the output, it checks the // parser-unary-relation-output arrayList "urgot" for unary // relationships. for (int i=0; i< exp.size(); i++) { if (!brgot.contains(exp.get(i))) { if (!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } // add the unary relation, count to total number of // binary relations sizeOfGotRelations++; } } // The size checking of the expected relationships vs output // relationships is done here purposefully, to accommodate if // there is any unary relationships present in the expected // output(see above for-loop also). However it only checks // whether parser-output resulted more relationships(binary+unary) // than expected relations. If the parser-output resulted in // fewer relationships(binary+unary) than expected it would // catch that in the above for-loop. if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; } public void report(boolean rc, String subsys) { if (rc) { System.err.println(subsys + ": Tested " + subpass + " sentences, test passed OK"); } else { int total = subpass + subfail; System.err.println(subsys + ": Test failed; out of " + total + " sentences tested,\n\t" + subfail + " sentences failed\n\t" + subpass + " sentences passed"); } subpass = 0; subfail = 0; } public boolean test_determiners() { boolean rc = true; rc &= test_sentence ("Ben ate my cookie.", "_subj(eat, Ben)\n" + "_obj(eat, cookie)\n" + "_poss(cookie, me)\n"); rc &= test_sentence ("Ben ate that cookie.", "_subj(eat, Ben)\n" + "_obj(eat, cookie)\n" + "_det(cookie, that)\n"); rc &= test_sentence ("All my writings are bad.", "_quantity(writings, all)\n" + "_poss(writings, me)\n" + "_predadj(writings, bad)\n"); rc &= test_sentence ("All his designs are bad.", "_quantity(design, all)\n" + "_poss(design, him)\n" + "_predadj(design, bad)\n"); rc &= test_sentence ("All the boys knew it.", "_subj(know, boy)\n" + "_obj(know, it)\n" + "_quantity(boy, all)\n"); rc &= test_sentence ("Joan thanked Susan for all the help she had given.", "_advmod(thank, for)\n" + "_pobj(for, help)\n" + "_subj(thank, Joan)\n" + "_obj(thank, Susan)\n" + "_quantity(help, all)\n" + "_subj(give, she)\n" + "_relmod(help, she)\n" + "_obj(give, help)\n"); report(rc, "Determiners"); return rc; } public boolean test_time() { boolean rc = true; rc &= test_sentence("I had breakfast at 8 am.", "_advmod(have, at)\n" + "_pobj(at, am)\n" + "_obj(have, breakfast)\n"+ "_subj(have, I)\n" + "_time(am, 8)\n"); rc &= test_sentence("I had supper before 6 pm.", "_advmod(have, before)\n" + "_pobj(before, pm)\n" + "_obj(have, supper)\n" + "_subj(have, I)\n" + "_time(pm, 6)\n"); report(rc, "Time"); return rc; } public boolean test_comparatives() { boolean rc = true; rc &= test_sentence ("Some people like pigs less than dogs.", "_compdeg(like, less)\n" + "_obj(like, pig)\n" + "_subj(like, people)\n" + "_compobj(than, dog)\n" + "_compprep(less, than)\n" + "than(pig, dog)\n" + "_comparative(like, pig)\n" + "comp_arg(like, dog)\n" + "_quantity(people, some)\n"); rc &= test_sentence ("Some people like pigs more than dogs.", "_compdeg(like, more)\n" + "_obj(like, pig)\n" + "_subj(like, people)\n" + "than(pig, dog)\n" + "_comparative(like, pig)\n" + "comp_arg(like, dog)\n" + "_compprep(more, than)\n" + "_compobj(than, dog)\n" + "_quantity(people, some)\n"); // Non-equi-gradable : Two entities one feature "more/less" rc &= test_sentence ("He is more intelligent than John.", "_compdeg(intelligent, more)\n" + "_comparative(intelligent, he)\n" + "comp_arg(intelligent, John)\n" + "_compobj(than, John)\n" + "than(he, John)\n" + "_predadj(he, intelligent)\n"); rc &= test_sentence ("He is less intelligent than John.", "_compdeg(intelligent, less)\n" + "_comparative(intelligent, he)\n" + "than(he, John)\n" + "comp_arg(intelligent, John)\n" + "_compobj(than, John)\n" + "_predadj(he, intelligent)\n"); rc &= test_sentence ("He runs more quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_compdeg(quickly, more)\n" + "_comparative(run, quickly)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs less quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_compdeg(quickly, less)\n" + "_comparative(run, quickly)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs more quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(do, quickly)\n" + "_subj(do, John)\n" + "_compdeg(quickly, more)\n" + "_compprep(more, than)\n" + "_comparative(run, quickly)\n" + "_compobj(than, do)\n" + "_comp(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs less quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(do, quickly)\n" + "_subj(do, John)\n" + "_compdeg(quickly, less)\n" + "_compprep(less, than)\n" + "_compobj(than, do)\n" + "than(he, John)\n" + "_comp(than, do)\n" + "_comparative(run, quickly)\n"); rc &= test_sentence ("He runs slower than John does.", "_advmod(run, slow)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_comp(than, do)\n" + "_compobj(than, John)\n" + "than(he, John)\n" + "_comparative(run, slow)\n" + "_compdeg(slow, more)\n"); rc &= test_sentence ("He runs more than John.", "_compdeg(run, more)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs less than John.", "_compdeg(run, less)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "_comparative(run, less)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs faster than John.", "than(he, John)\n" + "_comparative(run, fast)\n" + "_subj(run, he)\n" + "_advmod(run, fast)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(faster, than)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("He runs more slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "_compdeg(slowly, more)\n" + "_comparative(run, slowly)\n" + "_advmod(run, slowly)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs less slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "_comparative(run, slowly)\n" + "_advmod(run, slowly)\n" + "_compdeg(slowly, less)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs more miles than John does.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, more)\n" + "_compamt(mile, more)\n" + "_comparative(run, mile)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs fewer miles than John does.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, fewer)\n" + "_compamt(mile, fewer)\n" + "_comparative(run, mile)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs many more miles than John does.", "than(he, John)\n" + "_comparative(run, mile)\n" + "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(more, many)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "_compamt(mile, more)\n"); rc &= test_sentence ("He runs ten more miles than John.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "comp_arg(run, John)\n" + "_comparative(run, mile)\n" + "_quantity(more, ten)\n" + "_compobj(than, John)\n" + "_compamt(mile, more)\n"); rc &= test_sentence ("He runs almost ten more miles than John does.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(more, ten)\n" + "_comparative(run, mile)\n" + "_quantity_mod(ten, almost)\n" + "_compamt(mile, more)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs more often than John.", "_subj(run, he)\n" + "comp_arg(run, John)\n" + "_compdeg(often, more)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs less often than John.", "_subj(run, he)\n" + "comp_arg(run, John)\n" + "_compdeg(often, less)\n" + "_advmod(run, often)\n" + "_advmod(run, here)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "_comparative(run, often)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs here more often than John.", "_advmod(run, here)\n" + "_compdeg(often, more)\n" + "_advmod(run, often)\n" + "_subj(run, he)\n" + "comp_arg(run, John)\n" + "_comparative(run, often)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs here less often than John.", "_advmod(run, here)\n" + "_advmod(often, less)\n" + "_advmod(run, often)\n" + "_subj(run, he)\n" + "_comparative(run, often)\n" + "than(he, John)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "_compdeg(often, less)\n"); rc &= test_sentence ("He is faster than John.", "than(he, John)\n" + "_predadj(he, fast)\n" + "comp_arg(fast, John)\n" + "_comparative(fast, he)\n" + "_compobj(than, John)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("He is faster than John is.", "than(he, John)\n" + "_predadj(he, fast)\n" + "_subj(be, John)\n" + "_comparative(fast, he)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("His speed is faster than John's.", "than(He, John)\n" + "_predadj(speed, fast)\n" + "_poss(speed, he)\n" + "_comparative(fast, speed)\n" + "_compobj(than, John's)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("I run more than Ben.", "_subj(run, I)\n" + "_comp_arg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compprep(more, than)\n" + "than(I, Ben)\n" + "_compdeg(run, more)\n"); rc &= test_sentence ("I run less than Ben.", "_subj(run, I)\n" + "_comp_arg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compprep(less, than)\n" + "than(I, Ben)\n" + "_compdeg(run, less)\n"); rc &= test_sentence ("I run more miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "_quantity(mile, more)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n" + "_comparg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, more)\n"); rc &= test_sentence ("I run fewer miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "_quantity(mile, fewer)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n" + "_comparg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, fewer)\n"); rc &= test_sentence ("I run 10 more miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "comp_arg(run, Ben)\n" + "_quantity(more, 10)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, more)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run 10 fewer miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "comp_arg(run, Ben)\n" + "_quantity(fewer, 10)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, fewer)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run more often than Ben.", "_subj(run, I)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "comp_arg(run, Ben)\n" + "_subj(run, I)\n" + "_compobj(than, Ben)\n" + "_compdeg(often, more)\n" + "_compprep(more, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run less often than Ben.", "_subj(run, I)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "comp_arg(run, Ben)\n" + "_subj(run, I)\n" + "_compobj(than, Ben)\n" + "_compdeg(often, less)\n" + "_compprep(less, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run more often than Ben does.", "_subj(run, I)\n" + "_subj(do, Ben)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "_advmod(do, often)\n" + "_compdeg(often, more)\n" + "_compprep(more, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run less often than Ben does.", "_subj(run, I)\n" + "_subj(do, Ben)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "_advmod(do, often)\n" + "_compdeg(often, less)\n" + "_compprep(less, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run more often than Ben climbs.", "_subj(run, I)\n" + "_subj(climb, Ben)\n" + "_comparative(run, often)\n" + "than(I, Ben)\n" + "than1(run, climb)\n" + "_comp(than, climb)\n" + "_compdeg(often, more)\n" + "_compprep(more, than)\n" + "_advmod(run, often)\n"); rc &= test_sentence ("I run less often than Ben climbs.", "_subj(run, I)\n" + "_subj(climb, Ben)\n" + "_comparative(run, often)\n" + "than(I, Ben)\n" + "than1(run, climb)\n" + "_comp(than, climb)\n" + "_compdeg(often, less)\n" + "_compprep(less, than)\n" + "_advmod(run, often)\n"); rc &= test_sentence ("I run more races than Ben wins contests.", "_subj(run, I)\n" + "_obj(run, race)\n" + "_subj(win, Ben)\n" + "_obj(win, contest)\n" + "_quantity(race, more)\n" + "_comparative(run, race)\n" + "_comp(than, Ben)\n" + "than(I, Ben)\n" + "_compamt(race, more)\n"); rc &= test_sentence ("I run fewer races than Ben wins contests.", "_subj(run, I)\n" + "_obj(run, race)\n" + "_subj(win, Ben)\n" + "_obj(win, contest)\n" + "_comp(than, Ben)\n" + "_comparative(run, race)\n" + "than(I, Ben)\n" + "_compamt(race, fewer)\n"); rc &= test_sentence ("I have more chairs than Ben.", "_obj(have, chair)\n" + "_subj(have, I)\n" + "than(I, Ben)\n" + "_comparative(have, chair)\n" + "comp_arg(have, Ben)\n" + "_compobj(than, Ben)\n" + "_compamt(chair, more)\n"); rc &= test_sentence ("I have fewer chairs than Ben.", "_obj(have, chair)\n" + "_subj(have, I)\n" + "than(I, Ben)\n" + "_comparative(have, chair)\n" + "_compamt(chair, fewer)\n" + "_compobj(than, Ben)\n"); rc &= test_sentence ("He earns much more money than I do.", "_obj(earn, money)\n" + "_subj(do, I)\n" + "_subj(earn, he)\n" + "than(he, I)\n" + "_comparative(earn, money)\n" + "_compamt(money, more)\n" + "_compdeg(more, much)\n" + "_compobj(than, do)\n" + "_comp(than, do)\n"); rc &= test_sentence ("He earns much less money than I do.", "_obj(earn, money)\n" + "_subj(do, I)\n" + "_subj(earn, he)\n" + "than(he, I)\n" + "_comparative(earn, money)\n" + "_compamt(money, less)\n" + "_compdeg(less, much)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "degree(less, comparative)\n"); rc &= test_sentence ("She comes here more often than her husband.", "_advmod(come, here)\n" + "_compdeg(often, more)\n" + "_advmod(come, often)\n" + "_compprep(more, than)\n" + "_subj(come, she)\n" + "_poss(husband, her)\n" + "_comparative(come, often)\n" + "comp_arg(come, husband)\n" + "_compobj(than, husband)\n" + "than(she, husband)\n"); rc &= test_sentence ("She comes here less often than her husband.", "_advmod(come, here)\n" + "_compdeg(often, less)\n" + "_advmod(come, often)\n" + "_compprep(less, than)\n" + "_subj(come, she)\n" + "_poss(husband, her)\n" + "_comparative(come, often)\n" + "comp_arg(come, husband)\n" + "_compobj(than, husband)\n" + "than(she, husband)\n"); rc &= test_sentence ("Russian grammar is more difficult than English grammar.", "_compdeg(difficult, more)\n" + "_comparative(difficult, grammar)\n" + "_amod(grammar, Russian)\n" + "than(grammar, grammar)\n" + "_predadj(grammar, difficult)\n" + "_compobj(than, grammar)\n" + "_amod(grammar, English)\n"); rc &= test_sentence ("Russian grammar is less difficult than English grammar.", "_compdeg(difficult, less)\n" + "_comparative(difficult, grammar)\n" + "_amod(grammar, Russian)\n" + "than(grammar, grammar)\n" + "_predadj(grammar, difficult)\n" + "_compobj(than, grammar)\n" + "_amod(grammar, English)\n"); rc &= test_sentence ("My sister is much more intelligent than me.", "_compdeg(more, much)\n" + "_predadj(sister, intelligent)\n" + "_poss(sister, me)\n" + "than(sister, me)\n" + "_comparative(intelligent, sister)\n" + "comp_arg(intelligent, me)\n" + "_compobj(than, me)\n" + "_compdeg(intelligent, more)\n"); rc &= test_sentence ("My sister is much less intelligent than me.", "_compdeg(less, much)\n" + "_predadj(sister, intelligent)\n" + "_poss(sister, me)\n" + "than(sister, me)\n" + "_comparative(intelligent, sister)\n" + "comp_arg(intelligent, me)\n" + "_compobj(than, me)\n" + "_compdeg(intelligent, less)\n"); rc &= test_sentence ("I find maths lessons more enjoyable than science lessons.", "_iobj(find, maths)\n" + "_obj(find, lesson)\n" + "_subj(find, I)\n" + "_amod(lesson, enjoyable)\n" + "_nn(lesson, science)\n" + "than(maths, science)\n" + "_comparative(enjoyable, maths)\n" + "_advmod(enjoyable, more)\n" + "degree(enjoyable, comparative)\n"); rc &= test_sentence ("I find maths lessons less enjoyable than science lessons.", "_iobj(find, maths)\n" + "_obj(find, lesson)\n" + "_subj(find, I)\n" + "_amod(lesson, enjoyable)\n" + "_nn(lesson, science)\n" + "than(maths, science)\n" + "_comparative(enjoyable, maths)\n" + "_advmod(enjoyable, less)\n" + "degree(enjoyable, comparative)\n"); // Comparatives Without More/less terms rc &= test_sentence ("Her great-grandson is nicer than her great-granddaughter.", "than(great-grandson, great-granddaughter)\n" + "_predadj(great-grandson, nice)\n" + "_poss(great-grandson, her)\n" + "_poss(great-granddaughter, her)\n" + "_comparative(nice, great-grandson)\n" + "degree(nice, comparative)\n"); rc &= test_sentence ("George is cleverer than Norman.", "than(George, Norman)\n" + "_predadj(George, clever)\n" + "_comparative(clever, George)\n" + "degree(clever, comparative)\n"); rc &= test_sentence ("Kim is taller than Linda.", "than(Kim, Linda)\n" + "_predadj(Kim, tall)\n" + "_comparative(tall, Kim)\n" + "degree(tall, comparative)\n"); rc &= test_sentence ("Venus is brighter than Mars.", "than(Venus, Mars)\n" + "_predadj(Venus, bright)\n" + "_comparative(bright, Venus)\n" + "degree(bright, comparative)\n"); rc &= test_sentence ("Mary is shorter than Jane.", "than(Mary, Jane)\n" + "_predadj(Mary, short)\n" + "_comparative(short, Mary)\n" + "degree(short, comparative)\n"); rc &= test_sentence ("I am happier than you.", "than(I, you)\n" + "_predadj(I, happy)\n" + "_comparative(happy, I)\n" + "degree(happy, comparative)"); rc &= test_sentence ("His house is bigger than hers.", "than(house, hers)\n" + "_predadj(house, big)\n" + "_poss(house, him)\n" + "_comparative(big ,house)\n" + "degree(big, comparative)"); rc &= test_sentence ("She is two years older than me.", "_obj(is, year)\n" + "_amod(years, old)\n" + "_quantity(year, two)\n" + "numeric-FLAG(two, T)\n" + "than(she, me)\n" + "_comparative(old, she)\n" + "degree(old, comparative)"); rc &= test_sentence ("New York is much bigger than Boston.", "_subj(is, New_York)\n" + "_amod(much, big)\n" + "than(New_York, Boston)\n" + "_comparative(big, New_York)\n" + "degree(big, comparative)"); rc &= test_sentence ("He is a better player than Ronaldo.", "_obj(be, player)\n" + "_subj(be, he)\n" + "_amod(player, good)\n" + "than(he, Ronaldo)\n" + "_comparative(good, he)\n" + "degree(good, comparative)"); rc &= test_sentence ("France is a bigger country than Britain.", "_obj(is, country)\n" + "_subj(is, France)\n" + "_amod(country, big)\n" + "than(France, Britain)\n" + "_comparative(big, France)\n" + "degree(big, comparative)\n"); rc &= test_sentence ("That joke was funnier than his joke.", "_predadj(joke, funny)\n" + "than(joke, joke)\n" + "_det(joke, that)\n" + "_poss(joke, him)\n" + "_comparative(funny, joke)\n" + "degree(funny, comparative)"); rc &= test_sentence ("Our car is bigger than your car.", "than(car, car)\n" + "_predadj(car, big)\n" + "_poss(car, us)\n" + "_det(car, you)\n" + "_poss(car, you)\n" + "_comparative(big, car)\n" + "degree(big, comparative)"); // Sentences need to check rc &= test_sentence ("This computer is better than that one.", "than(computer, one)\n" + "_det(computer, this)\n" + "_predadj(computer, good)\n" + "_det(one, that)\n" + "degree(good, comparative)\n" + "_comparative(good, computer)\n"); rc &= test_sentence ("He's simpler than I thought.", "than(he, I)\n" + "_subj(think, I)\n" + "_comparative(simple, he)\n" + "_predadj(he, simple)\n" + "degree(simple, comparative)\n"); rc &= test_sentence ("She's stronger at chess than I am.", "at(strong, chess)\n" + "than(she, I)\n" + "_predadj(she, strong)\n" + "degree(strong, comparative)\n" + "_comparative(strong, she)\n"); rc &= test_sentence ("She's prettier than her mother.", "_predadj(she, pretty)\n" + "than(she, mother)\n" + "_poss(mother, her)\n" + "_comparative(pretty, she)\n" + "degree(pretty, comparative)\n"); rc &= test_sentence ("This exam was more difficult than the other.", "than(exam, other)\n" + "_det(exam, this)\n" + "_predadj(exam, difficult)\n" + "_advmod(difficult, more)\n" + "_comparative(difficult, exam)\n" + "degree(difficult, comparative)\n"); rc &= test_sentence ("It's much colder today than it was yesterday.", "_subj(be, it)\n" + "than(today, yesterday)\n" + "_advmod(cold, today)\n" + "_advmod(cold, yesterday)\n" + "_predadj(it, cold)\n" + "_comparative(cold, it)\n" + "degree(cold, comparative)\n"); rc &= test_sentence ("This grammar topic is easier than most others.", "than(topic, others)\n" + "_det(topic, this)\n" + "_nn(topic, grammar)\n" + "_predadj(topic, easy)\n" + "_quantity(others, most)\n" + "_comparative(easy, topic)\n" + "degree(easy, comparative)\n"); rc &= test_sentence ("I find science more difficult than mathematics.", "_obj(find, science)\n" + "_subj(find, I)\n" + "_advmod(difficult, more)\n" + "than(science, mathematics)\n" + "_comparative(difficult, science)\n" + "degree(difficult, comparative)\n"); //one entity two or more features rc &= test_sentence ("He is more intelligent than attractive.", "than(intelligent, attractive)\n" + "_predadj(he, intelligent)\n" + "_advmod(intelligent, more)\n" + "_comparative(intelligent, he)\n" + "degree(intelligent, comparative)\n"); rc &= test_sentence ("He is less intelligent than attractive.", "than(intelligent, attractive)\n" + "_predadj(he, intelligent)\n" + "_advmod(intelligent, less)\n" + "_comparative(intelligent, he)\n" + "degree(intelligent, comparative)\n"); rc &= test_sentence ("The dog was more hungry than angry.", "_predadj(dog, hungry)\n" + "than(hungry, angry)\n" + "_advmod(hungry, more)\n" + "_comparative(hungry, dog)\n" + "degree(hungry, comparative)\n"); rc &= test_sentence ("The dog was less hungry than angry.", "_predadj(dog, hungry)\n" + "than(hungry, angry)\n" + "_advmod(hungry, less)\n" + "_comparative(hungry, dog)\n" + "degree(hungry, comparative)\n"); rc &= test_sentence ("He did it more quickly than carefully.", "_obj(do, it)\n" + "_subj(do, he)\n" + "than(quickly, carefully)\n" + "_advmod(do, quickly)\n" + "_advmod(quickly, more)\n" + "_comparative(quickly, do)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He did it less quickly than carefully.", "_obj(do, it)\n" + "_subj(do, he)\n" + "than(quickly, carefully)\n" + "_advmod(do, quickly)\n" + "_advmod(quickly, less)\n" + "_comparative(quickly, do)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He has more money than time.", "_obj(have, money)\n" + "_subj(have, he)\n" + "than(money, time)\n" + "_quantity(money, more)\n" + "_comparative(money, have)\n" + "degree(more, comparative)\n"); rc &= test_sentence ("He has less money than time.", "_obj(have, money)\n" + "_subj(have, he)\n" + "than(money, time)\n" + "_quantity(money, less)\n" + "_comparative(money, have)\n" + "degree(less, comparative)\n"); rc &= test_sentence ("He plays more for money than for pleasure.", "_subj(play, he)\n" + "_obj(play, more)\n" + "for(play, money)\n" + "for(than, pleasure)\n" + "than(money, pleasure)\n" + "_comparative(more, play)\n" + "degree(more, comparative)\n"); rc &= test_sentence ("He plays less for money than for pleasure.", "_subj(play, he)\n" + "_obj(play, less)\n" + "for(play, money)\n" + "for(than, pleasure)\n" + "than(money, pleasure)\n" + "_comparative(less, play)\n" + "degree(less, comparative)\n"); //two entities two features rc &= test_sentence ("Jack is more ingenious than Ben is crazy.", "_predadj(Jack, ingenious)\n" + "_predadj(Ben, crazy)\n" + "_advmod(ingenious, more)\n" + "_comparative(ingenious, Jack)\n" + "than(Jack, Ben)\n" + "than1(ingenious, crazy)\n" + "degree(ingenious, comparative)\n"); rc &= test_sentence ("Jack is less ingenious than Ben is crazy.", "_predadj(Jack, ingenious)\n" + "_predadj(Ben, crazy)\n" + "_advmod(ingenious, less)\n" + "_comparative(ingenious, Jack)\n" + "than(Jack, Ben)\n" + "than1(ingenious, crazy)\n" + "degree(ingenious, comparative)\n"); //two entities two features Without More/less rc &= test_sentence ("I slept longer than he worked", "_subj(sleep, I)\n" + "_subj(work, he)\n" + "_advmod(sleep, long)\n" + "than(I, he)\n" + "than1(sleep, work)\n" + "_comparative(long, sleep)\n" + "degree(long, comparative)\n"); report(rc, "Comparatives"); return rc; } public boolean test_equatives() { boolean rc = true; //Equative:two entities one feature rc &= test_sentence ("Amen's hair is as long as Ben's.", "_poss(hair, Amen)\n" + "_predadj(hair, long)\n" + "as(long, Ben)\n" + "than(Amen, Ben)\n"); rc &= test_sentence ("Amenโ€™s hair is same as Benโ€™s.", "_poss(hair, Amen)\n" + "_predadj(hair, same)\n" + "as(same, Ben)\n" + "than(Amen, Ben)\n"); rc &= test_sentence ("Jackโ€™s hair color is similar to that of Benโ€™s.", "_poss(color, Jack)\n" + "_nn(color, hair)\n" + "_predadj(color, similar)\n" + "of(that, Ben)\n" + "to(similar, that)\n" + "than(Jack, Ben)\n"); rc &= test_sentence ("Jackโ€™s hair color is similar to Ben's", "_poss(color, Jack)\n" + "_nn(color, hair)\n" + "_predadj(color, similar)\n" + "to(similar, Ben)\n" + "than(Jack, Ben)\n"); rc &= test_sentence ("Jack is as intelligent as Ben.", "_predadj(Jack, intelligent)\n" + "_compdeg(intelligent, as)\n" + "_pobj(as, Ben)\n" + "_predadj(Ben, intelligent)\n" + "than(Jack, Ben)\n"); rc &= test_sentence ("The bookโ€™s color is same as that of the pen.", "_poss(color, book)\n" + "_predadj(color, same)\n" + "_compdeg(same, as)\n" + "_pobj(as, color)\n" + "_amod(color, of)\n" + "_pobj(of, pen)\n"); rc &= test_sentence ("The snail is running exactly as fast as the cheetah.", "_subj(run, snail)\n" + "_comp_arg(run, cheetah)\n" + "_advmod(run, fast)\n" + "_compdeg(fast, as)\n" + "_pobj(as, cheetah)\n" + "_advmod(as, exactly)\n" + "than(snail, cheetah)\n"); //one entity one feature, through time rc &= test_sentence ("The coffee tastes the same as it did last year.", "_subj(taste, coffee)\n" + "_advmod(taste, the_same)\n" + "_advmod(taste, as)\n" + "_advmod(do, year)\n" + "_subj(do, it)\n" + "_comp(as, do)\n" + "_amod(year, last)\n"); rc &= test_sentence ("The coffee tastes as it did last year.", "_subj(taste, coffee)\n" + "_advmod(do, year)\n" + "_subj(do, it)\n" + "_advmod(taste, as)\n" + "_comp(as, do)\n" + "_amod(year, last)\n"); rc &= test_sentence ("Mike runs as fast as he did last year.", "_subj(do, he)\n" + "_subj(run, Mike)\n" + "_compdeg(fast, as)\n" + "_comp(as, do)\n" + "_advmod(run, fast)\n" + "_advmod(do, year)\n" + "_advmod(do, fast)\n" + "_amod(year, last)\n" + "_advmod(as, run)\n" + "than(Mike, he)\n"); rc &= test_sentence ("The kick was as soft as the first.", "_predadj(kick, soft)\n" + "_pobj(as, first)\n" + "_compdeg(soft, as)\n"); rc &= test_sentence ("He is as smart as I ever expected him to be.", "_predadj(he, smart)\n" + "_subj(expect, I)\n" + "_to-do(expect, be)\n" + "_comp(as, expect)\n" + "_advmod(expect, ever)\n" + "_subj(be, him)\n" + "_compdeg(smart, as)\n"); report(rc, "Equatives"); return rc; } public boolean test_conjunctions() { boolean rc = true; // conjoined verbs rc &= test_sentence ("Scientists make observations and ask questions.", "_obj(make, observation)\n" + "_obj(ask, question)\n" + "_subj(make, scientist)\n" + "_subj(ask, scientist)\n" + "conj_and(make, ask)\n"); // conjoined nouns rc &= test_sentence ("She is a student and an employee.", "_obj(be, student)\n" + "_obj(be, employee)\n" + "_subj(be, she)\n" + "conj_and(student, employee)\n"); // conjoined adjectives rc &= test_sentence ("I hailed a black and white taxi.", "_obj(hail, taxi)\n" + "_subj(hail, I)\n" + "_amod(taxi, black)\n" + "_amod(taxi, white)\n" + "conj_and(black, white)\n"); // conjoined adverbs rc &= test_sentence ("She ran quickly and quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "conj_and(quickly, quietly)\n"); // conjoined verbs same object rc &= test_sentence ("He steals and eats the orange.", "_obj(steal, orange)\n" + "_obj(eat, orange)\n" + "_subj(steal, he)\n" + "_subj(eat, he)\n" + "conj_and(steal, eat)\n"); // adjectival modifiers on conjoined subject rc &= test_sentence ("The big truck and the little car collided.", "_amod(car, little)\n" + "_amod(truck, big)\n" + "_subj(collide, truck)\n" + "_subj(collide, car)\n" + "conj_and(truck, car)\n"); // verbs with modifiers rc &= test_sentence ("We ate dinner at home and went to the movies.", "_obj(eat, dinner)\n" + "conj_and(eat, go)\n" + "_advmod(eat, at)\n" + "_pobj(at, home)\n" + "_subj(eat, we)\n" + "_advmod(go, to)\n" + "_pobj(to, movie)\n" + "_subj(go, we)\n"); // verb with more modifiers rc &= test_sentence ("We ate a late dinner at home and went out to the movies afterwards.", "_obj(eat, dinner)\n" + "conj_and(eat, go_out)\n" + "_advmod(eat, at)\n" + "_advmod(go_out, to)\n" + "_pobj(at, home)\n" + "_subj(eat, we)\n" + "_pobj(to, movie)\n" + "_advmod(go_out, afterwards)\n" + "_subj(go_out, we)\n" + "_amod(dinner, late)\n"); // conjoined ditransitive verbs rc &= test_sentence ("She baked him a cake and sang him a song.", "_iobj(sing, him)\n" + "_obj(sing, song)\n" + "_subj(sing, she)\n" + "_iobj(bake, him)\n" + "_obj(bake, cake)\n" + "conj_and(bake, sing)\n" + "_subj(bake, she)\n"); // conjoined adverbs with modifiers rc &= test_sentence ("she ran very quickly and extremely quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "_advmod(quietly, extremely)\n" + "conj_and(quickly, quietly)\n" + "_advmod(quickly, very)\n"); // conjoined adverbs with out modifiers rc &= test_sentence ("She handled it quickly and gracefully.", "_obj(handle, it)\n" + "_advmod(handle, quickly)\n" + "_advmod(handle, gracefully)\n" + "_subj(handle, she)\n" + "conj_and(quickly, gracefully)\n"); // modifiers on conjoined adjectives rc &= test_sentence ("He had very long and very white hair.", "_obj(have, hair)\n" + "_subj(have, he)\n" + "_amod(hair, long)\n" + "_amod(hair, white)\n" + "_advmod(white, very)\n" + "conj_and(long, white)\n" + "_advmod(long, very)\n"); // adjectival modifiers on conjoined object rc &= test_sentence ("The collision was between the little car and the big truck.", "_pobj(between, car)\n" + "_pobj(between, truck)\n" + "_pobj(between, and)\n" + "_psubj(between, collision)\n" + "_amod(truck, big)\n" + "_amod(car, little)\n" + "conj_prep(between, and)\n" + "conj_and(car, truck)\n"); // Names Modifiers and conjunction rc &= test_sentence ("Big Tom and Angry Sue went to the movies.", "_pobj(to, movie)\n" + "_advmod(go, to)\n" + "_subj(go, Big_Tom)\n" + "_subj(go, Angry_Sue)\n" + "conj_and(Big_Tom, Angry_Sue)\n"); //Correlative conjunction rc &= test_sentence ("I could use neither the lorry nor the van.", "_modal(could, use)\n" + "conj_neither_nor(lorry, van)\n" + "_obj(use, lorry)\n" + "_obj(use, van)\n" + "_subj(use, I)\n"); report(rc, "Conjunction"); return rc; } public boolean test_extraposition() { boolean rc = true; rc &= test_sentence ("The woman who lives next door is a registered nurse.", "_obj(be, nurse)\n" + "_subj(be, woman)\n" + "_amod(nurse, registered)\n" + "_advmod(live, next_door)\n" + "_subj(live, woman)\n" + "_rel(who, live)\n" + "_relmod(woman, who)\n"); rc &= test_sentence ("A player who is injured has to leave the field.", "_to-do(have, leave)\n" + "_subj(have, player)\n" + "_obj(leave, field)\n" + "_rel(who, injured)\n" + "_predadj(player, injured)\n" + "_relmod(player, who)\n"); rc &= test_sentence ("Pizza, which most people love, is not very healthy.", "_advmod(very, not)\n" + "_advmod(healthy, very)\n" + "_obj(love, Pizza)\n" + "_quantity(people, most)\n" + "which(Pizza, love)\n" + "_subj(love, people)\n" + "_predadj(Pizza, healthy)\n" ); rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.", "_advmod(famous, very)\n" + "_advmod(belong, to)\n" + "_subj(belong, restaurant)\n" + "_poss(aunt, me)\n" + "_pobj(to, aunt)\n" + "_rel(which, belong)\n" + "_predadj(restaurant, famous)\n" + "_relmod(restaurant, which)\n"); rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.", "_obj(write, book)\n" + "_advmod(write, by)\n" + "_obj(read, book)\n" + "_advmod(read, in)\n" + "_subj(read, I)\n" + "_pobj(in, library)\n" + "_rel(which, read)\n" + "_relmod(book, which)\n" + "_pobj(by, Charles_Dickens)\n"); rc &= test_sentence("This is the book whose author I met in a library.", "_obj(be, book)\n" + "_subj(be, this)\n" + "_obj(meet, author)\n" + "_advmod(meet, in)\n" + "_subj(meet, I)\n" + "_pobj(in, library)\n" + "_pobj(whose, author)\n" + "_det(book, whose)\n"); rc &= test_sentence("The book that Jack lent me is very boring.", "_advmod(boring, very)\n" + "_obj(lend, book)\n" + "_iobj(lend, me)\n" + "_subj(lend, Jack)\n" + "_relmod(book, that)\n" + "_rel(that, lend)\n" + "_predadj(book, boring)\n"); rc &= test_sentence("They ate a special curry which was recommended by the restaurantโ€™s owner.", "_obj(eat, curry)\n" + "_subj(eat, they)\n" + "_obj(recommend, curry)\n" + "_advmod(recommend, by)\n" + "_pobj(by, owner)\n" + "_poss(owner, restaurant)\n" + "_rel(which, recommend)\n" + "_amod(curry, special)\n" + "_relmod(curry, which)\n"); rc &= test_sentence("The dog who Jack said chased me was black.", "_obj(chase, me)\n" + "_subj(chase, dog)\n" + "_rep(say, chase)\n" + "_rel(who, chase)\n" + "_subj(say, Jack)\n" + "_predadj(dog, black)\n" + "_relmod(dog, who)\n"); rc &= test_sentence("Jack, who hosted the party, is my cousin.", "_obj(be, cousin)\n" + "_subj(be, Jack)\n" + "_poss(cousin, me)\n" + "_obj(host, party)\n" + "_subj(host, Jack)\n" + "who(Jack, host)\n"); rc &= test_sentence("Jack, whose name is in that book, is the student near the window.", "near(be, window)\n" + "_obj(be, student)\n" + "_subj(be, Jack)\n" + "_pobj(in, book)\n" + "_psubj(in, name)\n" + "_det(book, that)\n" + "whose(Jack, name)\n"); rc &= test_sentence("Jack stopped the police car that was driving fast.", "_obj(stop, car)\n" + "_subj(stop, Jack)\n" + "_advmod(drive, fast)\n" + "_subj(drive, car)\n" + "_relmod(car, that)\n" + "_rel(that, drive)\n" + "_nn(car, police)\n"); rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.", "_obj(stop, car)\n" + "_pobj(by, sign)\n" + "_advmod(before, just)\n" + "_advmod(stand, on)\n" + "_pobj(on, street)\n" + "_advmod(stop, by)\n" + "_subj(stand, sign)\n" + "_relmod(sign, that)\n" + "_rel(that, stand)\n" + "_nn(sign, traffic)\n" + "_advmod(stop, just)\n" + "_pobj(before, crossroads)\n"); report(rc, "Extrapostion"); return rc; } public boolean test_interrogatives() { boolean rc = true; rc &= test_sentence ("What is Socrates?", "_obj(be, Socrates)\n" + "_subj(be, _$qVar)\n"); rc &= test_sentence ("Who is the teacher?", "_obj(be, teacher)\n" + "_subj(be, _$qVar)\n"); rc &= test_sentence ("Who is a man?", "_obj(be, man)\n" + "_subj(be, _$qVar)\n"); rc &= test_sentence ("Who told you that bullshit?", "_iobj(tell, you)\n" + "_obj(tell, bullshit)\n" + "_subj(tell, _$qVar)\n" + "_det(bullshit, that)\n"); rc &= test_sentence ("Who told that story to the police?", "_advmod(tell, to)\n" + "_pobj(to, police)\n" + "_obj(tell, story)\n" + "_subj(tell, _$qVar)\n" + "_det(story, that)\n"); rc &= test_sentence ("What gives you that idea?", "_iobj(give, you)\n" + "_obj(give, idea)\n" + "_subj(give, _$qVar)\n" + "_det(idea, that)\n"); rc &= test_sentence ("What did you tell the fuzz?", "_iobj(tell, fuzz)\n" + "_obj(tell, _$qVar)\n" + "_subj(tell, you)\n"); rc &= test_sentence ("What did you give to Mary?", "_advmod(give, to)\n" + "_pobj(to, Mary)\n" + "_obj(give, _$qVar)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Whom did you feed to the lions?", "_advmod(feed, to)\n" + "_obj(feed, _$qVar)\n" + "_subj(feed, you)\n" + "_pobj(to, lion)\n"); rc &= test_sentence ("To whom did you sell the children?", "_pobj(to, _$qVar)\n" + "_obj(sell, child)\n" + "_advmod(sell, to)\n" + "_subj(sell, you)\n"); rc &= test_sentence ("To what do we owe the pleasure?", "_pobj(to, _$qVar)\n" + "_obj(owe, pleasure)\n" + "_advmod(owe, to)\n" + "_subj(owe, we)\n"); rc &= test_sentence ("Who did you sell the children to?", "_advmod(sell, to)\n" + "_pobj(to, _$qVar)\n" + "_obj(sell, child)\n" + "_subj(sell, you)\n"); rc &= test_sentence ("What bothers you?", "_obj(bother, you)\n" + "_subj(bother, _$qVar)\n"); rc &= test_sentence ("Who programmed you?", "_obj(program, you)\n" + "_subj(program, _$qVar)\n"); rc &= test_sentence ("What is on the table?", "_pobj(on, table)\n" + "_psubj(on, _$qVar)\n"); rc &= test_sentence ("What did you say?", "_obj(say, _$qVar)\n" + "_subj(say, you)\n"); rc &= test_sentence ("Who do you love?", "_obj(love, _$qVar)\n" + "_subj(love, you)\n"); rc &= test_sentence ("What is for dinner?", "_pobj(for, dinner)\n" + "_psubj(for, _$qVar)\n"); rc &= test_sentence ("Who's on first?", "_pobj(on, first)\n" + "_psubj(on, _$qVar)\n" + "_advmod(be, on)\n"); rc &= test_sentence ("Who farted?", "_subj(fart, _$qVar)\n"); rc &= test_sentence ("What is happening?", "_subj(happen, _$qVar)\n"); rc &= test_sentence ("Who is correct?", "_predadj(_$qVar, correct)\n"); rc &= test_sentence ("What is right?", "_predadj(_$qVar, right)\n"); rc &= test_sentence ("What are you doing?", "_subj(_$qVar, you)\n"); rc &= test_sentence ("Are you the one?", "_obj(be, one)\n" + "_subj(be, you)\n"); rc &= test_sentence ("Are you mad?", "_predadj(you, mad)\n"); rc &= test_sentence ("Is the book under the table?", "_pobj(under, table)\n" + "_prepadj(book, under)\n" + "_subj(_%copula, book)\n"); rc &= test_sentence ("Does he seem mad?", "_to-be(seem, mad)\n" + "_subj(seem, he)\n"); rc &= test_sentence ("Does she want to help us?", "_obj(help, us)\n" + "_to-do(want, help)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Does she want you to help us?", "_obj(help, us)\n" + "_subj(help, you)\n" + "_to-do(want, help)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Was she good enough to help?", "_predadj(she, good)\n" + "_to-do(good, help)\n"); rc &= test_sentence ("Must she be able to sing?", "_to-do(able, sing)\n" + "_modal(must, able)\n" + "_predadj(she, able)\n"); rc &= test_sentence ("Does she want to sing?", "_to-do(want, sing)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Have you slept?", "_subj(sleep, you)\n"); rc &= test_sentence ("Will you sleep?", "_subj(sleep, you)\n" + "_modal(will, sleep)\n"); rc &= test_sentence ("Did you sleep?", "_subj(sleep, you)\n"); rc &= test_sentence ("Did you eat the pizza?", "_obj(eat, pizza)\n" + "_subj(eat, you)\n"); rc &= test_sentence ("Did you give her the money?", "_iobj(give, her)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Did you give the money to her?", "_advmod(give, to)\n" + "_pobj(to, her)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Maybe she eats lunch.", "_obj(eat, lunch)\n" + "_advmod(eat, maybe)\n" + "_subj(eat, she)\n"); rc &= test_sentence ("Perhaps she is nice.", "_advmod(nice, perhaps)\n" + "_predadj(she, nice)\n"); rc &= test_sentence ("She wants to help John.", "_to-do(want, help)\n" + "_subj(want, she)\n" + "_obj(help, John)\n"); rc &= test_sentence ("She wants you to help us.", "_to-do(want, help)\n" + "_subj(want, she)\n" + "_obj(help, us)\n" + "_subj(help, you)\n"); rc &= test_sentence ("She is nice to help with the project.", "_pobj(with, project)\n" + "_advmod(help, with)\n" + "_to-do(nice, help)\n" + "_predadj(she, nice)\n"); rc &= test_sentence ("She must be able to sing.", "_to-do(able, sing)\n" + "_modal(must, able)\n" + "_predadj(she, able)\n"); rc &= test_sentence ("She must need to sing?", "_to-do(need, sing)\n" + "_modal(must, need)\n" + "_subj(need, she)\n"); rc &= test_sentence ("She must want to sing?", "_to-do(want, sing)\n" + "_modal(must, want)\n" + "_subj(want, she)\n"); rc &= test_sentence ("She wants to sing.", "_to-do(want, sing)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Where do you live?", "_%atLocation(live, _$qVar)\n" + "_subj(live, you)\n"); rc &= test_sentence ("Where did you eat dinner?", "_%atLocation(eat, _$qVar)\n" + "_obj(eat, dinner)\n" + "_subj(eat, you)\n"); rc &= test_sentence ("Where is the party?", "_%atLocation(_%copula, _$qVar)\n" + "_subj(_%copula, party)\n"); rc &= test_sentence ("Where will she be happy?", "_%atLocation(happy, _$qVar)\n" + "_modal(will, happy)\n" + "_predadj(she, happy)\n"); rc &= test_sentence ("When did jazz die?", "_%atTime(die, _$qVar)\n" + "_subj(die, jazz)\n"); rc &= test_sentence ("When did you bake the cake?", "_%atTime(bake, _$qVar)\n" + "_obj(bake, cake)\n" + "_subj(bake, you)\n"); rc &= test_sentence ("When did you give him the money?", "_iobj(give, him)\n" + "_%atTime(give, _$qVar)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("When is the party?", "_%atTime(_%copula, _$qVar)\n" + "_subj(_%copula, party)\n"); rc &= test_sentence ("Why do you live?", "_%because(live, _$qVar)\n" + "_subj(live, you)\n"); rc &= test_sentence ("Why do you like terrible music?", "_%because(like, _$qVar)/n" + "_obj(like, music)\n" + "_subj(like, you)\n" + "_amod(music, terrible)\n"); rc &= test_sentence ("Why are you such a fool?", "_%because(be, _$qVar)\n" + "_obj(be, fool)\n" + "_subj(be, you)\n"); rc &= test_sentence ("How did you sleep?", "how(sleep, _$qVar)\n" + "_subj(sleep, you)\n"); rc &= test_sentence ("How was the party?", "how(_%copula, _$qVar)\n" + "_subj(_%copula, party)\n"); rc &= test_sentence ("How is your food?", "_poss(food, you)\n" + "how(_%copula, _$qVar)\n" + "_subj(_%copula, food)\n"); rc &= test_sentence ("How much money does it cost?", "_obj(cost, money)\n" + "_subj(cost, it)\n" + "_quantity(money, _$qVar)\n"); rc &= test_sentence ("How many books have you read?", "_obj(read, book)\n" + "_subj(read, you)\n" + "_quantity(book, _$qVar)\n"); rc &= test_sentence ("How fast does it go?", "_subj(go, it)\n" + "_advmod(go, fast)\n" + "_%howdeg(fast, _$qVar)\n" + "_subj(go, it)\n"); rc &= test_sentence ("How stupid are you?", "_%howdeg(stupid, _$qVar)\n" + "_predadj(stupid, you)\n" + "_subj(stupid, you)\n"); rc &= test_sentence ("Which girl do you like?", "_det(girl, _$qVar)\n" + "_obj(like, girl)\n" + "_subj(like, you)\n"); rc &= test_sentence ("Which girl likes you?", "_obj(like, you)\n" + "_subj(like, girl)\n" + "_det(girl, _$qVar)\n"); rc &= test_sentence ("Which girl is crazy?", "_det(girl, _$qVar)\n" + "_predadj(girl, crazy)\n"); rc &= test_sentence ("The books were written by Charles Dickens.", "_obj(write, book)\n" + "_advmod(write, by)\n" + "_pobj(by, Charles_Dickens)\n"); rc &= test_sentence ("The books are published.", "_obj(publish, book)\n"); rc &= test_sentence ("I did my homework, and I went to school.", "_obj(do, homework)\n" + "_subj(do, I)\n" + "_pobj(to, school)\n" + "_advmod(go, to)\n" + "_subj(go, I)\n" + "_poss(homework, me)\n"); rc &= test_sentence ("John and Madison eat the cake.", "_obj(eat, cake)\n" + "_subj(eat, John)\n" + "_subj(eat, Madison)\n" + "conj_and(John, Madison)\n"); rc &= test_sentence ("Joan is poor but happy.", "conj_but(poor, happy)\n" + "_predadj(Joan, poor)\n" + "_predadj(Joan, happy)\n"); rc &= test_sentence ("I think that dogs can fly.", "_rep(think, that)\n" + "_comp(that, fly)\n" + "_subj(think, I)\n" + "_modal(can, fly)\n" + "_subj(fly, dog)\n"); rc &= test_sentence ("He is glad that she won.", "_rep(glad, that)\n" + "_comp(that, win)\n" + "_subj(win, she)\n" + "_predadj(he, glad)\n"); rc &= test_sentence ("He ran so quickly that he flew.", "_comp(that, fly)\n" + "_advmod(quickly, so_that)\n" + "_subj(fly, he)\n" + "_compmod(so_that, that)\n" + "_advmod(run, quickly)\n" + "_subj(run, he)\n"); rc &= test_sentence ("Who are you?", "_subj(_%copula, you)\n"); rc &= test_sentence ("Who do you love?", "_obj(love, _$qVar)\n" + "_subj(love, you)\n"); rc &= test_sentence ("What do you think?", "_obj(think, _$qVar)\n" + "_subj(think, you)\n"); rc &= test_sentence ("To whom did you sell the children?", "_advmod(sell, to)\n" + "_obj(sell, child)\n" + "_subj(sell, you)\n" + "_pobj(to, _$qVar)\n"); rc &= test_sentence ("Why did you give him the money?", "_iobj(give, him)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Why are you so stupid?", "_%because(stupid, _$qVar)\n" + "_advmod(stupid, so)\n" + "_predadj(you, stupid)\n"); rc &= test_sentence ("How did you like the movie?", "_obj(like, movie)\n" + "how(like, _$qVar)\n" + "_subj(like, you)\n"); rc &= test_sentence ("How did you send him the message?", "_iobj(send, him)\n" + "_obj(send, message)\n" + "how(send, _$qVar)\n" + "_subj(send, you)\n"); report(rc, "Interrogatives"); return rc; } public boolean test_adverbials_adjectivals() { boolean rc = true; rc &= test_sentence ("He ran like the wind.", "_advmod(run, like)\n" + "_subj(run, he)\n" + "_pobj(like, wind)\n"); rc &= test_sentence ("He was boring to an insufferable degree.", "_advmod(boring, to)\n" + "_amod(degree, insufferable)\n" + "_pobj(to, degree)\n" + "_predadj(he, boring)\n"); rc &= test_sentence ("He spoke in order to impress himself.", "_goal(speak, impress)\n" + "_subj(speak, he)\n" + "_obj(impress, himself)\n"); rc &= test_sentence ("On Tuesday, he slept late.", "_advmod(sleep, on)\n" + "_advmod(sleep, late)\n" + "_subj(sleep, he)\n" + "_pobj(on, Tuesday)\n"); rc &= test_sentence ("Often, people confused him.", "_obj(confuse, him)\n" + "_advmod(confuse, often)\n" + "_subj(confuse, people)\n"); rc &= test_sentence ("The man in window is a spy.", "_obj(be, spy)\n" + "_subj(be, man)\n" + "_pobj(in, window)\n" + "_prepadj(man, in)\n"); rc &= test_sentence ("He wrote largely in his spare time.", "_advmod(write, in)\n" + "_subj(write, he)\n" + "_amod(time, spare)\n" + "_poss(time, him)\n" + "_pobj(in, time)\n" + "_advmod(in, largely)\n"); rc &= test_sentence ("The man running away from us is a thief.", "_obj(be, thief)\n" + "_subj(be, man)\n" + "_pobj(from, us)\n" + "_advmod(run_away, from)\n" + "_amod(man, run_away)\n"); rc &= test_sentence ("Among the employees was a deranged killer.", "_pobj(among, employee)\n" + "_amod(killer, deranged)\n" + "_predadj(killer, among)\n" + "_subj(be, killer)\n"); report(rc, "Adverbials and Adjectivals"); return rc; } public boolean test_complementation() { boolean rc = true; rc &= test_sentence ("The dog chasing the bird is happy.", "_obj(chase, bird)\n" + "_predadj(dog, happy)\n" + "_comp(dog, chase)\n"); rc &= test_sentence ("My sister always opens her mouth while eating.", "_obj(open, mouth)\n" + "_advmod(open, always)\n" + "_compmod(open, while)\n" + "_subj(open, My_sister)\n" + "_comp(while, eat)\n" + "_poss(mouth, her)\n"); rc &= test_sentence ("Aaron always reads while he rides the train.", "_advmod(read, always)\n" + "_compmod(read, while)\n" + "_subj(read, Aaron)\n" + "_obj(ride, train)\n" + "_subj(ride, he)\n" + "_comp(while, ride)\n"); rc &= test_sentence ("I sing because I'm happy.", "_%because(sing, because)\n" + "_subj(sing, I)\n" + "_predadj(I, happy)\n" + "_comp(because, happy)\n"); rc &= test_sentence ("I know that you love me.", "_rep(know, that)\n" + "_subj(know, I)\n" + "_obj(love, me)\n" + "_subj(love, you)\n" + "_comp(that, love)\n"); rc &= test_sentence ("I know you hate me.", "_rep(know, hate)\n" + "_subj(know, I)\n" + "_obj(hate, me)\n" + "_subj(hate, you)\n"); rc &= test_sentence ("I am certain that you are insane.", "_rep(certain, that)\n" + "_predadj(you, insane)\n" + "_comp(that, insane)\n" + "_predadj(I, certain)\n"); rc &= test_sentence ("The idea that he would invent AGI obsessed him.", "_obj(obsess, him)\n" + "_subj(obsess, idea)\n" + "_to-do(would, invent)\n" + "_comp(that, would)\n" + "_obj(invent, AGI)\n" + "_subj(invent, he)\n" + "_rep(idea, that)\n"); report(rc, "Complementation"); return rc; } public boolean test_special_preposition_stuff() { boolean rc = true; rc &= test_sentence ("Who did you give the book to?", "_advmod(give, to)\n" + "_obj(give, book)\n" + "_subj(give, you)\n" + "_pobj(to, _$qVar)\n"); rc &= test_sentence ("The people on whom you rely are sick.", "_advmod(rely, on)\n" + "_subj(rely, you)\n" + "_pobj(on, people)\n" + "_comp(on, rely)\n" + "_predadj(people, sick)\n"); report(rc, "Special preposition stuff"); return rc; } public static void main(String[] args) { setUpClass(); TestRelEx ts = new TestRelEx(); ts.runTests(); } // @Test public void runTests() { TestRelEx ts = this; boolean rc = true; rc &= ts.test_determiners(); rc &= ts.test_time(); rc &= ts.test_comparatives(); rc &= ts.test_equatives(); rc &= ts.test_extraposition(); rc &= ts.test_conjunctions(); rc &= ts.test_interrogatives(); if (rc) { System.err.println("Tested a total of " + ts.pass + " sentences, test passed OK"); } else { int total = ts.fail + ts.pass; System.err.println("Test failed; out of a total of " + total + " test sentences,\n\t" + ts.fail + " sentences failed\n\t" + ts.pass + " sentences passed"); } System.err.println("******************************"); System.err.println("Failed test sentences on Relex"); System.err.println("******************************"); if (sentfail.isEmpty()) System.err.println("All test sentences passed"); for(String temp : sentfail){ System.err.println(temp); } System.err.println("******************************\n"); } }
src/java_test/relex/test/TestRelEx.java
/* * Copyright 2009 Linas Vepstas * * 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 relex.test; import java.util.ArrayList; import java.util.Collections; import relex.ParsedSentence; import relex.RelationExtractor; import relex.Sentence; import relex.output.SimpleView; public class TestRelEx { private static RelationExtractor re; private int pass; private int fail; private int subpass; private int subfail; private static ArrayList<String> sentfail= new ArrayList<String>(); // @BeforeClass public static void setUpClass() { re = new RelationExtractor(); } public TestRelEx() { pass = 0; fail = 0; subpass = 0; subfail = 0; } public ArrayList<String> split(String a) { String[] sa = a.split("\n"); ArrayList<String> saa = new ArrayList<String>(); for (String s : sa) { saa.add(s); } Collections.sort (saa); return saa; } /** * First argument is the sentence. * Second argument is a list of the relations that RelEx * should be generating. * Return true if RelEx generates the same dependencies * as the second argument. */ public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); // Add number of binary relations from parser-output, // to total number of relationships gotten int sizeOfGotRelations = brgot.size(); // Check expected binary and unary relations. // The below for-loop checks whether all expected binary relations are // contained in the parser-binary-relation-output arrayList "brgot". // If any unary relations are expected in the output, it checks the // parser-unary-relation-output arrayList "urgot" for unary // relationships. for (int i=0; i< exp.size(); i++) { if (!brgot.contains(exp.get(i))) { if (!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } // add the unary relation, count to total number of // binary relations sizeOfGotRelations++; } } // The size checking of the expected relationships vs output // relationships is done here purposefully, to accommodate if // there is any unary relationships present in the expected // output(see above for-loop also). However it only checks // whether parser-output resulted more relationships(binary+unary) // than expected relations. If the parser-output resulted in // fewer relationships(binary+unary) than expected it would // catch that in the above for-loop. if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; } public void report(boolean rc, String subsys) { if (rc) { System.err.println(subsys + ": Tested " + subpass + " sentences, test passed OK"); } else { int total = subpass + subfail; System.err.println(subsys + ": Test failed; out of " + total + " sentences tested,\n\t" + subfail + " sentences failed\n\t" + subpass + " sentences passed"); } subpass = 0; subfail = 0; } public boolean test_determiners() { boolean rc = true; rc &= test_sentence ("Ben ate my cookie.", "_subj(eat, Ben)\n" + "_obj(eat, cookie)\n" + "_poss(cookie, me)\n"); rc &= test_sentence ("Ben ate that cookie.", "_subj(eat, Ben)\n" + "_obj(eat, cookie)\n" + "_det(cookie, that)\n"); rc &= test_sentence ("All my writings are bad.", "_quantity(writings, all)\n" + "_poss(writings, me)\n" + "_predadj(writings, bad)\n"); rc &= test_sentence ("All his designs are bad.", "_quantity(design, all)\n" + "_poss(design, him)\n" + "_predadj(design, bad)\n"); rc &= test_sentence ("All the boys knew it.", "_subj(know, boy)\n" + "_obj(know, it)\n" + "_quantity(boy, all)\n"); rc &= test_sentence ("Joan thanked Susan for all the help she had given.", "_advmod(thank, for)\n" + "_pobj(for, help)\n" + "_subj(thank, Joan)\n" + "_obj(thank, Susan)\n" + "_quantity(help, all)\n" + "_subj(give, she)\n" + "_relmod(help, she)\n" + "_obj(give, help)\n"); report(rc, "Determiners"); return rc; } public boolean test_time() { boolean rc = true; rc &= test_sentence("I had breakfast at 8 am.", "_advmod(have, at)\n" + "_pobj(at, am)\n" + "_obj(have, breakfast)\n"+ "_subj(have, I)\n" + "_time(am, 8)\n"); rc &= test_sentence("I had supper before 6 pm.", "_advmod(have, before)\n" + "_pobj(before, pm)\n" + "_obj(have, supper)\n" + "_subj(have, I)\n" + "_time(pm, 6)\n"); report(rc, "Time"); return rc; } public boolean test_comparatives() { boolean rc = true; rc &= test_sentence ("Some people like pigs less than dogs.", "_compdeg(like, less)\n" + "_obj(like, pig)\n" + "_subj(like, people)\n" + "_compobj(than, dog)\n" + "_compprep(less, than)\n" + "than(pig, dog)\n" + "_comparative(like, pig)\n" + "comp_arg(like, dog)\n" + "_quantity(people, some)\n"); rc &= test_sentence ("Some people like pigs more than dogs.", "_compdeg(like, more)\n" + "_obj(like, pig)\n" + "_subj(like, people)\n" + "than(pig, dog)\n" + "_comparative(like, pig)\n" + "comp_arg(like, dog)\n" + "_compprep(more, than)\n" + "_compobj(than, dog)\n" + "_quantity(people, some)\n"); // Non-equi-gradable : Two entities one feature "more/less" rc &= test_sentence ("He is more intelligent than John.", "_compdeg(intelligent, more)\n" + "_comparative(intelligent, he)\n" + "comp_arg(intelligent, John)\n" + "_compobj(than, John)\n" + "than(he, John)\n" + "_predadj(he, intelligent)\n"); rc &= test_sentence ("He is less intelligent than John.", "_compdeg(intelligent, less)\n" + "_comparative(intelligent, he)\n" + "than(he, John)\n" + "comp_arg(intelligent, John)\n" + "_compobj(than, John)\n" + "_predadj(he, intelligent)\n"); rc &= test_sentence ("He runs more quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_compdeg(quickly, more)\n" + "_comparative(run, quickly)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs less quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_compdeg(quickly, less)\n" + "_comparative(run, quickly)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs more quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(do, quickly)\n" + "_subj(do, John)\n" + "_compdeg(quickly, more)\n" + "_compprep(more, than)\n" + "_comparative(run, quickly)\n" + "_compobj(than, do)\n" + "_comp(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs less quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(do, quickly)\n" + "_subj(do, John)\n" + "_compdeg(quickly, less)\n" + "_compprep(less, than)\n" + "_compobj(than, do)\n" + "than(he, John)\n" + "_comp(than, do)\n" + "_comparative(run, quickly)\n"); rc &= test_sentence ("He runs slower than John does.", "_advmod(run, slow)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_comp(than, do)\n" + "_compobj(than, John)\n" + "than(he, John)\n" + "_comparative(run, slow)\n" + "_compdeg(slow, more)\n"); rc &= test_sentence ("He runs more than John.", "_compdeg(run, more)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs less than John.", "_compdeg(run, less)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "_comparative(run, less)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs faster than John.", "than(he, John)\n" + "_comparative(run, fast)\n" + "_subj(run, he)\n" + "_advmod(run, fast)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(faster, than)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("He runs more slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "_compdeg(slowly, more)\n" + "_comparative(run, slowly)\n" + "_advmod(run, slowly)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs less slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "_comparative(run, slowly)\n" + "_advmod(run, slowly)\n" + "_compdeg(slowly, less)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "comp_arg(run, John)\n"); rc &= test_sentence ("He runs more miles than John does.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, more)\n" + "_compamt(mile, more)\n" + "_comparative(run, mile)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs fewer miles than John does.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, fewer)\n" + "_compamt(mile, fewer)\n" + "_comparative(run, mile)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs many more miles than John does.", "than(he, John)\n" + "_comparative(run, mile)\n" + "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(more, many)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "_compamt(mile, more)\n"); rc &= test_sentence ("He runs ten more miles than John.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "comp_arg(run, John)\n" + "_comparative(run, mile)\n" + "_quantity(more, ten)\n" + "_compobj(than, John)\n" + "_compamt(mile, more)\n"); rc &= test_sentence ("He runs almost ten more miles than John does.", "_obj(run, mile)\n" + "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(more, ten)\n" + "_comparative(run, mile)\n" + "_quantity_mod(ten, almost)\n" + "_compamt(mile, more)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs more often than John.", "_subj(run, he)\n" + "comp_arg(run, John)\n" + "_compdeg(often, more)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs less often than John.", "_subj(run, he)\n" + "comp_arg(run, John)\n" + "_compdeg(often, less)\n" + "_advmod(run, often)\n" + "_advmod(run, here)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "_comparative(run, often)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs here more often than John.", "_advmod(run, here)\n" + "_compdeg(often, more)\n" + "_advmod(run, often)\n" + "_subj(run, he)\n" + "comp_arg(run, John)\n" + "_comparative(run, often)\n" + "_compobj(than, John)\n" + "_compprep(more, than)\n" + "than(he, John)\n"); rc &= test_sentence ("He runs here less often than John.", "_advmod(run, here)\n" + "_advmod(often, less)\n" + "_advmod(run, often)\n" + "_subj(run, he)\n" + "_comparative(run, often)\n" + "than(he, John)\n" + "comp_arg(run, John)\n" + "_compobj(than, John)\n" + "_compprep(less, than)\n" + "_compdeg(often, less)\n"); rc &= test_sentence ("He is faster than John.", "than(he, John)\n" + "_predadj(he, fast)\n" + "comp_arg(fast, John)\n" + "_comparative(fast, he)\n" + "_compobj(than, John)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("He is faster than John is.", "than(he, John)\n" + "_predadj(he, fast)\n" + "_subj(be, John)\n" + "_comparative(fast, he)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("His speed is faster than John's.", "than(He, John)\n" + "_predadj(speed, fast)\n" + "_poss(speed, he)\n" + "_comparative(fast, speed)\n" + "_compobj(than, John's)\n" + "_compdeg(fast, more)\n"); rc &= test_sentence ("I run more than Ben.", "_subj(run, I)\n" + "_comp_arg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compprep(more, than)\n" + "than(I, Ben)\n" + "_compdeg(run, more)\n"); rc &= test_sentence ("I run less than Ben.", "_subj(run, I)\n" + "_comp_arg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compprep(less, than)\n" + "than(I, Ben)\n" + "_compdeg(run, less)\n"); rc &= test_sentence ("I run more miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "_quantity(mile, more)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n" + "_comparg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, more)\n"); rc &= test_sentence ("I run fewer miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "_quantity(mile, fewer)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n" + "_comparg(run, Ben)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, fewer)\n"); rc &= test_sentence ("I run 10 more miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "comp_arg(run, Ben)\n" + "_quantity(more, 10)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, more)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run 10 fewer miles than Ben.", "_subj(run, I)\n" + "_obj(run, mile)\n" + "comp_arg(run, Ben)\n" + "_quantity(fewer, 10)\n" + "_compobj(than, Ben)\n" + "_compamt(mile, fewer)\n" + "_comparative(run, mile)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run more often than Ben.", "_subj(run, I)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "comp_arg(run, Ben)\n" + "_subj(run, I)\n" + "_compobj(than, Ben)\n" + "_compdeg(often, more)\n" + "_compprep(more, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run less often than Ben.", "_subj(run, I)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "comp_arg(run, Ben)\n" + "_subj(run, I)\n" + "_compobj(than, Ben)\n" + "_compdeg(often, less)\n" + "_compprep(less, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run more often than Ben does.", "_subj(run, I)\n" + "_subj(do, Ben)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "_advmod(do, often)\n" + "_compdeg(often, more)\n" + "_compprep(more, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run less often than Ben does.", "_subj(run, I)\n" + "_subj(do, Ben)\n" + "_advmod(run, often)\n" + "_comparative(run, often)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "_advmod(do, often)\n" + "_compdeg(often, less)\n" + "_compprep(less, than)\n" + "than(I, Ben)\n"); rc &= test_sentence ("I run more often than Ben climbs.", "_subj(run, I)\n" + "_subj(climb, Ben)\n" + "_comparative(run, often)\n" + "than(I, Ben)\n" + "than1(run, climb)\n" + "_comp(than, climb)\n" + "_compdeg(often, more)\n" + "_compprep(more, than)\n" + "_advmod(run, often)\n"); rc &= test_sentence ("I run less often than Ben climbs.", "_subj(run, I)\n" + "_subj(climb, Ben)\n" + "_comparative(run, often)\n" + "than(I, Ben)\n" + "than1(run, climb)\n" + "_comp(than, climb)\n" + "_compdeg(often, less)\n" + "_compprep(less, than)\n" + "_advmod(run, often)\n"); rc &= test_sentence ("I run more races than Ben wins contests.", "_subj(run, I)\n" + "_obj(run, race)\n" + "_subj(win, Ben)\n" + "_obj(win, contest)\n" + "_quantity(race, more)\n" + "_comparative(run, race)\n" + "_comp(than, Ben)\n" + "than(I, Ben)\n" + "_compamt(race, more)\n"); rc &= test_sentence ("I run fewer races than Ben wins contests.", "_subj(run, I)\n" + "_obj(run, race)\n" + "_subj(win, Ben)\n" + "_obj(win, contest)\n" + "_comp(than, Ben)\n" + "_comparative(run, race)\n" + "than(I, Ben)\n" + "_compamt(race, fewer)\n"); rc &= test_sentence ("I have more chairs than Ben.", "_obj(have, chair)\n" + "_subj(have, I)\n" + "than(I, Ben)\n" + "_comparative(have, chair)\n" + "comp_arg(have, Ben)\n" + "_compobj(than, Ben)\n" + "_compamt(chair, more)\n"); rc &= test_sentence ("I have fewer chairs than Ben.", "_obj(have, chair)\n" + "_subj(have, I)\n" + "than(I, Ben)\n" + "_comparative(have, chair)\n" + "_compamt(chair, fewer)\n" + "_compobj(than, Ben)\n"); rc &= test_sentence ("He earns much more money than I do.", "_obj(earn, money)\n" + "_subj(do, I)\n" + "_subj(earn, he)\n" + "than(he, I)\n" + "_comparative(earn, money)\n" + "_compamt(money, more)\n" + "_compdeg(more, much)\n" + "_compobj(than, do)\n" + "_comp(than, do)\n"); rc &= test_sentence ("He earns much less money than I do.", "_obj(earn, money)\n" + "_subj(do, I)\n" + "_subj(earn, he)\n" + "than(he, I)\n" + "_comparative(earn, money)\n" + "_compamt(money, less)\n" + "_compdeg(less, much)\n" + "_comp(than, do)\n" + "_compobj(than, do)\n" + "degree(less, comparative)\n"); rc &= test_sentence ("She comes here more often than her husband.", "_advmod(come, here)\n" + "_compdeg(often, more)\n" + "_advmod(come, often)\n" + "_compprep(more, than)\n" + "_subj(come, she)\n" + "_poss(husband, her)\n" + "_comparative(come, often)\n" + "comp_arg(come, husband)\n" + "_compobj(than, husband)\n" + "than(she, husband)\n"); rc &= test_sentence ("She comes here less often than her husband.", "_advmod(come, here)\n" + "_compdeg(often, less)\n" + "_advmod(come, often)\n" + "_compprep(less, than)\n" + "_subj(come, she)\n" + "_poss(husband, her)\n" + "_comparative(come, often)\n" + "comp_arg(come, husband)\n" + "_compobj(than, husband)\n" + "than(she, husband)\n"); rc &= test_sentence ("Russian grammar is more difficult than English grammar.", "_compdeg(difficult, more)\n" + "_comparative(difficult, grammar)\n" + "_amod(grammar, Russian)\n" + "than(grammar, grammar)\n" + "_predadj(grammar, difficult)\n" + "_compobj(than, grammar)\n" + "_amod(grammar, English)\n"); rc &= test_sentence ("Russian grammar is less difficult than English grammar.", "_compdeg(difficult, less)\n" + "_comparative(difficult, grammar)\n" + "_amod(grammar, Russian)\n" + "than(grammar, grammar)\n" + "_predadj(grammar, difficult)\n" + "_compobj(than, grammar)\n" + "_amod(grammar, English)\n"); rc &= test_sentence ("My sister is much more intelligent than me.", "_compdeg(more, much)\n" + "_predadj(sister, intelligent)\n" + "_poss(sister, me)\n" + "than(sister, me)\n" + "_comparative(intelligent, sister)\n" + "comp_arg(intelligent, me)\n" + "_compobj(than, me)\n" + "_compdeg(intelligent, more)\n"); rc &= test_sentence ("My sister is much less intelligent than me.", "_compdeg(less, much)\n" + "_predadj(sister, intelligent)\n" + "_poss(sister, me)\n" + "than(sister, me)\n" + "_comparative(intelligent, sister)\n" + "comp_arg(intelligent, me)\n" + "_compobj(than, me)\n" + "_compdeg(intelligent, less)\n"); rc &= test_sentence ("I find maths lessons more enjoyable than science lessons.", "_iobj(find, maths)\n" + "_obj(find, lesson)\n" + "_subj(find, I)\n" + "_amod(lesson, enjoyable)\n" + "_nn(lesson, science)\n" + "than(maths, science)\n" + "_comparative(enjoyable, maths)\n" + "_advmod(enjoyable, more)\n" + "degree(enjoyable, comparative)\n"); rc &= test_sentence ("I find maths lessons less enjoyable than science lessons.", "_iobj(find, maths)\n" + "_obj(find, lesson)\n" + "_subj(find, I)\n" + "_amod(lesson, enjoyable)\n" + "_nn(lesson, science)\n" + "than(maths, science)\n" + "_comparative(enjoyable, maths)\n" + "_advmod(enjoyable, less)\n" + "degree(enjoyable, comparative)\n"); // Comparatives Without More/less terms rc &= test_sentence ("Her great-grandson is nicer than her great-granddaughter.", "than(great-grandson, great-granddaughter)\n" + "_predadj(great-grandson, nice)\n" + "_poss(great-grandson, her)\n" + "_poss(great-granddaughter, her)\n" + "_comparative(nice, great-grandson)\n" + "degree(nice, comparative)\n"); rc &= test_sentence ("George is cleverer than Norman.", "than(George, Norman)\n" + "_predadj(George, clever)\n" + "_comparative(clever, George)\n" + "degree(clever, comparative)\n"); rc &= test_sentence ("Kim is taller than Linda.", "than(Kim, Linda)\n" + "_predadj(Kim, tall)\n" + "_comparative(tall, Kim)\n" + "degree(tall, comparative)\n"); rc &= test_sentence ("Venus is brighter than Mars.", "than(Venus, Mars)\n" + "_predadj(Venus, bright)\n" + "_comparative(bright, Venus)\n" + "degree(bright, comparative)\n"); rc &= test_sentence ("Mary is shorter than Jane.", "than(Mary, Jane)\n" + "_predadj(Mary, short)\n" + "_comparative(short, Mary)\n" + "degree(short, comparative)\n"); rc &= test_sentence ("I am happier than you.", "than(I, you)\n" + "_predadj(I, happy)\n" + "_comparative(happy, I)\n" + "degree(happy, comparative)"); rc &= test_sentence ("His house is bigger than hers.", "than(house, hers)\n" + "_predadj(house, big)\n" + "_poss(house, him)\n" + "_comparative(big ,house)\n" + "degree(big, comparative)"); rc &= test_sentence ("She is two years older than me.", "_obj(is, year)\n" + "_amod(years, old)\n" + "_quantity(year, two)\n" + "numeric-FLAG(two, T)\n" + "than(she, me)\n" + "_comparative(old, she)\n" + "degree(old, comparative)"); rc &= test_sentence ("New York is much bigger than Boston.", "_subj(is, New_York)\n" + "_amod(much, big)\n" + "than(New_York, Boston)\n" + "_comparative(big, New_York)\n" + "degree(big, comparative)"); rc &= test_sentence ("He is a better player than Ronaldo.", "_obj(be, player)\n" + "_subj(be, he)\n" + "_amod(player, good)\n" + "than(he, Ronaldo)\n" + "_comparative(good, he)\n" + "degree(good, comparative)"); rc &= test_sentence ("France is a bigger country than Britain.", "_obj(is, country)\n" + "_subj(is, France)\n" + "_amod(country, big)\n" + "than(France, Britain)\n" + "_comparative(big, France)\n" + "degree(big, comparative)\n"); rc &= test_sentence ("That joke was funnier than his joke.", "_predadj(joke, funny)\n" + "than(joke, joke)\n" + "_det(joke, that)\n" + "_poss(joke, him)\n" + "_comparative(funny, joke)\n" + "degree(funny, comparative)"); rc &= test_sentence ("Our car is bigger than your car.", "than(car, car)\n" + "_predadj(car, big)\n" + "_poss(car, us)\n" + "_det(car, you)\n" + "_poss(car, you)\n" + "_comparative(big, car)\n" + "degree(big, comparative)"); // Sentences need to check rc &= test_sentence ("This computer is better than that one.", "than(computer, one)\n" + "_det(computer, this)\n" + "_predadj(computer, good)\n" + "_det(one, that)\n" + "degree(good, comparative)\n" + "_comparative(good, computer)\n"); rc &= test_sentence ("He's simpler than I thought.", "than(he, I)\n" + "_subj(think, I)\n" + "_comparative(simple, he)\n" + "_predadj(he, simple)\n" + "degree(simple, comparative)\n"); rc &= test_sentence ("She's stronger at chess than I am.", "at(strong, chess)\n" + "than(she, I)\n" + "_predadj(she, strong)\n" + "degree(strong, comparative)\n" + "_comparative(strong, she)\n"); rc &= test_sentence ("She's prettier than her mother.", "_predadj(she, pretty)\n" + "than(she, mother)\n" + "_poss(mother, her)\n" + "_comparative(pretty, she)\n" + "degree(pretty, comparative)\n"); rc &= test_sentence ("This exam was more difficult than the other.", "than(exam, other)\n" + "_det(exam, this)\n" + "_predadj(exam, difficult)\n" + "_advmod(difficult, more)\n" + "_comparative(difficult, exam)\n" + "degree(difficult, comparative)\n"); rc &= test_sentence ("It's much colder today than it was yesterday.", "_subj(be, it)\n" + "than(today, yesterday)\n" + "_advmod(cold, today)\n" + "_advmod(cold, yesterday)\n" + "_predadj(it, cold)\n" + "_comparative(cold, it)\n" + "degree(cold, comparative)\n"); rc &= test_sentence ("This grammar topic is easier than most others.", "than(topic, others)\n" + "_det(topic, this)\n" + "_nn(topic, grammar)\n" + "_predadj(topic, easy)\n" + "_quantity(others, most)\n" + "_comparative(easy, topic)\n" + "degree(easy, comparative)\n"); rc &= test_sentence ("I find science more difficult than mathematics.", "_obj(find, science)\n" + "_subj(find, I)\n" + "_advmod(difficult, more)\n" + "than(science, mathematics)\n" + "_comparative(difficult, science)\n" + "degree(difficult, comparative)\n"); //one entity two or more features rc &= test_sentence ("He is more intelligent than attractive.", "than(intelligent, attractive)\n" + "_predadj(he, intelligent)\n" + "_advmod(intelligent, more)\n" + "_comparative(intelligent, he)\n" + "degree(intelligent, comparative)\n"); rc &= test_sentence ("He is less intelligent than attractive.", "than(intelligent, attractive)\n" + "_predadj(he, intelligent)\n" + "_advmod(intelligent, less)\n" + "_comparative(intelligent, he)\n" + "degree(intelligent, comparative)\n"); rc &= test_sentence ("The dog was more hungry than angry.", "_predadj(dog, hungry)\n" + "than(hungry, angry)\n" + "_advmod(hungry, more)\n" + "_comparative(hungry, dog)\n" + "degree(hungry, comparative)\n"); rc &= test_sentence ("The dog was less hungry than angry.", "_predadj(dog, hungry)\n" + "than(hungry, angry)\n" + "_advmod(hungry, less)\n" + "_comparative(hungry, dog)\n" + "degree(hungry, comparative)\n"); rc &= test_sentence ("He did it more quickly than carefully.", "_obj(do, it)\n" + "_subj(do, he)\n" + "than(quickly, carefully)\n" + "_advmod(do, quickly)\n" + "_advmod(quickly, more)\n" + "_comparative(quickly, do)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He did it less quickly than carefully.", "_obj(do, it)\n" + "_subj(do, he)\n" + "than(quickly, carefully)\n" + "_advmod(do, quickly)\n" + "_advmod(quickly, less)\n" + "_comparative(quickly, do)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He has more money than time.", "_obj(have, money)\n" + "_subj(have, he)\n" + "than(money, time)\n" + "_quantity(money, more)\n" + "_comparative(money, have)\n" + "degree(more, comparative)\n"); rc &= test_sentence ("He has less money than time.", "_obj(have, money)\n" + "_subj(have, he)\n" + "than(money, time)\n" + "_quantity(money, less)\n" + "_comparative(money, have)\n" + "degree(less, comparative)\n"); rc &= test_sentence ("He plays more for money than for pleasure.", "_subj(play, he)\n" + "_obj(play, more)\n" + "for(play, money)\n" + "for(than, pleasure)\n" + "than(money, pleasure)\n" + "_comparative(more, play)\n" + "degree(more, comparative)\n"); rc &= test_sentence ("He plays less for money than for pleasure.", "_subj(play, he)\n" + "_obj(play, less)\n" + "for(play, money)\n" + "for(than, pleasure)\n" + "than(money, pleasure)\n" + "_comparative(less, play)\n" + "degree(less, comparative)\n"); //two entities two features rc &= test_sentence ("Jack is more ingenious than Ben is crazy.", "_predadj(Jack, ingenious)\n" + "_predadj(Ben, crazy)\n" + "_advmod(ingenious, more)\n" + "_comparative(ingenious, Jack)\n" + "than(Jack, Ben)\n" + "than1(ingenious, crazy)\n" + "degree(ingenious, comparative)\n"); rc &= test_sentence ("Jack is less ingenious than Ben is crazy.", "_predadj(Jack, ingenious)\n" + "_predadj(Ben, crazy)\n" + "_advmod(ingenious, less)\n" + "_comparative(ingenious, Jack)\n" + "than(Jack, Ben)\n" + "than1(ingenious, crazy)\n" + "degree(ingenious, comparative)\n"); //two entities two features Without More/less rc &= test_sentence ("I slept longer than he worked", "_subj(sleep, I)\n" + "_subj(work, he)\n" + "_advmod(sleep, long)\n" + "than(I, he)\n" + "than1(sleep, work)\n" + "_comparative(long, sleep)\n" + "degree(long, comparative)\n"); report(rc, "Comparatives"); return rc; } public boolean test_equatives() { boolean rc = true; //Equative:two entities one feature rc &= test_sentence ("Amen's hair is as long as Ben's.", "_poss(hair, Amen)\n" + "_predadj(hair, long)\n" + "as(long, Ben)\n" + "than(Amen, Ben)\n"); rc &= test_sentence ("Amenโ€™s hair is same as Benโ€™s.", "_poss(hair, Amen)\n" + "_predadj(hair, same)\n" + "as(same, Ben)\n" + "than(Amen, Ben)\n"); rc &= test_sentence ("Jackโ€™s hair color is similar to that of Benโ€™s.", "_poss(color, Jack)\n" + "_nn(color, hair)\n" + "_predadj(color, similar)\n" + "of(that, Ben)\n" + "to(similar, that)\n" + "than(Jack, Ben)\n"); rc &= test_sentence ("Jackโ€™s hair color is similar to Ben's", "_poss(color, Jack)\n" + "_nn(color, hair)\n" + "_predadj(color, similar)\n" + "to(similar, Ben)\n" + "than(Jack, Ben)\n"); rc &= test_sentence ("Jack is as intelligent as Ben.", "_predadj(Jack, intelligent)\n" + "_compdeg(intelligent, as)\n" + "_pobj(as, Ben)\n" + "_predadj(Ben, intelligent)\n" + "than(Jack, Ben)\n"); rc &= test_sentence ("The bookโ€™s color is same as that of the pen.", "_poss(color, book)\n" + "_predadj(color, same)\n" + "_compdeg(same, as)\n" + "_pobj(as, color)\n" + "_amod(color, of)\n" + "_pobj(of, pen)\n"); rc &= test_sentence ("The snail is running exactly as fast as the cheetah.", "_subj(run, snail)\n" + "_comp_arg(run, cheetah)\n" + "_advmod(run, fast)\n" + "_compdeg(fast, as)\n" + "_pobj(as, cheetah)\n" + "_advmod(as, exactly)\n" + "than(snail, cheetah)\n"); //one entity one feature, through time rc &= test_sentence ("The coffee tastes the same as it did last year.", "_subj(taste, coffee)\n" + "_advmod(taste, the_same)\n" + "_advmod(taste, as)\n" + "_advmod(do, year)\n" + "_subj(do, it)\n" + "_comp(as, do)\n" + "_amod(year, last)\n"); rc &= test_sentence ("The coffee tastes as it did last year.", "_subj(taste, coffee)\n" + "_advmod(do, year)\n" + "_subj(do, it)\n" + "_advmod(taste, as)\n" + "_comp(as, do)\n" + "_amod(year, last)\n"); rc &= test_sentence ("Mike runs as fast as he did last year.", "_subj(do, he)\n" + "_subj(run, Mike)\n" + "_compdeg(fast, as)\n" + "_comp(as, do)\n" + "_advmod(run, fast)\n" + "_advmod(do, year)\n" + "_advmod(do, fast)\n" + "_amod(year, last)\n" + "_advmod(as, run)\n" + "than(Mike, he)\n"); rc &= test_sentence ("The kick was as soft as the first.", "_predadj(kick, soft)\n" + "_pobj(as, first)\n" + "_compdeg(soft, as)\n"); rc &= test_sentence ("He is as smart as I ever expected him to be.", "_predadj(he, smart)\n" + "_subj(expect, I)\n" + "_to-do(expect, be)\n" + "_comp(as, expect)\n" + "_advmod(expect, ever)\n" + "_subj(be, him)\n" + "_compdeg(smart, as)\n"); report(rc, "Equatives"); return rc; } public boolean test_conjunctions() { boolean rc = true; // conjoined verbs rc &= test_sentence ("Scientists make observations and ask questions.", "_obj(make, observation)\n" + "_obj(ask, question)\n" + "_subj(make, scientist)\n" + "_subj(ask, scientist)\n" + "conj_and(make, ask)\n"); // conjoined nouns rc &= test_sentence ("She is a student and an employee.", "_obj(be, student)\n" + "_obj(be, employee)\n" + "_subj(be, she)\n" + "conj_and(student, employee)\n"); // conjoined adjectives rc &= test_sentence ("I hailed a black and white taxi.", "_obj(hail, taxi)\n" + "_subj(hail, I)\n" + "_amod(taxi, black)\n" + "_amod(taxi, white)\n" + "conj_and(black, white)\n"); // conjoined adverbs rc &= test_sentence ("She ran quickly and quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "conj_and(quickly, quietly)\n"); // adjectival modifiers on conjoined subject rc &= test_sentence ("The big truck and the little car collided.", "_amod(car, little)\n" + "_amod(truck, big)\n" + "_subj(collide, truck)\n" + "_subj(collide, car)\n" + "conj_and(truck, car)\n"); // verbs with modifiers rc &= test_sentence ("We ate dinner at home and went to the movies.", "_obj(eat, dinner)\n" + "conj_and(eat, go)\n" + "_advmod(eat, at)\n" + "_pobj(at, home)\n" + "_subj(eat, we)\n" + "_advmod(go, to)\n" + "_pobj(to, movie)\n" + "_subj(go, we)\n"); // verb with more modifiers rc &= test_sentence ("We ate a late dinner at home and went out to the movies afterwards.", "_obj(eat, dinner)\n" + "conj_and(eat, go_out)\n" + "_advmod(eat, at)\n" + "_advmod(go_out, to)\n" + "_pobj(at, home)\n" + "_subj(eat, we)\n" + "_pobj(to, movie)\n" + "_advmod(go_out, afterwards)\n" + "_subj(go_out, we)\n" + "_amod(dinner, late)\n"); // conjoined ditransitive verbs rc &= test_sentence ("She baked him a cake and sang him a song.", "_iobj(sing, him)\n" + "_obj(sing, song)\n" + "_subj(sing, she)\n" + "_iobj(bake, him)\n" + "_obj(bake, cake)\n" + "conj_and(bake, sing)\n" + "_subj(bake, she)\n"); // conjoined adverbs with modifiers rc &= test_sentence ("she ran very quickly and extremely quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "_advmod(quietly, extremely)\n" + "conj_and(quickly, quietly)\n" + "_advmod(quickly, very)\n"); // conjoined adverbs with out modifiers rc &= test_sentence ("She handled it quickly and gracefully.", "_obj(handle, it)\n" + "_advmod(handle, quickly)\n" + "_advmod(handle, gracefully)\n" + "_subj(handle, she)\n" + "conj_and(quickly, gracefully)\n"); // modifiers on conjoined adjectives rc &= test_sentence ("He had very long and very white hair.", "_obj(have, hair)\n" + "_subj(have, he)\n" + "_amod(hair, long)\n" + "_amod(hair, white)\n" + "_advmod(white, very)\n" + "conj_and(long, white)\n" + "_advmod(long, very)\n"); // adjectival modifiers on conjoined object rc &= test_sentence ("The collision was between the little car and the big truck.", "_pobj(between, car)\n" + "_pobj(between, truck)\n" + "_pobj(between, and)\n" + "_psubj(between, collision)\n" + "_amod(truck, big)\n" + "_amod(car, little)\n" + "conj_prep(between, and)\n" + "conj_and(car, truck)\n"); // Names Modifiers and conjunction rc &= test_sentence ("Big Tom and Angry Sue went to the movies.", "_pobj(to, movie)\n" + "_advmod(go, to)\n" + "_subj(go, Big_Tom)\n" + "_subj(go, Angry_Sue)\n" + "conj_and(Big_Tom, Angry_Sue)\n"); //Correlative conjunction rc &= test_sentence ("I could use neither the lorry nor the van.", "_modal(could, use)\n" + "conj_neither_nor(lorry, van)\n" + "_obj(use, lorry)\n" + "_obj(use, van)\n" + "_subj(use, I)\n"); report(rc, "Conjunction"); return rc; } public boolean test_extraposition() { boolean rc = true; rc &= test_sentence ("The woman who lives next door is a registered nurse.", "_obj(be, nurse)\n" + "_subj(be, woman)\n" + "_amod(nurse, registered)\n" + "_advmod(live, next_door)\n" + "_subj(live, woman)\n" + "_rel(who, live)\n" + "_relmod(woman, who)\n"); rc &= test_sentence ("A player who is injured has to leave the field.", "_to-do(have, leave)\n" + "_subj(have, player)\n" + "_obj(leave, field)\n" + "_rel(who, injured)\n" + "_predadj(player, injured)\n" + "_relmod(player, who)\n"); rc &= test_sentence ("Pizza, which most people love, is not very healthy.", "_advmod(very, not)\n" + "_advmod(healthy, very)\n" + "_obj(love, Pizza)\n" + "_quantity(people, most)\n" + "which(Pizza, love)\n" + "_subj(love, people)\n" + "_predadj(Pizza, healthy)\n" ); rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.", "_advmod(famous, very)\n" + "_advmod(belong, to)\n" + "_subj(belong, restaurant)\n" + "_poss(aunt, me)\n" + "_pobj(to, aunt)\n" + "_rel(which, belong)\n" + "_predadj(restaurant, famous)\n" + "_relmod(restaurant, which)\n"); rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.", "_obj(write, book)\n" + "_advmod(write, by)\n" + "_obj(read, book)\n" + "_advmod(read, in)\n" + "_subj(read, I)\n" + "_pobj(in, library)\n" + "_rel(which, read)\n" + "_relmod(book, which)\n" + "_pobj(by, Charles_Dickens)\n"); rc &= test_sentence("This is the book whose author I met in a library.", "_obj(be, book)\n" + "_subj(be, this)\n" + "_obj(meet, author)\n" + "_advmod(meet, in)\n" + "_subj(meet, I)\n" + "_pobj(in, library)\n" + "_pobj(whose, author)\n" + "_det(book, whose)\n"); rc &= test_sentence("The book that Jack lent me is very boring.", "_advmod(boring, very)\n" + "_obj(lend, book)\n" + "_iobj(lend, me)\n" + "_subj(lend, Jack)\n" + "_relmod(book, that)\n" + "_rel(that, lend)\n" + "_predadj(book, boring)\n"); rc &= test_sentence("They ate a special curry which was recommended by the restaurantโ€™s owner.", "_obj(eat, curry)\n" + "_subj(eat, they)\n" + "_obj(recommend, curry)\n" + "_advmod(recommend, by)\n" + "_pobj(by, owner)\n" + "_poss(owner, restaurant)\n" + "_rel(which, recommend)\n" + "_amod(curry, special)\n" + "_relmod(curry, which)\n"); rc &= test_sentence("The dog who Jack said chased me was black.", "_obj(chase, me)\n" + "_subj(chase, dog)\n" + "_rep(say, chase)\n" + "_rel(who, chase)\n" + "_subj(say, Jack)\n" + "_predadj(dog, black)\n" + "_relmod(dog, who)\n"); rc &= test_sentence("Jack, who hosted the party, is my cousin.", "_obj(be, cousin)\n" + "_subj(be, Jack)\n" + "_poss(cousin, me)\n" + "_obj(host, party)\n" + "_subj(host, Jack)\n" + "who(Jack, host)\n"); rc &= test_sentence("Jack, whose name is in that book, is the student near the window.", "near(be, window)\n" + "_obj(be, student)\n" + "_subj(be, Jack)\n" + "_pobj(in, book)\n" + "_psubj(in, name)\n" + "_det(book, that)\n" + "whose(Jack, name)\n"); rc &= test_sentence("Jack stopped the police car that was driving fast.", "_obj(stop, car)\n" + "_subj(stop, Jack)\n" + "_advmod(drive, fast)\n" + "_subj(drive, car)\n" + "_relmod(car, that)\n" + "_rel(that, drive)\n" + "_nn(car, police)\n"); rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.", "_obj(stop, car)\n" + "_pobj(by, sign)\n" + "_advmod(before, just)\n" + "_advmod(stand, on)\n" + "_pobj(on, street)\n" + "_advmod(stop, by)\n" + "_subj(stand, sign)\n" + "_relmod(sign, that)\n" + "_rel(that, stand)\n" + "_nn(sign, traffic)\n" + "_advmod(stop, just)\n" + "_pobj(before, crossroads)\n"); report(rc, "Extrapostion"); return rc; } public boolean test_interrogatives() { boolean rc = true; rc &= test_sentence ("What is Socrates?", "_obj(be, Socrates)\n" + "_subj(be, _$qVar)\n"); rc &= test_sentence ("Who is the teacher?", "_obj(be, teacher)\n" + "_subj(be, _$qVar)\n"); rc &= test_sentence ("Who is a man?", "_obj(be, man)\n" + "_subj(be, _$qVar)\n"); rc &= test_sentence ("Who told you that bullshit?", "_iobj(tell, you)\n" + "_obj(tell, bullshit)\n" + "_subj(tell, _$qVar)\n" + "_det(bullshit, that)\n"); rc &= test_sentence ("Who told that story to the police?", "_advmod(tell, to)\n" + "_pobj(to, police)\n" + "_obj(tell, story)\n" + "_subj(tell, _$qVar)\n" + "_det(story, that)\n"); rc &= test_sentence ("What gives you that idea?", "_iobj(give, you)\n" + "_obj(give, idea)\n" + "_subj(give, _$qVar)\n" + "_det(idea, that)\n"); rc &= test_sentence ("What did you tell the fuzz?", "_iobj(tell, fuzz)\n" + "_obj(tell, _$qVar)\n" + "_subj(tell, you)\n"); rc &= test_sentence ("What did you give to Mary?", "_advmod(give, to)\n" + "_pobj(to, Mary)\n" + "_obj(give, _$qVar)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Whom did you feed to the lions?", "_advmod(feed, to)\n" + "_obj(feed, _$qVar)\n" + "_subj(feed, you)\n" + "_pobj(to, lion)\n"); rc &= test_sentence ("To whom did you sell the children?", "_pobj(to, _$qVar)\n" + "_obj(sell, child)\n" + "_advmod(sell, to)\n" + "_subj(sell, you)\n"); rc &= test_sentence ("To what do we owe the pleasure?", "_pobj(to, _$qVar)\n" + "_obj(owe, pleasure)\n" + "_advmod(owe, to)\n" + "_subj(owe, we)\n"); rc &= test_sentence ("Who did you sell the children to?", "_advmod(sell, to)\n" + "_pobj(to, _$qVar)\n" + "_obj(sell, child)\n" + "_subj(sell, you)\n"); rc &= test_sentence ("What bothers you?", "_obj(bother, you)\n" + "_subj(bother, _$qVar)\n"); rc &= test_sentence ("Who programmed you?", "_obj(program, you)\n" + "_subj(program, _$qVar)\n"); rc &= test_sentence ("What is on the table?", "_pobj(on, table)\n" + "_psubj(on, _$qVar)\n"); rc &= test_sentence ("What did you say?", "_obj(say, _$qVar)\n" + "_subj(say, you)\n"); rc &= test_sentence ("Who do you love?", "_obj(love, _$qVar)\n" + "_subj(love, you)\n"); rc &= test_sentence ("What is for dinner?", "_pobj(for, dinner)\n" + "_psubj(for, _$qVar)\n"); rc &= test_sentence ("Who's on first?", "_pobj(on, first)\n" + "_psubj(on, _$qVar)\n" + "_advmod(be, on)\n"); rc &= test_sentence ("Who farted?", "_subj(fart, _$qVar)\n"); rc &= test_sentence ("What is happening?", "_subj(happen, _$qVar)\n"); rc &= test_sentence ("Who is correct?", "_predadj(_$qVar, correct)\n"); rc &= test_sentence ("What is right?", "_predadj(_$qVar, right)\n"); rc &= test_sentence ("What are you doing?", "_subj(_$qVar, you)\n"); rc &= test_sentence ("Are you the one?", "_obj(be, one)\n" + "_subj(be, you)\n"); rc &= test_sentence ("Are you mad?", "_predadj(you, mad)\n"); rc &= test_sentence ("Is the book under the table?", "_pobj(under, table)\n" + "_prepadj(book, under)\n" + "_subj(_%copula, book)\n"); rc &= test_sentence ("Does he seem mad?", "_to-be(seem, mad)\n" + "_subj(seem, he)\n"); rc &= test_sentence ("Does she want to help us?", "_obj(help, us)\n" + "_to-do(want, help)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Does she want you to help us?", "_obj(help, us)\n" + "_subj(help, you)\n" + "_to-do(want, help)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Was she good enough to help?", "_predadj(she, good)\n" + "_to-do(good, help)\n"); rc &= test_sentence ("Must she be able to sing?", "_to-do(able, sing)\n" + "_modal(must, able)\n" + "_predadj(she, able)\n"); rc &= test_sentence ("Does she want to sing?", "_to-do(want, sing)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Have you slept?", "_subj(sleep, you)\n"); rc &= test_sentence ("Will you sleep?", "_subj(sleep, you)\n" + "_modal(will, sleep)\n"); rc &= test_sentence ("Did you sleep?", "_subj(sleep, you)\n"); rc &= test_sentence ("Did you eat the pizza?", "_obj(eat, pizza)\n" + "_subj(eat, you)\n"); rc &= test_sentence ("Did you give her the money?", "_iobj(give, her)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Did you give the money to her?", "_advmod(give, to)\n" + "_pobj(to, her)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Maybe she eats lunch.", "_obj(eat, lunch)\n" + "_advmod(eat, maybe)\n" + "_subj(eat, she)\n"); rc &= test_sentence ("Perhaps she is nice.", "_advmod(nice, perhaps)\n" + "_predadj(she, nice)\n"); rc &= test_sentence ("She wants to help John.", "_to-do(want, help)\n" + "_subj(want, she)\n" + "_obj(help, John)\n"); rc &= test_sentence ("She wants you to help us.", "_to-do(want, help)\n" + "_subj(want, she)\n" + "_obj(help, us)\n" + "_subj(help, you)\n"); rc &= test_sentence ("She is nice to help with the project.", "_pobj(with, project)\n" + "_advmod(help, with)\n" + "_to-do(nice, help)\n" + "_predadj(she, nice)\n"); rc &= test_sentence ("She must be able to sing.", "_to-do(able, sing)\n" + "_modal(must, able)\n" + "_predadj(she, able)\n"); rc &= test_sentence ("She must need to sing?", "_to-do(need, sing)\n" + "_modal(must, need)\n" + "_subj(need, she)\n"); rc &= test_sentence ("She must want to sing?", "_to-do(want, sing)\n" + "_modal(must, want)\n" + "_subj(want, she)\n"); rc &= test_sentence ("She wants to sing.", "_to-do(want, sing)\n" + "_subj(want, she)\n"); rc &= test_sentence ("Where do you live?", "_%atLocation(live, _$qVar)\n" + "_subj(live, you)\n"); rc &= test_sentence ("Where did you eat dinner?", "_%atLocation(eat, _$qVar)\n" + "_obj(eat, dinner)\n" + "_subj(eat, you)\n"); rc &= test_sentence ("Where is the party?", "_%atLocation(_%copula, _$qVar)\n" + "_subj(_%copula, party)\n"); rc &= test_sentence ("Where will she be happy?", "_%atLocation(happy, _$qVar)\n" + "_modal(will, happy)\n" + "_predadj(she, happy)\n"); rc &= test_sentence ("When did jazz die?", "_%atTime(die, _$qVar)\n" + "_subj(die, jazz)\n"); rc &= test_sentence ("When did you bake the cake?", "_%atTime(bake, _$qVar)\n" + "_obj(bake, cake)\n" + "_subj(bake, you)\n"); rc &= test_sentence ("When did you give him the money?", "_iobj(give, him)\n" + "_%atTime(give, _$qVar)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("When is the party?", "_%atTime(_%copula, _$qVar)\n" + "_subj(_%copula, party)\n"); rc &= test_sentence ("Why do you live?", "_%because(live, _$qVar)\n" + "_subj(live, you)\n"); rc &= test_sentence ("Why do you like terrible music?", "_%because(like, _$qVar)/n" + "_obj(like, music)\n" + "_subj(like, you)\n" + "_amod(music, terrible)\n"); rc &= test_sentence ("Why are you such a fool?", "_%because(be, _$qVar)\n" + "_obj(be, fool)\n" + "_subj(be, you)\n"); rc &= test_sentence ("How did you sleep?", "how(sleep, _$qVar)\n" + "_subj(sleep, you)\n"); rc &= test_sentence ("How was the party?", "how(_%copula, _$qVar)\n" + "_subj(_%copula, party)\n"); rc &= test_sentence ("How is your food?", "_poss(food, you)\n" + "how(_%copula, _$qVar)\n" + "_subj(_%copula, food)\n"); rc &= test_sentence ("How much money does it cost?", "_obj(cost, money)\n" + "_subj(cost, it)\n" + "_quantity(money, _$qVar)\n"); rc &= test_sentence ("How many books have you read?", "_obj(read, book)\n" + "_subj(read, you)\n" + "_quantity(book, _$qVar)\n"); rc &= test_sentence ("How fast does it go?", "_subj(go, it)\n" + "_advmod(go, fast)\n" + "_%howdeg(fast, _$qVar)\n" + "_subj(go, it)\n"); rc &= test_sentence ("How stupid are you?", "_%howdeg(stupid, _$qVar)\n" + "_predadj(stupid, you)\n" + "_subj(stupid, you)\n"); rc &= test_sentence ("Which girl do you like?", "_det(girl, _$qVar)\n" + "_obj(like, girl)\n" + "_subj(like, you)\n"); rc &= test_sentence ("Which girl likes you?", "_obj(like, you)\n" + "_subj(like, girl)\n" + "_det(girl, _$qVar)\n"); rc &= test_sentence ("Which girl is crazy?", "_det(girl, _$qVar)\n" + "_predadj(girl, crazy)\n"); rc &= test_sentence ("The books were written by Charles Dickens.", "_obj(write, book)\n" + "_advmod(write, by)\n" + "_pobj(by, Charles_Dickens)\n"); rc &= test_sentence ("The books are published.", "_obj(publish, book)\n"); rc &= test_sentence ("I did my homework, and I went to school.", "_obj(do, homework)\n" + "_subj(do, I)\n" + "_pobj(to, school)\n" + "_advmod(go, to)\n" + "_subj(go, I)\n" + "_poss(homework, me)\n"); rc &= test_sentence ("John and Madison eat the cake.", "_obj(eat, cake)\n" + "_subj(eat, John)\n" + "_subj(eat, Madison)\n" + "conj_and(John, Madison)\n"); rc &= test_sentence ("Joan is poor but happy.", "conj_but(poor, happy)\n" + "_predadj(Joan, poor)\n" + "_predadj(Joan, happy)\n"); rc &= test_sentence ("I think that dogs can fly.", "_rep(think, that)\n" + "_comp(that, fly)\n" + "_subj(think, I)\n" + "_modal(can, fly)\n" + "_subj(fly, dog)\n"); rc &= test_sentence ("He is glad that she won.", "_rep(glad, that)\n" + "_comp(that, win)\n" + "_subj(win, she)\n" + "_predadj(he, glad)\n"); rc &= test_sentence ("He ran so quickly that he flew.", "_comp(that, fly)\n" + "_advmod(quickly, so_that)\n" + "_subj(fly, he)\n" + "_compmod(so_that, that)\n" + "_advmod(run, quickly)\n" + "_subj(run, he)\n"); rc &= test_sentence ("Who are you?", "_subj(_%copula, you)\n"); rc &= test_sentence ("Who do you love?", "_obj(love, _$qVar)\n" + "_subj(love, you)\n"); rc &= test_sentence ("What do you think?", "_obj(think, _$qVar)\n" + "_subj(think, you)\n"); rc &= test_sentence ("To whom did you sell the children?", "_advmod(sell, to)\n" + "_obj(sell, child)\n" + "_subj(sell, you)\n" + "_pobj(to, _$qVar)\n"); rc &= test_sentence ("Why did you give him the money?", "_iobj(give, him)\n" + "_obj(give, money)\n" + "_subj(give, you)\n"); rc &= test_sentence ("Why are you so stupid?", "_%because(stupid, _$qVar)\n" + "_advmod(stupid, so)\n" + "_predadj(you, stupid)\n"); rc &= test_sentence ("How did you like the movie?", "_obj(like, movie)\n" + "how(like, _$qVar)\n" + "_subj(like, you)\n"); rc &= test_sentence ("How did you send him the message?", "_iobj(send, him)\n" + "_obj(send, message)\n" + "how(send, _$qVar)\n" + "_subj(send, you)\n"); report(rc, "Interrogatives"); return rc; } public boolean test_adverbials_adjectivals() { boolean rc = true; rc &= test_sentence ("He ran like the wind.", "_advmod(run, like)\n" + "_subj(run, he)\n" + "_pobj(like, wind)\n"); rc &= test_sentence ("He was boring to an insufferable degree.", "_advmod(boring, to)\n" + "_amod(degree, insufferable)\n" + "_pobj(to, degree)\n" + "_predadj(he, boring)\n"); rc &= test_sentence ("He spoke in order to impress himself.", "_goal(speak, impress)\n" + "_subj(speak, he)\n" + "_obj(impress, himself)\n"); rc &= test_sentence ("On Tuesday, he slept late.", "_advmod(sleep, on)\n" + "_advmod(sleep, late)\n" + "_subj(sleep, he)\n" + "_pobj(on, Tuesday)\n"); rc &= test_sentence ("Often, people confused him.", "_obj(confuse, him)\n" + "_advmod(confuse, often)\n" + "_subj(confuse, people)\n"); rc &= test_sentence ("The man in window is a spy.", "_obj(be, spy)\n" + "_subj(be, man)\n" + "_pobj(in, window)\n" + "_prepadj(man, in)\n"); rc &= test_sentence ("He wrote largely in his spare time.", "_advmod(write, in)\n" + "_subj(write, he)\n" + "_amod(time, spare)\n" + "_poss(time, him)\n" + "_pobj(in, time)\n" + "_advmod(in, largely)\n"); rc &= test_sentence ("The man running away from us is a thief.", "_obj(be, thief)\n" + "_subj(be, man)\n" + "_pobj(from, us)\n" + "_advmod(run_away, from)\n" + "_amod(man, run_away)\n"); rc &= test_sentence ("Among the employees was a deranged killer.", "_pobj(among, employee)\n" + "_amod(killer, deranged)\n" + "_predadj(killer, among)\n" + "_subj(be, killer)\n"); report(rc, "Adverbials and Adjectivals"); return rc; } public boolean test_complementation() { boolean rc = true; rc &= test_sentence ("The dog chasing the bird is happy.", "_obj(chase, bird)\n" + "_predadj(dog, happy)\n" + "_comp(dog, chase)\n"); rc &= test_sentence ("My sister always opens her mouth while eating.", "_obj(open, mouth)\n" + "_advmod(open, always)\n" + "_compmod(open, while)\n" + "_subj(open, My_sister)\n" + "_comp(while, eat)\n" + "_poss(mouth, her)\n"); rc &= test_sentence ("Aaron always reads while he rides the train.", "_advmod(read, always)\n" + "_compmod(read, while)\n" + "_subj(read, Aaron)\n" + "_obj(ride, train)\n" + "_subj(ride, he)\n" + "_comp(while, ride)\n"); rc &= test_sentence ("I sing because I'm happy.", "_%because(sing, because)\n" + "_subj(sing, I)\n" + "_predadj(I, happy)\n" + "_comp(because, happy)\n"); rc &= test_sentence ("I know that you love me.", "_rep(know, that)\n" + "_subj(know, I)\n" + "_obj(love, me)\n" + "_subj(love, you)\n" + "_comp(that, love)\n"); rc &= test_sentence ("I know you hate me.", "_rep(know, hate)\n" + "_subj(know, I)\n" + "_obj(hate, me)\n" + "_subj(hate, you)\n"); rc &= test_sentence ("I am certain that you are insane.", "_rep(certain, that)\n" + "_predadj(you, insane)\n" + "_comp(that, insane)\n" + "_predadj(I, certain)\n"); rc &= test_sentence ("The idea that he would invent AGI obsessed him.", "_obj(obsess, him)\n" + "_subj(obsess, idea)\n" + "_to-do(would, invent)\n" + "_comp(that, would)\n" + "_obj(invent, AGI)\n" + "_subj(invent, he)\n" + "_rep(idea, that)\n"); report(rc, "Complementation"); return rc; } public boolean test_special_preposition_stuff() { boolean rc = true; rc &= test_sentence ("Who did you give the book to?", "_advmod(give, to)\n" + "_obj(give, book)\n" + "_subj(give, you)\n" + "_pobj(to, _$qVar)\n"); rc &= test_sentence ("The people on whom you rely are sick.", "_advmod(rely, on)\n" + "_subj(rely, you)\n" + "_pobj(on, people)\n" + "_comp(on, rely)\n" + "_predadj(people, sick)\n"); report(rc, "Special preposition stuff"); return rc; } public static void main(String[] args) { setUpClass(); TestRelEx ts = new TestRelEx(); ts.runTests(); } // @Test public void runTests() { TestRelEx ts = this; boolean rc = true; rc &= ts.test_determiners(); rc &= ts.test_time(); rc &= ts.test_comparatives(); rc &= ts.test_equatives(); rc &= ts.test_extraposition(); rc &= ts.test_conjunctions(); rc &= ts.test_interrogatives(); if (rc) { System.err.println("Tested a total of " + ts.pass + " sentences, test passed OK"); } else { int total = ts.fail + ts.pass; System.err.println("Test failed; out of a total of " + total + " test sentences,\n\t" + ts.fail + " sentences failed\n\t" + ts.pass + " sentences passed"); } System.err.println("******************************"); System.err.println("Failed test sentences on Relex"); System.err.println("******************************"); if (sentfail.isEmpty()) System.err.println("All test sentences passed"); for(String temp : sentfail){ System.err.println(temp); } System.err.println("******************************\n"); } }
Added test case for one failing sentence
src/java_test/relex/test/TestRelEx.java
Added test case for one failing sentence
<ide><path>rc/java_test/relex/test/TestRelEx.java <ide> "_advmod(run, quietly)\n" + <ide> "_subj(run, she)\n" + <ide> "conj_and(quickly, quietly)\n"); <add> // conjoined verbs same object <add> rc &= test_sentence ("He steals and eats the orange.", <add> "_obj(steal, orange)\n" + <add> "_obj(eat, orange)\n" + <add> "_subj(steal, he)\n" + <add> "_subj(eat, he)\n" + <add> "conj_and(steal, eat)\n"); <ide> // adjectival modifiers on conjoined subject <ide> rc &= test_sentence ("The big truck and the little car collided.", <ide> "_amod(car, little)\n" +
JavaScript
mit
2d9ef421a21edadad6e2c7931af0eaf30110f145
0
d4rkd0s/bob,d4rkd0s/bob
$(function() { window.onload = function() { console.log("%c ~~~ Bob v0.2 - Developed by d4rkd0s ~~~ ", "color: #FFFFFF; font-size: 12px; background: #3F1338;"); var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { //setting up starting vars score = 0; console.log("%c score: 0 ", "color: #FFFFFF; font-size: 12px; background: #FD8223;"); lives = 3; console.log("%c lives: 3 ", "color: #FFFFFF; font-size: 12px; background: #FD8223;"); //game.load.image('bob', 'assets/images/bob.png'); game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80); console.log("%c loaded: spritesheet ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); game.load.image('apple', 'assets/images/apple_red.png'); game.load.image('background', 'assets/images/background.png'); console.log("%c loaded: background ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); //game.load.image('healthbar', 'assets/images/healthbar.png'); //console.log("%c loaded: healthbar ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); game.load.image('ocean', 'assets/images/ocean.png'); console.log("%c loaded: horse ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); game.load.image('horse', 'assets/images/horse.png'); console.log("%c set border: ocean ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); cursors = game.input.keyboard.createCursorKeys(); console.log("%c user input: enabled ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); //game.load.audio('jumpsound', 'assets/sounds/jump.wav'); //walking case switch function coroutine(f) { var o = f(); // instantiate the coroutine o.next(); // execute until the first yield return function(x) { o.next(x); } } var clock = coroutine(function*(_) { while (true) { yield _; foot = 0; yield _; foot = 1; } }); //walk step speed in ms setInterval(clock, 100); //notify user (console) console.log("%c walking: enabled ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); }//preload function create() { // A simple background for our game game.add.sprite(0, 0, 'background'); console.log("%c spawned: background ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;"); //Game Objects player = game.add.sprite(775, game.world.height - 150, 'bob'); console.log("%c spawned: player ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;"); apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple'); //var healthbar = game.add.sprite(0,0,'healthbar'); //healthbar.cropEnabled = true; //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width //text = "Score: " . score; //style = { font: "32px Arial", fill: "#3D4185", align: "center" }; //game.add.text(game.world.centerX-300, 0, text, style); //sound //jumpsound = game.add.audio('jumpsound'); //jumpsound.allowMultiple = false; ocean = game.add.sprite(0, game.world.height - 484, 'ocean'); console.log("%c spawned: border(ocean) ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;"); //add horse horse = game.add.sprite(450, game.world.height - 300, 'horse'); //ocean game.physics.enable(ocean, Phaser.Physics.ARCADE); console.log("%c physics: enabled(ocean) ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); ocean.body.immovable = true; console.log("%c locked: border(ocean) ", "color: #FFFFFF; font-size: 10px; background: #A40E38;"); //start physics game.physics.startSystem(Phaser.Physics.ARCADE); console.log("%c physics: enabled(player) ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); game.physics.arcade.enable(player); game.physics.arcade.enableBody(player); console.log("%c physics: bounds(player) ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); game.physics.arcade.enable(horse); game.physics.arcade.enableBody(horse); game.physics.arcade.enable(apple); game.physics.arcade.enableBody(apple); player.body.collideWorldBounds = true; horse.body.collideWorldBounds = true; apple.body.collideWorldBounds = true; console.log("%c collideWorldBounds: enabled ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); }//create() function update() { //ocean collision game.physics.arcade.collide(player, ocean); game.physics.arcade.collide(player, horse); game.physics.arcade.collide(player, apple); game.physics.arcade.collide(ocean, apple); game.physics.arcade.collide(horse, ocean); //horse.body.accelerateToObject(horse, player, 600, 250, 250); // Reset the players velocity (movement) player.body.velocity.x = 0; player.body.velocity.y = 0; horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50); if ( apple.alive == true){ if ( game.physics.arcade.collide(apple, player) == true ){ score = score + 1; apple.kill(); console.log(score); } if ( game.physics.arcade.collide(apple, horse) == true ){ score = score - 1; apple.kill(); console.log(score); } } else{ randY = Math.floor(Math.random()*(800-50+1)+50); randX = Math.floor(Math.random()*(300-50+1)+50); apple = game.add.sprite(randX, randY, 'apple'); game.physics.arcade.enable(apple); game.physics.arcade.enableBody(apple); apple.body.collideWorldBounds = true; game.physics.arcade.collide(player, apple); game.physics.arcade.collide(ocean, apple); } if (cursors.left.isDown) { if (cursors.up.isDown) { // Move to the left+up player.body.velocity.x = -100; player.body.velocity.y = -100; if ( foot == 0 ){ player.frame = 4; } if ( foot == 1 ){ player.frame = 5; } } else if (cursors.down.isDown) { // Move to the left+down player.body.velocity.x = -100; player.body.velocity.y = 100; if ( foot == 0 ){ player.frame = 4; } if ( foot == 1 ){ player.frame = 5; } } else { // Move to the left player.body.velocity.x = -180; if ( foot == 0 ){ player.frame = 4; } if ( foot == 1 ){ player.frame = 5; } } } else if (cursors.right.isDown) { if (cursors.up.isDown) { // Move to the right+up player.body.velocity.x = 100; player.body.velocity.y = -100; if ( foot == 0 ){ player.frame = 6; } if ( foot == 1 ){ player.frame = 7; } } else if (cursors.down.isDown) { // Move to the right+down player.body.velocity.x = 100; player.body.velocity.y = 100; if ( foot == 0 ){ player.frame = 6; } if ( foot == 1 ){ player.frame = 7; } } else { // Move to the right player.body.velocity.x = 180; if ( foot == 0 ){ player.frame = 6; } if ( foot == 1 ){ player.frame = 7; } } } else if (cursors.up.isDown) { // Move to the up player.body.velocity.y = -180; if ( foot == 0 ){ player.frame = 2; } if ( foot == 1 ){ player.frame = 3; } } else if (cursors.down.isDown) { // Move to the down player.body.velocity.y = 180; if ( foot == 0 ){ player.frame = 0; } if ( foot == 1 ){ player.frame = 1; } } } //update }; });
game.js
$(function() { window.onload = function() { console.log("%c ~~~ Bob v0.2 - Developed by d4rkd0s ~~~ ", "color: #FFFFFF; font-size: 12px; background: #3F1338;"); var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { //setting up starting vars score = 0; console.log("%c score: 0 ", "color: #FFFFFF; font-size: 12px; background: #FD8223;"); lives = 3; console.log("%c lives: 3 ", "color: #FFFFFF; font-size: 12px; background: #FD8223;"); //game.load.image('bob', 'assets/images/bob.png'); game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80); console.log("%c loaded: spritesheet ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); game.load.image('apple', 'assets/images/apple_red.png'); game.load.image('background', 'assets/images/background.png'); console.log("%c loaded: background ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); //game.load.image('healthbar', 'assets/images/healthbar.png'); //console.log("%c loaded: healthbar ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); game.load.image('ocean', 'assets/images/ocean.png'); console.log("%c loaded: horse ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); game.load.image('horse', 'assets/images/horse.png'); console.log("%c set border: ocean ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); cursors = game.input.keyboard.createCursorKeys(); console.log("%c user input: enabled ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); //game.load.audio('jumpsound', 'assets/sounds/jump.wav'); //walking case switch function coroutine(f) { var o = f(); // instantiate the coroutine o.next(); // execute until the first yield return function(x) { o.next(x); } } var clock = coroutine(function*(_) { while (true) { yield _; foot = 0; yield _; foot = 1; } }); //walk step speed in ms setInterval(clock, 100); //notify user (console) console.log("%c walking: enabled ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;"); }//preload function create() { // A simple background for our game game.add.sprite(0, 0, 'background'); console.log("%c spawned: background ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;"); //Game Objects player = game.add.sprite(775, game.world.height - 150, 'bob'); console.log("%c spawned: player ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;"); apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple'); //var healthbar = game.add.sprite(0,0,'healthbar'); //healthbar.cropEnabled = true; //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width //text = "Score: " . score; //style = { font: "32px Arial", fill: "#3D4185", align: "center" }; //game.add.text(game.world.centerX-300, 0, text, style); //sound //jumpsound = game.add.audio('jumpsound'); //jumpsound.allowMultiple = false; ocean = game.add.sprite(0, game.world.height - 484, 'ocean'); console.log("%c spawned: border(ocean) ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;"); //add horse horse = game.add.sprite(450, game.world.height - 300, 'horse'); //ocean game.physics.enable(ocean, Phaser.Physics.ARCADE); console.log("%c physics: enabled(ocean) ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); ocean.body.immovable = true; console.log("%c locked: border(ocean) ", "color: #FFFFFF; font-size: 10px; background: #A40E38;"); //start physics game.physics.startSystem(Phaser.Physics.ARCADE); console.log("%c physics: enabled(player) ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); game.physics.arcade.enable(player); game.physics.arcade.enableBody(player); console.log("%c physics: bounds(player) ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); game.physics.arcade.enable(horse); game.physics.arcade.enableBody(horse); game.physics.arcade.enable(apple); game.physics.arcade.enableBody(apple); player.body.collideWorldBounds = true; horse.body.collideWorldBounds = true; apple.body.collideWorldBounds = true; console.log("%c collideWorldBounds: enabled ", "color: #FFFFFF; font-size: 10px; background: #83CB53;"); }//create() function update() { //ocean collision game.physics.arcade.collide(player, ocean); game.physics.arcade.collide(player, horse); game.physics.arcade.collide(player, apple); game.physics.arcade.collide(ocean, apple); game.physics.arcade.collide(horse, ocean); //horse.body.accelerateToObject(horse, player, 600, 250, 250); // Reset the players velocity (movement) player.body.velocity.x = 0; player.body.velocity.y = 0; horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50); randY = Math.floor(Math.random()*(800-50+1)+50); randX = Math.floor(Math.random()*(300-50+1)+50); if ( apple.alive == true){ if ( game.physics.arcade.collide(apple, player) == true ){ score = score + 1; apple.kill(); console.log(score); } if ( game.physics.arcade.collide(apple, horse) == true ){ score = score - 1; apple.kill(); console.log(score); } } else{ apple = game.add.sprite(randX, randY, 'apple'); game.physics.arcade.enable(apple); game.physics.arcade.enableBody(apple); apple.body.collideWorldBounds = true; game.physics.arcade.collide(player, apple); game.physics.arcade.collide(ocean, apple); } if (cursors.left.isDown) { if (cursors.up.isDown) { // Move to the left+up player.body.velocity.x = -100; player.body.velocity.y = -100; if ( foot == 0 ){ player.frame = 4; } if ( foot == 1 ){ player.frame = 5; } } else if (cursors.down.isDown) { // Move to the left+down player.body.velocity.x = -100; player.body.velocity.y = 100; if ( foot == 0 ){ player.frame = 4; } if ( foot == 1 ){ player.frame = 5; } } else { // Move to the left player.body.velocity.x = -180; if ( foot == 0 ){ player.frame = 4; } if ( foot == 1 ){ player.frame = 5; } } } else if (cursors.right.isDown) { if (cursors.up.isDown) { // Move to the right+up player.body.velocity.x = 100; player.body.velocity.y = -100; if ( foot == 0 ){ player.frame = 6; } if ( foot == 1 ){ player.frame = 7; } } else if (cursors.down.isDown) { // Move to the right+down player.body.velocity.x = 100; player.body.velocity.y = 100; if ( foot == 0 ){ player.frame = 6; } if ( foot == 1 ){ player.frame = 7; } } else { // Move to the right player.body.velocity.x = 180; if ( foot == 0 ){ player.frame = 6; } if ( foot == 1 ){ player.frame = 7; } } } else if (cursors.up.isDown) { // Move to the up player.body.velocity.y = -180; if ( foot == 0 ){ player.frame = 2; } if ( foot == 1 ){ player.frame = 3; } } else if (cursors.down.isDown) { // Move to the down player.body.velocity.y = 180; if ( foot == 0 ){ player.frame = 0; } if ( foot == 1 ){ player.frame = 1; } } } //update }; });
Gen on apple get()
game.js
Gen on apple get()
<ide><path>ame.js <ide> <ide> horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50); <ide> <del> randY = Math.floor(Math.random()*(800-50+1)+50); <del> randX = Math.floor(Math.random()*(300-50+1)+50); <add> <ide> <ide> if ( apple.alive == true){ <ide> if ( game.physics.arcade.collide(apple, player) == true ){ <ide> } <ide> } <ide> else{ <add> randY = Math.floor(Math.random()*(800-50+1)+50); <add> randX = Math.floor(Math.random()*(300-50+1)+50); <ide> apple = game.add.sprite(randX, randY, 'apple'); <ide> game.physics.arcade.enable(apple); <ide> game.physics.arcade.enableBody(apple);
Java
bsd-2-clause
2d87b1fdb55b7eb38ded91d50db6600b5aa16a79
0
wsldl123292/jodd,javachengwc/jodd,oetting/jodd,Artemish/jodd,oetting/jodd,mtakaki/jodd,mohanaraosv/jodd,southwolf/jodd,vilmospapp/jodd,wsldl123292/jodd,wjw465150/jodd,mohanaraosv/jodd,wsldl123292/jodd,javachengwc/jodd,Artemish/jodd,Artemish/jodd,tempbottle/jodd,Artemish/jodd,mosoft521/jodd,vilmospapp/jodd,oblac/jodd,tempbottle/jodd,javachengwc/jodd,wjw465150/jodd,vilmospapp/jodd,southwolf/jodd,oetting/jodd,mtakaki/jodd,mosoft521/jodd,wjw465150/jodd,Artemish/jodd,mtakaki/jodd,oblac/jodd,mtakaki/jodd,vilmospapp/jodd,wjw465150/jodd,javachengwc/jodd,wsldl123292/jodd,oblac/jodd,tempbottle/jodd,southwolf/jodd,oblac/jodd,tempbottle/jodd,mohanaraosv/jodd,mosoft521/jodd,southwolf/jodd,oetting/jodd,mohanaraosv/jodd,vilmospapp/jodd,mosoft521/jodd
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved. package examples.util; import static jodd.util.ref.ReferenceType.*; import jodd.util.ref.ReferenceMap; import jodd.util.ref.ReferenceSet; import jodd.util.ThreadUtil; public class Weaks { public static void main(String[] args) { valueExample(); System.out.println("------------"); keyExample(); System.out.println("------------"); setExample(); } static void valueExample() { //ReferenceMap rm = new ReferenceMap(STRONG, STRONG); // false //ReferenceMap rm = new ReferenceMap(STRONG, SOFT); // false ReferenceMap rm = new ReferenceMap(STRONG, WEAK); // true String value = new String("value"); rm.put("key", value); System.out.println(rm.isEmpty()); value = null; System.gc(); System.gc(); ThreadUtil.sleep(5000); System.out.println(rm.isEmpty()); } static void keyExample() { ReferenceMap<String, String> rm = new ReferenceMap<String, String>(WEAK, STRONG); // true //ReferenceMap rm = new ReferenceMap(STRONG, STRONG); // false String key = "key"; rm.put(key, "value"); System.out.println(rm.isEmpty()); key = null; System.gc(); System.gc(); ThreadUtil.sleep(5000); System.out.println(rm.isEmpty()); } static void setExample() { ReferenceSet rs = new ReferenceSet(WEAK); // true String value = new String("value"); rs.add(value); System.out.println(rs.isEmpty()); value = null; System.gc(); System.gc(); ThreadUtil.sleep(5000); System.out.println(rs.isEmpty()); } }
mod/samples/src/examples/util/Weaks.java
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved. package examples.util; import static jodd.util.ref.ReferenceType.*; import jodd.util.ref.ReferenceMap; import jodd.util.ref.ReferenceSet; import jodd.util.ThreadUtil; public class Weaks { public static void main(String[] args) { valueExample(); System.out.println("------------"); keyExample(); System.out.println("------------"); setExample(); } static void valueExample() { //ReferenceMap rm = new ReferenceMap(STRONG, STRONG); // false //ReferenceMap rm = new ReferenceMap(STRONG, SOFT); // false ReferenceMap rm = new ReferenceMap(STRONG, WEAK); // true String value = new String("value"); rm.put("key", value); System.out.println(rm.isEmpty()); value = null; System.gc(); System.gc(); ThreadUtil.sleep(5000); System.out.println(rm.isEmpty()); } static void keyExample() { ReferenceMap rm = new ReferenceMap(WEAK, STRONG); // true //ReferenceMap rm = new ReferenceMap(STRONG, STRONG); // false String key = new String("key"); rm.put(key, "value"); System.out.println(rm.isEmpty()); key = null; System.gc(); System.gc(); ThreadUtil.sleep(5000); System.out.println(rm.isEmpty()); } static void setExample() { ReferenceSet rs = new ReferenceSet(WEAK); // true String value = new String("value"); rs.add(value); System.out.println(rs.isEmpty()); value = null; System.gc(); System.gc(); ThreadUtil.sleep(5000); System.out.println(rs.isEmpty()); } }
generics added to the example
mod/samples/src/examples/util/Weaks.java
generics added to the example
<ide><path>od/samples/src/examples/util/Weaks.java <ide> } <ide> <ide> static void keyExample() { <del> ReferenceMap rm = new ReferenceMap(WEAK, STRONG); // true <add> ReferenceMap<String, String> rm = new ReferenceMap<String, String>(WEAK, STRONG); // true <ide> //ReferenceMap rm = new ReferenceMap(STRONG, STRONG); // false <del> String key = new String("key"); <add> String key = "key"; <ide> rm.put(key, "value"); <ide> System.out.println(rm.isEmpty()); <ide>
Java
mit
c66ec92e1a134d984c8bc395137b68454aa2ec51
0
mezz/JustEnoughItems,mezz/JustEnoughItems
package mezz.jei.load; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import net.minecraft.resources.ResourceLocation; import com.google.common.base.Stopwatch; import mezz.jei.api.IModPlugin; import mezz.jei.plugins.vanilla.VanillaPlugin; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class PluginCaller { private static final Logger LOGGER = LogManager.getLogger(); public static void callOnPlugins(String title, List<IModPlugin> plugins, Consumer<IModPlugin> func) { List<IModPlugin> erroredPlugins = new ArrayList<>(); for (IModPlugin plugin : plugins) { try { ResourceLocation pluginUid = plugin.getPluginUid(); LOGGER.info("{}: {} ...", title, pluginUid); Stopwatch stopwatch = Stopwatch.createStarted(); func.accept(plugin); LOGGER.info("{}: {} took {}", title, pluginUid, stopwatch); } catch (RuntimeException | LinkageError e) { if (plugin instanceof VanillaPlugin) { throw e; } LOGGER.error("Caught an error from mod plugin: {} {}", plugin.getClass(), plugin.getPluginUid(), e); erroredPlugins.add(plugin); } } plugins.removeAll(erroredPlugins); } }
src/main/java/mezz/jei/load/PluginCaller.java
package mezz.jei.load; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import net.minecraft.resources.ResourceLocation; import com.google.common.base.Stopwatch; import mezz.jei.api.IModPlugin; import mezz.jei.plugins.vanilla.VanillaPlugin; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class PluginCaller { private static final Logger LOGGER = LogManager.getLogger(); public static void callOnPlugins(String title, List<IModPlugin> plugins, Consumer<IModPlugin> func) { List<IModPlugin> erroredPlugins = new ArrayList<>(); for (IModPlugin plugin : plugins) { try { ResourceLocation pluginUid = plugin.getPluginUid(); LOGGER.debug("{}: {} ...", title, pluginUid); Stopwatch stopwatch = Stopwatch.createStarted(); func.accept(plugin); LOGGER.debug("{}: {} took {}", title, pluginUid, stopwatch); } catch (RuntimeException | LinkageError e) { if (plugin instanceof VanillaPlugin) { throw e; } LOGGER.error("Caught an error from mod plugin: {} {}", plugin.getClass(), plugin.getPluginUid(), e); erroredPlugins.add(plugin); } } plugins.removeAll(erroredPlugins); } }
Log plugin load times at info level
src/main/java/mezz/jei/load/PluginCaller.java
Log plugin load times at info level
<ide><path>rc/main/java/mezz/jei/load/PluginCaller.java <ide> for (IModPlugin plugin : plugins) { <ide> try { <ide> ResourceLocation pluginUid = plugin.getPluginUid(); <del> LOGGER.debug("{}: {} ...", title, pluginUid); <add> LOGGER.info("{}: {} ...", title, pluginUid); <ide> Stopwatch stopwatch = Stopwatch.createStarted(); <ide> func.accept(plugin); <del> LOGGER.debug("{}: {} took {}", title, pluginUid, stopwatch); <add> LOGGER.info("{}: {} took {}", title, pluginUid, stopwatch); <ide> } catch (RuntimeException | LinkageError e) { <ide> if (plugin instanceof VanillaPlugin) { <ide> throw e;
Java
mit
a5a6841899f93fded5f413b569ef5c0ef23a43bc
0
mcflugen/wmt-rest,mcflugen/wmt-rest
/** * <License> */ package edu.colorado.csdms.wmt.client.control; import java.util.HashMap; import java.util.Map.Entry; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Window; import edu.colorado.csdms.wmt.client.data.ComponentJSO; import edu.colorado.csdms.wmt.client.data.ComponentListJSO; import edu.colorado.csdms.wmt.client.data.ModelJSO; import edu.colorado.csdms.wmt.client.data.ModelListJSO; import edu.colorado.csdms.wmt.client.data.ModelMetadataJSO; import edu.colorado.csdms.wmt.client.ui.RunInfoDialogBox; /** * A class that defines static methods for accessing, modifying and deleting, * through asynchronous HTTP GET and POST requests, the JSON files used to set * up, configure and run WMT. * * @author Mark Piper ([email protected]) */ public class DataTransfer { private static final String ERR_MSG = "Failed to send the request: "; /** * A JSNI method for creating a String from a JavaScriptObject. * * @see <a * href="http://stackoverflow.com/questions/4872770/excluding-gwt-objectid-from-json-stringifyjso-in-devmode">this</a> * discussion of '__gwt_ObjectId' * @param jso a JavaScriptObject * @return a String representation of the JavaScriptObject */ public final native static <T> String stringify(T jso) /*-{ return JSON.stringify(jso, function(key, value) { if (key == '__gwt_ObjectId') { return; } return value; }); }-*/; /** * A JSNI method for evaluating JSONs. This is a generic method. It returns * a JavaScript object of the type denoted by the type parameter T. * * @see <a * href="http://docs.oracle.com/javase/tutorial/extra/generics/methods.html">Generic * Methods</a> * @see <a * href="http://stackoverflow.com/questions/1843343/json-parse-vs-eval">JSON.parse * vs. eval()</a> * * @param jsonStr a trusted String * @return a JavaScriptObject that can be cast to an overlay type */ public final native static <T> T parse(String jsonStr) /*-{ return JSON.parse(jsonStr); }-*/; /** * Returns a deep copy of the input JavaScriptObject. * <p> * This is the public interface to {@link #copyImpl(JavaScriptObject)}, * which does the heavy lifting. * * @param jso a JavaScriptObject */ @SuppressWarnings("unchecked") public static <T extends JavaScriptObject> T copy(T jso) { return (T) copyImpl(jso); } /** * A recursive JSNI method for making a deep copy of an input * JavaScriptObject. This is the private implementation of * {@link #copy(JavaScriptObject)}. * * @see <a * href="http://stackoverflow.com/questions/4730463/gwt-overlay-deep-copy" * >This</a> example code was very helpful (thanks to the author, <a * href="http://stackoverflow.com/users/247462/javier-ferrero">Javier * Ferrero</a>!) * @param obj */ private static native JavaScriptObject copyImpl(JavaScriptObject obj) /*-{ if (obj == null) return obj; var copy; if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); } else if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { if (obj[i] == null || typeof obj[i] != "object") copy[i] = obj[i]; else copy[i] = @edu.colorado.csdms.wmt.client.control.DataTransfer::copyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]); } } else { copy = {}; for ( var attr in obj) { if (obj.hasOwnProperty(attr)) { if (obj[attr] == null || typeof obj[attr] != "object") copy[attr] = obj[attr]; else copy[attr] = @edu.colorado.csdms.wmt.client.control.DataTransfer::copyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[attr]); } } } return copy; }-*/; /** * A worker that builds a HTTP query string from a HashMap of key-value * entries. * * @param entries a HashMap of key-value pairs * @return the query, as a String */ private static String buildQueryString(HashMap<String, String> entries) { StringBuilder sb = new StringBuilder(); Integer entryCount = 0; for (Entry<String, String> entry : entries.entrySet()) { if (entryCount > 0) { sb.append("&"); } String encodedName = URL.encodeQueryString(entry.getKey()); sb.append(encodedName); sb.append("="); String encodedValue = URL.encodeQueryString(entry.getValue()); sb.append(encodedValue); entryCount++; } return sb.toString(); } /** * Makes an asynchronous HTTP GET request to retrieve the list of components * stored in the WMT database. * <p> * Note that on completion of the request, * {@link #getComponent(DataManager, String)} starts pulling data for * individual components from the server. * * @param data the DataManager object for the WMT session */ public static void getComponentList(DataManager data) { String url = DataURL.listComponents(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder .sendRequest(null, new ComponentListRequestCallback(data, url)); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to the server to retrieve the data * for a single component. * * @param data the DataManager object for the WMT session * @param componentId the identifier of the component in the database, a * String */ public static void getComponent(DataManager data, String componentId) { String url = DataURL.showComponent(data, componentId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ComponentRequestCallback(data, url)); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to retrieve the list of models * stored in the WMT database. * * @param data the DataManager object for the WMT session */ public static void getModelList(DataManager data) { String url = DataURL.listModels(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ModelListRequestCallback(data, url)); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes a pair of asynchronous HTTP GET requests to retrieve model data and * metadata from a server. * * @param data the DataManager object for the WMT session * @param modelId the unique identifier for the model in the database, an * Integer */ public static void getModel(DataManager data, Integer modelId) { // The "open" URL returns metadata (name, owner) in a ModelMetadataJSO, // while the "show" URL returns data in a ModelJSO. String openURL = DataURL.openModel(data, modelId); GWT.log(openURL); String showURL = DataURL.showModel(data, modelId); GWT.log(showURL); RequestBuilder openBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(openURL)); try { @SuppressWarnings("unused") Request openRequest = openBuilder.sendRequest(null, new ModelRequestCallback(data, openURL, "open")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } RequestBuilder showBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(showURL)); try { @SuppressWarnings("unused") Request showRequest = showBuilder.sendRequest(null, new ModelRequestCallback(data, showURL, "show")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to save a new model, or edits to * an existing model, to the server. * * @param data the DataManager object for the WMT session */ public static void postModel(DataManager data) { Integer modelId = data.getMetadata().getId(); GWT.log("all model ids: " + data.modelIdList.toString()); GWT.log("this model id: " + modelId.toString()); String url; if (data.modelIdList.contains(modelId)) { url = DataURL.editModel(data, modelId); } else { url = DataURL.newModel(data); } GWT.log(url); GWT.log(data.getModelString()); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("name", data.getModel().getName()); entries.put("json", data.getModelString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new ModelRequestCallback(data, url, "new/edit")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to delete a single model from the * WMT server. * * @param data the DataManager object for the WMT session * @param modelId the unique identifier for the model in the database */ public static void deleteModel(DataManager data, Integer modelId) { String url = DataURL.deleteModel(data, modelId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ModelRequestCallback(data, url, "delete")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to initialize a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void initModelRun(DataManager data) { String url = DataURL.newModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("name", data.getModel().getName()); entries.put("description", "A model submitted from the WMT GUI."); // XXX entries.put("model_id", ((Integer)data.getMetadata().getId()).toString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, "init")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to stage a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void stageModelRun(DataManager data) { String url = DataURL.stageModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("uuid", data.getSimulationId()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, "stage")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to launch a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void launchModelRun(DataManager data) { String url = DataURL.launchModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("uuid", data.getSimulationId()); entries.put("host", data.getHostname()); entries.put("username", data.getUsername()); entries.put("password", data.getPassword()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, "launch")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of the list of available components in the WMT database. On * success, the list of component ids are stored in the {@link DataManager} * object for the WMT session. Concurrently, * {@link DataTransfer#getComponent(DataManager, String)} is called to * download and store information on the listed components. */ public static class ComponentListRequestCallback implements RequestCallback { private DataManager data; private String url; public ComponentListRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ComponentListJSO jso = parse(rtxt); // Load the list of components into the DataManager. At the same time, // start pulling down data for the components. Asynchronicity is cool! for (int i = 0; i < jso.getComponents().length(); i++) { String componentId = jso.getComponents().get(i); data.componentIdList.add(componentId); getComponent(data, componentId); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of a component. On success, * {@link DataManager#addComponent(ComponentJSO)} and * {@link DataManager#addModelComponent(ComponentJSO)} are called to store * the (class) component and the model component in the DataManager object * for the WMT session. */ public static class ComponentRequestCallback implements RequestCallback { private DataManager data; private String url; public ComponentRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ComponentJSO jso = parse(rtxt); data.addComponent(jso); // "class" component data.addModelComponent(copy(jso)); // "instance" component, for model } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of the list of available models in the WMT database. On success, * the list of model names and ids are stored in the {@link DataManager} * object for the WMT session. */ public static class ModelListRequestCallback implements RequestCallback { private DataManager data; private String url; public ModelListRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ModelListJSO jso = parse(rtxt); // Start with clean lists of model names and ids. data.modelIdList.clear(); data.modelNameList.clear(); // Load the list of models into the DataManager. for (int i = 0; i < jso.getModels().length(); i++) { data.modelIdList.add(jso.getModels().get(i).getModelId()); data.modelNameList.add(jso.getModels().get(i).getName()); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a model * GET or POST request. * <p> * On a successful GET, {@link DataManager#deserialize()} is called to * populate the WMT GUI. On a successful POST, * {@link DataTransfer#getModelList(DataManager)} is called to refresh the * list of models available on the server. */ public static class ModelRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public ModelRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches("show")) { ModelJSO jso = parse(rtxt); data.setModel(jso); data.modelIsSaved(true); data.deserialize(); } if (type.matches("open")) { ModelMetadataJSO jso = parse(rtxt); data.setMetadata(jso); } if (type.matches("new/edit")) { data.modelIsSaved(true); data.getPerspective().setModelPanelTitle(); DataTransfer.getModelList(data); Integer modelId = Integer.valueOf(rtxt); data.getMetadata().setId(modelId); } if (type.matches("delete")) { DataTransfer.getModelList(data); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * TODO */ public static class RunRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public RunRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches("init")) { String uuid = rtxt.replaceAll("^\"|\"$", ""); data.setSimulationId(uuid); // store the run's uuid DataTransfer.stageModelRun(data); } if (type.matches("stage")) { DataTransfer.launchModelRun(data); } if (type.matches("launch")) { RunInfoDialogBox runInfo = new RunInfoDialogBox(); runInfo.center(); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } }
gui/src/edu/colorado/csdms/wmt/client/control/DataTransfer.java
/** * <License> */ package edu.colorado.csdms.wmt.client.control; import java.util.HashMap; import java.util.Map.Entry; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Window; import edu.colorado.csdms.wmt.client.data.ComponentJSO; import edu.colorado.csdms.wmt.client.data.ComponentListJSO; import edu.colorado.csdms.wmt.client.data.ModelJSO; import edu.colorado.csdms.wmt.client.data.ModelListJSO; import edu.colorado.csdms.wmt.client.data.ModelMetadataJSO; import edu.colorado.csdms.wmt.client.ui.RunInfoDialogBox; /** * A class that defines static methods for accessing, modifying and deleting, * through asynchronous HTTP GET and POST requests, the JSON files used to set * up, configure and run WMT. * * @author Mark Piper ([email protected]) */ public class DataTransfer { private static final String ERR_MSG = "Failed to send the request: "; /** * A JSNI method for creating a String from a JavaScriptObject. * * @see <a * href="http://stackoverflow.com/questions/4872770/excluding-gwt-objectid-from-json-stringifyjso-in-devmode">this</a> * discussion of '__gwt_ObjectId' * @param jso a JavaScriptObject * @return a String representation of the JavaScriptObject */ public final native static <T> String stringify(T jso) /*-{ return JSON.stringify(jso, function(key, value) { if (key == '__gwt_ObjectId') { return; } return value; }); }-*/; /** * A JSNI method for evaluating JSONs. This is a generic method. It returns * a JavaScript object of the type denoted by the type parameter T. * * @see <a * href="http://docs.oracle.com/javase/tutorial/extra/generics/methods.html">Generic * Methods</a> * @see <a * href="http://stackoverflow.com/questions/1843343/json-parse-vs-eval">JSON.parse * vs. eval()</a> * * @param jsonStr a trusted String * @return a JavaScriptObject that can be cast to an overlay type */ public final native static <T> T parse(String jsonStr) /*-{ return JSON.parse(jsonStr); }-*/; /** * Returns a deep copy of the input JavaScriptObject. * <p> * This is the public interface to {@link #copyImpl(JavaScriptObject)}, * which does the heavy lifting. * * @param jso a JavaScriptObject */ @SuppressWarnings("unchecked") public static <T extends JavaScriptObject> T copy(T jso) { return (T) copyImpl(jso); } /** * A recursive JSNI method for making a deep copy of an input * JavaScriptObject. This is the private implementation of * {@link #copy(JavaScriptObject)}. * * @see <a * href="http://stackoverflow.com/questions/4730463/gwt-overlay-deep-copy" * >This</a> example code was very helpful (thanks to the author, <a * href="http://stackoverflow.com/users/247462/javier-ferrero">Javier * Ferrero</a>!) * @param obj */ private static native JavaScriptObject copyImpl(JavaScriptObject obj) /*-{ if (obj == null) return obj; var copy; if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); } else if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { if (obj[i] == null || typeof obj[i] != "object") copy[i] = obj[i]; else copy[i] = @edu.colorado.csdms.wmt.client.control.DataTransfer::copyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]); } } else { copy = {}; for ( var attr in obj) { if (obj.hasOwnProperty(attr)) { if (obj[attr] == null || typeof obj[attr] != "object") copy[attr] = obj[attr]; else copy[attr] = @edu.colorado.csdms.wmt.client.control.DataTransfer::copyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[attr]); } } } return copy; }-*/; /** * A worker that builds a HTTP query string from a HashMap of key-value * entries. * * @param entries a HashMap of key-value pairs * @return the query, as a String */ private static String buildQueryString(HashMap<String, String> entries) { StringBuilder sb = new StringBuilder(); Integer entryCount = 0; for (Entry<String, String> entry : entries.entrySet()) { if (entryCount > 0) { sb.append("&"); } String encodedName = URL.encodeQueryString(entry.getKey()); sb.append(encodedName); sb.append("="); String encodedValue = URL.encodeQueryString(entry.getValue()); sb.append(encodedValue); entryCount++; } return sb.toString(); } /** * Makes an asynchronous HTTP GET request to retrieve the list of components * stored in the WMT database. * <p> * Note that on completion of the request, * {@link #getComponent(DataManager, String)} starts pulling data for * individual components from the server. * * @param data the DataManager object for the WMT session */ public static void getComponentList(DataManager data) { String url = DataURL.listComponents(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder .sendRequest(null, new ComponentListRequestCallback(data, url)); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to the server to retrieve the data * for a single component. * * @param data the DataManager object for the WMT session * @param componentId the identifier of the component in the database, a * String */ public static void getComponent(DataManager data, String componentId) { String url = DataURL.showComponent(data, componentId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ComponentRequestCallback(data, url)); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP GET request to retrieve the list of models * stored in the WMT database. * * @param data the DataManager object for the WMT session */ public static void getModelList(DataManager data) { String url = DataURL.listModels(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ModelListRequestCallback(data, url)); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes a pair of asynchronous HTTP GET requests to retrieve model data and * metadata from a server. * * @param data the DataManager object for the WMT session * @param modelId the unique identifier for the model in the database, an * Integer */ public static void getModel(DataManager data, Integer modelId) { // The "open" URL returns metadata (name, owner) in a ModelMetadataJSO, // while the "show" URL returns data in a ModelJSO. String openURL = DataURL.openModel(data, modelId); GWT.log(openURL); String showURL = DataURL.showModel(data, modelId); GWT.log(showURL); RequestBuilder openBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(openURL)); try { @SuppressWarnings("unused") Request openRequest = openBuilder.sendRequest(null, new ModelRequestCallback(data, openURL, "open")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } RequestBuilder showBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(showURL)); try { @SuppressWarnings("unused") Request showRequest = showBuilder.sendRequest(null, new ModelRequestCallback(data, showURL, "show")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to save a new model, or edits to * an existing model, to the server. * * @param data the DataManager object for the WMT session */ public static void postModel(DataManager data) { Integer modelId = data.getMetadata().getId(); GWT.log("all model ids: " + data.modelIdList.toString()); GWT.log("this model id: " + modelId.toString()); String url; if (data.modelIdList.contains(modelId)) { url = DataURL.editModel(data, modelId); } else { url = DataURL.newModel(data); } GWT.log(url); GWT.log(data.getModelString()); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("name", data.getModel().getName()); entries.put("json", data.getModelString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new ModelRequestCallback(data, url, "new/edit")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to delete a single model from the * WMT server. * * @param data the DataManager object for the WMT session * @param modelId the unique identifier for the model in the database */ public static void deleteModel(DataManager data, Integer modelId) { String url = DataURL.deleteModel(data, modelId); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); try { @SuppressWarnings("unused") Request request = builder.sendRequest(null, new ModelRequestCallback(data, url, "delete")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to initialize a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void initModelRun(DataManager data) { String url = DataURL.newModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("name", data.getModel().getName()); entries.put("description", "A model submitted from the WMT GUI."); // XXX entries.put("model_id", ((Integer)data.getMetadata().getId()).toString()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, "init")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTP POST request to stage a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void stageModelRun(DataManager data) { String url = DataURL.stageModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("uuid", data.getSimulationId()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, "stage")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * Makes an asynchronous HTTPS POST request to launch a model run on the * selected server. * * @param data the DataManager object for the WMT session */ public static void launchModelRun(DataManager data) { String url = DataURL.launchModelRun(data); GWT.log(url); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url)); HashMap<String, String> entries = new HashMap<String, String>(); entries.put("uuid", data.getSimulationId()); entries.put("host", data.getHostname()); entries.put("username", data.getUsername()); entries.put("password", data.getPassword()); String queryString = buildQueryString(entries); try { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); @SuppressWarnings("unused") Request request = builder.sendRequest(queryString, new RunRequestCallback(data, url, "launch")); } catch (RequestException e) { Window.alert(ERR_MSG + e.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of the list of available components in the WMT database. On * success, the list of component ids are stored in the {@link DataManager} * object for the WMT session. Concurrently, * {@link DataTransfer#getComponent(DataManager, String)} is called to * download and store information on the listed components. */ public static class ComponentListRequestCallback implements RequestCallback { private DataManager data; private String url; public ComponentListRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ComponentListJSO jso = parse(rtxt); // Load the list of components into the DataManager. At the same time, // start pulling down data for the components. Asynchronicity is cool! for (int i = 0; i < jso.getComponents().length(); i++) { String componentId = jso.getComponents().get(i); data.componentIdList.add(componentId); getComponent(data, componentId); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of a component. On success, * {@link DataManager#addComponent(ComponentJSO)} and * {@link DataManager#addModelComponent(ComponentJSO)} are called to store * the (class) component and the model component in the DataManager object * for the WMT session. */ public static class ComponentRequestCallback implements RequestCallback { private DataManager data; private String url; public ComponentRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ComponentJSO jso = parse(rtxt); data.addComponent(jso); // "class" component data.addModelComponent(copy(jso)); // "instance" component, for model } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a GET * request of the list of available models in the WMT database. On success, * the list of model names and ids are stored in the {@link DataManager} * object for the WMT session. */ public static class ModelListRequestCallback implements RequestCallback { private DataManager data; private String url; public ModelListRequestCallback(DataManager data, String url) { this.data = data; this.url = url; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); ModelListJSO jso = parse(rtxt); // Start with clean lists of model names and ids. data.modelIdList.clear(); data.modelNameList.clear(); // Load the list of models into the DataManager. for (int i = 0; i < jso.getModels().length(); i++) { data.modelIdList.add(jso.getModels().get(i).getModelId()); data.modelNameList.add(jso.getModels().get(i).getName()); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * A RequestCallback handler class that provides the callback for a model * GET or POST request. * <p> * On a successful GET, {@link DataManager#deserialize()} is called to * populate the WMT GUI. On a successful POST, * {@link DataTransfer#getModelList(DataManager)} is called to refresh the * list of models available on the server. */ public static class ModelRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public ModelRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches("show")) { ModelJSO jso = parse(rtxt); data.setModel(jso); data.modelIsSaved(true); data.deserialize(); } if (type.matches("open")) { ModelMetadataJSO jso = parse(rtxt); data.setMetadata(jso); } if (type.matches("new/edit")) { DataTransfer.getModelList(data); data.modelIsSaved(true); data.getPerspective().setModelPanelTitle(); } if (type.matches("delete")) { DataTransfer.getModelList(data); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } /** * TODO */ public static class RunRequestCallback implements RequestCallback { private DataManager data; private String url; private String type; public RunRequestCallback(DataManager data, String url, String type) { this.data = data; this.url = url; this.type = type; } @Override public void onResponseReceived(Request request, Response response) { if (Response.SC_OK == response.getStatusCode()) { String rtxt = response.getText(); GWT.log(rtxt); if (type.matches("init")) { String uuid = rtxt.replaceAll("^\"|\"$", ""); data.setSimulationId(uuid); // store the run's uuid DataTransfer.stageModelRun(data); } if (type.matches("stage")) { DataTransfer.launchModelRun(data); } if (type.matches("launch")) { RunInfoDialogBox runInfo = new RunInfoDialogBox(); runInfo.center(); } } else { String msg = "The URL '" + url + "' did not give an 'OK' response. " + "Response code: " + response.getStatusCode(); Window.alert(msg); } } @Override public void onError(Request request, Throwable exception) { Window.alert(ERR_MSG + exception.getMessage()); } } }
Fix issue with the "Save As" dialog popping up when saving an already-saved model Need to store id of saved model.
gui/src/edu/colorado/csdms/wmt/client/control/DataTransfer.java
Fix issue with the "Save As" dialog popping up when saving an already-saved model
<ide><path>ui/src/edu/colorado/csdms/wmt/client/control/DataTransfer.java <ide> data.setMetadata(jso); <ide> } <ide> if (type.matches("new/edit")) { <del> DataTransfer.getModelList(data); <ide> data.modelIsSaved(true); <ide> data.getPerspective().setModelPanelTitle(); <add> DataTransfer.getModelList(data); <add> Integer modelId = Integer.valueOf(rtxt); <add> data.getMetadata().setId(modelId); <ide> } <ide> if (type.matches("delete")) { <ide> DataTransfer.getModelList(data);
JavaScript
apache-2.0
1434a54008bcb1c01f180801f6c7784c251bb5dd
0
redforks/closure-library,joeltine/closure-library,federkasten/closure-library,chone/closure-library,talshani/google-closure-library,gterzian/closure-library,redforks/closure-library,ducklord/closure-library,kencheung/closure-library,concavelenz/closure-library,jupeter/composer-closure-library,mail-apps/closure-library,gfredericks/closure-library,gingerik/closure-library,teppeis/closure-library,jbnicolai/closure-library,closure-library-geeks/closure-library-jp,real/closure-library,moagrius/closure-library,jvu/closure-library,vlkous/closure-library,jooking/closure-library,Prinhotels/closure-library,yathit/closure-library,real/closure-library,gterzian/closure-library,redforks/closure-library,mail-apps/closure-library,moagrius/closure-library,alexg-dev/closure-library,AlexanderZon/closure-library,jbnicolai/closure-library,Dominator008/closure-library,neraliu/closure-library,nicks/closure-library,jeffbcross/closure-library,teppeis/closure-library.old,fivetran/closure-library,grpbwl/closure-library,jhiswin/idiil-closure-library,beni55/closure-library,talshani/google-closure-library,ominux/closure-library,manakor/closure-library,chrisprice/closure-library,gregrperkins/closure-library,AlastairTaft/closure-library,Prinhotels/closure-library,Luzzifa/closure-library,mmazaheri/closure-library,beni55/closure-library,vincenta/closure-library,jooking/closure-library,manakor/closure-library,nanaze/closure,AlexanderZon/closure-library,rikuayanokozy/closure-library,lucidsoftware/closure-library,wagjo/closure-library,Anish2/closure-library,beni55/closure-library,grpbwl/closure-library,fivetran/closure-library,nalaswad/nalaswad-closure,vincenta/closure-library,mrourke/closure-library,joeltine/closure-library,AlexanderZon/closure-library,vlkous/closure-library,moagrius/closure-library,real/closure-library,real/closure-library,codyebberson/closure-library,nanaze/closure-rhino-fork,ominux/closure-library,redforks/closure-library,Aniaf/fkorboukh-js-new,igrep/closure-library,Prinhotels/closure-library,Luzzifa/closure-library,ChadKillingsworth/closure-library,nicks/closure-library,chone/closure-library,Anish2/closure-library,sunilkumargit/closure-library,AlastairTaft/closure-library,Medium/closure-library,valerysamovich/closure-library,mjul/closure-library,alexg-dev/closure-library,metamolecular/closure-library,4u/closure-library,closure-library-geeks/closure-library-jp,jeffbcross/closure-library,plu83/closure-library,knutwalker/google-closure-library,lewistg/closure-library,google/closure-library,Aniaf/fkorboukh-js-new,Luzzifa/closure-library,codyebberson/closure-library,yathit/closure-library,igrep/closure-library,rikuayanokozy/closure-library,kencheung/closure-library,bebbi/closure-library,alexg-dev/closure-library,neraliu/closure-library,gfredericks/closure-library,Medium/closure-library,kangkot/closure-library,federkasten/closure-library,gingerik/closure-library,wenzowski/closure-library,gterzian/closure-library,kencheung/closure-library,maureknob/blockly-maure,rikuayanokozy/closure-library,nanaze/closure-rhino-fork,knutwalker/google-closure-library,maureknob/blockly-maure,nicks/closure-library,Tinkerforge/tvpl-closure-library,rikuayanokozy/closure-library,jvu/closure-library,teppeis/closure-library,gregrperkins/closure-library,bebbi/closure-library,mrourke/closure-library,mjul/closure-library,bebbi/closure-library,Anish2/closure-library,ominux/closure-library,Ju2ender/closure-library,sevaseva/closure-library,jvu/closure-library,jeffbcross/closure-library,kangkot/closure-library,neraliu/closure-library,grpbwl/closure-library,valerysamovich/closure-library,platinumpixs/google-closure-library,bebbi/closure-library,mrourke/closure-library,Dominator008/closure-library,google/closure-library,Ju2ender/closure-library,alexg-dev/closure-library,plu83/closure-library,google/closure-library,lucidsoftware/closure-library,lewistg/closure-library,sevaseva/closure-library,nanaze/closure,wenzowski/closure-library,gterzian/closure-library,Medium/closure-library,ducklord/closure-library,beni55/closure-library,Tinkerforge/tvpl-closure-library,concavelenz/closure-library,ikabirov/closure-library,closure-library-geeks/closure-library-jp,jbnicolai/closure-library,ominux/closure-library,ralic/closure-library,jhiswin/idiil-closure-library,Aniaf/fkorboukh-js-new,Ju2ender/closure-library,jooking/closure-library,joeltine/closure-library,kencheung/closure-library,vincenta/closure-library,sunilkumargit/closure-library,ChadKillingsworth/closure-library,jvu/closure-library,lucidsoftware/closure-library,maureknob/blockly-maure,concavelenz/closure-library,mail-apps/closure-library,nanaze/closure-rhino-fork,teppeis/closure-library,gingerik/closure-library,chrisprice/closure-library,mail-apps/closure-library,google/closure-library,metamolecular/closure-library,gingerik/closure-library,nicks/closure-library,google/closure-library,JasOXIII/closure-library,codyebberson/closure-library,Tinkerforge/tvpl-closure-library,lewistg/closure-library,ducklord/closure-library,mmazaheri/closure-library,moagrius/closure-library,Dominator008/closure-library,Prinhotels/closure-library,JasOXIII/closure-library,plu83/closure-library,JasOXIII/closure-library,teppeis/closure-library,vlkous/closure-library,Anish2/closure-library,metamolecular/closure-library,federkasten/closure-library,Aniaf/fkorboukh-js-new,wagjo/closure-library,EarthShipSolution1/closure-library,4u/closure-library,AlastairTaft/closure-library,vincenta/closure-library,maureknob/blockly-maure,chone/closure-library,concavelenz/closure-library,sevaseva/closure-library,vlkous/closure-library,nalaswad/nalaswad-closure,manakor/closure-library,igrep/closure-library,platinumpixs/google-closure-library,teppeis/closure-library.old,AlexanderZon/closure-library,ralic/closure-library,jooking/closure-library,lucidsoftware/closure-library,ducklord/closure-library,jeffbcross/closure-library,wagjo/closure-library,igrep/closure-library,chrisprice/closure-library,teppeis/closure-library.old,codyebberson/closure-library,platinumpixs/google-closure-library,kangkot/closure-library,plu83/closure-library,mmazaheri/closure-library,joeltine/closure-library,EarthShipSolution1/closure-library,platinumpixs/google-closure-library,ChadKillingsworth/closure-library,jupeter/composer-closure-library,ralic/closure-library,Medium/closure-library,JasOXIII/closure-library,Luzzifa/closure-library,ikabirov/closure-library,jhiswin/idiil-closure-library,yathit/closure-library,neraliu/closure-library,ikabirov/closure-library,ChadKillingsworth/closure-library,wenzowski/closure-library,nalaswad/nalaswad-closure,gfredericks/closure-library,sunilkumargit/closure-library,federkasten/closure-library,grpbwl/closure-library,nalaswad/nalaswad-closure,Ju2ender/closure-library,gfredericks/closure-library,jbnicolai/closure-library,ralic/closure-library,fivetran/closure-library,AlastairTaft/closure-library,EarthShipSolution1/closure-library,ikabirov/closure-library,Dominator008/closure-library,jhiswin/idiil-closure-library,chrisprice/closure-library,Tinkerforge/tvpl-closure-library,talshani/google-closure-library,jupeter/composer-closure-library,manakor/closure-library,chone/closure-library,valerysamovich/closure-library,kangkot/closure-library,sevaseva/closure-library,mrourke/closure-library,sunilkumargit/closure-library,valerysamovich/closure-library,lewistg/closure-library,yathit/closure-library
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of a basic slider control. * * Models a control that allows to select a sub-range within a given * range of values using two thumbs. The underlying range is modeled * as a range model, where the min thumb points to value of the * rangemodel, and the max thumb points to value + extent of the range * model. * * The currently selected range is exposed through methods * getValue() and getExtent(). * * The reason for modelling the basic slider state as value + extent is * to be able to capture both, a two-thumb slider to select a range, and * a single-thumb slider to just select a value (in the latter case, extent * is always zero). We provide subclasses (twothumbslider.js and slider.js) * that model those special cases of this control. * * All rendering logic is left out, so that the subclasses can define * their own rendering. To do so, the subclasses overwrite: * - createDom * - decorateInternal * - getCssClass * */ goog.provide('goog.ui.SliderBase'); goog.provide('goog.ui.SliderBase.Orientation'); goog.require('goog.Timer'); goog.require('goog.dom'); goog.require('goog.dom.a11y'); goog.require('goog.dom.a11y.Role'); goog.require('goog.dom.a11y.State'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.KeyHandler'); goog.require('goog.events.KeyHandler.EventType'); goog.require('goog.events.MouseWheelHandler'); goog.require('goog.events.MouseWheelHandler.EventType'); goog.require('goog.fx.Animation.EventType'); goog.require('goog.fx.Dragger'); goog.require('goog.fx.Dragger.EventType'); goog.require('goog.fx.dom.SlideFrom'); goog.require('goog.math'); goog.require('goog.math.Coordinate'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.RangeModel'); /** * This creates a SliderBase object. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @constructor * @extends {goog.ui.Component} */ goog.ui.SliderBase = function(opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); this.rangeModel = new goog.ui.RangeModel; // Don't use getHandler because it gets cleared in exitDocument. goog.events.listen(this.rangeModel, goog.ui.Component.EventType.CHANGE, this.handleRangeModelChange, false, this); }; goog.inherits(goog.ui.SliderBase, goog.ui.Component); /** * Enum for representing the orientation of the slider. * * @enum {string} */ goog.ui.SliderBase.Orientation = { VERTICAL: 'vertical', HORIZONTAL: 'horizontal' }; /** * Orientation of the slider. * @type {goog.ui.SliderBase.Orientation} * @private */ goog.ui.SliderBase.prototype.orientation_ = goog.ui.SliderBase.Orientation.HORIZONTAL; /** * When the user holds down the mouse on the slider background, the closest * thumb will move in "lock-step" towards the mouse. This number indicates how * long each step should take (in milliseconds). * @type {number} * @private */ goog.ui.SliderBase.MOUSE_DOWN_INCREMENT_INTERVAL_ = 200; /** * How long the animations should take (in milliseconds). * @type {number} * @private */ goog.ui.SliderBase.ANIMATION_INTERVAL_ = 100; /** * The underlying range model * @type {goog.ui.RangeModel} * @protected */ goog.ui.SliderBase.prototype.rangeModel; /** * The minThumb dom-element, pointing to the start of the selected range. * @type {HTMLDivElement} * @protected */ goog.ui.SliderBase.prototype.valueThumb; /** * The maxThumb dom-element, pointing to the end of the selected range. * @type {HTMLDivElement} * @protected */ goog.ui.SliderBase.prototype.extentThumb; /** * The thumb that we should be moving (only relevant when timed move is active). * @type {HTMLDivElement} * @private */ goog.ui.SliderBase.prototype.thumbToMove_; /** * The object handling keyboard events. * @type {goog.events.KeyHandler} * @private */ goog.ui.SliderBase.prototype.keyHandler_; /** * The object handling mouse wheel events. * @type {goog.events.MouseWheelHandler} * @private */ goog.ui.SliderBase.prototype.mouseWheelHandler_; /** * The Dragger for dragging the valueThumb. * @type {goog.fx.Dragger} * @private */ goog.ui.SliderBase.prototype.valueDragger_; /** * The Dragger for dragging the extentThumb. * @type {goog.fx.Dragger} * @private */ goog.ui.SliderBase.prototype.extentDragger_; /** * If we are currently animating the thumb. * @private * @type {boolean} */ goog.ui.SliderBase.prototype.isAnimating_ = false; /** * Whether clicking on the backgtround should move directly to that point. * @private * @type {boolean} */ goog.ui.SliderBase.prototype.moveToPointEnabled_ = false; /** * The amount to increment/decrement for page up/down as well as when holding * down the mouse button on the background. * @private * @type {number} */ goog.ui.SliderBase.prototype.blockIncrement_ = 10; /** * The minimal extent. The class will ensure that the extent cannot shrink * to a value smaller than minExtent. * @private * @type {number} */ goog.ui.SliderBase.prototype.minExtent_ = 0; /** * Returns the CSS class applied to the slider element for the given * orientation. Subclasses must override this method. * @param {goog.ui.SliderBase.Orientation} orient The orientation. * @return {string} The CSS class applied to slider elements. * @protected */ goog.ui.SliderBase.prototype.getCssClass = goog.abstractMethod; /** @inheritDoc */ goog.ui.SliderBase.prototype.createDom = function() { goog.ui.SliderBase.superClass_.createDom.call(this); var element = this.getDomHelper().createDom('div', this.getCssClass(this.orientation_)); this.decorateInternal(element); }; /** * Subclasses must implement this method and set the valueThumb and * extentThumb to non-null values. * @type {function() : void} * @protected */ goog.ui.SliderBase.prototype.createThumbs = goog.abstractMethod; /** @inheritDoc */ goog.ui.SliderBase.prototype.decorateInternal = function(element) { goog.ui.SliderBase.superClass_.decorateInternal.call(this, element); goog.dom.classes.add(element, this.getCssClass(this.orientation_)); this.createThumbs(); this.setAriaRoles(); }; /** * Called when the DOM for the component is for sure in the document. * Subclasses should override this method to set this element's role. */ goog.ui.SliderBase.prototype.enterDocument = function() { goog.ui.SliderBase.superClass_.enterDocument.call(this); // Attach the events this.valueDragger_ = new goog.fx.Dragger(this.valueThumb); this.extentDragger_ = new goog.fx.Dragger(this.extentThumb); // The slider is handling the positioning so make the defaultActions empty. this.valueDragger_.defaultAction = this.extentDragger_.defaultAction = goog.nullFunction; this.keyHandler_ = new goog.events.KeyHandler(this.getElement()); this.mouseWheelHandler_ = new goog.events.MouseWheelHandler( this.getElement()); this.getHandler(). listen(this.valueDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, this.handleBeforeDrag_). listen(this.extentDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, this.handleBeforeDrag_). listen(this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.handleKeyDown_). listen(this.getElement(), goog.events.EventType.MOUSEDOWN, this.handleMouseDown_). listen(this.mouseWheelHandler_, goog.events.MouseWheelHandler.EventType.MOUSEWHEEL, this.handleMouseWheel_); this.getElement().tabIndex = 0; this.updateUi_(); }; /** * Handler for the before drag event. We use the event properties to determine * the new value. * @param {goog.fx.DragEvent} e The drag event used to drag the thumb. * @private */ goog.ui.SliderBase.prototype.handleBeforeDrag_ = function(e) { var thumbToDrag = e.dragger == this.valueDragger_ ? this.valueThumb : this.extentThumb; var value; if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var availHeight = this.getElement().clientHeight - thumbToDrag.offsetHeight; value = (availHeight - e.top) / availHeight * (this.getMaximum() - this.getMinimum()) + this.getMinimum(); } else { var availWidth = this.getElement().clientWidth - thumbToDrag.offsetWidth; value = (e.left / availWidth) * (this.getMaximum() - this.getMinimum()) + this.getMinimum(); } // Bind the value within valid range before calling setThumbPosition_. // This is necessary because setThumbPosition_ is a no-op for values outside // of the legal range. For drag operations, we want the handle to snap to the // last valid value instead of remaining at the previous position. if (e.dragger == this.valueDragger_) { value = Math.min(Math.max(value, this.getMinimum()), this.getValue() + this.getExtent()); } else { value = Math.min(Math.max(value, this.getValue()), this.getMaximum()); } this.setThumbPosition_(thumbToDrag, value); }; /** * Event handler for the key down event. This is used to update the value * based on the key pressed. * @param {goog.events.KeyEvent} e The keyboard event object. * @private */ goog.ui.SliderBase.prototype.handleKeyDown_ = function(e) { var handled = true; switch (e.keyCode) { case goog.events.KeyCodes.HOME: this.animatedSetValue(this.getMinimum()); break; case goog.events.KeyCodes.END: this.animatedSetValue(this.getMaximum()); break; case goog.events.KeyCodes.PAGE_UP: this.moveThumbs(this.getBlockIncrement()); break; case goog.events.KeyCodes.PAGE_DOWN: this.moveThumbs(-this.getBlockIncrement()); break; case goog.events.KeyCodes.LEFT: case goog.events.KeyCodes.DOWN: this.moveThumbs(e.shiftKey ? -this.getBlockIncrement() : -this.getUnitIncrement()); break; case goog.events.KeyCodes.RIGHT: case goog.events.KeyCodes.UP: this.moveThumbs(e.shiftKey ? this.getBlockIncrement() : this.getUnitIncrement()); break; default: handled = false; } if (handled) { e.preventDefault(); } }; /** * Handler for the mouse down event. * @param {goog.events.Event} e The mouse event object. * @private */ goog.ui.SliderBase.prototype.handleMouseDown_ = function(e) { if (this.getElement().focus) { this.getElement().focus(); } // Known Element. var target = /** @type {Element} */ (e.target); if (!goog.dom.contains(this.valueThumb, target) && !goog.dom.contains(this.extentThumb, target)) { if (this.moveToPointEnabled_) { // just set the value directly based on the position of the click this.animatedSetValue(this.getValueFromMousePosition_(e)); } else { // start a timer that incrementally moves the handle this.startBlockIncrementing_(e); } } }; /** * Handler for the mouse wheel event. * @param {goog.events.MouseWheelEvent} e The mouse wheel event object. * @private */ goog.ui.SliderBase.prototype.handleMouseWheel_ = function(e) { // Just move one unit increment per mouse wheel event var direction = e.detail > 0 ? -1 : 1; this.moveThumbs(direction * this.getUnitIncrement()); e.preventDefault(); }; /** * Starts the animation that causes the thumb to increment/decrement by the * block increment when the user presses down on the background. * @param {goog.events.Event} e The mouse event object. * @private */ goog.ui.SliderBase.prototype.startBlockIncrementing_ = function(e) { this.storeMousePos_(e); this.thumbToMove_ = this.getClosestThumb_(this.getValueFromMousePosition_(e)); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { this.incrementing_ = this.lastMousePosition_ < this.thumbToMove_.offsetTop; } else { this.incrementing_ = this.lastMousePosition_ > this.thumbToMove_.offsetLeft + this.thumbToMove_.offsetWidth; } var doc = goog.dom.getOwnerDocument(this.getElement()); this.getHandler(). listen(doc, goog.events.EventType.MOUSEUP, this.handleMouseUp_, true). listen(this.getElement(), goog.events.EventType.MOUSEMOVE, this.storeMousePos_); if (!this.incTimer_) { this.incTimer_ = new goog.Timer( goog.ui.SliderBase.MOUSE_DOWN_INCREMENT_INTERVAL_); this.getHandler().listen(this.incTimer_, goog.Timer.TICK, this.handleTimerTick_); } this.handleTimerTick_(); this.incTimer_.start(); }; /** * Handler for the tick event dispatched by the timer used to update the value * in a block increment. This is also called directly from * startBlockIncrementing_. * @private */ goog.ui.SliderBase.prototype.handleTimerTick_ = function() { var value; if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var mouseY = this.lastMousePosition_; var thumbY = this.thumbToMove_.offsetTop; if (this.incrementing_) { if (mouseY < thumbY) { value = this.getThumbPosition_(this.thumbToMove_) + this.getBlockIncrement(); } } else { var thumbH = this.thumbToMove_.offsetHeight; if (mouseY > thumbY + thumbH) { value = this.getThumbPosition_(this.thumbToMove_) - this.getBlockIncrement(); } } } else { var mouseX = this.lastMousePosition_; var thumbX = this.thumbToMove_.offsetLeft; if (this.incrementing_) { var thumbW = this.thumbToMove_.offsetWidth; if (mouseX > thumbX + thumbW) { value = this.getThumbPosition_(this.thumbToMove_) + this.getBlockIncrement(); } } else { if (mouseX < thumbX) { value = this.getThumbPosition_(this.thumbToMove_) - this.getBlockIncrement(); } } } if (goog.isDef(value)) { // not all code paths sets the value variable this.setThumbPosition_(this.thumbToMove_, value); } }; /** * Handler for the mouse up event. * @param {goog.events.Event} e The event object. * @private */ goog.ui.SliderBase.prototype.handleMouseUp_ = function(e) { if (this.incTimer_) { this.incTimer_.stop(); } var doc = goog.dom.getOwnerDocument(this.getElement()); this.getHandler(). unlisten(doc, goog.events.EventType.MOUSEUP, this.handleMouseUp_, true). unlisten(this.getElement(), goog.events.EventType.MOUSEMOVE, this.storeMousePos_); }; /** * Returns the relative mouse position to the slider. * @param {goog.events.Event} e The mouse event object. * @return {number} The relative mouse position to the slider. * @private */ goog.ui.SliderBase.prototype.getRelativeMousePos_ = function(e) { var coord = goog.style.getRelativePosition(e, this.getElement()); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { return coord.y; } else { return coord.x; } }; /** * Stores the current mouse position so that it can be used in the timer. * @param {goog.events.Event} e The mouse event object. * @private */ goog.ui.SliderBase.prototype.storeMousePos_ = function(e) { this.lastMousePosition_ = this.getRelativeMousePos_(e); }; /** * Returns the value to use for the current mouse position * @param {goog.events.Event} e The mouse event object. * @return {number} The value that this mouse position represents. * @private */ goog.ui.SliderBase.prototype.getValueFromMousePosition_ = function(e) { var min = this.getMinimum(); var max = this.getMaximum(); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var thumbH = this.valueThumb.offsetHeight; var availH = this.getElement().clientHeight - thumbH; var y = this.getRelativeMousePos_(e) - thumbH / 2; return (max - min) * (availH - y) / availH + min; } else { var thumbW = this.valueThumb.offsetWidth; var availW = this.getElement().clientWidth - thumbW; var x = this.getRelativeMousePos_(e) - thumbW / 2; return (max - min) * x / availW + min; } }; /** * @param {HTMLDivElement} thumb The thumb object. * @return {number} The position of the specified thumb. * @private */ goog.ui.SliderBase.prototype.getThumbPosition_ = function(thumb) { if (thumb == this.valueThumb) { return this.rangeModel.getValue(); } else if (thumb == this.extentThumb) { return this.rangeModel.getValue() + this.rangeModel.getExtent(); } else { throw Error('Illegal thumb element. Neither minThumb nor maxThumb'); } }; /** * Moves the thumbs by the specified delta as follows * - as long as both thumbs stay within [min,max], both thumbs are moved * - once a thumb reaches or exceeds min (or max, respectively), it stays * - at min (or max, respectively). * In case both thumbs have reached min (or max), no change event will fire. * @param {number} delta The delta by which to move the selected range. */ goog.ui.SliderBase.prototype.moveThumbs = function(delta) { var newMinPos = this.getThumbPosition_(this.valueThumb) + delta; var newMaxPos = this.getThumbPosition_(this.extentThumb) + delta; // correct min / max positions to be within bounds newMinPos = goog.math.clamp( newMinPos, this.getMinimum(), this.getMaximum() - this.minExtent_); newMaxPos = goog.math.clamp( newMaxPos, this.getMinimum() + this.minExtent_, this.getMaximum()); // Set value and extent atomically this.setValueAndExtent(newMinPos, newMaxPos - newMinPos); }; /** * Sets the position of the given thumb. The set is ignored and no CHANGE event * fires if it violates the constraint minimum <= value (valueThumb position) <= * value + extent (extentThumb position) <= maximum. * * Note: To keep things simple, the setThumbPosition_ function does not have the * side-effect of "correcting" value or extent to fit the above constraint as it * is the case in the underlying range model. Instead, we simply ignore the * call. Callers must make these adjustements explicitly if they wish. * @param {Element} thumb The thumb whose position to set. * @param {number} position The position to move the thumb to. * @private */ goog.ui.SliderBase.prototype.setThumbPosition_ = function(thumb, position) { var intermediateExtent = null; // Make sure the maxThumb stays within minThumb <= maxThumb <= maximum if (thumb == this.extentThumb && position <= this.rangeModel.getMaximum() && position >= this.rangeModel.getValue() + this.minExtent_) { // For the case where there is only one thumb, we don't want to set the // extent twice, causing two change events, so delay setting until we know // if there will be a subsequent change. intermediateExtent = position - this.rangeModel.getValue(); } // Make sure the minThumb stays within minimum <= minThumb <= maxThumb var currentExtent = intermediateExtent || this.rangeModel.getExtent(); if (thumb == this.valueThumb && position >= this.getMinimum() && position <= this.rangeModel.getValue() + currentExtent - this.minExtent_) { var newExtent = currentExtent - (position - this.rangeModel.getValue()); // The range model will round the value and extent. Since we're setting // both, extent and value at the same time, it can happen that the // rounded sum of position and extent is not equal to the sum of the // position and extent rounded individually. If this happens, we simply // ignore the update to prevent inconsistent moves of the extent thumb. if (this.rangeModel.roundToStepWithMin(position) + this.rangeModel.roundToStepWithMin(newExtent) == this.rangeModel.roundToStepWithMin(position + newExtent)) { // Atomically update the position and extent. this.setValueAndExtent(position, newExtent); intermediateExtent = null; } } // Need to be able to set extent to 0. if (intermediateExtent != null) { this.rangeModel.setExtent(intermediateExtent); } }; /** * Sets the value and extent of the underlying range model. We enforce that * getMinimum() <= value <= getMaximum() - extent and * getMinExtent <= extent <= getMaximum() - getValue() * If this is not satisifed for the given extent, the call is ignored and no * CHANGE event fires. This is a utility method to allow setting the thumbs * simultaneously and ensuring that only one event fires. * @param {number} value The value to which to set the value. * @param {number} extent The value to which to set the extent. */ goog.ui.SliderBase.prototype.setValueAndExtent = function(value, extent) { if (this.getMinimum() <= value && value <= this.getMaximum() - extent && this.minExtent_ <= extent && extent <= this.getMaximum() - value) { if (value == this.getValue() && extent == this.getExtent()) { return; } // because the underlying range model applies adjustements of value // and extent to fit within bounds, we need to reset the extent // first so these adjustements don't kick in. this.rangeModel.setMute(true); this.rangeModel.setExtent(0); this.rangeModel.setValue(value); this.rangeModel.setExtent(extent); this.rangeModel.setMute(false); this.updateUi_(); this.dispatchEvent(goog.ui.Component.EventType.CHANGE); } }; /** * @return {number} The minimum value. */ goog.ui.SliderBase.prototype.getMinimum = function() { return this.rangeModel.getMinimum(); }; /** * Sets the minimum number. * @param {number} min The minimum value. */ goog.ui.SliderBase.prototype.setMinimum = function(min) { this.rangeModel.setMinimum(min); }; /** * @return {number} The maximum value. */ goog.ui.SliderBase.prototype.getMaximum = function() { return this.rangeModel.getMaximum(); }; /** * Sets the maximum number. * @param {number} max The maximum value. */ goog.ui.SliderBase.prototype.setMaximum = function(max) { this.rangeModel.setMaximum(max); }; /** * @return {HTMLDivElement} The value thumb element. */ goog.ui.SliderBase.prototype.getValueThumb = function() { return this.valueThumb; }; /** * @return {HTMLDivElement} The extent thumb element. */ goog.ui.SliderBase.prototype.getExtentThumb = function() { return this.extentThumb; }; /** * @param {number} position The position to get the closest thumb to. * @return {HTMLDivElement} The thumb that is closest to the given position. * @private */ goog.ui.SliderBase.prototype.getClosestThumb_ = function(position) { if (position <= (this.rangeModel.getValue() + this.rangeModel.getExtent() / 2)) { return this.valueThumb; } else { return this.extentThumb; } }; /** * Call back when the internal range model changes. Sub-classes may override * and re-enter this method to update a11y state. Consider protected. * @param {goog.events.Event} e The event object. * @protected */ goog.ui.SliderBase.prototype.handleRangeModelChange = function(e) { this.updateUi_(); this.updateAriaStates(); this.dispatchEvent(goog.ui.Component.EventType.CHANGE); }; /** * This is called when we need to update the size of the thumb. This happens * when first created as well as when the value and the orientation changes. * @private */ goog.ui.SliderBase.prototype.updateUi_ = function() { if (this.valueThumb && !this.isAnimating_) { var minCoord = this.getThumbCoordinateForValue_( this.getThumbPosition_(this.valueThumb)); var maxCoord = this.getThumbCoordinateForValue_( this.getThumbPosition_(this.extentThumb)); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { this.valueThumb.style.top = minCoord.y + 'px'; this.extentThumb.style.top = maxCoord.y + 'px'; } else { this.valueThumb.style.left = minCoord.x + 'px'; this.extentThumb.style.left = maxCoord.x + 'px'; } } }; /** * Returns the position to move the handle to for a given value * @param {number} val The value to get the coordinate for. * @return {goog.math.Coordinate} Coordinate with either x or y set. * @private */ goog.ui.SliderBase.prototype.getThumbCoordinateForValue_ = function(val) { var coord = new goog.math.Coordinate; if (this.valueThumb) { var min = this.getMinimum(); var max = this.getMaximum(); // This check ensures the ratio never take NaN value, which is possible when // the slider min & max are same numbers (i.e. 1). var ratio = (val == min && min == max) ? 0 : (val - min) / (max - min); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var thumbHeight = this.valueThumb.offsetHeight; var h = this.getElement().clientHeight - thumbHeight; var bottom = Math.round(ratio * h); coord.y = h - bottom; } else { var w = this.getElement().clientWidth - this.valueThumb.offsetWidth; var left = Math.round(ratio * w); coord.x = left; } } return coord; }; /** * Sets the value and starts animating the handle towards that position. * @param {number} v Value to set and animate to. */ goog.ui.SliderBase.prototype.animatedSetValue = function(v) { // the value might be out of bounds v = Math.min(this.getMaximum(), Math.max(v, this.getMinimum())); if (this.currentAnimation_) { this.currentAnimation_.stop(true); } var end; var thumb = this.getClosestThumb_(v); var coord = this.getThumbCoordinateForValue_(v); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { end = [thumb.offsetLeft, coord.y]; } else { end = [coord.x, thumb.offsetTop]; } var animation = new goog.fx.dom.SlideFrom(thumb, end, goog.ui.SliderBase.ANIMATION_INTERVAL_); this.currentAnimation_ = animation; this.getHandler().listen(animation, goog.fx.Animation.EventType.END, this.endAnimation_); this.isAnimating_ = true; this.setThumbPosition_(thumb, v); animation.play(false); }; /** * Sets the isAnimating_ field to false once the animation is done. * @param {goog.fx.AnimationEvent} e Event object passed by the animation * object. * @private */ goog.ui.SliderBase.prototype.endAnimation_ = function(e) { this.isAnimating_ = false; }; /** * Changes the orientation. * @param {goog.ui.SliderBase.Orientation} orient The orientation. */ goog.ui.SliderBase.prototype.setOrientation = function(orient) { if (this.orientation_ != orient) { var oldCss = this.getCssClass(this.orientation_); var newCss = this.getCssClass(orient); this.orientation_ = orient; // Update the DOM if (this.getElement()) { goog.dom.classes.swap(this.getElement(), oldCss, newCss); // we need to reset the left and top this.valueThumb.style.left = this.valueThumb.style.top = ''; this.extentThumb.style.left = this.extentThumb.style.top = ''; this.updateUi_(); } } }; /** * @return {goog.ui.SliderBase.Orientation} the orientation of the slider. */ goog.ui.SliderBase.prototype.getOrientation = function() { return this.orientation_; }; /** @inheritDoc */ goog.ui.SliderBase.prototype.disposeInternal = function() { goog.ui.SliderBase.superClass_.disposeInternal.call(this); if (this.incTimer_) { this.incTimer_.dispose(); } delete this.incTimer_; if (this.currentAnimation_) { this.currentAnimation_.dispose(); } delete this.currentAnimation_; delete this.valueThumb; delete this.extentThumb; this.rangeModel.dispose(); delete this.rangeModel; if (this.keyHandler_) { this.keyHandler_.dispose(); delete this.keyHandler_; } if (this.mouseWheelHandler_) { this.mouseWheelHandler_.dispose(); delete this.mouseWheelHandler_; } if (this.valueDragger_) { this.valueDragger_.dispose(); delete this.valueDragger_; } if (this.extentDragger_) { this.extentDragger_.dispose(); delete this.extentDragger_; } }; /** * @return {number} The amount to increment/decrement for page up/down as well * as when holding down the mouse button on the background. */ goog.ui.SliderBase.prototype.getBlockIncrement = function() { return this.blockIncrement_; }; /** * Sets the amount to increment/decrement for page up/down as well as when * holding down the mouse button on the background. * * @param {number} value The value to set the block increment to. */ goog.ui.SliderBase.prototype.setBlockIncrement = function(value) { this.blockIncrement_ = value; }; /** * Sets the minimal value that the extent may have. * * @param {number} value The minimal value for the extent. */ goog.ui.SliderBase.prototype.setMinExtent = function(value) { this.minExtent_ = value; }; /** * The amount to increment/decrement for up, down, left and right arrow keys. * @private * @type {number} */ goog.ui.SliderBase.prototype.unitIncrement_ = 1; /** * @return {number} The amount to increment/decrement for up, down, left and * right arrow keys. */ goog.ui.SliderBase.prototype.getUnitIncrement = function() { return this.unitIncrement_; }; /** * Sets the amount to increment/decrement for up, down, left and right arrow * keys. * @param {number} value The value to set the unit increment to. */ goog.ui.SliderBase.prototype.setUnitIncrement = function(value) { this.unitIncrement_ = value; }; /** * @return {?number} The step value used to determine how to round the value. */ goog.ui.SliderBase.prototype.getStep = function() { return this.rangeModel.getStep(); }; /** * Sets the step value. The step value is used to determine how to round the * value. * @param {?number} step The step size. */ goog.ui.SliderBase.prototype.setStep = function(step) { this.rangeModel.setStep(step); }; /** * @return {boolean} Whether clicking on the backgtround should move directly to * that point. */ goog.ui.SliderBase.prototype.getMoveToPointEnabled = function() { return this.moveToPointEnabled_; }; /** * Sets whether clicking on the background should move directly to that point. * @param {boolean} val Whether clicking on the background should move directly * to that point. */ goog.ui.SliderBase.prototype.setMoveToPointEnabled = function(val) { this.moveToPointEnabled_ = val; }; /** * @return {number} The value of the underlying range model. */ goog.ui.SliderBase.prototype.getValue = function() { return this.rangeModel.getValue(); }; /** * Sets the value of the underlying range model. We enforce that * getMinimum() <= value <= getMaximum() - getExtent() * If this is not satisifed for the given value, the call is ignored and no * CHANGE event fires. * @param {number} value The value. */ goog.ui.SliderBase.prototype.setValue = function(value) { // Set the position through the thumb method to enforce constraints. this.setThumbPosition_(this.valueThumb, value); }; /** * @return {number} The value of the extent of the underlying range model. */ goog.ui.SliderBase.prototype.getExtent = function() { return this.rangeModel.getExtent(); }; /** * Sets the extent of the underlying range model. We enforce that * getMinExtent() <= extent <= getMaximum() - getValue() * If this is not satisifed for the given extent, the call is ignored and no * CHANGE event fires. * @param {number} extent The value to which to set the extent. */ goog.ui.SliderBase.prototype.setExtent = function(extent) { // Set the position through the thumb method to enforce constraints. this.setThumbPosition_(this.extentThumb, (this.rangeModel.getValue() + extent)); }; /** * Change the visibility of the slider. * You must call this if you had set the slider's value when it was invisible. * @param {boolean} visible Whether to show the slider. */ goog.ui.SliderBase.prototype.setVisible = function(visible) { goog.style.showElement(this.getElement(), visible); if (visible) { this.updateUi_(); } }; /** * Set a11y roles and state. * @protected */ goog.ui.SliderBase.prototype.setAriaRoles = function() { goog.dom.a11y.setRole(this.getElement(), goog.dom.a11y.Role.SLIDER); this.updateAriaStates(); }; /** * Set a11y roles and state when values change. * @protected */ goog.ui.SliderBase.prototype.updateAriaStates = function() { var element = this.getElement(); if (element) { goog.dom.a11y.setState(element, goog.dom.a11y.State.VALUEMIN, this.getMinimum()); goog.dom.a11y.setState(element, goog.dom.a11y.State.VALUEMAX, this.getMaximum()); goog.dom.a11y.setState(element, goog.dom.a11y.State.VALUENOW, this.getValue()); } };
closure/goog/ui/sliderbase.js
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of a basic slider control. * * Models a control that allows to select a sub-range within a given * range of values using two thumbs. The underlying range is modeled * as a range model, where the min thumb points to value of the * rangemodel, and the max thumb points to value + extent of the range * model. * * The currently selected range is exposed through methods * getValue() and getExtent(). * * The reason for modelling the basic slider state as value + extent is * to be able to capture both, a two-thumb slider to select a range, and * a single-thumb slider to just select a value (in the latter case, extent * is always zero). We provide subclasses (twothumbslider.js and slider.js) * that model those special cases of this control. * * All rendering logic is left out, so that the subclasses can define * their own rendering. To do so, the subclasses overwrite: * - createDom * - decorateInternal * - getCssClass * */ goog.provide('goog.ui.SliderBase'); goog.provide('goog.ui.SliderBase.Orientation'); goog.require('goog.Timer'); goog.require('goog.dom'); goog.require('goog.dom.a11y'); goog.require('goog.dom.a11y.Role'); goog.require('goog.dom.a11y.State'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.KeyHandler'); goog.require('goog.events.KeyHandler.EventType'); goog.require('goog.events.MouseWheelHandler'); goog.require('goog.events.MouseWheelHandler.EventType'); goog.require('goog.fx.Animation.EventType'); goog.require('goog.fx.Dragger'); goog.require('goog.fx.Dragger.EventType'); goog.require('goog.fx.dom.SlideFrom'); goog.require('goog.math'); goog.require('goog.math.Coordinate'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.RangeModel'); /** * This creates a SliderBase object. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @constructor * @extends {goog.ui.Component} */ goog.ui.SliderBase = function(opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); this.rangeModel = new goog.ui.RangeModel; // Don't use getHandler because it gets cleared in exitDocument. goog.events.listen(this.rangeModel, goog.ui.Component.EventType.CHANGE, this.handleRangeModelChange, false, this); }; goog.inherits(goog.ui.SliderBase, goog.ui.Component); /** * Enum for representing the orientation of the slider. * * @enum {string} */ goog.ui.SliderBase.Orientation = { VERTICAL: 'vertical', HORIZONTAL: 'horizontal' }; /** * Orientation of the slider. * @type {goog.ui.SliderBase.Orientation} * @private */ goog.ui.SliderBase.prototype.orientation_ = goog.ui.SliderBase.Orientation.HORIZONTAL; /** * When the user holds down the mouse on the slider background, the closest * thumb will move in "lock-step" towards the mouse. This number indicates how * long each step should take (in milliseconds). * @type {number} * @private */ goog.ui.SliderBase.MOUSE_DOWN_INCREMENT_INTERVAL_ = 200; /** * How long the animations should take (in milliseconds). * @type {number} * @private */ goog.ui.SliderBase.ANIMATION_INTERVAL_ = 100; /** * The underlying range model * @type {goog.ui.RangeModel} * @protected */ goog.ui.SliderBase.prototype.rangeModel; /** * The minThumb dom-element, pointing to the start of the selected range. * @type {HTMLDivElement} * @protected */ goog.ui.SliderBase.prototype.valueThumb; /** * The maxThumb dom-element, pointing to the end of the selected range. * @type {HTMLDivElement} * @protected */ goog.ui.SliderBase.prototype.extentThumb; /** * The thumb that we should be moving (only relevant when timed move is active). * @type {HTMLDivElement} * @private */ goog.ui.SliderBase.prototype.thumbToMove_; /** * The object handling keyboard events. * @type {goog.events.KeyHandler} * @private */ goog.ui.SliderBase.prototype.keyHandler_; /** * The object handling mouse wheel events. * @type {goog.events.MouseWheelHandler} * @private */ goog.ui.SliderBase.prototype.mouseWheelHandler_; /** * The Dragger for dragging the valueThumb. * @type {goog.fx.Dragger} * @private */ goog.ui.SliderBase.prototype.valueDragger_; /** * The Dragger for dragging the extentThumb. * @type {goog.fx.Dragger} * @private */ goog.ui.SliderBase.prototype.extentDragger_; /** * If we are currently animating the thumb. * @private * @type {boolean} */ goog.ui.SliderBase.prototype.isAnimating_ = false; /** * Whether clicking on the backgtround should move directly to that point. * @private * @type {boolean} */ goog.ui.SliderBase.prototype.moveToPointEnabled_ = false; /** * The amount to increment/decrement for page up/down as well as when holding * down the mouse button on the background. * @private * @type {number} */ goog.ui.SliderBase.prototype.blockIncrement_ = 10; /** * The minimal extent. The class will ensure that the extent cannot shrink * to a value smaller than minExtent. * @private * @type {number} */ goog.ui.SliderBase.prototype.minExtent_ = 0; /** * Returns the CSS class applied to the slider element for the given * orientation. Subclasses must override this method. * @param {goog.ui.SliderBase.Orientation} orient The orientation. * @return {string} The CSS class applied to slider elements. * @protected */ goog.ui.SliderBase.prototype.getCssClass = goog.abstractMethod; /** @inheritDoc */ goog.ui.SliderBase.prototype.createDom = function() { goog.ui.SliderBase.superClass_.createDom.call(this); var element = this.getDomHelper().createDom('div', this.getCssClass(this.orientation_)); this.decorateInternal(element); }; /** * Subclasses must implement this method and set the valueThumb and * extentThumb to non-null values. * @type {function() : void} * @protected */ goog.ui.SliderBase.prototype.createThumbs = goog.abstractMethod; /** @inheritDoc */ goog.ui.SliderBase.prototype.decorateInternal = function(element) { goog.ui.SliderBase.superClass_.decorateInternal.call(this, element); goog.dom.classes.add(element, this.getCssClass(this.orientation_)); this.createThumbs(); this.setAriaRoles(); }; /** * Called when the DOM for the component is for sure in the document. * Subclasses should override this method to set this element's role. */ goog.ui.SliderBase.prototype.enterDocument = function() { goog.ui.SliderBase.superClass_.enterDocument.call(this); // Attach the events this.valueDragger_ = new goog.fx.Dragger(this.valueThumb); this.extentDragger_ = new goog.fx.Dragger(this.extentThumb); // The slider is handling the positioning so make the defaultActions empty. this.valueDragger_.defaultAction = this.extentDragger_.defaultAction = goog.nullFunction; this.keyHandler_ = new goog.events.KeyHandler(this.getElement()); this.mouseWheelHandler_ = new goog.events.MouseWheelHandler( this.getElement()); this.getHandler(). listen(this.valueDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, this.handleBeforeDrag_). listen(this.extentDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, this.handleBeforeDrag_). listen(this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.handleKeyDown_). listen(this.getElement(), goog.events.EventType.MOUSEDOWN, this.handleMouseDown_). listen(this.mouseWheelHandler_, goog.events.MouseWheelHandler.EventType.MOUSEWHEEL, this.handleMouseWheel_); this.getElement().tabIndex = 0; this.updateUi_(); }; /** * Handler for the before drag event. We use the event properties to determine * the new value. * @param {goog.fx.DragEvent} e The drag event used to drag the thumb. * @private */ goog.ui.SliderBase.prototype.handleBeforeDrag_ = function(e) { var thumbToDrag = e.dragger == this.valueDragger_ ? this.valueThumb : this.extentThumb; var value; if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var availHeight = this.getElement().clientHeight - thumbToDrag.offsetHeight; value = (availHeight - e.top) / availHeight * (this.getMaximum() - this.getMinimum()) + this.getMinimum(); } else { var availWidth = this.getElement().clientWidth - thumbToDrag.offsetWidth; value = (e.left / availWidth) * (this.getMaximum() - this.getMinimum()) + this.getMinimum(); } // Bind the value within valid range before calling setThumbPosition_. // This is necessary because setThumbPosition_ is a no-op for values outside // of the legal range. For drag operations, we want the handle to snap to the // last valid value instead of remaining at the previous position. if (e.dragger == this.valueDragger_) { value = Math.min(Math.max(value, this.getMinimum()), this.getValue() + this.getExtent()); } else { value = Math.min(Math.max(value, this.getValue()), this.getMaximum()); } this.setThumbPosition_(thumbToDrag, value); }; /** * Event handler for the key down event. This is used to update the value * based on the key pressed. * @param {goog.events.KeyEvent} e The keyboard event object. * @private */ goog.ui.SliderBase.prototype.handleKeyDown_ = function(e) { var handled = true; switch (e.keyCode) { case goog.events.KeyCodes.HOME: this.animatedSetValue(this.getMinimum()); break; case goog.events.KeyCodes.END: this.animatedSetValue(this.getMaximum()); break; case goog.events.KeyCodes.PAGE_UP: this.moveThumbs(this.getBlockIncrement()); break; case goog.events.KeyCodes.PAGE_DOWN: this.moveThumbs(-this.getBlockIncrement()); break; case goog.events.KeyCodes.LEFT: case goog.events.KeyCodes.DOWN: this.moveThumbs(e.shiftKey ? -this.getBlockIncrement() : -this.getUnitIncrement()); break; case goog.events.KeyCodes.RIGHT: case goog.events.KeyCodes.UP: this.moveThumbs(e.shiftKey ? this.getBlockIncrement() : this.getUnitIncrement()); break; default: handled = false; } if (handled) { e.preventDefault(); } }; /** * Handler for the mouse down event. * @param {goog.events.Event} e The mouse event object. * @private */ goog.ui.SliderBase.prototype.handleMouseDown_ = function(e) { if (this.getElement().focus) { this.getElement().focus(); } // Known Element. var target = /** @type {Element} */ (e.target); if (!goog.dom.contains(this.valueThumb, target) && !goog.dom.contains(this.extentThumb, target)) { if (this.moveToPointEnabled_) { // just set the value directly based on the position of the click this.animatedSetValue(this.getValueFromMousePosition_(e)); } else { // start a timer that incrementally moves the handle this.startBlockIncrementing_(e); } } }; /** * Handler for the mouse wheel event. * @param {goog.events.MouseWheelEvent} e The mouse wheel event object. * @private */ goog.ui.SliderBase.prototype.handleMouseWheel_ = function(e) { // Just move one unit increment per mouse wheel event var direction = e.detail > 0 ? -1 : 1; this.moveThumbs(direction * this.getUnitIncrement()); e.preventDefault(); }; /** * Starts the animation that causes the thumb to increment/decrement by the * block increment when the user presses down on the background. * @param {goog.events.Event} e The mouse event object. * @private */ goog.ui.SliderBase.prototype.startBlockIncrementing_ = function(e) { this.storeMousePos_(e); this.thumbToMove_ = this.getClosestThumb_(this.getValueFromMousePosition_(e)); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { this.incrementing_ = this.lastMousePosition_ < this.thumbToMove_.offsetTop; } else { this.incrementing_ = this.lastMousePosition_ > this.thumbToMove_.offsetLeft + this.thumbToMove_.offsetWidth; } var doc = goog.dom.getOwnerDocument(this.getElement()); this.getHandler(). listen(doc, goog.events.EventType.MOUSEUP, this.handleMouseUp_, true). listen(this.getElement(), goog.events.EventType.MOUSEMOVE, this.storeMousePos_); if (!this.incTimer_) { this.incTimer_ = new goog.Timer( goog.ui.SliderBase.MOUSE_DOWN_INCREMENT_INTERVAL_); this.getHandler().listen(this.incTimer_, goog.Timer.TICK, this.handleTimerTick_); } this.handleTimerTick_(); this.incTimer_.start(); }; /** * Handler for the tick event dispatched by the timer used to update the value * in a block increment. This is also called directly from * startBlockIncrementing_. * @private */ goog.ui.SliderBase.prototype.handleTimerTick_ = function() { var value; if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var mouseY = this.lastMousePosition_; var thumbY = this.thumbToMove_.offsetTop; if (this.incrementing_) { if (mouseY < thumbY) { value = this.getThumbPosition_(this.thumbToMove_) + this.getBlockIncrement(); } } else { var thumbH = this.thumbToMove_.offsetHeight; if (mouseY > thumbY + thumbH) { value = this.getThumbPosition_(this.thumbToMove_) - this.getBlockIncrement(); } } } else { var mouseX = this.lastMousePosition_; var thumbX = this.thumbToMove_.offsetLeft; if (this.incrementing_) { var thumbW = this.thumbToMove_.offsetWidth; if (mouseX > thumbX + thumbW) { value = this.getThumbPosition_(this.thumbToMove_) + this.getBlockIncrement(); } } else { if (mouseX < thumbX) { value = this.getThumbPosition_(this.thumbToMove_) - this.getBlockIncrement(); } } } if (goog.isDef(value)) { // not all code paths sets the value variable this.setThumbPosition_(this.thumbToMove_, value); } }; /** * Handler for the mouse up event. * @param {goog.events.Event} e The event object. * @private */ goog.ui.SliderBase.prototype.handleMouseUp_ = function(e) { if (this.incTimer_) { this.incTimer_.stop(); } var doc = goog.dom.getOwnerDocument(this.getElement()); this.getHandler(). unlisten(doc, goog.events.EventType.MOUSEUP, this.handleMouseUp_, true). unlisten(this.getElement(), goog.events.EventType.MOUSEMOVE, this.storeMousePos_); }; /** * Returns the relative mouse position to the slider. * @param {goog.events.Event} e The mouse event object. * @return {number} The relative mouse position to the slider. * @private */ goog.ui.SliderBase.prototype.getRelativeMousePos_ = function(e) { var coord = goog.style.getRelativePosition(e, this.getElement()); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { return coord.y; } else { return coord.x; } }; /** * Stores the current mouse position so that it can be used in the timer. * @param {goog.events.Event} e The mouse event object. * @private */ goog.ui.SliderBase.prototype.storeMousePos_ = function(e) { this.lastMousePosition_ = this.getRelativeMousePos_(e); }; /** * Returns the value to use for the current mouse position * @param {goog.events.Event} e The mouse event object. * @return {number} The value that this mouse position represents. * @private */ goog.ui.SliderBase.prototype.getValueFromMousePosition_ = function(e) { var min = this.getMinimum(); var max = this.getMaximum(); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var thumbH = this.valueThumb.offsetHeight; var availH = this.getElement().clientHeight - thumbH; var y = this.getRelativeMousePos_(e) - thumbH / 2; return (max - min) * (availH - y) / availH + min; } else { var thumbW = this.valueThumb.offsetWidth; var availW = this.getElement().clientWidth - thumbW; var x = this.getRelativeMousePos_(e) - thumbW / 2; return (max - min) * x / availW + min; } }; /** * @param {HTMLDivElement} thumb The thumb object. * @return {number} The position of the specified thumb. * @private */ goog.ui.SliderBase.prototype.getThumbPosition_ = function(thumb) { if (thumb == this.valueThumb) { return this.rangeModel.getValue(); } else if (thumb == this.extentThumb) { return this.rangeModel.getValue() + this.rangeModel.getExtent(); } else { throw Error('Illegal thumb element. Neither minThumb nor maxThumb'); } }; /** * Moves the thumbs by the specified delta as follows * - as long as both thumbs stay within [min,max], both thumbs are moved * - once a thumb reaches or exceeds min (or max, respectively), it stays * - at min (or max, respectively). * In case both thumbs have reached min (or max), no change event will fire. * @param {number} delta The delta by which to move the selected range. */ goog.ui.SliderBase.prototype.moveThumbs = function(delta) { var newMinPos = this.getThumbPosition_(this.valueThumb) + delta; var newMaxPos = this.getThumbPosition_(this.extentThumb) + delta; // correct min / max positions to be within bounds newMinPos = goog.math.clamp( newMinPos, this.getMinimum(), this.getMaximum() - this.minExtent_); newMaxPos = goog.math.clamp( newMaxPos, this.getMinimum() + this.minExtent_, this.getMaximum()); // Set value and extent atomically this.setValueAndExtent(newMinPos, newMaxPos - newMinPos); }; /** * Sets the position of the given thumb. The set is ignored and no CHANGE event * fires if it violates the constraint minimum <= value (valueThumb position) <= * value + extent (extentThumb position) <= maximum. * * Note: To keep things simple, the setThumbPosition_ function does not have the * side-effect of "correcting" value or extent to fit the above constraint as it * is the case in the underlying range model. Instead, we simply ignore the * call. Callers must make these adjustements explicitly if they wish. * @param {Element} thumb The thumb whose position to set. * @param {number} position The position to move the thumb to. * @private */ goog.ui.SliderBase.prototype.setThumbPosition_ = function(thumb, position) { var intermediateExtent = null; // Make sure the maxThumb stays within minThumb <= maxThumb <= maximum if (thumb == this.extentThumb && position <= this.rangeModel.getMaximum() && position >= this.rangeModel.getValue() + this.minExtent_) { // For the case where there is only one thumb, we don't want to set the // extent twice, causing two change events, so delay setting until we know // if there will be a subsequent change. intermediateExtent = position - this.rangeModel.getValue(); } // Make sure the minThumb stays within minimum <= minThumb <= maxThumb var currentExtent = intermediateExtent || this.rangeModel.getExtent(); if (thumb == this.valueThumb && position >= this.getMinimum() && position <= this.rangeModel.getValue() + currentExtent - this.minExtent_) { var newExtent = currentExtent - (position - this.rangeModel.getValue()); // The range model will round the value and extent. Since we're setting // both, extent and value at the same time, it can happen that the // rounded sum of position and extent is not equal to the sum of the // position and extent rounded individually. If this happens, we simply // ignore the update to prevent inconsistent moves of the extent thumb. if (this.rangeModel.roundToStepWithMin(position) + this.rangeModel.roundToStepWithMin(newExtent) == this.rangeModel.roundToStepWithMin(position + newExtent)) { // Atomically update the position and extent. this.setValueAndExtent(position, newExtent); intermediateExtent = null; } } // Need to be able to set extent to 0. if (intermediateExtent != null) { this.rangeModel.setExtent(intermediateExtent); } }; /** * Sets the value and extent of the underlying range model. We enforce that * getMinimum() <= value <= getMaximum() - extent and * getMinExtent <= extent <= getMaximum() - getValue() * If this is not satisifed for the given extent, the call is ignored and no * CHANGE event fires. This is a utility method to allow setting the thumbs * simultaneously and ensuring that only one event fires. * @param {number} value The value to which to set the value. * @param {number} extent The value to which to set the extent. */ goog.ui.SliderBase.prototype.setValueAndExtent = function(value, extent) { if (this.getMinimum() <= value && value <= this.getMaximum() - extent && this.minExtent_ <= extent && extent <= this.getMaximum() - value) { if (value == this.getValue() && extent == this.getExtent()) { return; } // because the underlying range model applies adjustements of value // and extent to fit within bounds, we need to reset the extent // first so these adjustements don't kick in. this.rangeModel.setMute(true); this.rangeModel.setExtent(0); this.rangeModel.setValue(value); this.rangeModel.setExtent(extent); this.rangeModel.setMute(false); this.updateUi_(); this.dispatchEvent(goog.ui.Component.EventType.CHANGE); } }; /** * @return {number} The minimum value. */ goog.ui.SliderBase.prototype.getMinimum = function() { return this.rangeModel.getMinimum(); }; /** * Sets the minimum number. * @param {number} min The minimum value. */ goog.ui.SliderBase.prototype.setMinimum = function(min) { this.rangeModel.setMinimum(min); }; /** * @return {number} The maximum value. */ goog.ui.SliderBase.prototype.getMaximum = function() { return this.rangeModel.getMaximum(); }; /** * Sets the maximum number. * @param {number} max The maximum value. */ goog.ui.SliderBase.prototype.setMaximum = function(max) { this.rangeModel.setMaximum(max); }; /** * @return {HTMLDivElement} The value thumb element. */ goog.ui.SliderBase.prototype.getValueThumb = function() { return this.valueThumb; }; /** * @return {HTMLDivElement} The extent thumb element. */ goog.ui.SliderBase.prototype.getExtentThumb = function() { return this.extentThumb; }; /** * @param {number} position The position to get the closest thumb to. * @return {HTMLDivElement} The thumb that is closest to the given position. * @private */ goog.ui.SliderBase.prototype.getClosestThumb_ = function(position) { if (position <= (this.rangeModel.getValue() + this.rangeModel.getExtent() / 2)) { return this.valueThumb; } else { return this.extentThumb; } }; /** * Call back when the internal range model changes. Sub-classes may override * and re-enter this method to update a11y state. Consider protected. * @param {goog.events.Event} e The event object. * @protected */ goog.ui.SliderBase.prototype.handleRangeModelChange = function(e) { this.updateUi_(); this.updateAriaStates(); this.dispatchEvent(goog.ui.Component.EventType.CHANGE); }; /** * This is called when we need to update the size of the thumb. This happens * when first created as well as when the value and the orientation changes. * @private */ goog.ui.SliderBase.prototype.updateUi_ = function() { if (this.valueThumb && !this.isAnimating_) { var minCoord = this.getThumbCoordinateForValue_( this.getThumbPosition_(this.valueThumb)); var maxCoord = this.getThumbCoordinateForValue_( this.getThumbPosition_(this.extentThumb)); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { this.valueThumb.style.top = minCoord.y + 'px'; this.extentThumb.style.top = maxCoord.y + 'px'; } else { this.valueThumb.style.left = minCoord.x + 'px'; this.extentThumb.style.left = maxCoord.x + 'px'; } } }; /** * Returns the position to move the handle to for a given value * @param {number} val The value to get the coordinate for. * @return {goog.math.Coordinate} Coordinate with either x or y set. * @private */ goog.ui.SliderBase.prototype.getThumbCoordinateForValue_ = function(val) { var coord = new goog.math.Coordinate; if (this.valueThumb) { var min = this.getMinimum(); var max = this.getMaximum(); // This check ensures the ratio never take NaN value, which is possible when // the slider min & max are same numbers (i.e. 1). var ratio = (val == min && min == max) ? 0 : (val - min) / (max - min); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var thumbHeight = this.valueThumb.offsetHeight; var h = this.getElement().clientHeight - thumbHeight; var bottom = Math.round(ratio * h); coord.y = h - bottom; } else { var w = this.getElement().clientWidth - this.valueThumb.offsetWidth; var left = Math.round(ratio * w); coord.x = left; } } return coord; }; /** * Sets the value and starts animating the handle towards that position. * @param {number} v Value to set and animate to. */ goog.ui.SliderBase.prototype.animatedSetValue = function(v) { // the value might be out of bounds v = Math.min(this.getMaximum(), Math.max(v, this.getMinimum())); if (this.currentAnimation_) { this.currentAnimation_.stop(true); } var end; var thumb = this.getClosestThumb_(v); var coord = this.getThumbCoordinateForValue_(v); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { end = [thumb.offsetLeft, coord.y]; } else { end = [coord.x, thumb.offsetTop]; } var animation = new goog.fx.dom.SlideFrom(thumb, end, goog.ui.SliderBase.ANIMATION_INTERVAL_); this.currentAnimation_ = animation; this.getHandler().listen(animation, goog.fx.Animation.EventType.END, this.endAnimation_); this.isAnimating_ = true; this.setThumbPosition_(thumb, v); animation.play(false); }; /** * Sets the isAnimating_ field to false once the animation is done. * @param {goog.fx.AnimationEvent} e Event object passed by the animation * object. * @private */ goog.ui.SliderBase.prototype.endAnimation_ = function(e) { this.isAnimating_ = false; }; /** * Changes the orientation. * @param {goog.ui.SliderBase.Orientation} orient The orientation. */ goog.ui.SliderBase.prototype.setOrientation = function(orient) { if (this.orientation_ != orient) { var oldCss = this.getCssClass(this.orientation_); var newCss = this.getCssClass(orient); this.orientation_ = orient; // Update the DOM if (this.getElement()) { goog.dom.classes.swap(this.getElement(), oldCss, newCss); // we need to reset the left and top this.valueThumb.style.left = this.valueThumb.style.top = ''; this.extentThumb.style.left = this.extentThumb.style.top = ''; this.updateUi_(); } } }; /** * @return {goog.ui.SliderBase.Orientation} the orientation of the slider. */ goog.ui.SliderBase.prototype.getOrientation = function() { return this.orientation_; }; /** @inheritDoc */ goog.ui.SliderBase.prototype.disposeInternal = function() { goog.ui.SliderBase.superClass_.disposeInternal.call(this); if (this.incTimer_) { this.incTimer_.dispose(); } delete this.incTimer_; if (this.currentAnimation_) { this.currentAnimation_.dispose(); } delete this.currentAnimation_; delete this.valueThumb; delete this.extentThumb; this.rangeModel.dispose(); delete this.rangeModel; if (this.keyHandler_) { this.keyHandler_.dispose(); delete this.keyHandler_; } if (this.mouseWheelHandler_) { this.mouseWheelHandler_.dispose(); delete this.mouseWheelHandler_; } }; /** * @return {number} The amount to increment/decrement for page up/down as well * as when holding down the mouse button on the background. */ goog.ui.SliderBase.prototype.getBlockIncrement = function() { return this.blockIncrement_; }; /** * Sets the amount to increment/decrement for page up/down as well as when * holding down the mouse button on the background. * * @param {number} value The value to set the block increment to. */ goog.ui.SliderBase.prototype.setBlockIncrement = function(value) { this.blockIncrement_ = value; }; /** * Sets the minimal value that the extent may have. * * @param {number} value The minimal value for the extent. */ goog.ui.SliderBase.prototype.setMinExtent = function(value) { this.minExtent_ = value; }; /** * The amount to increment/decrement for up, down, left and right arrow keys. * @private * @type {number} */ goog.ui.SliderBase.prototype.unitIncrement_ = 1; /** * @return {number} The amount to increment/decrement for up, down, left and * right arrow keys. */ goog.ui.SliderBase.prototype.getUnitIncrement = function() { return this.unitIncrement_; }; /** * Sets the amount to increment/decrement for up, down, left and right arrow * keys. * @param {number} value The value to set the unit increment to. */ goog.ui.SliderBase.prototype.setUnitIncrement = function(value) { this.unitIncrement_ = value; }; /** * @return {?number} The step value used to determine how to round the value. */ goog.ui.SliderBase.prototype.getStep = function() { return this.rangeModel.getStep(); }; /** * Sets the step value. The step value is used to determine how to round the * value. * @param {?number} step The step size. */ goog.ui.SliderBase.prototype.setStep = function(step) { this.rangeModel.setStep(step); }; /** * @return {boolean} Whether clicking on the backgtround should move directly to * that point. */ goog.ui.SliderBase.prototype.getMoveToPointEnabled = function() { return this.moveToPointEnabled_; }; /** * Sets whether clicking on the background should move directly to that point. * @param {boolean} val Whether clicking on the background should move directly * to that point. */ goog.ui.SliderBase.prototype.setMoveToPointEnabled = function(val) { this.moveToPointEnabled_ = val; }; /** * @return {number} The value of the underlying range model. */ goog.ui.SliderBase.prototype.getValue = function() { return this.rangeModel.getValue(); }; /** * Sets the value of the underlying range model. We enforce that * getMinimum() <= value <= getMaximum() - getExtent() * If this is not satisifed for the given value, the call is ignored and no * CHANGE event fires. * @param {number} value The value. */ goog.ui.SliderBase.prototype.setValue = function(value) { // Set the position through the thumb method to enforce constraints. this.setThumbPosition_(this.valueThumb, value); }; /** * @return {number} The value of the extent of the underlying range model. */ goog.ui.SliderBase.prototype.getExtent = function() { return this.rangeModel.getExtent(); }; /** * Sets the extent of the underlying range model. We enforce that * getMinExtent() <= extent <= getMaximum() - getValue() * If this is not satisifed for the given extent, the call is ignored and no * CHANGE event fires. * @param {number} extent The value to which to set the extent. */ goog.ui.SliderBase.prototype.setExtent = function(extent) { // Set the position through the thumb method to enforce constraints. this.setThumbPosition_(this.extentThumb, (this.rangeModel.getValue() + extent)); }; /** * Change the visibility of the slider. * You must call this if you had set the slider's value when it was invisible. * @param {boolean} visible Whether to show the slider. */ goog.ui.SliderBase.prototype.setVisible = function(visible) { goog.style.showElement(this.getElement(), visible); if (visible) { this.updateUi_(); } }; /** * Set a11y roles and state. * @protected */ goog.ui.SliderBase.prototype.setAriaRoles = function() { goog.dom.a11y.setRole(this.getElement(), goog.dom.a11y.Role.SLIDER); this.updateAriaStates(); }; /** * Set a11y roles and state when values change. * @protected */ goog.ui.SliderBase.prototype.updateAriaStates = function() { var element = this.getElement(); if (element) { goog.dom.a11y.setState(element, goog.dom.a11y.State.VALUEMIN, this.getMinimum()); goog.dom.a11y.setState(element, goog.dom.a11y.State.VALUEMAX, this.getMaximum()); goog.dom.a11y.setState(element, goog.dom.a11y.State.VALUENOW, this.getValue()); } };
Fixed a memory leak. R=arv DELTA=8 (8 added, 0 deleted, 0 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=1290 git-svn-id: a40d3b3c31bd0c2f1a55c3521b995692a6f04bd9@840 0b95b8e8-c90f-11de-9d4f-f947ee5921c8
closure/goog/ui/sliderbase.js
<ide><path>losure/goog/ui/sliderbase.js <ide> this.mouseWheelHandler_.dispose(); <ide> delete this.mouseWheelHandler_; <ide> } <add> if (this.valueDragger_) { <add> this.valueDragger_.dispose(); <add> delete this.valueDragger_; <add> } <add> if (this.extentDragger_) { <add> this.extentDragger_.dispose(); <add> delete this.extentDragger_; <add> } <ide> }; <ide> <ide>
Java
apache-2.0
041b3e4b68139ab39f022dcf3c174a815501e4b9
0
baiwyc119/aerogear-unifiedpush-server,IvanGurtler/aerogear-unifiedpush-server,aerobase/unifiedpush-server,julioa/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,diogoalbuquerque/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,C-B4/unifiedpush-server,lholmquist/aerogear-unified-push-server,danielpassos/aerogear-unifiedpush-server,IvanGurtler/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,danielpassos/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,yvnicolas/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,secondsun/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,IvanGurtler/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,fheng/aerogear-unifiedpush-server,C-B4/unifiedpush-server,lfryc/aerogear-unifiedpush-server,secondsun/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,thradec/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,julioa/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,aerobase/unifiedpush-server,abstractj/aerogear-unifiedpush-server,lfryc/aerogear-unifiedpush-server,C-B4/unifiedpush-server,gunnarmorling/aerogear-unifiedpush-server,gunnarmorling/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,aerobase/unifiedpush-server,fheng/aerogear-unifiedpush-server,diogoalbuquerque/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,diogoalbuquerque/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,danielpassos/aerogear-unifiedpush-server,aerogear/aerogear-unifiedpush-server,abstractj/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,C-B4/unifiedpush-server,danielpassos/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,lfryc/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,aerogear/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,gunnarmorling/aerogear-unifiedpush-server,idelpivnitskiy/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,aerogear/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,matzew/aerogear-unifiedpush-server,lholmquist/aerogear-unified-push-server,julioa/aerogear-unifiedpush-server,matzew/aerogear-unifiedpush-server,sinarz/aerogear-unifiedpush-server,secondsun/aerogear-unifiedpush-server,yvnicolas/aerogear-unifiedpush-server,andresgalante/aerogear-unifiedpush-server,edewit/aerogear-unifiedpush-server,baiwyc119/aerogear-unifiedpush-server
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual 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.jboss.aerogear.unifiedpush.message.sender; import ar.com.fernandospr.wns.WnsService; import ar.com.fernandospr.wns.exceptions.WnsException; import ar.com.fernandospr.wns.model.WnsNotificationResponse; import ar.com.fernandospr.wns.model.WnsToast; import ar.com.fernandospr.wns.model.builders.WnsToastBuilder; import org.jboss.aerogear.unifiedpush.api.Variant; import org.jboss.aerogear.unifiedpush.api.WindowsVariant; import org.jboss.aerogear.unifiedpush.message.UnifiedPushMessage; import org.jboss.aerogear.unifiedpush.service.ClientInstallationService; import org.jboss.aerogear.unifiedpush.utils.AeroGearLogger; import javax.inject.Inject; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; @SenderType(WindowsVariant.class) public class WNSPushNotificationSender implements PushNotificationSender { private final AeroGearLogger logger = AeroGearLogger.getInstance(WNSPushNotificationSender.class); @Inject private ClientInstallationService clientInstallationService; @Override public void sendPushMessage(Variant variant, Collection<String> clientIdentifiers, UnifiedPushMessage pushMessage, NotificationSenderCallback senderCallback) { // no need to send empty list if (clientIdentifiers.isEmpty()) { return; } final WindowsVariant windowsVariant = (WindowsVariant) variant; WnsService wnsService = new WnsService(windowsVariant.getSid(), windowsVariant.getClientSecret(), true); //simple initial version just send toast message WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01(pushMessage.getMessage().getAlert()).build(); try { Set<String> expiredClientIdentifiers = new HashSet<String>(clientIdentifiers.size()); final List<WnsNotificationResponse> responses = wnsService.pushToast(new ArrayList<String>(clientIdentifiers), toast); for (WnsNotificationResponse response : responses) { if (response.code == HttpServletResponse.SC_GONE) { expiredClientIdentifiers.add(response.channelUri); } } if (!expiredClientIdentifiers.isEmpty()) { logger.info(String.format("Deleting '%d' expired WNS installations", expiredClientIdentifiers.size())); clientInstallationService.removeInstallationsForVariantByDeviceTokens(variant.getVariantID(), expiredClientIdentifiers); } logger.fine("Message to WNS has been submitted"); senderCallback.onSuccess(); } catch (WnsException exception) { senderCallback.onError(exception.getMessage()); } } }
push/src/main/java/org/jboss/aerogear/unifiedpush/message/sender/WNSPushNotificationSender.java
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual 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.jboss.aerogear.unifiedpush.message.sender; import ar.com.fernandospr.wns.WnsService; import ar.com.fernandospr.wns.exceptions.WnsException; import ar.com.fernandospr.wns.model.WnsNotificationResponse; import ar.com.fernandospr.wns.model.WnsToast; import ar.com.fernandospr.wns.model.builders.WnsToastBuilder; import org.jboss.aerogear.unifiedpush.api.Variant; import org.jboss.aerogear.unifiedpush.api.WindowsVariant; import org.jboss.aerogear.unifiedpush.message.UnifiedPushMessage; import org.jboss.aerogear.unifiedpush.service.ClientInstallationService; import javax.inject.Inject; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; @SenderType(WindowsVariant.class) public class WNSPushNotificationSender implements PushNotificationSender { private final Logger logger = Logger.getLogger(WNSPushNotificationSender.class.getName()); @Inject private ClientInstallationService clientInstallationService; @Override public void sendPushMessage(Variant variant, Collection<String> clientIdentifiers, UnifiedPushMessage pushMessage, NotificationSenderCallback senderCallback) { // no need to send empty list if (clientIdentifiers.isEmpty()) { return; } final WindowsVariant windowsVariant = (WindowsVariant) variant; WnsService wnsService = new WnsService(windowsVariant.getSid(), windowsVariant.getClientSecret(), true); //simple initial version just send toast message WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01(pushMessage.getMessage().getAlert()).build(); try { Set<String> expiredClientIdentifiers = new HashSet<String>(clientIdentifiers.size()); final List<WnsNotificationResponse> responses = wnsService.pushToast(new ArrayList<String>(clientIdentifiers), toast); for (WnsNotificationResponse response : responses) { if (response.code == HttpServletResponse.SC_GONE) { expiredClientIdentifiers.add(response.channelUri); } } if (!expiredClientIdentifiers.isEmpty()) { logger.log(Level.INFO, String.format("Deleting '%d' expired WNS installations", expiredClientIdentifiers.size())); clientInstallationService.removeInstallationsForVariantByDeviceTokens(variant.getVariantID(), expiredClientIdentifiers); } logger.log(Level.FINE, "Message to WNS has been submitted"); senderCallback.onSuccess(); } catch (WnsException exception) { senderCallback.onError(exception.getMessage()); } } }
Using AG logger
push/src/main/java/org/jboss/aerogear/unifiedpush/message/sender/WNSPushNotificationSender.java
Using AG logger
<ide><path>ush/src/main/java/org/jboss/aerogear/unifiedpush/message/sender/WNSPushNotificationSender.java <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <ide> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <add> * http://www.apache.org/licenses/LICENSE-2.0 <ide> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> import org.jboss.aerogear.unifiedpush.api.WindowsVariant; <ide> import org.jboss.aerogear.unifiedpush.message.UnifiedPushMessage; <ide> import org.jboss.aerogear.unifiedpush.service.ClientInstallationService; <add>import org.jboss.aerogear.unifiedpush.utils.AeroGearLogger; <ide> <ide> import javax.inject.Inject; <ide> import javax.servlet.http.HttpServletResponse; <ide> import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Set; <del>import java.util.logging.Level; <del>import java.util.logging.Logger; <ide> <ide> @SenderType(WindowsVariant.class) <ide> public class WNSPushNotificationSender implements PushNotificationSender { <ide> <del> private final Logger logger = Logger.getLogger(WNSPushNotificationSender.class.getName()); <add> private final AeroGearLogger logger = AeroGearLogger.getInstance(WNSPushNotificationSender.class); <ide> <ide> @Inject <ide> private ClientInstallationService clientInstallationService; <ide> } <ide> } <ide> if (!expiredClientIdentifiers.isEmpty()) { <del> logger.log(Level.INFO, String.format("Deleting '%d' expired WNS installations", expiredClientIdentifiers.size())); <add> logger.info(String.format("Deleting '%d' expired WNS installations", expiredClientIdentifiers.size())); <ide> clientInstallationService.removeInstallationsForVariantByDeviceTokens(variant.getVariantID(), expiredClientIdentifiers); <ide> } <del> logger.log(Level.FINE, "Message to WNS has been submitted"); <add> logger.fine("Message to WNS has been submitted"); <ide> senderCallback.onSuccess(); <ide> } catch (WnsException exception) { <ide> senderCallback.onError(exception.getMessage());
Java
apache-2.0
1d824b5f32207c4283141d65ad219ef113b93083
0
robertdale/tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,artem-aliev/tinkerpop,krlohnes/tinkerpop,pluradj/incubator-tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,jorgebay/tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop
/* * 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.tinkerpop.gremlin.structure.util; import org.apache.tinkerpop.gremlin.structure.Graph; import java.io.Closeable; import java.util.Iterator; /** * An extension of {@code Iterator} that implements {@code Closeable} which allows a {@link Graph} implementation * that hold open resources to provide the user the option to release those resources. * * @author Stephen Mallette (http://stephen.genoprime.com) */ public interface CloseableIterator<T> extends Iterator<T>, Closeable { /** * Wraps an existing {@code Iterator} in a {@code CloseableIterator}. If the {@code Iterator} is already of that * type then it will simply be returned as-is. */ public static <T> CloseableIterator<T> asCloseable(final Iterator<T> iterator) { if (iterator instanceof CloseableIterator) return (CloseableIterator<T>) iterator; return new DefaultCloseableIterator<T>(iterator); } @Override public default void close() { // do nothing by default } public static <T> void closeIterator(final Iterator<T> iterator) { if (iterator instanceof AutoCloseable) { try { ((AutoCloseable) iterator).close(); } catch (Exception e) { throw new RuntimeException(e); } } } }
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/CloseableIterator.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.tinkerpop.gremlin.structure.util; import org.apache.tinkerpop.gremlin.structure.Graph; import java.io.Closeable; import java.util.Iterator; /** * An extension of {@code Iterator} that implements {@code Closeable} which allows a {@link Graph} implementation * that hold open resources to provide the user the option to release those resources. * * @author Stephen Mallette (http://stephen.genoprime.com) */ public interface CloseableIterator<T> extends Iterator<T>, Closeable { /** * Wraps an existing {@code Iterator} in a {@code CloseableIterator}. If the {@code Iterator} is already of that * type then it will simply be returned as-is. */ public static <T> CloseableIterator<T> asCloseable(final Iterator<T> iterator) { if (iterator instanceof CloseableIterator) return (CloseableIterator<T>) iterator; return new DefaultCloseableIterator<T>(iterator); } @Override public default void close() { // do nothing by default } public static <T> void closeIterator(Iterator<T> iterator) { if (iterator instanceof AutoCloseable) { try { ((AutoCloseable) iterator).close(); } catch (Exception e) { throw new RuntimeException(e); } } } }
Finalize a variable CTR
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/CloseableIterator.java
Finalize a variable CTR
<ide><path>remlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/CloseableIterator.java <ide> // do nothing by default <ide> } <ide> <del> public static <T> void closeIterator(Iterator<T> iterator) { <add> public static <T> void closeIterator(final Iterator<T> iterator) { <ide> if (iterator instanceof AutoCloseable) { <ide> try { <ide> ((AutoCloseable) iterator).close();
Java
mit
0d434ee2d5e19aea3e086884bad12d87a5c0d0d9
0
JCThePants/TPRegions
/* This file is part of TPRegions for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.bukkit.tpregions.regions; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.performance.SingleCache; import com.jcwhatever.bukkit.generic.regions.ReadOnlyRegion; import com.jcwhatever.bukkit.generic.storage.BatchOperation; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.utils.PreCon; import org.bukkit.Location; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class TPRegionManager { private static TPRegionManager _instance; public static TPRegionManager get() { return _instance; } private Map<String, TPRegion> _regionMap = new HashMap<String, TPRegion>(); private IDataNode _settings; private SingleCache<RegionType, List<TPRegion>> _regionsByTypeCache = new SingleCache<RegionType, List<TPRegion>>(); public TPRegionManager(IDataNode settings) { _instance = this; _settings = settings; loadRegions(); } public TPRegion getRegion(String name) { return _regionMap.get(name.toLowerCase()); } public List<TPRegion> getRegions() { return new ArrayList<TPRegion>(_regionMap.values()); } public List<TPRegion> getRegions(RegionType type) { if (_regionsByTypeCache.keyEquals(type)) return new ArrayList<TPRegion>(_regionsByTypeCache.getValue()); List<TPRegion> regions = new ArrayList<TPRegion>(); for (TPRegion region : getRegions()) { if (region.getType() == type) regions.add(region); } _regionsByTypeCache.set(type, new ArrayList<TPRegion>(regions)); return regions; } public TPRegion getRegionAt(Location location) { PreCon.notNull(location); Set<ReadOnlyRegion> regions = GenericsLib.getRegionManager().getRegions(location); for (ReadOnlyRegion region : regions) { if (region.getHandleClass().equals(TPRegion.class)) { return getRegion(region.getName()); } } return null; } public TPRegion createRegion(String name, final Location p1, final Location p2) { IDataNode settings = _settings.getNode(name); final TPRegion region = new TPRegion(name, settings); settings.runBatchOperation(new BatchOperation() { @Override public void run(IDataNode dataNode) { region.setCoords(p1, p2); } }); _regionMap.put(region.getSearchName(), region); _regionsByTypeCache.reset(); region.init(this); return region; } public boolean delete(String name) { TPRegion region = getRegion(name); if (region == null) return false; _settings.set(region.getName(), null); _settings.saveAsync(null); region.dispose(); _regionMap.remove(region.getSearchName()); List<TPRegion> regions = getRegions(); for (TPRegion r : regions) { if (r.getDestination() != null && r.getDestination() == region) { r.setDestination(null); } } return true; } private void loadRegions() { Set<String> regionNames = _settings.getSubNodeNames(); if (regionNames == null || regionNames.isEmpty()) return; for (String regionName : regionNames) { loadRegion(regionName, _settings.getNode(regionName)); } for (TPRegion region : _regionMap.values()) { region.init(this); } } private void loadRegion(String name, IDataNode settings) { TPRegion region = new TPRegion(name, settings); _regionMap.put(region.getSearchName(), region); } }
src/com/jcwhatever/bukkit/tpregions/regions/TPRegionManager.java
/* This file is part of TPRegions for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.bukkit.tpregions.regions; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.performance.SingleCache; import com.jcwhatever.bukkit.generic.regions.ReadOnlyRegion; import com.jcwhatever.bukkit.generic.storage.BatchOperation; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.utils.PreCon; import org.bukkit.Location; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class TPRegionManager { private static TPRegionManager _instance; public static TPRegionManager get() { return _instance; } private Map<String, TPRegion> _regionMap = new HashMap<String, TPRegion>(); private IDataNode _settings; private SingleCache<RegionType, List<TPRegion>> _regionsByTypeCache = new SingleCache<RegionType, List<TPRegion>>(); public TPRegionManager(IDataNode settings) { _instance = this; _settings = settings; loadRegions(); } public TPRegion getRegion(String name) { return _regionMap.get(name.toLowerCase()); } public List<TPRegion> getRegions() { return new ArrayList<TPRegion>(_regionMap.values()); } public List<TPRegion> getRegions(RegionType type) { if (_regionsByTypeCache.keyEquals(type)) return new ArrayList<TPRegion>(_regionsByTypeCache.getValue()); List<TPRegion> regions = new ArrayList<TPRegion>(); for (TPRegion region : getRegions()) { if (region.getType() == type) regions.add(region); } _regionsByTypeCache.set(type, new ArrayList<TPRegion>(regions)); return regions; } public TPRegion getRegionAt(Location location) { PreCon.notNull(location); Set<ReadOnlyRegion> regions = GenericsLib.getRegionManager().getRegions(location); for (ReadOnlyRegion region : regions) { if (region.getHandleClass().equals(TPRegion.class)) { return getRegion(region.getName()); } } return null; } public TPRegion createRegion(String name, final Location p1, final Location p2) { IDataNode settings = _settings.getNode(name); final TPRegion region = new TPRegion(name, settings); settings.runBatchOperation(new BatchOperation() { @Override public void run(IDataNode config) { region.setCoords(p1, p2); } }); _regionMap.put(region.getSearchName(), region); _regionsByTypeCache.reset(); region.init(this); return region; } public boolean delete(String name) { TPRegion region = getRegion(name); if (region == null) return false; _settings.set(region.getName(), null); _settings.saveAsync(null); region.dispose(); _regionMap.remove(region.getSearchName()); List<TPRegion> regions = getRegions(); for (TPRegion r : regions) { if (r.getDestination() != null && r.getDestination() == region) { r.setDestination(null); } } return true; } private void loadRegions() { Set<String> regionNames = _settings.getSubNodeNames(); if (regionNames == null || regionNames.isEmpty()) return; for (String regionName : regionNames) { loadRegion(regionName, _settings.getNode(regionName)); } for (TPRegion region : _regionMap.values()) { region.init(this); } } private void loadRegion(String name, IDataNode settings) { TPRegion region = new TPRegion(name, settings); _regionMap.put(region.getSearchName(), region); } }
refactoring, add comments
src/com/jcwhatever/bukkit/tpregions/regions/TPRegionManager.java
refactoring, add comments
<ide><path>rc/com/jcwhatever/bukkit/tpregions/regions/TPRegionManager.java <ide> settings.runBatchOperation(new BatchOperation() { <ide> <ide> @Override <del> public void run(IDataNode config) { <add> public void run(IDataNode dataNode) { <ide> region.setCoords(p1, p2); <ide> } <ide> });
Java
epl-1.0
1c527f8a873f0e7fb47ec724faee479f7b8bea7d
0
gastaldi/furnace,forge/furnace,pplatek/furnace,koentsje/forge-furnace
/* ] * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.furnace.impl.modules; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.jar.JarFile; import java.util.logging.Logger; import org.jboss.forge.furnace.Furnace; import org.jboss.forge.furnace.addons.Addon; import org.jboss.forge.furnace.addons.AddonId; import org.jboss.forge.furnace.addons.AddonView; import org.jboss.forge.furnace.exception.ContainerException; import org.jboss.forge.furnace.impl.addons.AddonLifecycleManager; import org.jboss.forge.furnace.impl.addons.AddonRepositoryImpl; import org.jboss.forge.furnace.impl.addons.AddonStateManager; import org.jboss.forge.furnace.impl.modules.providers.FurnaceContainerSpec; import org.jboss.forge.furnace.impl.modules.providers.SystemClasspathSpec; import org.jboss.forge.furnace.impl.modules.providers.XPathJDKClasspathSpec; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jboss.forge.furnace.repositories.AddonRepository; import org.jboss.forge.furnace.versions.Version; import org.jboss.modules.DependencySpec; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.modules.ModuleSpec; import org.jboss.modules.ModuleSpec.Builder; import org.jboss.modules.ResourceLoaderSpec; import org.jboss.modules.ResourceLoaders; import org.jboss.modules.filter.PathFilters; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> */ public class AddonModuleLoader extends ModuleLoader { private static final Logger logger = Logger.getLogger(AddonModuleLoader.class.getName()); private Iterable<ModuleSpecProvider> moduleProviders; private AddonModuleIdentifierCache moduleCache; private AddonModuleJarFileCache moduleJarFileCache; private AddonLifecycleManager lifecycleManager; private AddonStateManager stateManager; private ThreadLocal<Addon> currentAddon = new ThreadLocal<Addon>(); private Furnace furnace; public AddonModuleLoader(Furnace furnace, AddonLifecycleManager lifecycleManager, AddonStateManager stateManager) { this.furnace = furnace; this.lifecycleManager = lifecycleManager; this.stateManager = stateManager; this.moduleCache = new AddonModuleIdentifierCache(); this.moduleJarFileCache = new AddonModuleJarFileCache(); installModuleMBeanServer(); } /** * Loads a module for the given Addon. */ public final Module loadAddonModule(Addon addon) throws ModuleLoadException { try { this.currentAddon.set(addon); ModuleIdentifier moduleId = moduleCache.getModuleId(addon); Module result = loadModule(moduleId); return result; } catch (ModuleLoadException e) { throw e; } finally { this.currentAddon.remove(); } } @Override protected Module preloadModule(ModuleIdentifier identifier) throws ModuleLoadException { Module pluginModule = super.preloadModule(identifier); return pluginModule; } @Override protected ModuleSpec findModule(ModuleIdentifier id) throws ModuleLoadException { ModuleSpec result = findRegularModule(id); if (result == null && currentAddon.get() != null) result = findAddonModule(id); return result; } private ModuleSpec findRegularModule(ModuleIdentifier id) { ModuleSpec result = null; for (ModuleSpecProvider p : getModuleProviders()) { result = p.get(this, id); if (result != null) break; } return result; } private Iterable<ModuleSpecProvider> getModuleProviders() { if (moduleProviders == null) moduleProviders = ServiceLoader.load(ModuleSpecProvider.class, furnace.getRuntimeClassLoader()); return moduleProviders; } private ModuleSpec findAddonModule(ModuleIdentifier id) { Addon addon = currentAddon.get(); if (addon != null) { Set<AddonView> views = stateManager.getViewsOf(addon); AddonId found = addon.getId(); for (AddonRepository repository : views.iterator().next().getRepositories()) { if (repository.isEnabled(found) && repository.isDeployed(found)) { Addon mappedAddon = moduleCache.getAddon(id); if (mappedAddon != null && mappedAddon.getId().equals(found)) { Builder builder = ModuleSpec.build(id); builder.addDependency(DependencySpec.createModuleDependencySpec(SystemClasspathSpec.ID)); builder.addDependency(DependencySpec.createModuleDependencySpec(XPathJDKClasspathSpec.ID)); builder.addDependency(DependencySpec.createModuleDependencySpec(PathFilters.acceptAll(), PathFilters.rejectAll(), null, FurnaceContainerSpec.ID, false)); try { addContainerDependencies(views, repository, found, builder); } catch (ContainerException e) { logger.warning(e.getMessage()); return null; } try { addAddonDependencies(views, repository, found, builder); } catch (ContainerException e) { logger.warning(e.getMessage()); return null; } builder.addDependency(DependencySpec.createLocalDependencySpec(PathFilters.acceptAll(), PathFilters.acceptAll())); addLocalResources(repository, found, builder, id); return builder.create(); } } } } return null; } private void addLocalResources(AddonRepository repository, AddonId found, Builder builder, ModuleIdentifier id) { List<File> resources = repository.getAddonResources(found); for (File file : resources) { try { if (file.isDirectory()) { builder.addResourceRoot( ResourceLoaderSpec.createResourceLoaderSpec( ResourceLoaders.createFileResourceLoader(file.getName(), file), PathFilters.acceptAll()) ); } else if (file.length() > 0) { JarFile jarFile = new JarFile(file); moduleJarFileCache.addJarFileReference(id, jarFile); builder.addResourceRoot( ResourceLoaderSpec.createResourceLoaderSpec( ResourceLoaders.createJarResourceLoader(file.getName(), jarFile), PathFilters.acceptAll()) ); } } catch (IOException e) { throw new ContainerException("Could not load resources from [" + file.getAbsolutePath() + "]", e); } } } private void addContainerDependencies(Set<AddonView> views, AddonRepository repository, AddonId found, Builder builder) throws ContainerException { Set<AddonDependencyEntry> addons = repository.getAddonDependencies(found); for (AddonDependencyEntry dependency : addons) { /* * Containers should always take precedence at runtime. */ if (dependency.getName().startsWith("org.jboss.forge.furnace:container")) addAddonDependency(views, found, builder, dependency); } } private void addAddonDependencies(Set<AddonView> views, AddonRepository repository, AddonId found, Builder builder) throws ContainerException { Set<AddonDependencyEntry> addons = repository.getAddonDependencies(found); for (AddonDependencyEntry dependency : addons) { if (!dependency.getName().startsWith("org.jboss.forge.furnace:container")) addAddonDependency(views, found, builder, dependency); } } private void addAddonDependency(Set<AddonView> views, AddonId found, Builder builder, AddonDependencyEntry dependency) { AddonId addonId = stateManager.resolveAddonId(views, dependency.getName()); ModuleIdentifier moduleId = null; if (addonId != null) { Addon addon = lifecycleManager.getAddon(views, addonId); moduleId = findCompatibleInstalledModule(addonId); if (moduleId != null) { builder.addDependency(DependencySpec.createModuleDependencySpec( PathFilters.not(PathFilters.getMetaInfFilter()), dependency.isExported() ? PathFilters.acceptAll() : PathFilters.rejectAll(), this, moduleCache.getModuleId(addon), dependency.isOptional())); } } if (!dependency.isOptional() && (addonId == null || moduleId == null)) throw new ContainerException("Dependency [" + dependency + "] could not be loaded for addon [" + found + "]"); } private ModuleIdentifier findCompatibleInstalledModule(AddonId addonId) { ModuleIdentifier result = null; Addon addon = currentAddon.get(); Version runtimeAPIVersion = AddonRepositoryImpl.getRuntimeAPIVersion(); for (AddonRepository repository : stateManager.getViewsOf(addon).iterator().next().getRepositories()) { List<AddonId> enabled = repository.listEnabledCompatibleWithVersion(runtimeAPIVersion); for (AddonId id : enabled) { if (id.getName().equals(addonId.getName())) { result = moduleCache.getModuleId(addon); break; } } } return result; } @Override public String toString() { return "AddonModuleLoader"; } public void releaseAddonModule(Addon addon) { ModuleIdentifier id = moduleCache.getModuleId(addon); moduleJarFileCache.closeJarFileReferences(id); Module loadedModule = findLoadedModuleLocal(id); if (loadedModule != null) unloadModuleLocal(loadedModule); moduleCache.clear(addon); } /** * Installs the MBeanServer. */ private void installModuleMBeanServer() { try { Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer"); method.setAccessible(true); method.invoke(null); } catch (Exception e) { throw new ContainerException("Could not install Modules MBean server", e); } } }
container/src/main/java/org/jboss/forge/furnace/impl/modules/AddonModuleLoader.java
/* ] * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.furnace.impl.modules; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.jar.JarFile; import java.util.logging.Logger; import org.jboss.forge.furnace.Furnace; import org.jboss.forge.furnace.addons.Addon; import org.jboss.forge.furnace.addons.AddonId; import org.jboss.forge.furnace.addons.AddonView; import org.jboss.forge.furnace.exception.ContainerException; import org.jboss.forge.furnace.impl.addons.AddonLifecycleManager; import org.jboss.forge.furnace.impl.addons.AddonRepositoryImpl; import org.jboss.forge.furnace.impl.addons.AddonStateManager; import org.jboss.forge.furnace.impl.modules.providers.FurnaceContainerSpec; import org.jboss.forge.furnace.impl.modules.providers.SystemClasspathSpec; import org.jboss.forge.furnace.impl.modules.providers.XPathJDKClasspathSpec; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jboss.forge.furnace.repositories.AddonRepository; import org.jboss.forge.furnace.versions.Version; import org.jboss.modules.DependencySpec; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.modules.ModuleSpec; import org.jboss.modules.ModuleSpec.Builder; import org.jboss.modules.ResourceLoaderSpec; import org.jboss.modules.ResourceLoaders; import org.jboss.modules.filter.PathFilters; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> */ public class AddonModuleLoader extends ModuleLoader { private static final Logger logger = Logger.getLogger(AddonModuleLoader.class.getName()); private Iterable<ModuleSpecProvider> moduleProviders; private AddonModuleIdentifierCache moduleCache; private AddonModuleJarFileCache moduleJarFileCache; private AddonLifecycleManager lifecycleManager; private AddonStateManager stateManager; private ThreadLocal<Addon> currentAddon = new ThreadLocal<Addon>(); private Furnace furnace; public AddonModuleLoader(Furnace furnace, AddonLifecycleManager lifecycleManager, AddonStateManager stateManager) { this.furnace = furnace; this.lifecycleManager = lifecycleManager; this.stateManager = stateManager; this.moduleCache = new AddonModuleIdentifierCache(); this.moduleJarFileCache = new AddonModuleJarFileCache(); installModuleMBeanServer(); } /** * Loads a module for the given Addon. */ public final Module loadAddonModule(Addon addon) throws ModuleLoadException { try { this.currentAddon.set(addon); ModuleIdentifier moduleId = moduleCache.getModuleId(addon); Module result = loadModule(moduleId); return result; } catch (ModuleLoadException e) { throw e; } finally { this.currentAddon.remove(); } } @Override protected Module preloadModule(ModuleIdentifier identifier) throws ModuleLoadException { Module pluginModule = super.preloadModule(identifier); return pluginModule; } @Override protected ModuleSpec findModule(ModuleIdentifier id) throws ModuleLoadException { ModuleSpec result = findRegularModule(id); if (result == null && currentAddon.get() != null) result = findAddonModule(id); return result; } private ModuleSpec findRegularModule(ModuleIdentifier id) { ModuleSpec result = null; for (ModuleSpecProvider p : getModuleProviders()) { result = p.get(this, id); if (result != null) break; } return result; } private Iterable<ModuleSpecProvider> getModuleProviders() { if (moduleProviders == null) moduleProviders = ServiceLoader.load(ModuleSpecProvider.class, furnace.getRuntimeClassLoader()); return moduleProviders; } private ModuleSpec findAddonModule(ModuleIdentifier id) { Addon addon = currentAddon.get(); if (addon != null) { Set<AddonView> views = stateManager.getViewsOf(addon); AddonId found = addon.getId(); for (AddonRepository repository : views.iterator().next().getRepositories()) { if (repository.isEnabled(found) && repository.isDeployed(found)) { Addon mappedAddon = moduleCache.getAddon(id); if (mappedAddon != null && mappedAddon.getId().equals(found)) { Builder builder = ModuleSpec.build(id); builder.addDependency(DependencySpec.createModuleDependencySpec(SystemClasspathSpec.ID)); builder.addDependency(DependencySpec.createModuleDependencySpec(XPathJDKClasspathSpec.ID)); builder.addDependency(DependencySpec.createModuleDependencySpec(PathFilters.acceptAll(), PathFilters.rejectAll(), null, FurnaceContainerSpec.ID, false)); try { addContainerDependencies(views, repository, found, builder); } catch (ContainerException e) { logger.warning(e.getMessage()); return null; } builder.addDependency(DependencySpec.createLocalDependencySpec(PathFilters.acceptAll(), PathFilters.acceptAll())); try { addAddonDependencies(views, repository, found, builder); } catch (ContainerException e) { logger.warning(e.getMessage()); return null; } addLocalResources(repository, found, builder, id); return builder.create(); } } } } return null; } private void addLocalResources(AddonRepository repository, AddonId found, Builder builder, ModuleIdentifier id) { List<File> resources = repository.getAddonResources(found); for (File file : resources) { try { if (file.isDirectory()) { builder.addResourceRoot( ResourceLoaderSpec.createResourceLoaderSpec( ResourceLoaders.createFileResourceLoader(file.getName(), file), PathFilters.acceptAll()) ); } else if (file.length() > 0) { JarFile jarFile = new JarFile(file); moduleJarFileCache.addJarFileReference(id, jarFile); builder.addResourceRoot( ResourceLoaderSpec.createResourceLoaderSpec( ResourceLoaders.createJarResourceLoader(file.getName(), jarFile), PathFilters.acceptAll()) ); } } catch (IOException e) { throw new ContainerException("Could not load resources from [" + file.getAbsolutePath() + "]", e); } } } private void addContainerDependencies(Set<AddonView> views, AddonRepository repository, AddonId found, Builder builder) throws ContainerException { Set<AddonDependencyEntry> addons = repository.getAddonDependencies(found); for (AddonDependencyEntry dependency : addons) { /* * Containers should always take precedence at runtime. */ if (dependency.getName().startsWith("org.jboss.forge.furnace:container")) addAddonDependency(views, found, builder, dependency); } } private void addAddonDependencies(Set<AddonView> views, AddonRepository repository, AddonId found, Builder builder) throws ContainerException { Set<AddonDependencyEntry> addons = repository.getAddonDependencies(found); for (AddonDependencyEntry dependency : addons) { if (!dependency.getName().startsWith("org.jboss.forge.furnace:container")) addAddonDependency(views, found, builder, dependency); } } private void addAddonDependency(Set<AddonView> views, AddonId found, Builder builder, AddonDependencyEntry dependency) { AddonId addonId = stateManager.resolveAddonId(views, dependency.getName()); ModuleIdentifier moduleId = null; if (addonId != null) { Addon addon = lifecycleManager.getAddon(views, addonId); moduleId = findCompatibleInstalledModule(addonId); if (moduleId != null) { builder.addDependency(DependencySpec.createModuleDependencySpec( PathFilters.not(PathFilters.getMetaInfFilter()), dependency.isExported() ? PathFilters.acceptAll() : PathFilters.rejectAll(), this, moduleCache.getModuleId(addon), dependency.isOptional())); } } if (!dependency.isOptional() && (addonId == null || moduleId == null)) throw new ContainerException("Dependency [" + dependency + "] could not be loaded for addon [" + found + "]"); } private ModuleIdentifier findCompatibleInstalledModule(AddonId addonId) { ModuleIdentifier result = null; Addon addon = currentAddon.get(); Version runtimeAPIVersion = AddonRepositoryImpl.getRuntimeAPIVersion(); for (AddonRepository repository : stateManager.getViewsOf(addon).iterator().next().getRepositories()) { List<AddonId> enabled = repository.listEnabledCompatibleWithVersion(runtimeAPIVersion); for (AddonId id : enabled) { if (id.getName().equals(addonId.getName())) { result = moduleCache.getModuleId(addon); break; } } } return result; } @Override public String toString() { return "AddonModuleLoader"; } public void releaseAddonModule(Addon addon) { ModuleIdentifier id = moduleCache.getModuleId(addon); moduleJarFileCache.closeJarFileReferences(id); Module loadedModule = findLoadedModuleLocal(id); if (loadedModule != null) unloadModuleLocal(loadedModule); moduleCache.clear(addon); } /** * Installs the MBeanServer. */ private void installModuleMBeanServer() { try { Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer"); method.setAccessible(true); method.invoke(null); } catch (Exception e) { throw new ContainerException("Could not install Modules MBean server", e); } } }
Fix classloader ordering
container/src/main/java/org/jboss/forge/furnace/impl/modules/AddonModuleLoader.java
Fix classloader ordering
<ide><path>ontainer/src/main/java/org/jboss/forge/furnace/impl/modules/AddonModuleLoader.java <ide> return null; <ide> } <ide> <del> builder.addDependency(DependencySpec.createLocalDependencySpec(PathFilters.acceptAll(), <del> PathFilters.acceptAll())); <del> <ide> try <ide> { <ide> addAddonDependencies(views, repository, found, builder); <ide> logger.warning(e.getMessage()); <ide> return null; <ide> } <add> <add> builder.addDependency(DependencySpec.createLocalDependencySpec(PathFilters.acceptAll(), <add> PathFilters.acceptAll())); <ide> <ide> addLocalResources(repository, found, builder, id); <ide>
Java
apache-2.0
1439ba78081a6ad4293bc02f0e5ac419dc974824
0
sunhai1988/nutz-book-project,wendal/nutz-book-project,wendal/nutz-book-project,sunhai1988/nutz-book-project,sunhai1988/nutz-book-project,sunhai1988/nutz-book-project,wendal/nutz-book-project,wendal/nutz-book-project
src/org/nutz/integration/shiro/ShiroSessionProvider.java
package org.nutz.integration.shiro; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.web.servlet.ShiroHttpServletRequest; import org.nutz.mvc.SessionProvider; /** * ไปฃ็†Nutzๅ†…้ƒจไฝฟ็”จSession็š„่ฐƒ็”จไธบShiro็š„Shiro็š„session * @author wendal * */ public class ShiroSessionProvider implements SessionProvider { public HttpServletRequest filter(HttpServletRequest req, HttpServletResponse resp, ServletContext servletContext) { if ("OPTIONS".equalsIgnoreCase(req.getMethod())) { resp.addHeader("Access-Control-Allow-Origin", "*"); resp.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key"); } if (req instanceof ShiroHttpServletRequest) return req; return new ShiroHttpServletRequest(req, servletContext, true); } public void notifyStop() { } }
remove: ShiroSessionProviderๅœจshiroๆ’ไปถๅทฒ็ปๆœ‰ๆไพ›
src/org/nutz/integration/shiro/ShiroSessionProvider.java
remove: ShiroSessionProviderๅœจshiroๆ’ไปถๅทฒ็ปๆœ‰ๆไพ›
<ide><path>rc/org/nutz/integration/shiro/ShiroSessionProvider.java <del>package org.nutz.integration.shiro; <del> <del>import javax.servlet.ServletContext; <del>import javax.servlet.http.HttpServletRequest; <del>import javax.servlet.http.HttpServletResponse; <del> <del>import org.apache.shiro.web.servlet.ShiroHttpServletRequest; <del>import org.nutz.mvc.SessionProvider; <del> <del>/** <del> * ไปฃ็†Nutzๅ†…้ƒจไฝฟ็”จSession็š„่ฐƒ็”จไธบShiro็š„Shiro็š„session <del> * @author wendal <del> * <del> */ <del>public class ShiroSessionProvider implements SessionProvider { <del> <del> public HttpServletRequest filter(HttpServletRequest req, HttpServletResponse resp, ServletContext servletContext) { <del> if ("OPTIONS".equalsIgnoreCase(req.getMethod())) { <del> resp.addHeader("Access-Control-Allow-Origin", "*"); <del> resp.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key"); <del> } <del> if (req instanceof ShiroHttpServletRequest) <del> return req; <del> return new ShiroHttpServletRequest(req, servletContext, true); <del> } <del> <del> public void notifyStop() { <del> } <del> <del>}
Java
mit
8c48677789c4fa8e1d5ac74ea9a171094c375605
0
huangj7/doco,tj-recess/doco,marcosvidolin/doco
package com.vidolima.doco; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; import com.google.appengine.api.search.GeoPoint; import com.vidolima.doco.annotation.DocumentField; import com.vidolima.doco.annotation.DocumentId; import com.vidolima.doco.annotation.FieldType; import com.vidolima.doco.exception.DocumentParseException; /** * This class is used to create {@link Document}s instances from Objects. * * @author Marcos Alexandre Vidolin de Lima * @since January 28, 2014 */ final class DocumentParser { /** * Obtains the {@link java.lang.reflect.Field} annotated with * {@link DocumentId} annotation. * * @param classOfObj * the class of the object that contains the field * @return the {@link java.lang.reflect.Field} that contains the * {@link DocumentId} annotation * @exception DocumentParseException */ private java.lang.reflect.Field getDocumentIdField(Class<?> classOfObj) throws DocumentParseException { List<java.lang.reflect.Field> result = ReflectionUtils .getAnnotatedFields(classOfObj, DocumentId.class); if (result.size() > 1) { throw new DocumentParseException( "More than one occurrence of @DocumentId found in " + classOfObj); } if (result.isEmpty()) { throw new DocumentParseException( "No @DocumentId annotation was found in " + classOfObj); } return result.get(0); } /** * Obtains all the {@link java.lang.reflect.Field}s annotated with the * {@link DocumentId}. * * @param classOfObj * the class of the object that contains the fields to be search * @return all the annotated {@link java.lang.reflect.Field} that contains * the {@link DocumentField} annotation. */ List<java.lang.reflect.Field> getAllDocumentField(Class<?> classOfObj) { return ReflectionUtils.getAnnotatedFields(classOfObj, DocumentField.class); } /** * Returns the {@link DocumentId} value of a given Object. * * @param obj * the object base * @param classOfObj * the class of object * @return the id of the document * @throws IllegalArgumentException * @throws IllegalAccessException */ @SuppressWarnings({ "unchecked", "rawtypes" }) private <T> T getId(Object obj, Class<?> classOfObj, Class classOfT) throws IllegalArgumentException, IllegalAccessException { java.lang.reflect.Field field = getDocumentIdField(classOfObj); T id = (T) ReflectionUtils.getFieldValue(field, obj, classOfT); if (id == null) { throw new DocumentParseException("No id was set to \"" + field.getName() + "\" field in " + classOfObj); } return id; } /** * Obtains a list of {@link com.google.appengine.api.search.Field} from * {@link FieldType}. * * @param obj * the object base * @param classOfObj * the class of object * @return a list of {@link com.google.appengine.api.search.Field} * @throws IllegalArgumentException * @throws IllegalAccessException */ List<com.google.appengine.api.search.Field> getAllSearchFieldsByType( Object obj, Class<?> classOfObj, FieldType fieldType) throws IllegalArgumentException, IllegalAccessException { List<com.google.appengine.api.search.Field> fields = new ArrayList<Field>( 0); for (java.lang.reflect.Field f : getAllDocumentField(classOfObj)) { // TODO: validate field (declaration of annotation) DocumentField annotation = ObjectParser .getDocumentFieldAnnotation(f); if (annotation.type().equals(fieldType)) { String name = ObjectParser.getFieldNameValue(f, annotation); Object fieldValue = f.get(obj); com.google.appengine.api.search.Field field = getSearchFieldByFieldType( name, fieldValue, fieldType); fields.add(field); } } return fields; } /** * Obtains all fields with Doco annotations. * * @param obj * the origin object * @param classOfObj * the class of obj * @return a list of {@link com.google.appengine.api.search.Field} * @throws IllegalArgumentException * @throws IllegalAccessException */ List<com.google.appengine.api.search.Field> getAllSearchFields(Object obj, Class<?> classOfObj) throws IllegalArgumentException, IllegalAccessException { List<com.google.appengine.api.search.Field> fields = new ArrayList<com.google.appengine.api.search.Field>(); for (FieldType type : FieldType.values()) { for (com.google.appengine.api.search.Field f : getAllSearchFieldsByType( obj, classOfObj, type)) { fields.add(f); } } return fields; } /** * Obtains a {@link com.google.appengine.api.search.Field} given a name, * value and type. * * @param fieldValue * the value to be set to the returned field * @param name * the name of returned field * @param fieldType * the {@link FieldType} * @return the {@link com.google.appengine.api.search.Field} * @throws IllegalAccessException */ private com.google.appengine.api.search.Field getSearchFieldByFieldType( String name, Object fieldValue, FieldType fieldType) throws IllegalAccessException { if (FieldType.TEXT.equals(fieldType)) { String text = (String) fieldValue; return Field.newBuilder().setName(name).setText(text).build(); } if (FieldType.HTML.equals(fieldType)) { String html = (String) fieldValue; return Field.newBuilder().setName(name).setHTML(html).build(); } if (FieldType.ATOM.equals(fieldType)) { String atom = (String) fieldValue; return Field.newBuilder().setName(name).setAtom(atom).build(); } if (FieldType.DATE.equals(fieldType)) { if (fieldValue == null) { throw new NullPointerException( "Date and geopoint fields must be assigned a non-null value."); } Date date = (Date) fieldValue; return Field.newBuilder().setName(name).setDate(date).build(); } if (FieldType.GEO_POINT.equals(fieldType)) { if (fieldValue == null) { throw new NullPointerException( "Date and geopoint fields must be assigned a non-null value."); } GeoPoint geoPoint = (GeoPoint) fieldValue; return Field.newBuilder().setName(name).setGeoPoint(geoPoint) .build(); } if (FieldType.NUMBER.equals(fieldType)) { Double number = (Double) fieldValue; return Field.newBuilder().setName(name).setNumber(number).build(); } // Note: When you create a document you must specify all of its // attributes using the Document.Builder class method. You cannot add, // remove, or delete fields, nor change the identifier or any other // attribute once the document has been created. Date and geopoint // fields must be assigned a non-null value. Atom, text, HTML, and // number fields can be empty return null; } /** * Parses a object to an {@link Document}. * * @param obj * the object to be parsed * @param typeOfObj * the base class of the given object * @return a {@link Document} * @throws IllegalAccessException * @throws IllegalArgumentException */ Document parseDocument(Object obj, Class<?> classOfObj) throws IllegalArgumentException, IllegalAccessException { java.lang.reflect.Field field = getDocumentIdField(classOfObj); String id = String.valueOf(getId(obj, classOfObj, field.getType())); Document.Builder builder = Document.newBuilder().setId(id); for (com.google.appengine.api.search.Field f : getAllSearchFields(obj, classOfObj)) { if (f != null) { builder.addField(f); } } return builder.build(); } }
src/main/java/com/vidolima/doco/DocumentParser.java
package com.vidolima.doco; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; import com.google.appengine.api.search.GeoPoint; import com.vidolima.doco.annotation.DocumentField; import com.vidolima.doco.annotation.DocumentId; import com.vidolima.doco.annotation.FieldType; import com.vidolima.doco.exception.DocumentParseException; /** * This class is used to create {@link Document}s instances from Objects. * * @author Marcos Alexandre Vidolin de Lima * @since January 28, 2014 */ final class DocumentParser { /** * Obtains the {@link java.lang.reflect.Field} annotated with * {@link DocumentId} annotation. * * @param classOfObj * the class of the object that contains the field * @return the {@link java.lang.reflect.Field} that contains the * {@link DocumentId} annotation * @exception DocumentParseException */ private java.lang.reflect.Field getDocumentIdField(Class<?> classOfObj) throws DocumentParseException { List<java.lang.reflect.Field> result = ReflectionUtils .getAnnotatedFields(classOfObj, DocumentId.class); if (result.size() > 1) { throw new DocumentParseException( "More than one occurrence of @DocumentId found in " + classOfObj); } if (result.isEmpty()) { throw new DocumentParseException( "No @DocumentId annotation was found in " + classOfObj); } return result.get(0); } /** * Obtains all the {@link java.lang.reflect.Field}s annotated with the * {@link DocumentId}. * * @param classOfObj * the class of the object that contains the fields to be search * @return all the annotated {@link java.lang.reflect.Field} that contains * the {@link DocumentField} annotation. */ List<java.lang.reflect.Field> getAllDocumentField(Class<?> classOfObj) { return ReflectionUtils.getAnnotatedFields(classOfObj, DocumentField.class); } /** * Returns the {@link DocumentId} value of a given Object. * * @param obj * the object base * @param classOfObj * the class of object * @return the id of the document * @throws IllegalArgumentException * @throws IllegalAccessException */ @SuppressWarnings({ "unchecked", "rawtypes" }) private <T> T getId(Object obj, Class<?> classOfObj, Class classOfT) throws IllegalArgumentException, IllegalAccessException { java.lang.reflect.Field field = getDocumentIdField(classOfObj); T id = (T) ReflectionUtils.getFieldValue(field, obj, classOfT); if (id == null) { throw new DocumentParseException("No id was set to \"" + field.getName() + "\" field in " + classOfObj); } return id; } /** * Obtains a list of {@link com.google.appengine.api.search.Field} from * {@link FieldType}. * * @param obj * the object base * @param classOfObj * the class of object * @return a list of {@link com.google.appengine.api.search.Field} * @throws IllegalArgumentException * @throws IllegalAccessException */ List<com.google.appengine.api.search.Field> getAllSearchFieldsByType( Object obj, Class<?> classOfObj, FieldType fieldType) throws IllegalArgumentException, IllegalAccessException { List<com.google.appengine.api.search.Field> fields = new ArrayList<Field>( 0); for (java.lang.reflect.Field f : getAllDocumentField(classOfObj)) { // TODO: validate field (declaration of annotation) DocumentField annotation = ObjectParser .getDocumentFieldAnnotation(f); if (annotation.type().equals(fieldType)) { String name = ObjectParser.getFieldNameValue(f, annotation); Object fieldValue = f.get(obj); com.google.appengine.api.search.Field field = getSearchFieldByFieldType( name, fieldValue, fieldType); fields.add(field); } } return fields; } /** * Obtains all fields with Doco annotations. * * @param obj * the origin object * @param classOfObj * the class of obj * @return a list of {@link com.google.appengine.api.search.Field} * @throws IllegalArgumentException * @throws IllegalAccessException */ List<com.google.appengine.api.search.Field> getAllSearchFields(Object obj, Class<?> classOfObj) throws IllegalArgumentException, IllegalAccessException { List<com.google.appengine.api.search.Field> fields = new ArrayList<com.google.appengine.api.search.Field>(); for (FieldType type : FieldType.values()) { for (com.google.appengine.api.search.Field f : getAllSearchFieldsByType( obj, classOfObj, type)) { fields.add(f); } } return fields; } /** * Obtains a {@link com.google.appengine.api.search.Field} given a name, * value and type. * * @param fieldValue * the value to be set to the returned field * @param name * the name of returned field * @param fieldType * the {@link FieldType} * @return the {@link com.google.appengine.api.search.Field} * @throws IllegalAccessException */ private com.google.appengine.api.search.Field getSearchFieldByFieldType( String name, Object fieldValue, FieldType fieldType) throws IllegalAccessException { if (FieldType.TEXT.equals(fieldType)) { String text = (String) fieldValue; return Field.newBuilder().setName(name).setText(text).build(); } if (FieldType.HTML.equals(fieldType)) { String html = (String) fieldValue; return Field.newBuilder().setName(name).setHTML(html).build(); } if (FieldType.ATOM.equals(fieldType)) { String atom = (String) fieldValue; return Field.newBuilder().setName(name).setAtom(atom).build(); } if (FieldType.DATE.equals(fieldType)) { if (fieldValue == null) { throw new NullPointerException( "Date and geopoint fields must be assigned a non-null value."); } Date date = (Date) fieldValue; return Field.newBuilder().setName(name).setDate(date).build(); } if (FieldType.GEO_POINT.equals(fieldType)) { if (fieldValue == null) { throw new NullPointerException( "Date and geopoint fields must be assigned a non-null value."); } GeoPoint geoPoint = (GeoPoint) fieldValue; return Field.newBuilder().setName(name).setGeoPoint(geoPoint) .build(); } if (FieldType.NUMBER.equals(fieldType)) { Double number = (Double) fieldValue; return Field.newBuilder().setName(name).setNumber(number).build(); } // Note: When you create a document you must specify all of its // attributes using the Document.Builder class method. You cannot add, // remove, or delete fields, nor change the identifier or any other // attribute once the document has been created. Date and geopoint // fields must be assigned a non-null value. Atom, text, HTML, and // number fields can be empty return null; } /** * Parses a object to an {@link Document}. * * @param obj * the object to be parsed * @param typeOfObj * the base class of the given object * @return a {@link Document} * @throws IllegalAccessException * @throws IllegalArgumentException */ @SuppressWarnings("rawtypes") Document parseDocument(Object obj, Class<?> classOfObj) throws IllegalArgumentException, IllegalAccessException { java.lang.reflect.Field field = getDocumentIdField(classOfObj); String id = String.valueOf(getId(obj, classOfObj, field.getType())); Document.Builder builder = Document.newBuilder().setId(id); for (com.google.appengine.api.search.Field f : getAllSearchFields(obj, classOfObj)) { if (f != null) { builder.addField(f); } } return builder.build(); } }
Removed @SuppressWarnings(rawtypes)
src/main/java/com/vidolima/doco/DocumentParser.java
Removed @SuppressWarnings(rawtypes)
<ide><path>rc/main/java/com/vidolima/doco/DocumentParser.java <ide> * @throws IllegalAccessException <ide> * @throws IllegalArgumentException <ide> */ <del> @SuppressWarnings("rawtypes") <ide> Document parseDocument(Object obj, Class<?> classOfObj) <ide> throws IllegalArgumentException, IllegalAccessException { <ide>
JavaScript
mit
4d4e56006c52a5e3e71d68f5cc861cd759f362a6
0
briantanner/eris,Flyy-y/eris,Datamats/eris,abalabahaha/eris
"use strict"; const Bucket = require("./util/Bucket"); const Channel = require("./core/Channel"); const Collection = require("./util/Collection"); const Endpoints = require("./Constants").Endpoints; const EventEmitter = require("eventemitter3"); const ExtendedUser = require("./core/ExtendedUser"); const GroupChannel = require("./core/GroupChannel"); const Guild = require("./core/Guild"); const GuildIntegration = require("./core/GuildIntegration"); const HTTPS = require("https"); const Invite = require("./core/Invite"); const Message = require("./core/Message"); const MultipartData = require("./util/MultipartData"); const PermissionOverwrite = require("./core/PermissionOverwrite"); const PrivateChannel = require("./core/PrivateChannel"); const Promise = require("bluebird"); const Relationship = require("./core/Relationship"); const Role = require("./core/Role"); const Shard = require("./core/Shard"); const User = require("./core/User"); const VoiceConnection = require("./core/VoiceConnection"); /** * Represents the main Eris client * @extends EventEmitter * @prop {String} token The bot user token * @prop {Boolean?} bot Whether the bot user belongs to an OAuth2 application * @prop {Object} options Eris options * @prop {Object} channelGuildMap Object mapping channel IDs to guild IDs * @prop {Collection<Shard>} shards Collection of shards Eris is using * @prop {Collection<Guild>} guilds Collection of guilds the bot is in * @prop {Object} privateChannelMap Object mapping user IDs to private channel IDs * @prop {Collection<PrivateChannel>} privateChannels Collection of private channels the bot is in * @prop {Collection<GroupChannel>} groupChannels Collection of group channels the bot is in (user accounts only) * @prop {Collection<VoiceConnection>} voiceConnections Collection of VoiceConnections the bot has * @prop {Object} retryAfters Object mapping endpoints to ratelimit expiry timestamps * @prop {Object} guildShardMap Object mapping guild IDs to shard IDs * @prop {Number} startTime Timestamp of bot ready event * @prop {Collection<Guild>} unavailableGuilds Collection of unavailable guilds the bot is in * @prop {Number} uptime How long in milliseconds the bot has been up for * @prop {User} user The bot user * @prop {Collection<User>} users Collection of users the bot sees */ class Client extends EventEmitter { /** * Create a Client * @arg {String} token bot token * @arg {Object} [options] Eris options (all options are optional) * @arg {Boolean} [options.autoreconnect=true] Have Eris autoreconnect when connection is lost * @arg {Boolean} [options.buckets=true] Use buckets instead of regular 429 retry * @arg {Boolean} [options.cleanContent=true] Whether to enable the Messages.cleanContent and Message.channelMentions properties or not * @arg {Boolean} [options.compress=true] Whether to request WebSocket data to be compressed or not * @arg {Number} [options.connectionTimeout=5000] How long in milliseconds to wait for the connection to handshake with the server * @arg {Object} [options.disableEvents] If disableEvents[eventName] is true, the WS event will not be processed. This can cause significant performance increase on large bots. <a href="reference.html#ws-event-names">A full list of the WS event names can be found on the docs reference page</a> * @arg {Boolean} [options.disableEveryone=true] When true, filter out @everyone/@here by default in createMessage/editMessage * @arg {Number} [options.firstShardID=0] The ID of the first shard to run for this client * @arg {Boolean} [options.getAllUsers=false] Get all the users in every guild. Ready time will be severely delayed * @arg {Number} [options.guildCreateTimeout=2000] Timeout when waiting for guilds before the ready event * @arg {Number} [options.largeThreshold=250] The maximum number of offline users per guild during initial guild data transmission * @arg {Number} [options.lastShardID=options.maxShards - 1] The ID of the last shard to run for this client * @arg {Number} [options.maxShards=1] The total number of shards you want to run * @arg {Number} [options.messageLimit=100] The maximum size of a channel message cache * @arg {Boolean} [options.opusOnly=false] Whether to suppress the node-opus not found error or not * @arg {Number} [options.guildCreateTimeout=2000] How long in milliseconds to wait for a GULID_CREATE before "ready" is fired. Increase this value if you notice missing guilds * @arg {Number} [options.voiceDataTimeout=2000] Timeout when waiting for voice data (-1 for no timeout) * @arg {Number} [options.sequencerWait=200] How long to wait between sending potentially ratelimited requests. This number should be at least 3/4 your ping (in milliseconds) * @arg {Number} [options.gatewayVersion=5] What Discord gateway versio to use (4 and 5 are supported) * @returns {Client} A Client object */ constructor(token, options) { super(); if(!token) { throw new Error("Token not specified"); } this.options = { autoreconnect: true, buckets: true, cleanContent: true, compress: true, connectionTimeout: 5000, disableEvents: {}, disableEveryone: true, firstShardID: 0, gatewayVersion: 6, getAllUsers: false, guildCreateTimeout: 2000, largeThreshold: 250, maxShards: 1, messageLimit: 100, opusOnly: false, sequencerWait: 200, voiceDataTimeout: 2000 }; if(typeof options === "object") { for(var property of Object.keys(options)) { this.options[property] = options[property]; } } if(this.options.lastShardID === undefined) { this.options.lastShardID = this.options.maxShards - 1; } Endpoints.BASE_URL = Endpoints.BASE_URL(this.options.gatewayVersion); this.token = token; this.ready = false; this.startTime = 0; this.userAgent = `DiscordBot (https://github.com/abalabahaha/eris, ${require("../package.json").version})`; this.lastReadyPacket = 0; this.connectQueue = []; this.channelGuildMap = {}; this.shards = new Collection(Shard); this.groupChannels = new Collection(GroupChannel); this.guilds = new Collection(Guild); this.privateChannelMap = {}; this.privateChannels = new Collection(PrivateChannel); this.retryAfters = {}; this.guildShardMap = {}; this.voiceConnections = new Collection(VoiceConnection); this.unavailableGuilds = new Collection(Guild); this.users = new Collection(User); this.buckets = {}; if(this.options.buckets) { this.buckets["bot:msg:dm"] = new Bucket(5, 5000, this.options.sequencerWait); this.buckets["bot:msg:global"] = new Bucket(50, 10000, this.options.sequencerWait); this.buckets["dmsg:undefined"] = new Bucket(5, 1000, this.options.sequencerWait); this.buckets["msg"] = new Bucket(10, 10000, this.options.sequencerWait); this.buckets["username"] = new Bucket(2, 3600000, this.options.sequencerWait); } } get uptime() { return this.startTime ? Date.now() - this.startTime : 0; } validateToken() { if(this.bot !== undefined) { return Promise.resolve(); } return this.getSelf().then((user) => { if(!user.bot) { this.options.maxShards = 1; this.options.firstShardID = this.options.lastShardID = 0; this.relationships = new Collection(Relationship); } else { this.token = `Bot ${this.token}`; } this.bot = user.bot; this.emit("debug", `The bot user appears to be a ${this.bot ? "OAuth bot" : "user account"}`); }); } /** * Tells all shards to connect. Creates shards if there aren't enough * @returns {Promise} Resolves when all shards are initialized */ connect() { return this.validateToken().then(() => this.getGateway()).then(() => { for(var i = this.options.firstShardID; i <= this.options.lastShardID; ++i) { let shard = this.shards.get(i); if(!shard) { shard = this.shards.add(new Shard(i, this)); shard.on("ready", () => { /** * Fired when a shard turns ready * @event Client#shardReady * @prop {Number} id The ID of the shard */ this.emit("shardReady", shard.id); if(this.ready) { return; } for(var other of this.shards) { if(!other[1].ready) { return; } } this.ready = true; this.startTime = Date.now(); /** * Fired when all shards turn ready * @event Client#ready */ this.emit("ready"); }); shard.on("resume", () => { /** * Fired when a shard resumes * @event Client#shardResume * @prop {Number} id The ID of the shard */ this.emit("shardResume", shard.id); if(this.ready) { return; } for(var other of this.shards) { if(!other[1].ready) { return; } } this.ready = true; this.startTime = Date.now(); this.emit("ready"); }); shard.on("disconnect", (error) => { /** * Fired when a shard disconnects * @event Client#shardDisconnect * @prop {Error?} error The error, if any * @prop {Number} id The ID of the shard */ this.emit("shardDisconnect", error, shard.id); if(!this.ready) { return; } for(var other of this.shards) { if(other[1].ready) { return; } } this.ready = false; this.startTime = 0; /** * Fired when all shards disconnect * @event Client#disconnect */ this.emit("disconnect"); }); } this.queueConnect(shard); } }); } /** * Get the Discord websocket gateway URL. * @returns {Promise<String>} Resolves with the gateway URL */ getGateway() { if(this.gatewayURL) { return Promise.resolve(this.gatewayURL); } return this.callAPI("GET", Endpoints.GATEWAY, true).then((data) => { if(data.url) { if(data.url.includes("?")) { data.url = data.url.substring(0, data.url.indexOf("?")); } if(!data.url.endsWith("/")) { data.url += "/"; } this.gatewayURL = `${data.url}?encoding=json&v=${this.options.gatewayVersion}`; return Promise.resolve(this.gatewayURL); } else { return Promise.reject(new Error("Invalid response from gateway REST call")); } }); } queueConnect(shard) { if(this.lastReadyPacket <= Date.now() - 5250 && !this.shards.find((shard) => shard.connecting)) { shard.connect(); } else { this.connectQueue.push(shard); this.tryConnect(); } } tryConnect() { if(!this.connectTimeout) { this.connectTimeout = setTimeout(() => { if(this.connectQueue.length > 0 && this.lastReadyPacket <= Date.now() - 5250 && !this.shards.find((shard) => shard.connecting)) { this.connectQueue.shift().connect(); } this.connectTimeout = null; if(this.connectQueue.length > 0) { this.tryConnect(); } }, Math.min(Math.max(250, Date.now() - 5250 - this.lastReadyPacket), 5250)); } } /** * Disconnects all shards * @arg {Object?} [options] Shard disconnect options * @arg {String | Boolean} [options.reconnect] false means destroy everything, true means you want to reconnect in the future, "auto" will autoreconnect */ disconnect(options) { this.ready = false; this.shards.forEach((shard) => { shard.disconnect(options); }); this.connectQueue = []; } /** * Joins a voice channel. If joining a group call, the voice connection ID will be stored in voiceConnections as "call". Otherwise, it will be the guild ID * @arg {String} channelID The ID of the voice channel * @returns {Promise<VoiceConnection>} Resolves with an established VoiceConnection */ joinVoiceChannel(channelID) { var channel = this.getChannel(channelID); if(!channel) { return Promise.reject(new Error("Channel not found")); } if(channel.guild && !channel.permissionsOf(this.user.id).json.voiceConnect) { return Promise.reject(new Error("Insufficient permission to connect to voice channel")); } var guildID = channel.guild && this.channelGuildMap[channelID] || "call"; var connection = this.voiceConnections.get(guildID); if(connection) { connection.switchChannel(channelID); if(connection.ready) { return Promise.resolve(connection); } } else { connection = this.voiceConnections.add(new VoiceConnection(guildID, this.shards.get(channel.guild && this.guildShardMap[guildID] || 0))); connection.connect(channelID); } return new Promise((resolve, reject) => { var disconnectHandler, readyHandler; disconnectHandler = (err) => { connection.removeListener("ready", readyHandler); reject(err); }; readyHandler = () => { connection.removeListener("disconnect", disconnectHandler); resolve(connection); }; connection.once("ready", readyHandler); connection.once("disconnect", disconnectHandler); }); } /** * Leaves a voice channel * @arg {String} channelID The ID of the voice channel */ leaveVoiceChannel(channelID) { var channel = this.getChannel(channelID); if(!channel) { return Promise.reject(new Error("Channel not found")); } var connection = this.voiceConnections.get(channel.guild && this.channelGuildMap[channelID] || "call"); if(connection) { connection.disconnect(); this.voiceConnections.remove(connection); } } /** * Updates the bot's status (for all guilds) * @arg {Boolean?} [idle] Sets if the bot is idle (true) or online (false) * @arg {Object?} [game] Sets the bot's active game, null to clear * @arg {String} game.name Sets the name of the bot's active game * @arg {Number} [game.type] The type of game. 0 is default, 1 is Twitch, 2 is YouTube * @arg {String} [game.url] Sets the url of the shard's active game */ editStatus(idle, game) { this.shards.forEach((shard) => { shard.editStatus(idle, game); }); } /** * Updates the bot's idle status (for all guilds) * @arg {Boolean} idle Sets if the bot is idle (true) or online (false) */ editIdle(idle) { this.editStatus(idle); } /** * Updates the bot's active game (for all guilds) * @arg {Object?} game Sets the bot's active game, null to clear * @arg {String} game.name Sets the name of the bot's active game * @arg {Number} [game.type] The type of game. 0 is default, 1 is Twitch, 2 is YouTube * @arg {String} [game.url] Sets the url of the shard's active game */ editGame(game) { this.editStatus(null, game); } /** * Get a Channel object from a channelID * @arg {String} [channelID] The ID of the channel * @returns {Channel} */ getChannel(channelID) { return this.channelGuildMap[channelID] ? this.guilds.get(this.channelGuildMap[channelID]).channels.get(channelID) : this.privateChannels.get(channelID) || this.groupChannels.get(channelID); } /** * Create a channel in a guild * @arg {String} guildID The ID of the guild to create the channel in * @arg {String} name The name of the channel * @arg {String} [type=0/"text"] The type of the channel, either 0 or 2 ("text" or "voice" respectively in gateway 5 and under) * @returns {Promise<Channel>} */ createChannel(guildID, name, type) { var guild = this.guilds.get(guildID); if(!guild) { return Promise.reject(new Error(`Guild ${guildID} not found`)); } return this.callAPI("POST", Endpoints.GUILD_CHANNELS(guildID), true, { name, type }).then((channel) => new Channel(channel, guild)); } /** * Edit a channel's properties * @arg {String} channelID The ID of the channel * @arg {Object} options The properties to edit * @arg {String} [options.name] The name of the channel * @arg {String} [options.icon] The icon of the channel as a base64 data URI (group channels only) * @arg {String} [options.ownerID] The ID of the channel owner (group channels only) * @arg {String} [options.topic] The topic of the channel (guild text channels only) * @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only) * @arg {Number} [options.userLimit] The channel user limit (guild voice channels only) * @returns {Promise<Channel>} */ editChannel(channelID, options) { var channel = this.getChannel(channelID); if(!channel) { return Promise.reject(new Error(`Channel ${channelID} not found`)); } return this.callAPI("PATCH", Endpoints.CHANNEL(channelID), true, { name: options.name || channel.name, icon: channel.type === 3 ? options.icon || channel.icon : undefined, owner_id: channel.type === 3 ? options.ownerID || channel.ownerID : undefined, topic: channel.type === "text" || channel.type === 0 ? options.topic || channel.topic : undefined, bitrate: channel.type === "voice" || channel.type === 2 ? options.bitrate || channel.bitrate : undefined, user_limit: channel.type === "voice" || channel.type === 2 ? (options.userLimit !== undefined ? options.userLimit : channel.userLimit) : undefined }).then((data) => { if(channel.guild) { return new Channel(data, channel.guild); } else { return new GroupChannel(data, this); } }); } /** * Edit a guild channel's position. Note that channel position numbers are lowest on top and highest at the bottom. * @arg {String} guildID The ID of the guild the channel is in * @arg {String} channelID The ID of the channel * @arg {Number} position The position of the new channel * @returns {Promise} */ editChannelPosition(guildID, channelID, position) { var channels = this.guilds.get(guildID).channels; var channel = channels.get(channelID); if(!channel) { return Promise.reject(new Error(`Channel ${channelID} not found`)); } if(channel.position === position) { return Promise.resolve(); } var min = Math.min(position, channel.position); var max = Math.max(position, channel.position); channels = channels.filter((chan) => chan.type === channel.type && min <= chan.position && chan.position <= max && chan.id !== channelID).sort((a, b) => a.position - b.position); if(position > channel.position) { channels.push(channel); } else { channels.unshift(channel); } return this.callAPI("PATCH", Endpoints.GUILD_CHANNELS(guildID), true, channels.map((channel, index) => ({ id: channel.id, position: index + min }))); } /** * Edit a channel's properties * @arg {String} channelID The ID of the channel * @returns {Promise<Channel>} */ deleteChannel(channelID) { return this.callAPI("DELETE", Endpoints.CHANNEL(channelID), true); } /** * Send typing status in a channel * @arg {String} channelID The ID of the channel * @returns {Promise} */ sendChannelTyping(channelID) { return this.callAPI("POST", Endpoints.CHANNEL_TYPING(channelID), true); } /** * Create a channel permission overwrite * @arg {String} channelID The ID of channel * @arg {String} overwriteID The ID of the overwritten user or role * @arg {Number} allow The permissions number for allowed permissions * @arg {Number} deny The permissions number for denied permissions * @arg {String} type The object type of the overwrite, either "member" or "role" * @returns {Promise<PermissionOverwrite>} */ editChannelPermission(channelID, overwriteID, allow, deny, type) { return this.callAPI("PUT", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, { allow, deny, type }).then((permissionOverwrite) => new PermissionOverwrite(permissionOverwrite)); } /** * Create a channel permission overwrite * @arg {String} channelID The ID of the channel * @arg {String} overwriteID The ID of the overwritten user or role * @returns {Promise} */ deleteChannelPermission(channelID, overwriteID) { return this.callAPI("DELETE", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true); } /** * Get all invites in a channel * @arg {String} channelID The ID of the channel * @returns {Promise<Invite[]>} */ getChannelInvites(channelID) { return this.callAPI("GET", Endpoints.CHANNEL_MESSAGES(channelID), true).then((invites) => invites.map((invite) => new Invite(invite))); } /** * Create an invite for a channel * @arg {String} channelID The ID of the channel * @arg {Object} [options] Invite generation options * @arg {Number} [options.maxAge] How long the invite should last in seconds * @arg {Number} [options.maxUses] How many uses the invite should last for * @arg {Boolean} [options.temporary] Whether the invite is temporary or not * @arg {Boolean} [options.xkcdpass] Whether the invite is human readable or not * @returns {Promise<Invite>} */ createInvite(channelID, options) { options = options || {}; return this.callAPI("POST", Endpoints.CHANNEL_INVITES(channelID), true, { max_age: options.maxAge, max_uses: options.maxUses, temporary: options.temporary, xkcdpass: options.xkcdpass }).then((invite) => new Invite(invite)); } /** * Create a gulid role * @arg {String} guildID The ID of the guild to create the role in * @returns {Promise<Role>} */ createRole(guildID) { return this.callAPI("POST", Endpoints.GUILD_ROLES(guildID), true).then((role) => new Role(role)); } /** * Edit a gulid role * @arg {String} guildID The ID of the guild the role is in * @arg {String} roleID The ID of the role * @arg {Object} options The properties to edit * @arg {String} [options.name] The name of the role * @arg {Number} [options.permissions] The role permissions number * @arg {Number} [options.color] The hex color of the role, in number form (ex: 0x3da5b3 or 4040115) * @arg {Boolean} [options.hoist] Whether to hoist the role in the user list or not * @returns {Promise<Role>} */ editRole(guildID, roleID, options) { var role = this.guilds.get(guildID).roles.get(roleID); return this.callAPI("PATCH", Endpoints.GUILD_ROLE(guildID, roleID), true, { name: options.name || role.name, permissions: options.permissions || role.permissions, color: options.color, hoist: options.hoist }).then((role) => new Role(role)); } /** * Edit a guild role's position. Note that role position numbers are highest on top and lowest at the bottom. * @arg {String} guildID The ID of the guild the role is in * @arg {String} roleID The ID of the role * @arg {Number} position The new position of the role * @returns {Promise} */ editRolePosition(guildID, roleID, position) { if(guildID === roleID) { return Promise.reject(new Error("Cannot move default role")); } var roles = this.guilds.get(guildID).roles; var role = roles.get(roleID); if(!role) { return Promise.reject(new Error(`Role ${roleID} not found`)); } if(role.position === position) { return Promise.resolve(); } var min = Math.min(position, role.position); var max = Math.max(position, role.position); roles = roles.filter((role) => min <= role.position && role.position <= max && role.id !== roleID).sort((a, b) => a.position - b.position); if(position > role.position) { roles.push(role); } else { roles.unshift(role); } return this.callAPI("PATCH", Endpoints.GUILD_ROLES(guildID), true, roles.map((role, index) => ({ id: role.id, position: index + min }))); } /**, * Create a gulid role * @arg {String} guildID The ID of the guild to create the role in * @arg {String} roleID The ID of the role * @returns {Promise} */ deleteRole(guildID, roleID) { return this.callAPI("DELETE", Endpoints.GUILD_ROLE(guildID, roleID), true); } /** * Get the prune count for a guild * @arg {String} guildID The ID of the guild * @arg {Number} days The number of days of inactivity to prune for * @returns {Promise<Number>} Resolves with the number of users that would be pruned */ getPruneCount(guildID, days) { return this.callAPI("GET", Endpoints.GUILD_PRUNE(guildID), true, { days }).then((data) => data.pruned); } /** * Begin pruning a guild * @arg {String} guildID The ID of the guild * @arg {Number} days The number of days of inactivity to prune for * @returns {Promise<Number>} Resolves with the number of pruned users */ pruneMembers(guildID, days) { return this.callAPI("POST", Endpoints.GUILD_PRUNE(guildID), true, { days }).then((data) => data.pruned); } /** * Get possible voice reigons for a guild * @arg {String} guildID The ID of the guild * @returns {Promise<Object[]>} Resolves with an array of voice region objects */ getVoiceRegions(guildID) { return guildID ? this.callAPI("GET", Endpoints.GUILD_VOICE_REGIONS(guildID), true) : this.callAPI("GET", Endpoints.VOICE_REGIONS, true); // TODO parse regions } /** * Get info on an invite * @arg {String} inviteID The ID of the invite * @returns {Promise<Invite>} */ getInvite(inviteID) { return this.callAPI("GET", Endpoints.INVITE(inviteID), true).then((invite) => { if(this.getChannel(invite.channel.id).permissionsOf(this.user.id).json.manageChannels) { // TODO verify this is the right permission return this.callAPI("POST", Endpoints.CHANNEL_INVITES(invite.channel.id), true, { validate: inviteID }).then((extendedInvite) => new Invite(extendedInvite)); } return new Invite(invite); }); } /** * Accept an invite (not for bot accounts) * @arg {String} inviteID The ID of the invite * @returns {Promise<Invite>} */ acceptInvite(inviteID) { return this.callAPI("POST", Endpoints.INVITE(inviteID), true).then((invite) => new Invite(invite)); } /** * Delete an invite * @arg {String} inviteID The ID of the invite * @returns {Promise} */ deleteInvite(inviteID) { return this.callAPI("DELETE", Endpoints.INVITE(inviteID), true); } /** * Get properties of the bot user * @returns {Promise<ExtendedUser>} */ getSelf() { return this.callAPI("GET", Endpoints.ME, true).then((data) => new ExtendedUser(data)); } /** * Edit properties of the bot user * @arg {Object} options The properties to edit * @arg {String} [options.username] The new username * @arg {String} [options.avatar] The new avatar as a base64 data URI * @returns {Promise<ExtendedUser>} */ editSelf(options) { if(!this.user) { return Promise.reject(new Error("Bot not ready yet")); } return this.callAPI("PATCH", Endpoints.ME, true, { username: options.username || this.user.username, avatar: options.avatar || this.user.avatar }).then((data) => new ExtendedUser(data)); } /** * Get a DM channel with a user, or create one if it does not exist * @arg {String} userID The ID of the user * @returns {Promise<PrivateChannel>} */ getDMChannel(userID) { if(this.privateChannelMap[userID]) { return Promise.resolve(this.privateChannels.get(this.privateChannelMap[userID])); } return this.callAPI("POST", Endpoints.ME_CHANNELS, true, { recipients: [userID], type: 1 }).then((privateChannel) => new PrivateChannel(privateChannel, this)); } /** * Get a previous message in a channel * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise<Message>} */ getMessage(channelID, messageID) { return this.callAPI("GET", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true).then((message) => new Message(message, this)); } /** * Get previous messages in a channel * @arg {String} channelID The ID of the channel * @arg {Number} [limit=50] The max number of messages to get (maximum 100) * @arg {String} [before] Get messages before this message ID * @arg {String} [after] Get messages after this message ID * @arg {String} [around] Get messages around this message ID (does not work with limit > 100) * @returns {Promise<Message[]>} */ getMessages(channelID, limit, before, after, around) { if(limit && limit > 100) { return new Promise((resolve, reject) => { var logs = []; var get = (_before, _after) => { this.callAPI("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, { limit: 100, before: _before, after: _after }).catch(reject).then((messages) => { if(limit <= messages.length) { return resolve(logs.concat((_after ? messages.reverse() : messages).splice(0, limit).map((message) => new Message(message, this)))); } limit -= messages.length; logs = logs.concat((_after ? messages.reverse() : messages).map((message) => new Message(message, this))); if(messages.length < 100) { return resolve(logs); } this.emit("debug", "Getting " + limit + " more messages during getMessages for " + channelID, -1); get((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id); }); }; get(before, after); }); } return this.callAPI("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, { limit: limit || 50, before, after, around }).then((messages) => messages.map((message) => { try { return new Message(message, this); } catch(err) { this.emit("error", "ERROR CREATING MESSAGE FROM CHANNEL MESSAGES: " + JSON.stringify(messages)); return null; } })); } /** * Get all the pins in a channel * @arg {String} channelID The ID of the channel * @returns {Promise<Message[]>} */ getPins(channelID) { return this.callAPI("GET", Endpoints.CHANNEL_PINS(channelID), true).then((messages) => messages.map((message) => new Message(message, this))); } /** * Create a message in a channel * @arg {String} channelID The ID of the channel * @arg {String | Object} content A string or object. If an object is passed: * @arg {String} content.content A content string * @arg {Boolean} [content.tts] Set the message TTS flag * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default) * @arg {Object} [file] A file object * @arg {String} file.file A readable stream or buffer * @arg {String} file.name What to name the file * @returns {Promise<Message>} */ createMessage(channelID, content, file) { if(!content) { content = ""; } if(typeof content !== "object" || content.content === undefined) { content = { content: content.toString() }; } else if(typeof content.content !== "string") { content.content = (content.content || "").toString(); } if(content.content === "" && !file) { return Promise.reject(new Error("No content or file")); } if(content.disableEveryone !== undefined ? content.disableEveryone : this.options.disableEveryone) { content.content = content.content.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere"); } return this.callAPI("POST", Endpoints.CHANNEL_MESSAGES(channelID), true, content, file).then((message) => new Message(message, this)); } /** * Edit a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @arg {String} content The updated message content * @arg {Boolean} [disableEveryone] Whether to filter @everyone/@here or not (overrides default) * @returns {Promise<Message>} */ editMessage(channelID, messageID, content, disableEveryone) { if(typeof content !== "string") { content = content.toString(); } if(disableEveryone !== undefined ? disableEveryone : this.options.disableEveryone) { content = content.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere"); } return this.callAPI("PATCH", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true, { content }).then((message) => new Message(message, this)); } /** * Pin a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise} */ pinMessage(channelID, messageID) { return this.callAPI("PUT", Endpoints.CHANNEL_PIN(channelID, messageID), true); } /** * Unpin a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise} */ unpinMessage(channelID, messageID) { return this.callAPI("DELETE", Endpoints.CHANNEL_PIN(channelID, messageID), true); } /** * Delete a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise} */ deleteMessage(channelID, messageID) { return this.callAPI("DELETE", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true); } /** * Bulk delete messages * @arg {String} channelID The ID of the channel * @arg {String[]} messageIDs Array of message IDs to delete * @returns {Promise} */ deleteMessages(channelID, messageIDs) { if(messageIDs.length === 0) { return Promise.resolve(); } if(messageIDs.length === 1) { return this.deleteMessage(channelID, messageIDs[0]); } if(messageIDs.length > 100) { return this.callAPI("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, { messages: messageIDs.splice(0, 100) }).then(() => { setTimeout(() => { this.deleteMessages(channelID, messageIDs); }, 1000); }); } return this.callAPI("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, { messages: messageIDs }); } /** * Purge previous messages in a channel with an optional filter (bot accounts only) * @arg {String} channelID The ID of the channel * @arg {Number} limit The max number of messages to search through, -1 for no limit * @arg {function} [filter] Optional filter function that returns a boolean when passed a Message object * @arg {String} [before] Get messages before this message ID * @arg {String} [after] Get messages after this message ID * @returns {Promise<Number>} Resolves with the number of messages deleted */ purgeChannel(channelID, limit, filter, before, after) { if(typeof filter === "string") { filter = (msg) => msg.content.includes(filter); } return new Promise((resolve, reject) => { var toDelete = []; var deleted = 0; var done = false; var checkToDelete = () => { var messageIDs = (done && toDelete) || (toDelete.length >= 100 && toDelete.splice(0, 100)); if(messageIDs) { deleted += messageIDs.length; this.deleteMessages(channelID, messageIDs).catch(reject).then(() => { if(done) { return resolve(deleted); } setTimeout(() => { checkToDelete(); }, 1000); }); } else if(done) { return resolve(deleted); } else { setTimeout(() => { checkToDelete(); }, 250); } }; var del = (_before, _after) => { this.getMessages(channelID, 100, _before, _after).catch(reject).then((messages) => { if(limit === 0) { done = true; return; } for(var message of messages) { if(limit === 0) { break; } if(!filter || filter(message)) { toDelete.push(message.id); } limit--; } if(limit === 0 || messages.length < 100) { done = true; return; } del((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id); }); }; del(before, after); checkToDelete(); }); } /** * Get a list of integrations for a guild * @arg {String} guildID The ID of the guild * @returns {Promise<GuildIntegration[]>} */ getGuildIntegrations(guildID) { var guild = this.guilds.get(guildID); return this.callAPI("GET", Endpoints.GUILD_INTEGRATIONS(guildID), true).then((integrations) => integrations.map((integration) => new GuildIntegration(integration, guild))); } // adding createGuildIntegration is questionable, why are you doing this programatically /** * Edit a guild integration * @arg {String} guildID The ID of the guild * @arg {String} integrationID The ID of the integration * @arg {Object} options The properties to edit * @arg {String} [options.expireBehavior] What to do when a user's subscription runs out * @arg {String} [options.expireGracePeriod] How long before the integration's role is removed from an unsubscribed user * @arg {String} [options.enableEmoticons] Whether to enable integration emoticons or not * @returns {Promise} */ editGuildIntegration(guildID, integrationID, options) { return this.callAPI("DELETE", Endpoints.GUILD_INTEGRATION(guildID, integrationID), true, { expire_behavior: options.expireBehavior, expire_grace_period: options.expireGracePeriod, enable_emoticons: options.enableEmoticons }); } /** * Delete a guild integration * @arg {String} guildID The ID of the guild * @arg {String} integrationID The ID of the integration * @returns {Promise} */ deleteGuildIntegration(guildID, integrationID) { return this.callAPI("DELETE", Endpoints.GUILD_INTEGRATION(guildID, integrationID), true); } /** * Force a guild integration to sync * @arg {String} guildID The ID of the guild * @arg {String} integrationID The ID of the integration * @returns {Promise} */ syncGuildIntegration(guildID, integrationID) { return this.callAPI("POST", Endpoints.GUILD_INTEGRATION_SYNC(guildID, integrationID), true); } /** * Get all invites in a guild * @arg {String} guildID The ID of the guild * @returns {Promise<Invite[]>} */ getGuildInvites(guildID) { return this.callAPI("GET", Endpoints.GUILD_INVITES(guildID), true).then((invites) => invites.map((invite) => new Invite(invite))); } /** * Ban a user from a guild * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @arg {Number} [deleteMessageDays=0] Number of days to delete messages for * @returns {Promise} */ banGuildMember(guildID, userID, deleteMessageDays) { return this.callAPI("PUT", Endpoints.GUILD_BAN(guildID, userID), true, { delete_message_days: deleteMessageDays || 0 }); } /** * Unban a user from a guild * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @returns {Promise} */ unbanGuildMember(guildID, userID) { return this.callAPI("DELETE", Endpoints.GUILD_BAN(guildID, userID), true); } /** * Create a guild * @arg {String} name The name of the guild * @arg {String} region The region of the guild * @arg {String} [icon] The guild icon as a base64 data URI * @returns {Promise<Guild>} */ createGuild(name, region, icon) { icon = icon || null; return this.callAPI("POST", Endpoints.GUILDS, true, { name, region, icon }).then((guild) => new Guild(guild, this)); } /** * Edit a guild * @arg {String} guildID The ID of the guild * @arg {Object} options The properties to edit * @arg {String} [options.name] The ID of the guild * @arg {String} [options.region] The region of the guild * @arg {String} [options.icon] The guild icon as a base64 data URI * @arg {Number} [options.verificationLevel] The guild verification level * @arg {String} [options.afkChannelID] The ID of the AFK voice channel * @arg {Number} [options.afkTimeout] The AFK timeout in seconds * @arg {String} [options.ownerID] The ID of the user to transfer server ownership to (bot user must be owner) * @arg {String} [options.splash] The guild splash image as a base64 data URI (VIP only) * @returns {Promise<Guild>} */ editGuild(guildID, options) { var guild = this.guilds.get(guildID); if(!guild) { return Promise.reject(new Error(`Guild ${guildID} not found`)); } return this.callAPI("PATCH", Endpoints.GUILD(guildID), true, { name: options.name || guild.name, region: options.region, icon: options.icon, verification_level: options.verificationLevel, afk_channel_id: options.afkChannelID, afk_timeout: options.afkTimeout, splash: options.splash, owner_id: options.ownerID }).then((guild) => new Guild(guild, this)); } /** * Get the ban list of a guild * @arg {String} guildID The ID of the guild * @returns {Promise<User[]>} */ getGuildBans(guildID) { return this.callAPI("GET", Endpoints.GUILD_BANS(guildID), true).then((bans) => bans.map((ban) => new User(ban.user))); } /** * Edit a guild member * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @arg {Object} options The properties to edit * @arg {String[]} [options.roles] The array of role IDs the user should have * @arg {String} [options.nick] Set the user's server nickname, "" to remove * @arg {Boolean} [options.mute] Server mute the user * @arg {Boolean} [options.deaf] Server deafen the user * @arg {String} [options.channelID] The ID of the voice channel to move the user to (must be in voice) * @returns {Promise} */ editGuildMember(guildID, userID, options) { return this.callAPI("PATCH", Endpoints.GUILD_MEMBER(guildID, userID), true, { roles: options.roles, nick: options.nick, mute: options.mute, deaf: options.deaf, channel_id: options.channelID }); } /** * Edit the bot's nickname in a guild * @arg {String} guildID The ID of the guild * @arg {String} nick The nickname * @returns {Promise} */ editNickname(guildID, nick) { return this.callAPI("PATCH", Endpoints.GUILD_ME_NICK(guildID), true, { nick }); } /** * Remove (kick) a member from a guild * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @returns {Promise} */ deleteGuildMember(guildID, userID) { return this.callAPI("DELETE", Endpoints.GUILD_MEMBER(guildID, userID), true); } /** * Delete a guild (bot account must be user) * @arg {String} guildID The ID of the guild * @returns {Promise} */ deleteGuild(guildID) { return this.callAPI("DELETE", Endpoints.GUILD(guildID), true); } /** * Leave a guild * @arg {String} guildID The ID of the guild * @returns {Promise} */ leaveGuild(guildID) { return this.callAPI("DELETE", Endpoints.ME_GUILD(guildID), true); } /** * Get data on an OAuth2 application * @arg {String} [appID="@me"] The client ID of the application to get data for. "@me" refers to the logged in user's own application * @returns {Promise<Object>} The bot's application data. Refer to <a href="https://discordapp.com/developers/docs/topics/oauth2#get-current-application-information">the official Discord API documentation entry</a> for Object structure */ getOAuthApplication(appID) { return this.callAPI("GET", Endpoints.OAUTH2_APPLICATION(appID || "@me"), true); } bucketsFromRequest(method, url, body) { var match = url.match(/^\/channels\/([0-9]+)\/messages(\/[0-9]+)?$/); if(match) { if(method === "DELETE" && this.getChannel(match[1])) { return ["dmsg:" + this.channelGuildMap[match[1]]]; } else if(this.user.bot) { if(method === "POST" || method === "PATCH") { if(this.privateChannels.get(match[1])) { return ["bot:msg:dm", "bot:msg:global"]; } else if(this.channelGuildMap[match[1]]) { return ["bot:msg:guild:" + this.channelGuildMap[match[1]], "bot:msg:global"]; } } } else { return ["msg"]; } } else if(method === "PATCH" || method === "DELETE") { if(url === "/users/@me" && this.user && body && body.username !== this.user.username) { return ["username"]; } else if((match = url.match(/^\/guilds\/([0-9]+)\/members\/[0-9]+$/))) { return ["guild_member:" + match[1]]; } else if((match = url.match(/^\/guilds\/([0-9]+)\/members\/@me\/nick$/))) { return ["guild_member_nick:" + match[1]]; } } return []; } /** * Make an API request * @arg {String} method Lowercase HTTP method * @arg {String} url URL of the endpoint * @arg {Boolean} auth Whether to add the Authorization header and token or not * @arg {Object} [body] Request payload * @arg {Object} [file] File object * @arg {String} file.file A readable stream or buffer * @arg {String} file.name What to name the file * @returns {Promise<Object>} Resolves with the returned JSON data */ callAPI(method, url, auth, body, file) { var resolve, reject; var promise = new Promise((res, rej) => { resolve = res; reject = rej; }); var buckets = this.bucketsFromRequest(method, url, body); var attempts = 1; var actualCall = () => { var headers = { "User-Agent": this.userAgent }; var data; if(auth) { headers.Authorization = this.token; } if(file && file.file) { data = new MultipartData(); headers["Content-Type"] = "multipart/form-data; boundary=" + data.boundary; data.attach("file", file.file, file.name); if(body) { Object.keys(body).forEach((key) => data.attach(key, body[key])); } data = data.finish(); } else if(body) { if(method === "GET" || (method === "PUT" && url.includes("/bans/"))) { // TODO remove PUT case when devs fix var qs = "" Object.keys(body).forEach((key) => qs += `&${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`); url += "?" + qs.substring(1); } else { data = JSON.stringify(body); headers["Content-Type"] = "application/json"; } } var req = HTTPS.request({ method: method, host: "discordapp.com", path: Endpoints.BASE_URL + url, headers: headers }); req.on("error", (err) => { req.abort(); reject(err); }); req.on("response", (resp) => { var response = []; resp.on("data", (chunk) => { response.push(chunk); }); resp.once("end", () => { response = Buffer.concat(response).toString("utf8"); if(resp.statusCode >= 300) { if(resp.statusCode === 429) { if(this.options.buckets) { this.emit("warn", "UNEXPECTED BUCKET 429 (โ•ฏยฐโ–กยฐ๏ผ‰โ•ฏ๏ธต โ”ปโ”โ”ป " + response); } else { if(buckets.length < 1) { this.emit("warn", "UNEXPECTED 429 (โ•ฏยฐโ–กยฐ๏ผ‰โ•ฏ๏ธต โ”ปโ”โ”ป " + response); } try { response = JSON.parse(response); } catch(err) { req.abort(); return reject("Invalid JSON: " + response); } setTimeout(actualCall, this.buckets[buckets[0]] = response.retry_after); this.buckets[buckets[0]] += Date.now(); return; } } else if(resp.statusCode === 502 && ++attempts < 4) { setTimeout(actualCall, Math.floor(Math.random() * 900 + 100)); return; } var err = new Error(`${resp.statusCode} ${resp.statusMessage}`); err.resp = resp; err.response = response; err.req = req; req.abort(); return reject(err); } if(response.length > 0) { if(resp.headers["content-type"] === "application/json") { try { response = JSON.parse(response); } catch(err) { req.abort(); return reject("Invalid JSON: " + response); } } } resolve(response); }); }); req.end(data); }; if(this.options.buckets) { var waitFor = 1; var i = 0; var done = () => { if(++i === waitFor) { actualCall(); } }; for(let bucket of buckets) { ++waitFor; this.buckets[bucket].queue(done); } done(); } else { if(this.buckets[buckets[0]]) { if(this.buckets[buckets[0]] <= Date.now) { this.buckets[buckets[0]] = null; } else { setTimeout(actualCall, this.buckets[buckets[0]]); } } else { actualCall(); } } return promise; } } module.exports = Client;
lib/Client.js
"use strict"; const Bucket = require("./util/Bucket"); const Channel = require("./core/Channel"); const Collection = require("./util/Collection"); const Endpoints = require("./Constants").Endpoints; const EventEmitter = require("eventemitter3"); const ExtendedUser = require("./core/ExtendedUser"); const GroupChannel = require("./core/GroupChannel"); const Guild = require("./core/Guild"); const GuildIntegration = require("./core/GuildIntegration"); const HTTPS = require("https"); const Invite = require("./core/Invite"); const Message = require("./core/Message"); const MultipartData = require("./util/MultipartData"); const PermissionOverwrite = require("./core/PermissionOverwrite"); const PrivateChannel = require("./core/PrivateChannel"); const Promise = require("bluebird"); const Relationship = require("./core/Relationship"); const Role = require("./core/Role"); const Shard = require("./core/Shard"); const User = require("./core/User"); const VoiceConnection = require("./core/VoiceConnection"); /** * Represents the main Eris client * @extends EventEmitter * @prop {String} token The bot user token * @prop {Boolean?} bot Whether the bot user belongs to an OAuth2 application * @prop {Object} options Eris options * @prop {Object} channelGuildMap Object mapping channel IDs to guild IDs * @prop {Collection<Shard>} shards Collection of shards Eris is using * @prop {Collection<Guild>} guilds Collection of guilds the bot is in * @prop {Object} privateChannelMap Object mapping user IDs to private channel IDs * @prop {Collection<PrivateChannel>} privateChannels Collection of private channels the bot is in * @prop {Collection<GroupChannel>} groupChannels Collection of group channels the bot is in (user accounts only) * @prop {Collection<VoiceConnection>} voiceConnections Collection of VoiceConnections the bot has * @prop {Object} retryAfters Object mapping endpoints to ratelimit expiry timestamps * @prop {Object} guildShardMap Object mapping guild IDs to shard IDs * @prop {Number} startTime Timestamp of bot ready event * @prop {Collection<Guild>} unavailableGuilds Collection of unavailable guilds the bot is in * @prop {Number} uptime How long in milliseconds the bot has been up for * @prop {User} user The bot user * @prop {Collection<User>} users Collection of users the bot sees */ class Client extends EventEmitter { /** * Create a Client * @arg {String} token bot token * @arg {Object} [options] Eris options (all options are optional) * @arg {Boolean} [options.autoreconnect=true] Have Eris autoreconnect when connection is lost * @arg {Boolean} [options.buckets=true] Use buckets instead of regular 429 retry * @arg {Boolean} [options.cleanContent=true] Whether to enable the Messages.cleanContent and Message.channelMentions properties or not * @arg {Boolean} [options.compress=true] Whether to request WebSocket data to be compressed or not * @arg {Number} [options.connectionTimeout=5000] How long in milliseconds to wait for the connection to handshake with the server * @arg {Object} [options.disableEvents] If disableEvents[eventName] is true, the WS event will not be processed. This can cause significant performance increase on large bots. <a href="reference.html#ws-event-names">A full list of the WS event names can be found on the docs reference page</a> * @arg {Boolean} [options.disableEveryone=true] When true, filter out @everyone/@here by default in createMessage/editMessage * @arg {Number} [options.firstShardID=0] The ID of the first shard to run for this client * @arg {Boolean} [options.getAllUsers=false] Get all the users in every guild. Ready time will be severely delayed * @arg {Number} [options.guildCreateTimeout=2000] Timeout when waiting for guilds before the ready event * @arg {Number} [options.largeThreshold=250] The maximum number of offline users per guild during initial guild data transmission * @arg {Number} [options.lastShardID=options.maxShards - 1] The ID of the last shard to run for this client * @arg {Number} [options.maxShards=1] The total number of shards you want to run * @arg {Number} [options.messageLimit=100] The maximum size of a channel message cache * @arg {Boolean} [options.opusOnly=false] Whether to suppress the node-opus not found error or not * @arg {Number} [options.guildCreateTimeout=2000] How long in milliseconds to wait for a GULID_CREATE before "ready" is fired. Increase this value if you notice missing guilds * @arg {Number} [options.voiceDataTimeout=2000] Timeout when waiting for voice data (-1 for no timeout) * @arg {Number} [options.sequencerWait=200] How long to wait between sending potentially ratelimited requests. This number should be at least 3/4 your ping (in milliseconds) * @arg {Number} [options.gatewayVersion=5] What Discord gateway versio to use (4 and 5 are supported) * @returns {Client} A Client object */ constructor(token, options) { super(); if(!token) { throw new Error("Token not specified"); } this.options = { autoreconnect: true, buckets: true, cleanContent: true, compress: true, connectionTimeout: 5000, disableEvents: {}, disableEveryone: true, firstShardID: 0, gatewayVersion: 6, getAllUsers: false, guildCreateTimeout: 2000, largeThreshold: 250, maxShards: 1, messageLimit: 100, opusOnly: false, sequencerWait: 200, voiceDataTimeout: 2000 }; if(typeof options === "object") { for(var property of Object.keys(options)) { this.options[property] = options[property]; } } if(this.options.lastShardID === undefined) { this.options.lastShardID = this.options.maxShards - 1; } Endpoints.BASE_URL = Endpoints.BASE_URL(this.options.gatewayVersion); this.token = token; this.ready = false; this.startTime = 0; this.userAgent = `DiscordBot (https://github.com/abalabahaha/eris, ${require("../package.json").version})`; this.lastReadyPacket = 0; this.connectQueue = []; this.channelGuildMap = {}; this.shards = new Collection(Shard); this.groupChannels = new Collection(GroupChannel); this.guilds = new Collection(Guild); this.privateChannelMap = {}; this.privateChannels = new Collection(PrivateChannel); this.retryAfters = {}; this.guildShardMap = {}; this.voiceConnections = new Collection(VoiceConnection); this.unavailableGuilds = new Collection(Guild); this.users = new Collection(User); this.buckets = {}; if(this.options.buckets) { this.buckets["bot:msg:dm"] = new Bucket(5, 5000, this.options.sequencerWait); this.buckets["bot:msg:global"] = new Bucket(50, 10000, this.options.sequencerWait); this.buckets["dmsg:undefined"] = new Bucket(5, 1000, this.options.sequencerWait); this.buckets["msg"] = new Bucket(10, 10000, this.options.sequencerWait); this.buckets["username"] = new Bucket(2, 3600000, this.options.sequencerWait); } } get uptime() { return this.startTime ? Date.now() - this.startTime : 0; } validateToken() { if(this.bot !== undefined) { return Promise.resolve(); } return this.getSelf().then((user) => { if(!user.bot) { this.options.maxShards = 1; this.options.firstShardID = this.options.lastShardID = 0; this.relationships = new Collection(Relationship); } else { this.token = `Bot ${this.token}`; } this.bot = user.bot; this.emit("debug", `The bot user appears to be a ${this.bot ? "OAuth bot" : "user account"}`); }); } /** * Tells all shards to connect. Creates shards if there aren't enough * @returns {Promise} Resolves when all shards are initialized */ connect() { return this.validateToken().then(() => this.getGateway()).then(() => { for(var i = this.options.firstShardID; i <= this.options.lastShardID; ++i) { let shard = this.shards.get(i); if(!shard) { shard = this.shards.add(new Shard(i, this)); shard.on("ready", () => { /** * Fired when a shard turns ready * @event Client#shardReady * @prop {Number} id The ID of the shard */ this.emit("shardReady", shard.id); if(this.ready) { return; } for(var other of this.shards) { if(!other[1].ready) { return; } } this.ready = true; this.startTime = Date.now(); /** * Fired when all shards turn ready * @event Client#ready */ this.emit("ready"); }); shard.on("resume", () => { /** * Fired when a shard resumes * @event Client#shardResume * @prop {Number} id The ID of the shard */ this.emit("shardResume", shard.id); if(this.ready) { return; } for(var other of this.shards) { if(!other[1].ready) { return; } } this.ready = true; this.startTime = Date.now(); this.emit("ready"); }); shard.on("disconnect", (error) => { /** * Fired when a shard disconnects * @event Client#shardDisconnect * @prop {Error?} error The error, if any * @prop {Number} id The ID of the shard */ this.emit("shardDisconnect", error, shard.id); if(!this.ready) { return; } for(var other of this.shards) { if(other[1].ready) { return; } } this.ready = false; this.startTime = 0; /** * Fired when all shards disconnect * @event Client#disconnect */ this.emit("disconnect"); }); } this.queueConnect(shard); } }); } /** * Get the Discord websocket gateway URL. * @returns {Promise<String>} Resolves with the gateway URL */ getGateway() { if(this.gatewayURL) { return Promise.resolve(this.gatewayURL); } return this.callAPI("GET", Endpoints.GATEWAY, true).then((data) => { if(data.url) { if(data.url.includes("?")) { data.url = data.url.substring(0, data.url.indexOf("?")); } if(!data.url.endsWith("/")) { data.url += "/"; } this.gatewayURL = `${data.url}?encoding=json&v=${this.options.gatewayVersion}`; return Promise.resolve(this.gatewayURL); } else { return Promise.reject(new Error("Invalid response from gateway REST call")); } }); } queueConnect(shard) { if(this.lastReadyPacket <= Date.now() - 5250 && !this.shards.find((shard) => shard.connecting)) { shard.connect(); } else { this.connectQueue.push(shard); this.tryConnect(); } } tryConnect() { if(!this.connectTimeout) { this.connectTimeout = setTimeout(() => { if(this.connectQueue.length > 0 && this.lastReadyPacket <= Date.now() - 5250 && !this.shards.find((shard) => shard.connecting)) { this.connectQueue.shift().connect(); } this.connectTimeout = null; if(this.connectQueue.length > 0) { this.tryConnect(); } }, Math.min(Math.max(250, Date.now() - 5250 - this.lastReadyPacket), 5250)); } } /** * Disconnects all shards * @arg {Object?} [options] Shard disconnect options * @arg {String | Boolean} [options.reconnect] false means destroy everything, true means you want to reconnect in the future, "auto" will autoreconnect */ disconnect(options) { this.ready = false; this.shards.forEach((shard) => { shard.disconnect(options); }); this.connectQueue = []; } /** * Joins a voice channel. If joining a group call, the voice connection ID will be stored in voiceConnections as "call". Otherwise, it will be the guild ID * @arg {String} channelID The ID of the voice channel * @returns {Promise<VoiceConnection>} Resolves with an established VoiceConnection */ joinVoiceChannel(channelID) { var channel = this.getChannel(channelID); if(!channel) { return Promise.reject(new Error("Channel not found")); } if(channel.guild && !channel.permissionsOf(this.user.id).json.voiceConnect) { return Promise.reject(new Error("Insufficient permission to connect to voice channel")); } var guildID = channel.guild && this.channelGuildMap[channelID] || "call"; var connection = this.voiceConnections.get(guildID); if(connection) { connection.switchChannel(channelID); if(connection.ready) { return Promise.resolve(connection); } } else { connection = this.voiceConnections.add(new VoiceConnection(guildID, this.shards.get(channel.guild && this.guildShardMap[guildID] || 0))); connection.connect(channelID); } return new Promise((resolve, reject) => { var disconnectHandler, readyHandler; disconnectHandler = (err) => { connection.removeListener("ready", readyHandler); reject(err); }; readyHandler = () => { connection.removeListener("disconnect", disconnectHandler); resolve(connection); }; connection.once("ready", readyHandler); connection.once("disconnect", disconnectHandler); }); } /** * Leaves a voice channel * @arg {String} channelID The ID of the voice channel */ leaveVoiceChannel(channelID) { var channel = this.getChannel(channelID); if(!channel) { return Promise.reject(new Error("Channel not found")); } var connection = this.voiceConnections.get(channel.guild && this.channelGuildMap[channelID] || "call"); if(connection) { connection.disconnect(); this.voiceConnections.remove(connection); } } /** * Updates the bot's status (for all guilds) * @arg {Boolean?} [idle] Sets if the bot is idle (true) or online (false) * @arg {Object?} [game] Sets the bot's active game, null to clear * @arg {String} game.name Sets the name of the bot's active game * @arg {Number} [game.type] The type of game. 0 is default, 1 is Twitch, 2 is YouTube * @arg {String} [game.url] Sets the url of the shard's active game */ editStatus(idle, game) { this.shards.forEach((shard) => { shard.editStatus(idle, game); }); } /** * Updates the bot's idle status (for all guilds) * @arg {Boolean} idle Sets if the bot is idle (true) or online (false) */ editIdle(idle) { this.editStatus(idle); } /** * Updates the bot's active game (for all guilds) * @arg {Object?} game Sets the bot's active game, null to clear * @arg {String} game.name Sets the name of the bot's active game * @arg {Number} [game.type] The type of game. 0 is default, 1 is Twitch, 2 is YouTube * @arg {String} [game.url] Sets the url of the shard's active game */ editGame(game) { this.editStatus(null, game); } /** * Get a Channel object from a channelID * @arg {String} [channelID] The ID of the channel * @returns {Channel} */ getChannel(channelID) { return this.channelGuildMap[channelID] ? this.guilds.get(this.channelGuildMap[channelID]).channels.get(channelID) : this.privateChannels.get(channelID) || this.groupChannels.get(channelID); } /** * Create a channel in a guild * @arg {String} guildID The ID of the guild to create the channel in * @arg {String} name The name of the channel * @arg {String} [type=0/"text"] The type of the channel, either 0 or 2 ("text" or "voice" respectively in gateway 5 and under) * @returns {Promise<Channel>} */ createChannel(guildID, name, type) { var guild = this.guilds.get(guildID); if(!guild) { return Promise.reject(new Error(`Guild ${guildID} not found`)); } return this.callAPI("POST", Endpoints.GUILD_CHANNELS(guildID), true, { name, type }).then((channel) => new Channel(channel, guild)); } /** * Edit a channel's properties * @arg {String} channelID The ID of the channel * @arg {Object} options The properties to edit * @arg {String} [options.name] The name of the channel * @arg {String} [options.icon] The icon of the channel as a base64 data string (group channels only) * @arg {String} [options.ownerID] The ID of the channel owner (group channels only) * @arg {String} [options.topic] The topic of the channel (guild text channels only) * @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only) * @arg {Number} [options.userLimit] The channel user limit (guild voice channels only) * @returns {Promise<Channel>} */ editChannel(channelID, options) { var channel = this.getChannel(channelID); if(!channel) { return Promise.reject(new Error(`Channel ${channelID} not found`)); } return this.callAPI("PATCH", Endpoints.CHANNEL(channelID), true, { name: options.name || channel.name, icon: channel.type === 3 ? options.icon || channel.icon : undefined, owner_id: channel.type === 3 ? options.ownerID || channel.ownerID : undefined, topic: channel.type === "text" || channel.type === 0 ? options.topic || channel.topic : undefined, bitrate: channel.type === "voice" || channel.type === 2 ? options.bitrate || channel.bitrate : undefined, user_limit: channel.type === "voice" || channel.type === 2 ? (options.userLimit !== undefined ? options.userLimit : channel.userLimit) : undefined }).then((data) => { if(channel.guild) { return new Channel(data, channel.guild); } else { return new GroupChannel(data, this); } }); } /** * Edit a guild channel's position. Note that channel position numbers are lowest on top and highest at the bottom. * @arg {String} guildID The ID of the guild the channel is in * @arg {String} channelID The ID of the channel * @arg {Number} position The position of the new channel * @returns {Promise} */ editChannelPosition(guildID, channelID, position) { var channels = this.guilds.get(guildID).channels; var channel = channels.get(channelID); if(!channel) { return Promise.reject(new Error(`Channel ${channelID} not found`)); } if(channel.position === position) { return Promise.resolve(); } var min = Math.min(position, channel.position); var max = Math.max(position, channel.position); channels = channels.filter((chan) => chan.type === channel.type && min <= chan.position && chan.position <= max && chan.id !== channelID).sort((a, b) => a.position - b.position); if(position > channel.position) { channels.push(channel); } else { channels.unshift(channel); } return this.callAPI("PATCH", Endpoints.GUILD_CHANNELS(guildID), true, channels.map((channel, index) => ({ id: channel.id, position: index + min }))); } /** * Edit a channel's properties * @arg {String} channelID The ID of the channel * @returns {Promise<Channel>} */ deleteChannel(channelID) { return this.callAPI("DELETE", Endpoints.CHANNEL(channelID), true); } /** * Send typing status in a channel * @arg {String} channelID The ID of the channel * @returns {Promise} */ sendChannelTyping(channelID) { return this.callAPI("POST", Endpoints.CHANNEL_TYPING(channelID), true); } /** * Create a channel permission overwrite * @arg {String} channelID The ID of channel * @arg {String} overwriteID The ID of the overwritten user or role * @arg {Number} allow The permissions number for allowed permissions * @arg {Number} deny The permissions number for denied permissions * @arg {String} type The object type of the overwrite, either "member" or "role" * @returns {Promise<PermissionOverwrite>} */ editChannelPermission(channelID, overwriteID, allow, deny, type) { return this.callAPI("PUT", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true, { allow, deny, type }).then((permissionOverwrite) => new PermissionOverwrite(permissionOverwrite)); } /** * Create a channel permission overwrite * @arg {String} channelID The ID of the channel * @arg {String} overwriteID The ID of the overwritten user or role * @returns {Promise} */ deleteChannelPermission(channelID, overwriteID) { return this.callAPI("DELETE", Endpoints.CHANNEL_PERMISSION(channelID, overwriteID), true); } /** * Get all invites in a channel * @arg {String} channelID The ID of the channel * @returns {Promise<Invite[]>} */ getChannelInvites(channelID) { return this.callAPI("GET", Endpoints.CHANNEL_MESSAGES(channelID), true).then((invites) => invites.map((invite) => new Invite(invite))); } /** * Create an invite for a channel * @arg {String} channelID The ID of the channel * @arg {Object} [options] Invite generation options * @arg {Number} [options.maxAge] How long the invite should last in seconds * @arg {Number} [options.maxUses] How many uses the invite should last for * @arg {Boolean} [options.temporary] Whether the invite is temporary or not * @arg {Boolean} [options.xkcdpass] Whether the invite is human readable or not * @returns {Promise<Invite>} */ createInvite(channelID, options) { options = options || {}; return this.callAPI("POST", Endpoints.CHANNEL_INVITES(channelID), true, { max_age: options.maxAge, max_uses: options.maxUses, temporary: options.temporary, xkcdpass: options.xkcdpass }).then((invite) => new Invite(invite)); } /** * Create a gulid role * @arg {String} guildID The ID of the guild to create the role in * @returns {Promise<Role>} */ createRole(guildID) { return this.callAPI("POST", Endpoints.GUILD_ROLES(guildID), true).then((role) => new Role(role)); } /** * Edit a gulid role * @arg {String} guildID The ID of the guild the role is in * @arg {String} roleID The ID of the role * @arg {Object} options The properties to edit * @arg {String} [options.name] The name of the role * @arg {Number} [options.permissions] The role permissions number * @arg {Number} [options.color] The hex color of the role, in number form (ex: 0x3da5b3 or 4040115) * @arg {Boolean} [options.hoist] Whether to hoist the role in the user list or not * @returns {Promise<Role>} */ editRole(guildID, roleID, options) { var role = this.guilds.get(guildID).roles.get(roleID); return this.callAPI("PATCH", Endpoints.GUILD_ROLE(guildID, roleID), true, { name: options.name || role.name, permissions: options.permissions || role.permissions, color: options.color, hoist: options.hoist }).then((role) => new Role(role)); } /** * Edit a guild role's position. Note that role position numbers are highest on top and lowest at the bottom. * @arg {String} guildID The ID of the guild the role is in * @arg {String} roleID The ID of the role * @arg {Number} position The new position of the role * @returns {Promise} */ editRolePosition(guildID, roleID, position) { if(guildID === roleID) { return Promise.reject(new Error("Cannot move default role")); } var roles = this.guilds.get(guildID).roles; var role = roles.get(roleID); if(!role) { return Promise.reject(new Error(`Role ${roleID} not found`)); } if(role.position === position) { return Promise.resolve(); } var min = Math.min(position, role.position); var max = Math.max(position, role.position); roles = roles.filter((role) => min <= role.position && role.position <= max && role.id !== roleID).sort((a, b) => a.position - b.position); if(position > role.position) { roles.push(role); } else { roles.unshift(role); } return this.callAPI("PATCH", Endpoints.GUILD_ROLES(guildID), true, roles.map((role, index) => ({ id: role.id, position: index + min }))); } /**, * Create a gulid role * @arg {String} guildID The ID of the guild to create the role in * @arg {String} roleID The ID of the role * @returns {Promise} */ deleteRole(guildID, roleID) { return this.callAPI("DELETE", Endpoints.GUILD_ROLE(guildID, roleID), true); } /** * Get the prune count for a guild * @arg {String} guildID The ID of the guild * @arg {Number} days The number of days of inactivity to prune for * @returns {Promise<Number>} Resolves with the number of users that would be pruned */ getPruneCount(guildID, days) { return this.callAPI("GET", Endpoints.GUILD_PRUNE(guildID), true, { days }).then((data) => data.pruned); } /** * Begin pruning a guild * @arg {String} guildID The ID of the guild * @arg {Number} days The number of days of inactivity to prune for * @returns {Promise<Number>} Resolves with the number of pruned users */ pruneMembers(guildID, days) { return this.callAPI("POST", Endpoints.GUILD_PRUNE(guildID), true, { days }).then((data) => data.pruned); } /** * Get possible voice reigons for a guild * @arg {String} guildID The ID of the guild * @returns {Promise<Object[]>} Resolves with an array of voice region objects */ getVoiceRegions(guildID) { return guildID ? this.callAPI("GET", Endpoints.GUILD_VOICE_REGIONS(guildID), true) : this.callAPI("GET", Endpoints.VOICE_REGIONS, true); // TODO parse regions } /** * Get info on an invite * @arg {String} inviteID The ID of the invite * @returns {Promise<Invite>} */ getInvite(inviteID) { return this.callAPI("GET", Endpoints.INVITE(inviteID), true).then((invite) => { if(this.getChannel(invite.channel.id).permissionsOf(this.user.id).json.manageChannels) { // TODO verify this is the right permission return this.callAPI("POST", Endpoints.CHANNEL_INVITES(invite.channel.id), true, { validate: inviteID }).then((extendedInvite) => new Invite(extendedInvite)); } return new Invite(invite); }); } /** * Accept an invite (not for bot accounts) * @arg {String} inviteID The ID of the invite * @returns {Promise<Invite>} */ acceptInvite(inviteID) { return this.callAPI("POST", Endpoints.INVITE(inviteID), true).then((invite) => new Invite(invite)); } /** * Delete an invite * @arg {String} inviteID The ID of the invite * @returns {Promise} */ deleteInvite(inviteID) { return this.callAPI("DELETE", Endpoints.INVITE(inviteID), true); } /** * Get properties of the bot user * @returns {Promise<ExtendedUser>} */ getSelf() { return this.callAPI("GET", Endpoints.ME, true).then((data) => new ExtendedUser(data)); } /** * Edit properties of the bot user * @arg {Object} options The properties to edit * @arg {String} [options.username] The new username * @arg {String} [options.avatar] The new avatar as a base64 data string * @returns {Promise<ExtendedUser>} */ editSelf(options) { if(!this.user) { return Promise.reject(new Error("Bot not ready yet")); } return this.callAPI("PATCH", Endpoints.ME, true, { username: options.username || this.user.username, avatar: options.avatar || this.user.avatar }).then((data) => new ExtendedUser(data)); } /** * Get a DM channel with a user, or create one if it does not exist * @arg {String} userID The ID of the user * @returns {Promise<PrivateChannel>} */ getDMChannel(userID) { if(this.privateChannelMap[userID]) { return Promise.resolve(this.privateChannels.get(this.privateChannelMap[userID])); } return this.callAPI("POST", Endpoints.ME_CHANNELS, true, { recipients: [userID], type: 1 }).then((privateChannel) => new PrivateChannel(privateChannel, this)); } /** * Get a previous message in a channel * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise<Message>} */ getMessage(channelID, messageID) { return this.callAPI("GET", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true).then((message) => new Message(message, this)); } /** * Get previous messages in a channel * @arg {String} channelID The ID of the channel * @arg {Number} [limit=50] The max number of messages to get (maximum 100) * @arg {String} [before] Get messages before this message ID * @arg {String} [after] Get messages after this message ID * @arg {String} [around] Get messages around this message ID (does not work with limit > 100) * @returns {Promise<Message[]>} */ getMessages(channelID, limit, before, after, around) { if(limit && limit > 100) { return new Promise((resolve, reject) => { var logs = []; var get = (_before, _after) => { this.callAPI("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, { limit: 100, before: _before, after: _after }).catch(reject).then((messages) => { if(limit <= messages.length) { return resolve(logs.concat((_after ? messages.reverse() : messages).splice(0, limit).map((message) => new Message(message, this)))); } limit -= messages.length; logs = logs.concat((_after ? messages.reverse() : messages).map((message) => new Message(message, this))); if(messages.length < 100) { return resolve(logs); } this.emit("debug", "Getting " + limit + " more messages during getMessages for " + channelID, -1); get((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id); }); }; get(before, after); }); } return this.callAPI("GET", Endpoints.CHANNEL_MESSAGES(channelID), true, { limit: limit || 50, before, after, around }).then((messages) => messages.map((message) => { try { return new Message(message, this); } catch(err) { this.emit("error", "ERROR CREATING MESSAGE FROM CHANNEL MESSAGES: " + JSON.stringify(messages)); return null; } })); } /** * Get all the pins in a channel * @arg {String} channelID The ID of the channel * @returns {Promise<Message[]>} */ getPins(channelID) { return this.callAPI("GET", Endpoints.CHANNEL_PINS(channelID), true).then((messages) => messages.map((message) => new Message(message, this))); } /** * Create a message in a channel * @arg {String} channelID The ID of the channel * @arg {String | Object} content A string or object. If an object is passed: * @arg {String} content.content A content string * @arg {Boolean} [content.tts] Set the message TTS flag * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default) * @arg {Object} [file] A file object * @arg {String} file.file A readable stream or buffer * @arg {String} file.name What to name the file * @returns {Promise<Message>} */ createMessage(channelID, content, file) { if(!content) { content = ""; } if(typeof content !== "object" || content.content === undefined) { content = { content: content.toString() }; } else if(typeof content.content !== "string") { content.content = (content.content || "").toString(); } if(content.content === "" && !file) { return Promise.reject(new Error("No content or file")); } if(content.disableEveryone !== undefined ? content.disableEveryone : this.options.disableEveryone) { content.content = content.content.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere"); } return this.callAPI("POST", Endpoints.CHANNEL_MESSAGES(channelID), true, content, file).then((message) => new Message(message, this)); } /** * Edit a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @arg {String} content The updated message content * @arg {Boolean} [disableEveryone] Whether to filter @everyone/@here or not (overrides default) * @returns {Promise<Message>} */ editMessage(channelID, messageID, content, disableEveryone) { if(typeof content !== "string") { content = content.toString(); } if(disableEveryone !== undefined ? disableEveryone : this.options.disableEveryone) { content = content.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere"); } return this.callAPI("PATCH", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true, { content }).then((message) => new Message(message, this)); } /** * Pin a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise} */ pinMessage(channelID, messageID) { return this.callAPI("PUT", Endpoints.CHANNEL_PIN(channelID, messageID), true); } /** * Unpin a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise} */ unpinMessage(channelID, messageID) { return this.callAPI("DELETE", Endpoints.CHANNEL_PIN(channelID, messageID), true); } /** * Delete a message * @arg {String} channelID The ID of the channel * @arg {String} messageID The ID of the message * @returns {Promise} */ deleteMessage(channelID, messageID) { return this.callAPI("DELETE", Endpoints.CHANNEL_MESSAGE(channelID, messageID), true); } /** * Bulk delete messages * @arg {String} channelID The ID of the channel * @arg {String[]} messageIDs Array of message IDs to delete * @returns {Promise} */ deleteMessages(channelID, messageIDs) { if(messageIDs.length === 0) { return Promise.resolve(); } if(messageIDs.length === 1) { return this.deleteMessage(channelID, messageIDs[0]); } if(messageIDs.length > 100) { return this.callAPI("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, { messages: messageIDs.splice(0, 100) }).then(() => { setTimeout(() => { this.deleteMessages(channelID, messageIDs); }, 1000); }); } return this.callAPI("POST", Endpoints.CHANNEL_BULK_DELETE(channelID), true, { messages: messageIDs }); } /** * Purge previous messages in a channel with an optional filter (bot accounts only) * @arg {String} channelID The ID of the channel * @arg {Number} limit The max number of messages to search through, -1 for no limit * @arg {function} [filter] Optional filter function that returns a boolean when passed a Message object * @arg {String} [before] Get messages before this message ID * @arg {String} [after] Get messages after this message ID * @returns {Promise<Number>} Resolves with the number of messages deleted */ purgeChannel(channelID, limit, filter, before, after) { if(typeof filter === "string") { filter = (msg) => msg.content.includes(filter); } return new Promise((resolve, reject) => { var toDelete = []; var deleted = 0; var done = false; var checkToDelete = () => { var messageIDs = (done && toDelete) || (toDelete.length >= 100 && toDelete.splice(0, 100)); if(messageIDs) { deleted += messageIDs.length; this.deleteMessages(channelID, messageIDs).catch(reject).then(() => { if(done) { return resolve(deleted); } setTimeout(() => { checkToDelete(); }, 1000); }); } else if(done) { return resolve(deleted); } else { setTimeout(() => { checkToDelete(); }, 250); } }; var del = (_before, _after) => { this.getMessages(channelID, 100, _before, _after).catch(reject).then((messages) => { if(limit === 0) { done = true; return; } for(var message of messages) { if(limit === 0) { break; } if(!filter || filter(message)) { toDelete.push(message.id); } limit--; } if(limit === 0 || messages.length < 100) { done = true; return; } del((_before || !_after) && messages[messages.length - 1].id, _after && messages[0].id); }); }; del(before, after); checkToDelete(); }); } /** * Get a list of integrations for a guild * @arg {String} guildID The ID of the guild * @returns {Promise<GuildIntegration[]>} */ getGuildIntegrations(guildID) { var guild = this.guilds.get(guildID); return this.callAPI("GET", Endpoints.GUILD_INTEGRATIONS(guildID), true).then((integrations) => integrations.map((integration) => new GuildIntegration(integration, guild))); } // adding createGuildIntegration is questionable, why are you doing this programatically /** * Edit a guild integration * @arg {String} guildID The ID of the guild * @arg {String} integrationID The ID of the integration * @arg {Object} options The properties to edit * @arg {String} [options.expireBehavior] What to do when a user's subscription runs out * @arg {String} [options.expireGracePeriod] How long before the integration's role is removed from an unsubscribed user * @arg {String} [options.enableEmoticons] Whether to enable integration emoticons or not * @returns {Promise} */ editGuildIntegration(guildID, integrationID, options) { return this.callAPI("DELETE", Endpoints.GUILD_INTEGRATION(guildID, integrationID), true, { expire_behavior: options.expireBehavior, expire_grace_period: options.expireGracePeriod, enable_emoticons: options.enableEmoticons }); } /** * Delete a guild integration * @arg {String} guildID The ID of the guild * @arg {String} integrationID The ID of the integration * @returns {Promise} */ deleteGuildIntegration(guildID, integrationID) { return this.callAPI("DELETE", Endpoints.GUILD_INTEGRATION(guildID, integrationID), true); } /** * Force a guild integration to sync * @arg {String} guildID The ID of the guild * @arg {String} integrationID The ID of the integration * @returns {Promise} */ syncGuildIntegration(guildID, integrationID) { return this.callAPI("POST", Endpoints.GUILD_INTEGRATION_SYNC(guildID, integrationID), true); } /** * Get all invites in a guild * @arg {String} guildID The ID of the guild * @returns {Promise<Invite[]>} */ getGuildInvites(guildID) { return this.callAPI("GET", Endpoints.GUILD_INVITES(guildID), true).then((invites) => invites.map((invite) => new Invite(invite))); } /** * Ban a user from a guild * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @arg {Number} [deleteMessageDays=0] Number of days to delete messages for * @returns {Promise} */ banGuildMember(guildID, userID, deleteMessageDays) { return this.callAPI("PUT", Endpoints.GUILD_BAN(guildID, userID), true, { delete_message_days: deleteMessageDays || 0 }); } /** * Unban a user from a guild * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @returns {Promise} */ unbanGuildMember(guildID, userID) { return this.callAPI("DELETE", Endpoints.GUILD_BAN(guildID, userID), true); } /** * Create a guild * @arg {String} name The name of the guild * @arg {String} region The region of the guild * @arg {String} [icon] The guild icon as a base64 data string * @returns {Promise<Guild>} */ createGuild(name, region, icon) { icon = icon || null; return this.callAPI("POST", Endpoints.GUILDS, true, { name, region, icon }).then((guild) => new Guild(guild, this)); } /** * Edit a guild * @arg {String} guildID The ID of the guild * @arg {Object} options The properties to edit * @arg {String} [options.name] The ID of the guild * @arg {String} [options.region] The region of the guild * @arg {String} [options.icon] The guild icon as a base64 data string * @arg {Number} [options.verificationLevel] The guild verification level * @arg {String} [options.afkChannelID] The ID of the AFK voice channel * @arg {Number} [options.afkTimeout] The AFK timeout in seconds * @arg {String} [options.ownerID] The ID of the user to transfer server ownership to (bot user must be owner) * @arg {String} [options.splash] The guild splash image as a base64 data string (VIP only) * @returns {Promise<Guild>} */ editGuild(guildID, options) { var guild = this.guilds.get(guildID); if(!guild) { return Promise.reject(new Error(`Guild ${guildID} not found`)); } return this.callAPI("PATCH", Endpoints.GUILD(guildID), true, { name: options.name || guild.name, region: options.region, icon: options.icon, verification_level: options.verificationLevel, afk_channel_id: options.afkChannelID, afk_timeout: options.afkTimeout, splash: options.splash, owner_id: options.ownerID }).then((guild) => new Guild(guild, this)); } /** * Get the ban list of a guild * @arg {String} guildID The ID of the guild * @returns {Promise<User[]>} */ getGuildBans(guildID) { return this.callAPI("GET", Endpoints.GUILD_BANS(guildID), true).then((bans) => bans.map((ban) => new User(ban.user))); } /** * Edit a guild member * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @arg {Object} options The properties to edit * @arg {String[]} [options.roles] The array of role IDs the user should have * @arg {String} [options.nick] Set the user's server nickname, "" to remove * @arg {Boolean} [options.mute] Server mute the user * @arg {Boolean} [options.deaf] Server deafen the user * @arg {String} [options.channelID] The ID of the voice channel to move the user to (must be in voice) * @returns {Promise} */ editGuildMember(guildID, userID, options) { return this.callAPI("PATCH", Endpoints.GUILD_MEMBER(guildID, userID), true, { roles: options.roles, nick: options.nick, mute: options.mute, deaf: options.deaf, channel_id: options.channelID }); } /** * Edit the bot's nickname in a guild * @arg {String} guildID The ID of the guild * @arg {String} nick The nickname * @returns {Promise} */ editNickname(guildID, nick) { return this.callAPI("PATCH", Endpoints.GUILD_ME_NICK(guildID), true, { nick }); } /** * Remove (kick) a member from a guild * @arg {String} guildID The ID of the guild * @arg {String} userID The ID of the user * @returns {Promise} */ deleteGuildMember(guildID, userID) { return this.callAPI("DELETE", Endpoints.GUILD_MEMBER(guildID, userID), true); } /** * Delete a guild (bot account must be user) * @arg {String} guildID The ID of the guild * @returns {Promise} */ deleteGuild(guildID) { return this.callAPI("DELETE", Endpoints.GUILD(guildID), true); } /** * Leave a guild * @arg {String} guildID The ID of the guild * @returns {Promise} */ leaveGuild(guildID) { return this.callAPI("DELETE", Endpoints.ME_GUILD(guildID), true); } /** * Get data on an OAuth2 application * @arg {String} [appID="@me"] The client ID of the application to get data for. "@me" refers to the logged in user's own application * @returns {Promise<Object>} The bot's application data. Refer to <a href="https://discordapp.com/developers/docs/topics/oauth2#get-current-application-information">the official Discord API documentation entry</a> for Object structure */ getOAuthApplication(appID) { return this.callAPI("GET", Endpoints.OAUTH2_APPLICATION(appID || "@me"), true); } bucketsFromRequest(method, url, body) { var match = url.match(/^\/channels\/([0-9]+)\/messages(\/[0-9]+)?$/); if(match) { if(method === "DELETE" && this.getChannel(match[1])) { return ["dmsg:" + this.channelGuildMap[match[1]]]; } else if(this.user.bot) { if(method === "POST" || method === "PATCH") { if(this.privateChannels.get(match[1])) { return ["bot:msg:dm", "bot:msg:global"]; } else if(this.channelGuildMap[match[1]]) { return ["bot:msg:guild:" + this.channelGuildMap[match[1]], "bot:msg:global"]; } } } else { return ["msg"]; } } else if(method === "PATCH" || method === "DELETE") { if(url === "/users/@me" && this.user && body && body.username !== this.user.username) { return ["username"]; } else if((match = url.match(/^\/guilds\/([0-9]+)\/members\/[0-9]+$/))) { return ["guild_member:" + match[1]]; } else if((match = url.match(/^\/guilds\/([0-9]+)\/members\/@me\/nick$/))) { return ["guild_member_nick:" + match[1]]; } } return []; } /** * Make an API request * @arg {String} method Lowercase HTTP method * @arg {String} url URL of the endpoint * @arg {Boolean} auth Whether to add the Authorization header and token or not * @arg {Object} [body] Request payload * @arg {Object} [file] File object * @arg {String} file.file A readable stream or buffer * @arg {String} file.name What to name the file * @returns {Promise<Object>} Resolves with the returned JSON data */ callAPI(method, url, auth, body, file) { var resolve, reject; var promise = new Promise((res, rej) => { resolve = res; reject = rej; }); var buckets = this.bucketsFromRequest(method, url, body); var attempts = 1; var actualCall = () => { var headers = { "User-Agent": this.userAgent }; var data; if(auth) { headers.Authorization = this.token; } if(file && file.file) { data = new MultipartData(); headers["Content-Type"] = "multipart/form-data; boundary=" + data.boundary; data.attach("file", file.file, file.name); if(body) { Object.keys(body).forEach((key) => data.attach(key, body[key])); } data = data.finish(); } else if(body) { if(method === "GET" || (method === "PUT" && url.includes("/bans/"))) { // TODO remove PUT case when devs fix var qs = "" Object.keys(body).forEach((key) => qs += `&${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`); url += "?" + qs.substring(1); } else { data = JSON.stringify(body); headers["Content-Type"] = "application/json"; } } var req = HTTPS.request({ method: method, host: "discordapp.com", path: Endpoints.BASE_URL + url, headers: headers }); req.on("error", (err) => { req.abort(); reject(err); }); req.on("response", (resp) => { var response = []; resp.on("data", (chunk) => { response.push(chunk); }); resp.once("end", () => { response = Buffer.concat(response).toString("utf8"); if(resp.statusCode >= 300) { if(resp.statusCode === 429) { if(this.options.buckets) { this.emit("warn", "UNEXPECTED BUCKET 429 (โ•ฏยฐโ–กยฐ๏ผ‰โ•ฏ๏ธต โ”ปโ”โ”ป " + response); } else { if(buckets.length < 1) { this.emit("warn", "UNEXPECTED 429 (โ•ฏยฐโ–กยฐ๏ผ‰โ•ฏ๏ธต โ”ปโ”โ”ป " + response); } try { response = JSON.parse(response); } catch(err) { req.abort(); return reject("Invalid JSON: " + response); } setTimeout(actualCall, this.buckets[buckets[0]] = response.retry_after); this.buckets[buckets[0]] += Date.now(); return; } } else if(resp.statusCode === 502 && ++attempts < 4) { setTimeout(actualCall, Math.floor(Math.random() * 900 + 100)); return; } var err = new Error(`${resp.statusCode} ${resp.statusMessage}`); err.resp = resp; err.response = response; err.req = req; req.abort(); return reject(err); } if(response.length > 0) { if(resp.headers["content-type"] === "application/json") { try { response = JSON.parse(response); } catch(err) { req.abort(); return reject("Invalid JSON: " + response); } } } resolve(response); }); }); req.end(data); }; if(this.options.buckets) { var waitFor = 1; var i = 0; var done = () => { if(++i === waitFor) { actualCall(); } }; for(let bucket of buckets) { ++waitFor; this.buckets[bucket].queue(done); } done(); } else { if(this.buckets[buckets[0]]) { if(this.buckets[buckets[0]] <= Date.now) { this.buckets[buckets[0]] = null; } else { setTimeout(actualCall, this.buckets[buckets[0]]); } } else { actualCall(); } } return promise; } } module.exports = Client;
Make docs on base64 parameters a bit clearer (#53) * Make docs on base64 string parameters a bit clearer * (โ•ฏยฐโ–กยฐ๏ผ‰โ•ฏ๏ธต โ”ปโ”โ”ป
lib/Client.js
Make docs on base64 parameters a bit clearer (#53)
<ide><path>ib/Client.js <ide> * @arg {String} channelID The ID of the channel <ide> * @arg {Object} options The properties to edit <ide> * @arg {String} [options.name] The name of the channel <del> * @arg {String} [options.icon] The icon of the channel as a base64 data string (group channels only) <add> * @arg {String} [options.icon] The icon of the channel as a base64 data URI (group channels only) <ide> * @arg {String} [options.ownerID] The ID of the channel owner (group channels only) <ide> * @arg {String} [options.topic] The topic of the channel (guild text channels only) <ide> * @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only) <ide> * Edit properties of the bot user <ide> * @arg {Object} options The properties to edit <ide> * @arg {String} [options.username] The new username <del> * @arg {String} [options.avatar] The new avatar as a base64 data string <add> * @arg {String} [options.avatar] The new avatar as a base64 data URI <ide> * @returns {Promise<ExtendedUser>} <ide> */ <ide> editSelf(options) { <ide> * Create a guild <ide> * @arg {String} name The name of the guild <ide> * @arg {String} region The region of the guild <del> * @arg {String} [icon] The guild icon as a base64 data string <add> * @arg {String} [icon] The guild icon as a base64 data URI <ide> * @returns {Promise<Guild>} <ide> */ <ide> createGuild(name, region, icon) { <ide> * @arg {Object} options The properties to edit <ide> * @arg {String} [options.name] The ID of the guild <ide> * @arg {String} [options.region] The region of the guild <del> * @arg {String} [options.icon] The guild icon as a base64 data string <add> * @arg {String} [options.icon] The guild icon as a base64 data URI <ide> * @arg {Number} [options.verificationLevel] The guild verification level <ide> * @arg {String} [options.afkChannelID] The ID of the AFK voice channel <ide> * @arg {Number} [options.afkTimeout] The AFK timeout in seconds <ide> * @arg {String} [options.ownerID] The ID of the user to transfer server ownership to (bot user must be owner) <del> * @arg {String} [options.splash] The guild splash image as a base64 data string (VIP only) <add> * @arg {String} [options.splash] The guild splash image as a base64 data URI (VIP only) <ide> * @returns {Promise<Guild>} <ide> */ <ide> editGuild(guildID, options) {
Java
mpl-2.0
9f91dcae0e0f7928e1284eb4f858b95b40e19f51
0
openMF/android-client,openMF/android-client
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.savingaccountsummary; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.QuickContactBadge; import android.widget.TextView; import android.widget.Toast; import com.mifos.api.GenericResponse; import com.mifos.mifosxdroid.R; import com.mifos.mifosxdroid.adapters.SavingsAccountTransactionsListAdapter; import com.mifos.mifosxdroid.core.MifosBaseActivity; import com.mifos.mifosxdroid.core.ProgressableFragment; import com.mifos.mifosxdroid.online.datatable.DataTableFragment; import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment; import com.mifos.mifosxdroid.online.savingsaccountactivate.SavingsAccountActivateFragment; import com.mifos.mifosxdroid.online.savingsaccountapproval.SavingsAccountApprovalFragment; import com.mifos.objects.accounts.savings.DepositType; import com.mifos.objects.accounts.savings.SavingsAccountWithAssociations; import com.mifos.objects.accounts.savings.Status; import com.mifos.objects.accounts.savings.Transaction; import com.mifos.utils.Constants; import com.mifos.utils.FragmentConstants; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class SavingsAccountSummaryFragment extends ProgressableFragment implements SavingsAccountSummaryMvpView { public static final int MENU_ITEM_DATA_TABLES = 1001; public static final int MENU_ITEM_DOCUMENTS = 1004; private static final int ACTION_APPROVE_SAVINGS = 4; private static final int ACTION_ACTIVATE_SAVINGS = 5; public int savingsAccountNumber; public DepositType savingsAccountType; @BindView(R.id.tv_clientName) TextView tv_clientName; @BindView(R.id.quickContactBadge_client) QuickContactBadge quickContactBadge; @BindView(R.id.tv_savings_product_short_name) TextView tv_savingsProductName; @BindView(R.id.tv_savingsAccountNumber) TextView tv_savingsAccountNumber; @BindView(R.id.tv_savings_account_balance) TextView tv_savingsAccountBalance; @BindView(R.id.tv_total_deposits) TextView tv_totalDeposits; @BindView(R.id.tv_total_withdrawals) TextView tv_totalWithdrawals; @BindView(R.id.lv_savings_transactions) ListView lv_Transactions; @BindView(R.id.tv_interest_earned) TextView tv_interestEarned; @BindView(R.id.bt_deposit) Button bt_deposit; @BindView(R.id.bt_withdrawal) Button bt_withdrawal; @BindView(R.id.bt_approve_saving) Button bt_approve_saving; @Inject SavingsAccountSummaryPresenter mSavingAccountSummaryPresenter; // Cached List of all savings account transactions // that are used for inflation of rows in // Infinite Scroll View List<Transaction> listOfAllTransactions = new ArrayList<Transaction>(); SavingsAccountTransactionsListAdapter savingsAccountTransactionsListAdapter; private View rootView; private int processSavingTransactionAction = -1; private SavingsAccountWithAssociations savingsAccountWithAssociations; private boolean parentFragment = true; private boolean loadmore; // variable to enable and disable loading of data into listview // variables to capture position of first visible items // so that while loading the listview does not scroll automatically private int index, top; // variables to control amount of data loading on each load private int initial = 0; private int last = 5; private OnFragmentInteractionListener mListener; public static SavingsAccountSummaryFragment newInstance(int savingsAccountNumber, DepositType type, boolean parentFragment) { SavingsAccountSummaryFragment fragment = new SavingsAccountSummaryFragment(); Bundle args = new Bundle(); args.putInt(Constants.SAVINGS_ACCOUNT_NUMBER, savingsAccountNumber); args.putParcelable(Constants.SAVINGS_ACCOUNT_TYPE, type); args.putBoolean(Constants.IS_A_PARENT_FRAGMENT, parentFragment); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { savingsAccountNumber = getArguments().getInt(Constants.SAVINGS_ACCOUNT_NUMBER); savingsAccountType = getArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE); parentFragment = getArguments().getBoolean(Constants.IS_A_PARENT_FRAGMENT); } inflateSavingsAccountSummary(); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_savings_account_summary, container, false); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); ButterKnife.bind(this, rootView); mSavingAccountSummaryPresenter.attachView(this); mSavingAccountSummaryPresenter .loadSavingAccount(savingsAccountType.getEndpoint(), savingsAccountNumber); return rootView; } /** * This Method setting the ToolBar Title and Requesting the API for Saving Account */ public void inflateSavingsAccountSummary() { showProgress(true); switch (savingsAccountType.getServerType()) { case RECURRING: setToolbarTitle(getResources().getString(R.string.recurringAccountSummary)); break; default: setToolbarTitle(getResources().getString(R.string.savingsAccountSummary)); break; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; if (!parentFragment) { getActivity().finish(); } } @Override public void onPrepareOptionsMenu(Menu menu) { menu.clear(); menu.add(Menu.NONE, MENU_ITEM_DATA_TABLES, Menu.NONE, Constants .DATA_TABLE_SAVINGS_ACCOUNTS_NAME); menu.add(Menu.NONE, MENU_ITEM_DOCUMENTS, Menu.NONE, getResources().getString(R.string.documents)); super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == MENU_ITEM_DOCUMENTS) { loadDocuments(); } else if (id == MENU_ITEM_DATA_TABLES) { loadSavingsDataTables(); } return super.onOptionsItemSelected(item); } @OnClick(R.id.bt_deposit) public void onDepositButtonClicked() { mListener.doTransaction(savingsAccountWithAssociations, Constants.SAVINGS_ACCOUNT_TRANSACTION_DEPOSIT, savingsAccountType); } @OnClick(R.id.bt_withdrawal) public void onWithdrawalButtonClicked() { mListener.doTransaction(savingsAccountWithAssociations, Constants.SAVINGS_ACCOUNT_TRANSACTION_WITHDRAWAL, savingsAccountType); } @OnClick(R.id.bt_approve_saving) public void onProcessTransactionClicked() { if (processSavingTransactionAction == ACTION_APPROVE_SAVINGS) { approveSavings(); } else if (processSavingTransactionAction == ACTION_ACTIVATE_SAVINGS) { activateSavings(); } else { Log.i(getActivity().getLocalClassName(), getResources().getString(R.string.transaction_action_not_set)); } } public void enableInfiniteScrollOfTransactions() { lv_Transactions.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { loadmore = !(scrollState == SCROLL_STATE_IDLE); } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { final int lastItem = firstVisibleItem + visibleItemCount; if (firstVisibleItem == 0) return; if (lastItem == totalItemCount && loadmore) { loadmore = false; loadNextFiveTransactions(); } } }); } public void loadNextFiveTransactions() { index = lv_Transactions.getFirstVisiblePosition(); View v = lv_Transactions.getChildAt(0); top = (v == null) ? 0 : v.getTop(); last += 5; if (last > listOfAllTransactions.size()) { last = listOfAllTransactions.size(); savingsAccountTransactionsListAdapter = new SavingsAccountTransactionsListAdapter(getActivity(), listOfAllTransactions.subList(initial, last)); savingsAccountTransactionsListAdapter.notifyDataSetChanged(); lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter); lv_Transactions.setSelectionFromTop(index, top); return; } savingsAccountTransactionsListAdapter = new SavingsAccountTransactionsListAdapter(getActivity(), listOfAllTransactions.subList(initial, last)); savingsAccountTransactionsListAdapter.notifyDataSetChanged(); lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter); lv_Transactions.setSelectionFromTop(index, top); } public void loadDocuments() { DocumentListFragment documentListFragment = DocumentListFragment.newInstance(Constants .ENTITY_TYPE_SAVINGS, savingsAccountNumber); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, documentListFragment); fragmentTransaction.commit(); } public void approveSavings() { SavingsAccountApprovalFragment savingsAccountApproval = SavingsAccountApprovalFragment .newInstance(savingsAccountNumber, savingsAccountType); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, savingsAccountApproval); fragmentTransaction.commit(); } public void activateSavings() { SavingsAccountActivateFragment savingsAccountApproval = SavingsAccountActivateFragment .newInstance(savingsAccountNumber, savingsAccountType); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, savingsAccountApproval); fragmentTransaction.commit(); } public void loadSavingsDataTables() { DataTableFragment loanAccountFragment = DataTableFragment.newInstance(Constants .DATA_TABLE_NAME_SAVINGS, savingsAccountNumber); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, loanAccountFragment); fragmentTransaction.commit(); } public void toggleTransactionCapabilityOfAccount(Status status) { if (!status.getActive()) { bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); } } @Override public void showSavingAccount(SavingsAccountWithAssociations savingsAccountWithAssociations) { /* Activity is null - Fragment has been detached; no need to do anything. */ if (getActivity() == null) return; if (savingsAccountWithAssociations != null) { this.savingsAccountWithAssociations = savingsAccountWithAssociations; tv_clientName.setText(savingsAccountWithAssociations.getClientName()); tv_savingsProductName.setText(savingsAccountWithAssociations.getSavingsProductName()); tv_savingsAccountNumber.setText(savingsAccountWithAssociations.getAccountNo()); if (savingsAccountWithAssociations.getSummary().getTotalInterestEarned() != null) { tv_interestEarned.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getTotalInterestEarned())); } else { tv_interestEarned.setText("0.0"); } tv_savingsAccountBalance.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getAccountBalance())); if (savingsAccountWithAssociations.getSummary().getTotalDeposits() != null) { tv_totalDeposits.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getTotalDeposits())); } else { tv_totalDeposits.setText("0.0"); } if (savingsAccountWithAssociations.getSummary().getTotalWithdrawals() != null) { tv_totalWithdrawals.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getTotalWithdrawals())); } else { tv_totalWithdrawals.setText("0.0"); } savingsAccountTransactionsListAdapter = new SavingsAccountTransactionsListAdapter(getActivity(), savingsAccountWithAssociations.getTransactions().size() < last ? savingsAccountWithAssociations.getTransactions() : savingsAccountWithAssociations.getTransactions().subList(initial, last) ); lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter); // Cache transactions here listOfAllTransactions.addAll(savingsAccountWithAssociations.getTransactions()); lv_Transactions.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { /* On Click at a Savings Account Transaction 1. get the transactionId of that transaction 2. get the account Balance after that transaction */ int transactionId = listOfAllTransactions.get(i).getId(); double runningBalance = listOfAllTransactions.get(i).getRunningBalance(); //Display them as a Formatted string in a toast message Toast.makeText(getActivity(), String.format(getResources() .getString(R.string.savings_transaction_detail), transactionId, runningBalance), Toast.LENGTH_LONG).show(); } }); if (savingsAccountWithAssociations.getStatus().getSubmittedAndPendingApproval()) { bt_approve_saving.setEnabled(true); bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); bt_approve_saving.setText(getResources().getString(R.string.approve_savings)); processSavingTransactionAction = ACTION_APPROVE_SAVINGS; } else if (!(savingsAccountWithAssociations.getStatus().getActive())) { bt_approve_saving.setEnabled(true); bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); bt_approve_saving.setText(getResources().getString(R.string.activate_savings)); processSavingTransactionAction = ACTION_ACTIVATE_SAVINGS; } else if (savingsAccountWithAssociations.getStatus().getClosed()) { bt_approve_saving.setEnabled(false); bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); bt_approve_saving .setText(getResources().getString(R.string.savings_account_closed)); } else { inflateSavingsAccountSummary(); bt_approve_saving.setVisibility(View.GONE); } enableInfiniteScrollOfTransactions(); } } @Override public void showSavingsActivatedSuccessfully(GenericResponse genericResponse) { Toast.makeText(getActivity(), getResources().getString(R.string.savings_account_activated), Toast.LENGTH_LONG).show(); getActivity().getSupportFragmentManager().popBackStack(); } @Override public void showFetchingError(int s) { Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show(); } @Override public void showFetchingError(String errorMessage) { Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show(); } @Override public void showProgressbar(boolean b) { showProgress(b); } @Override public void onDestroyView() { super.onDestroyView(); mSavingAccountSummaryPresenter.detachView(); } public interface OnFragmentInteractionListener { void doTransaction(SavingsAccountWithAssociations savingsAccountWithAssociations, String transactionType, DepositType accountType); } }
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingaccountsummary/SavingsAccountSummaryFragment.java
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.savingaccountsummary; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.QuickContactBadge; import android.widget.TextView; import android.widget.Toast; import com.mifos.api.GenericResponse; import com.mifos.mifosxdroid.R; import com.mifos.mifosxdroid.adapters.SavingsAccountTransactionsListAdapter; import com.mifos.mifosxdroid.core.MifosBaseActivity; import com.mifos.mifosxdroid.core.ProgressableFragment; import com.mifos.mifosxdroid.online.datatable.DataTableFragment; import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment; import com.mifos.mifosxdroid.online.savingsaccountactivate.SavingsAccountActivateFragment; import com.mifos.mifosxdroid.online.savingsaccountapproval.SavingsAccountApprovalFragment; import com.mifos.objects.accounts.savings.DepositType; import com.mifos.objects.accounts.savings.SavingsAccountWithAssociations; import com.mifos.objects.accounts.savings.Status; import com.mifos.objects.accounts.savings.Transaction; import com.mifos.utils.Constants; import com.mifos.utils.FragmentConstants; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class SavingsAccountSummaryFragment extends ProgressableFragment implements SavingsAccountSummaryMvpView { public static final int MENU_ITEM_DATA_TABLES = 1001; public static final int MENU_ITEM_DOCUMENTS = 1004; private static final int ACTION_APPROVE_SAVINGS = 4; private static final int ACTION_ACTIVATE_SAVINGS = 5; public int savingsAccountNumber; public DepositType savingsAccountType; @BindView(R.id.tv_clientName) TextView tv_clientName; @BindView(R.id.quickContactBadge_client) QuickContactBadge quickContactBadge; @BindView(R.id.tv_savings_product_short_name) TextView tv_savingsProductName; @BindView(R.id.tv_savingsAccountNumber) TextView tv_savingsAccountNumber; @BindView(R.id.tv_savings_account_balance) TextView tv_savingsAccountBalance; @BindView(R.id.tv_total_deposits) TextView tv_totalDeposits; @BindView(R.id.tv_total_withdrawals) TextView tv_totalWithdrawals; @BindView(R.id.lv_savings_transactions) ListView lv_Transactions; @BindView(R.id.tv_interest_earned) TextView tv_interestEarned; @BindView(R.id.bt_deposit) Button bt_deposit; @BindView(R.id.bt_withdrawal) Button bt_withdrawal; @BindView(R.id.bt_approve_saving) Button bt_approve_saving; @Inject SavingsAccountSummaryPresenter mSavingAccountSummaryPresenter; // Cached List of all savings account transactions // that are used for inflation of rows in // Infinite Scroll View List<Transaction> listOfAllTransactions = new ArrayList<Transaction>(); SavingsAccountTransactionsListAdapter savingsAccountTransactionsListAdapter; private View rootView; private int processSavingTransactionAction = -1; private SavingsAccountWithAssociations savingsAccountWithAssociations; private boolean parentFragment = true; private boolean loadmore; // variable to enable and disable loading of data into listview // variables to capture position of first visible items // so that while loading the listview does not scroll automatically private int index, top; // variables to control amount of data loading on each load private int initial = 0; private int last = 5; private OnFragmentInteractionListener mListener; public static SavingsAccountSummaryFragment newInstance(int savingsAccountNumber, DepositType type, boolean parentFragment) { SavingsAccountSummaryFragment fragment = new SavingsAccountSummaryFragment(); Bundle args = new Bundle(); args.putInt(Constants.SAVINGS_ACCOUNT_NUMBER, savingsAccountNumber); args.putParcelable(Constants.SAVINGS_ACCOUNT_TYPE, type); args.putBoolean(Constants.IS_A_PARENT_FRAGMENT, parentFragment); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { savingsAccountNumber = getArguments().getInt(Constants.SAVINGS_ACCOUNT_NUMBER); savingsAccountType = getArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE); parentFragment = getArguments().getBoolean(Constants.IS_A_PARENT_FRAGMENT); } setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_savings_account_summary, container, false); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); ButterKnife.bind(this, rootView); mSavingAccountSummaryPresenter.attachView(this); mSavingAccountSummaryPresenter .loadSavingAccount(savingsAccountType.getEndpoint(), savingsAccountNumber); return rootView; } /** * This Method setting the ToolBar Title and Requesting the API for Saving Account */ public void inflateSavingsAccountSummary() { showProgress(true); switch (savingsAccountType.getServerType()) { case RECURRING: setToolbarTitle(getResources().getString(R.string.recurringAccountSummary)); break; default: setToolbarTitle(getResources().getString(R.string.savingsAccountSummary)); break; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; if (!parentFragment) { getActivity().finish(); } } @Override public void onPrepareOptionsMenu(Menu menu) { menu.clear(); menu.add(Menu.NONE, MENU_ITEM_DATA_TABLES, Menu.NONE, Constants .DATA_TABLE_SAVINGS_ACCOUNTS_NAME); menu.add(Menu.NONE, MENU_ITEM_DOCUMENTS, Menu.NONE, getResources().getString(R.string.documents)); super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == MENU_ITEM_DOCUMENTS) { loadDocuments(); } else if (id == MENU_ITEM_DATA_TABLES) { loadSavingsDataTables(); } return super.onOptionsItemSelected(item); } @OnClick(R.id.bt_deposit) public void onDepositButtonClicked() { mListener.doTransaction(savingsAccountWithAssociations, Constants.SAVINGS_ACCOUNT_TRANSACTION_DEPOSIT, savingsAccountType); } @OnClick(R.id.bt_withdrawal) public void onWithdrawalButtonClicked() { mListener.doTransaction(savingsAccountWithAssociations, Constants.SAVINGS_ACCOUNT_TRANSACTION_WITHDRAWAL, savingsAccountType); } @OnClick(R.id.bt_approve_saving) public void onProcessTransactionClicked() { if (processSavingTransactionAction == ACTION_APPROVE_SAVINGS) { approveSavings(); } else if (processSavingTransactionAction == ACTION_ACTIVATE_SAVINGS) { activateSavings(); } else { Log.i(getActivity().getLocalClassName(), getResources().getString(R.string.transaction_action_not_set)); } } public void enableInfiniteScrollOfTransactions() { lv_Transactions.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { loadmore = !(scrollState == SCROLL_STATE_IDLE); } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { final int lastItem = firstVisibleItem + visibleItemCount; if (firstVisibleItem == 0) return; if (lastItem == totalItemCount && loadmore) { loadmore = false; loadNextFiveTransactions(); } } }); } public void loadNextFiveTransactions() { index = lv_Transactions.getFirstVisiblePosition(); View v = lv_Transactions.getChildAt(0); top = (v == null) ? 0 : v.getTop(); last += 5; if (last > listOfAllTransactions.size()) { last = listOfAllTransactions.size(); savingsAccountTransactionsListAdapter = new SavingsAccountTransactionsListAdapter(getActivity(), listOfAllTransactions.subList(initial, last)); savingsAccountTransactionsListAdapter.notifyDataSetChanged(); lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter); lv_Transactions.setSelectionFromTop(index, top); return; } savingsAccountTransactionsListAdapter = new SavingsAccountTransactionsListAdapter(getActivity(), listOfAllTransactions.subList(initial, last)); savingsAccountTransactionsListAdapter.notifyDataSetChanged(); lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter); lv_Transactions.setSelectionFromTop(index, top); } public void loadDocuments() { DocumentListFragment documentListFragment = DocumentListFragment.newInstance(Constants .ENTITY_TYPE_SAVINGS, savingsAccountNumber); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, documentListFragment); fragmentTransaction.commit(); } public void approveSavings() { SavingsAccountApprovalFragment savingsAccountApproval = SavingsAccountApprovalFragment .newInstance(savingsAccountNumber, savingsAccountType); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, savingsAccountApproval); fragmentTransaction.commit(); } public void activateSavings() { SavingsAccountActivateFragment savingsAccountApproval = SavingsAccountActivateFragment .newInstance(savingsAccountNumber, savingsAccountType); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, savingsAccountApproval); fragmentTransaction.commit(); } public void loadSavingsDataTables() { DataTableFragment loanAccountFragment = DataTableFragment.newInstance(Constants .DATA_TABLE_NAME_SAVINGS, savingsAccountNumber); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_SAVINGS_ACCOUNT_SUMMARY); fragmentTransaction.replace(R.id.container, loanAccountFragment); fragmentTransaction.commit(); } public void toggleTransactionCapabilityOfAccount(Status status) { if (!status.getActive()) { bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); } } @Override public void showSavingAccount(SavingsAccountWithAssociations savingsAccountWithAssociations) { /* Activity is null - Fragment has been detached; no need to do anything. */ if (getActivity() == null) return; if (savingsAccountWithAssociations != null) { this.savingsAccountWithAssociations = savingsAccountWithAssociations; tv_clientName.setText(savingsAccountWithAssociations.getClientName()); tv_savingsProductName.setText(savingsAccountWithAssociations.getSavingsProductName()); tv_savingsAccountNumber.setText(savingsAccountWithAssociations.getAccountNo()); if (savingsAccountWithAssociations.getSummary().getTotalInterestEarned() != null) { tv_interestEarned.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getTotalInterestEarned())); } else { tv_interestEarned.setText("0.0"); } tv_savingsAccountBalance.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getAccountBalance())); if (savingsAccountWithAssociations.getSummary().getTotalDeposits() != null) { tv_totalDeposits.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getTotalDeposits())); } else { tv_totalDeposits.setText("0.0"); } if (savingsAccountWithAssociations.getSummary().getTotalWithdrawals() != null) { tv_totalWithdrawals.setText(String.valueOf(savingsAccountWithAssociations .getSummary().getTotalWithdrawals())); } else { tv_totalWithdrawals.setText("0.0"); } savingsAccountTransactionsListAdapter = new SavingsAccountTransactionsListAdapter(getActivity(), savingsAccountWithAssociations.getTransactions().size() < last ? savingsAccountWithAssociations.getTransactions() : savingsAccountWithAssociations.getTransactions().subList(initial, last) ); lv_Transactions.setAdapter(savingsAccountTransactionsListAdapter); // Cache transactions here listOfAllTransactions.addAll(savingsAccountWithAssociations.getTransactions()); lv_Transactions.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { /* On Click at a Savings Account Transaction 1. get the transactionId of that transaction 2. get the account Balance after that transaction */ int transactionId = listOfAllTransactions.get(i).getId(); double runningBalance = listOfAllTransactions.get(i).getRunningBalance(); //Display them as a Formatted string in a toast message Toast.makeText(getActivity(), String.format(getResources() .getString(R.string.savings_transaction_detail), transactionId, runningBalance), Toast.LENGTH_LONG).show(); } }); if (savingsAccountWithAssociations.getStatus().getSubmittedAndPendingApproval()) { bt_approve_saving.setEnabled(true); bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); bt_approve_saving.setText(getResources().getString(R.string.approve_savings)); processSavingTransactionAction = ACTION_APPROVE_SAVINGS; } else if (!(savingsAccountWithAssociations.getStatus().getActive())) { bt_approve_saving.setEnabled(true); bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); bt_approve_saving.setText(getResources().getString(R.string.activate_savings)); processSavingTransactionAction = ACTION_ACTIVATE_SAVINGS; } else if (savingsAccountWithAssociations.getStatus().getClosed()) { bt_approve_saving.setEnabled(false); bt_deposit.setVisibility(View.GONE); bt_withdrawal.setVisibility(View.GONE); bt_approve_saving .setText(getResources().getString(R.string.savings_account_closed)); } else { inflateSavingsAccountSummary(); bt_approve_saving.setVisibility(View.GONE); } enableInfiniteScrollOfTransactions(); } } @Override public void showSavingsActivatedSuccessfully(GenericResponse genericResponse) { Toast.makeText(getActivity(), getResources().getString(R.string.savings_account_activated), Toast.LENGTH_LONG).show(); getActivity().getSupportFragmentManager().popBackStack(); } @Override public void showFetchingError(int s) { Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show(); } @Override public void showFetchingError(String errorMessage) { Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show(); } @Override public void showProgressbar(boolean b) { showProgress(b); } @Override public void onDestroyView() { super.onDestroyView(); mSavingAccountSummaryPresenter.detachView(); } public interface OnFragmentInteractionListener { void doTransaction(SavingsAccountWithAssociations savingsAccountWithAssociations, String transactionType, DepositType accountType); } }
Fix:Wrong Toolbar title in Savings Account summary
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingaccountsummary/SavingsAccountSummaryFragment.java
Fix:Wrong Toolbar title in Savings Account summary
<ide><path>ifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingaccountsummary/SavingsAccountSummaryFragment.java <ide> savingsAccountType = getArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE); <ide> parentFragment = getArguments().getBoolean(Constants.IS_A_PARENT_FRAGMENT); <ide> } <add> inflateSavingsAccountSummary(); <ide> setHasOptionsMenu(true); <ide> } <ide>
Java
bsd-3-clause
f8b18fa275dce742d3141fcfb638db9ff8594605
0
compgen-io/ngsutilsj,compgen-io/ngsutilsj
package io.compgen.ngsutils.cli.bam; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMFileWriter; import htsjdk.samtools.SAMFileWriterFactory; import htsjdk.samtools.SAMProgramRecord; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.exceptions.CommandArgumentException; import io.compgen.cmdline.impl.AbstractCommand; import io.compgen.common.progress.FileChannelStats; import io.compgen.common.progress.ProgressMessage; import io.compgen.common.progress.ProgressUtils; import io.compgen.ngsutils.bam.support.BamHeaderUtils; import io.compgen.ngsutils.bam.support.ReadUtils; import io.compgen.ngsutils.support.CloseableFinalizer; @Command(name="bam-discord", desc="Extract all discordant reads from a BAM file", category="bam", doc="Note: for paired-end reads, both reads must be mapped.") public class BamDiscord extends AbstractCommand { private String filename = null; private boolean lenient = false; private boolean silent = false; private int intraChromDistance = 10000; private String concordFilename = null; private String discordFilename = null; private String tmpDir = null; private boolean noIntraChrom = false; @UnnamedArg(name = "FILE") public void setFilename(String filename) { this.filename = filename; } @Option(desc = "Use lenient validation strategy", name="lenient") public void setLenient(boolean lenient) { this.lenient = lenient; } @Option(desc = "Use silent validation strategy", name="silent") public void setSilent(boolean silent) { this.silent = silent; } @Option(desc="Write temporary files here", name="tmpdir", helpValue="dir") public void setTmpDir(String tmpDir) { this.tmpDir = tmpDir; } @Option(desc = "Maximum intra-chromosomal distance (pairs aligned more than this distance apart will be flagged as discordant)", name="dist", defaultValue="10000") public void setIntraChromDistance(int intraChromDistance) { this.intraChromDistance = intraChromDistance; } @Option(desc = "No intra-chromosomal discordant reads (in proper orientation)", name="no-intrachrom") public void setNoIntraChrom(boolean noIntraChrom) { this.noIntraChrom = noIntraChrom; } @Option(desc = "Discordant read output BAM", name="discord", helpValue="fname") public void setDiscordFilename(String discordFilename) { this.discordFilename = discordFilename; } @Option(desc = "Concordant read output BAM", name="concord", helpValue="fname") public void setConcordFilename(String concordFilename) { this.concordFilename = concordFilename; } @Exec public void exec() throws IOException, CommandArgumentException { if (filename == null) { throw new CommandArgumentException("You must specify an input BAM filename!"); } if (concordFilename == null && discordFilename == null) { throw new CommandArgumentException("You must specify --discord or --concord (or both)!"); } if (concordFilename != null && concordFilename.equals("-") && discordFilename != null && discordFilename.equals("-")) { throw new CommandArgumentException("You cannot write both --discord and --concord to stdout (-)!"); } SamReaderFactory readerFactory = SamReaderFactory.makeDefault(); if (lenient) { readerFactory.validationStringency(ValidationStringency.LENIENT); } else if (silent) { readerFactory.validationStringency(ValidationStringency.SILENT); } SamReader reader = null; String name; FileChannel channel = null; if (filename.equals("-")) { reader = readerFactory.open(SamInputResource.of(System.in)); name = "<stdin>"; } else { File f = new File(filename); FileInputStream fis = new FileInputStream(f); channel = fis.getChannel(); reader = readerFactory.open(SamInputResource.of(fis)); name = f.getName(); } SAMFileWriter concord = null; SAMFileWriter discord = null; if (concordFilename != null) { SAMFileWriterFactory factory = new SAMFileWriterFactory(); File outfile = null; OutputStream outStream = null; if (concordFilename.equals("-")) { outStream = new BufferedOutputStream(System.out); } else { outfile = new File(concordFilename); } if (tmpDir != null) { factory.setTempDirectory(new File(tmpDir)); } else if (outfile == null || outfile.getParent() == null) { factory.setTempDirectory(new File(".").getCanonicalFile()); } else if (outfile!=null) { factory.setTempDirectory(outfile.getParentFile()); } SAMFileHeader header = reader.getFileHeader().clone(); SAMProgramRecord pg = BamHeaderUtils.buildSAMProgramRecord("bam-discord", header); List<SAMProgramRecord> pgRecords = new ArrayList<SAMProgramRecord>(header.getProgramRecords()); pgRecords.add(0, pg); header.setProgramRecords(pgRecords); if (outfile != null) { concord = factory.makeBAMWriter(header, true, outfile); } else { concord = factory.makeBAMWriter(header, true, outStream); } } if (discordFilename != null) { SAMFileWriterFactory factory = new SAMFileWriterFactory(); File outfile = null; OutputStream outStream = null; if (discordFilename.equals("-")) { outStream = new BufferedOutputStream(System.out); } else { outfile = new File(discordFilename); } if (tmpDir != null) { factory.setTempDirectory(new File(tmpDir)); } else if (outfile == null || outfile.getParent() == null) { factory.setTempDirectory(new File(".").getCanonicalFile()); } else if (outfile!=null) { factory.setTempDirectory(outfile.getParentFile()); } SAMFileHeader header = reader.getFileHeader().clone(); SAMProgramRecord pg = BamHeaderUtils.buildSAMProgramRecord("bam-discord", header); List<SAMProgramRecord> pgRecords = new ArrayList<SAMProgramRecord>(header.getProgramRecords()); pgRecords.add(0, pg); header.setProgramRecords(pgRecords); if (outfile != null) { discord = factory.makeBAMWriter(header, true, outfile); } else { discord = factory.makeBAMWriter(header, true, outStream); } } Iterator<SAMRecord> it = ProgressUtils.getIterator(name, reader.iterator(), (channel == null)? null : new FileChannelStats(channel), new ProgressMessage<SAMRecord>() { long i = 0; @Override public String msg(SAMRecord current) { i++; return i+" "+current.getReadName(); }}, new CloseableFinalizer<SAMRecord>()); long totalCount = 0; long discordCount = 0; while (it.hasNext()) { SAMRecord read = it.next(); if (read.getReadPairedFlag() && (read.getMateUnmappedFlag() || read.getReadUnmappedFlag())) { continue; } totalCount++; if (ReadUtils.isDiscordant(read, intraChromDistance, !noIntraChrom)) { discordCount++; if (discord != null) { discord.addAlignment(read); } } else if (concord != null) { concord.addAlignment(read); } } reader.close(); if (discord != null) { discord.close(); } if (concord != null) { concord.close(); } System.err.println("Total reads : "+totalCount); System.err.println("Discordant reads: "+discordCount); } }
src/java/io/compgen/ngsutils/cli/bam/BamDiscord.java
package io.compgen.ngsutils.cli.bam; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMFileWriter; import htsjdk.samtools.SAMFileWriterFactory; import htsjdk.samtools.SAMProgramRecord; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.exceptions.CommandArgumentException; import io.compgen.cmdline.impl.AbstractCommand; import io.compgen.common.progress.FileChannelStats; import io.compgen.common.progress.ProgressMessage; import io.compgen.common.progress.ProgressUtils; import io.compgen.ngsutils.bam.support.BamHeaderUtils; import io.compgen.ngsutils.bam.support.ReadUtils; import io.compgen.ngsutils.support.CloseableFinalizer; @Command(name="bam-discord", desc="Extract all discordant reads from a BAM file", category="bam") public class BamDiscord extends AbstractCommand { private String filename = null; private boolean lenient = false; private boolean silent = false; private int intraChromDistance = 10000; private String concordFilename = null; private String discordFilename = null; private String tmpDir = null; private boolean noIntraChrom = false; @UnnamedArg(name = "FILE") public void setFilename(String filename) { this.filename = filename; } @Option(desc = "Use lenient validation strategy", name="lenient") public void setLenient(boolean lenient) { this.lenient = lenient; } @Option(desc = "Use silent validation strategy", name="silent") public void setSilent(boolean silent) { this.silent = silent; } @Option(desc="Write temporary files here", name="tmpdir", helpValue="dir") public void setTmpDir(String tmpDir) { this.tmpDir = tmpDir; } @Option(desc = "Maximum intra-chromosomal distance (pairs aligned more than this distance apart will be flagged as discordant)", name="dist", defaultValue="10000") public void setIntraChromDistance(int intraChromDistance) { this.intraChromDistance = intraChromDistance; } @Option(desc = "No intra-chromosomal discordant reads (in proper orientation)", name="no-intrachrom") public void setNoIntraChrom(boolean noIntraChrom) { this.noIntraChrom = noIntraChrom; } @Option(desc = "Discordant read output BAM", name="discord", helpValue="fname") public void setDiscordFilename(String discordFilename) { this.discordFilename = discordFilename; } @Option(desc = "Concordant read output BAM", name="concord", helpValue="fname") public void setConcordFilename(String concordFilename) { this.concordFilename = concordFilename; } @Exec public void exec() throws IOException, CommandArgumentException { if (filename == null) { throw new CommandArgumentException("You must specify an input BAM filename!"); } if (concordFilename == null && discordFilename == null) { throw new CommandArgumentException("You must specify --discord or --concord (or both)!"); } if (concordFilename != null && concordFilename.equals("-") && discordFilename != null && discordFilename.equals("-")) { throw new CommandArgumentException("You cannot write both --discord and --concord to stdout (-)!"); } SamReaderFactory readerFactory = SamReaderFactory.makeDefault(); if (lenient) { readerFactory.validationStringency(ValidationStringency.LENIENT); } else if (silent) { readerFactory.validationStringency(ValidationStringency.SILENT); } SamReader reader = null; String name; FileChannel channel = null; if (filename.equals("-")) { reader = readerFactory.open(SamInputResource.of(System.in)); name = "<stdin>"; } else { File f = new File(filename); FileInputStream fis = new FileInputStream(f); channel = fis.getChannel(); reader = readerFactory.open(SamInputResource.of(fis)); name = f.getName(); } SAMFileWriter concord = null; SAMFileWriter discord = null; if (concordFilename != null) { SAMFileWriterFactory factory = new SAMFileWriterFactory(); File outfile = null; OutputStream outStream = null; if (concordFilename.equals("-")) { outStream = new BufferedOutputStream(System.out); } else { outfile = new File(concordFilename); } if (tmpDir != null) { factory.setTempDirectory(new File(tmpDir)); } else if (outfile == null || outfile.getParent() == null) { factory.setTempDirectory(new File(".").getCanonicalFile()); } else if (outfile!=null) { factory.setTempDirectory(outfile.getParentFile()); } SAMFileHeader header = reader.getFileHeader().clone(); SAMProgramRecord pg = BamHeaderUtils.buildSAMProgramRecord("bam-discord", header); List<SAMProgramRecord> pgRecords = new ArrayList<SAMProgramRecord>(header.getProgramRecords()); pgRecords.add(0, pg); header.setProgramRecords(pgRecords); if (outfile != null) { concord = factory.makeBAMWriter(header, true, outfile); } else { concord = factory.makeBAMWriter(header, true, outStream); } } if (discordFilename != null) { SAMFileWriterFactory factory = new SAMFileWriterFactory(); File outfile = null; OutputStream outStream = null; if (discordFilename.equals("-")) { outStream = new BufferedOutputStream(System.out); } else { outfile = new File(discordFilename); } if (tmpDir != null) { factory.setTempDirectory(new File(tmpDir)); } else if (outfile == null || outfile.getParent() == null) { factory.setTempDirectory(new File(".").getCanonicalFile()); } else if (outfile!=null) { factory.setTempDirectory(outfile.getParentFile()); } SAMFileHeader header = reader.getFileHeader().clone(); SAMProgramRecord pg = BamHeaderUtils.buildSAMProgramRecord("bam-discord", header); List<SAMProgramRecord> pgRecords = new ArrayList<SAMProgramRecord>(header.getProgramRecords()); pgRecords.add(0, pg); header.setProgramRecords(pgRecords); if (outfile != null) { discord = factory.makeBAMWriter(header, true, outfile); } else { discord = factory.makeBAMWriter(header, true, outStream); } } Iterator<SAMRecord> it = ProgressUtils.getIterator(name, reader.iterator(), (channel == null)? null : new FileChannelStats(channel), new ProgressMessage<SAMRecord>() { long i = 0; @Override public String msg(SAMRecord current) { i++; return i+" "+current.getReadName(); }}, new CloseableFinalizer<SAMRecord>()); long totalCount = 0; long discordCount = 0; while (it.hasNext()) { totalCount++; SAMRecord read = it.next(); if (ReadUtils.isDiscordant(read, intraChromDistance, !noIntraChrom)) { discordCount++; if (discord != null) { discord.addAlignment(read); } } else if (concord != null) { concord.addAlignment(read); } } reader.close(); if (discord != null) { discord.close(); } if (concord != null) { concord.close(); } System.err.println("Total reads : "+totalCount); System.err.println("Discordant reads: "+discordCount); } }
discord / concordant reads must have both pairs mapped.
src/java/io/compgen/ngsutils/cli/bam/BamDiscord.java
discord / concordant reads must have both pairs mapped.
<ide><path>rc/java/io/compgen/ngsutils/cli/bam/BamDiscord.java <ide> import io.compgen.ngsutils.bam.support.ReadUtils; <ide> import io.compgen.ngsutils.support.CloseableFinalizer; <ide> <del>@Command(name="bam-discord", desc="Extract all discordant reads from a BAM file", category="bam") <add>@Command(name="bam-discord", desc="Extract all discordant reads from a BAM file", category="bam", doc="Note: for paired-end reads, both reads must be mapped.") <ide> public class BamDiscord extends AbstractCommand { <ide> private String filename = null; <ide> private boolean lenient = false; <ide> long discordCount = 0; <ide> <ide> while (it.hasNext()) { <add> SAMRecord read = it.next(); <add> <add> if (read.getReadPairedFlag() && (read.getMateUnmappedFlag() || read.getReadUnmappedFlag())) { <add> continue; <add> } <add> <ide> totalCount++; <del> SAMRecord read = it.next(); <ide> <ide> if (ReadUtils.isDiscordant(read, intraChromDistance, !noIntraChrom)) { <ide> discordCount++;
Java
apache-2.0
077cf2dbf8b63b4600ff19b36de2e24448f84439
0
jboss-qa/jcontainer-manager,jboss-qa/jcontainer-manager
/* * Copyright 2015 Red Hat Inc. and/or its affiliates and other 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.jboss.qa.jcontainer.util; import java.lang.management.ManagementFactory; import lombok.extern.slf4j.Slf4j; @Slf4j public final class PidUtils { private PidUtils() { } private static Long cachedPid; public static Long getPID() { if (cachedPid == null) { initPid(); } log.debug("My PID is {}", cachedPid); return cachedPid; } private static void initPid() { Long pid = null; // TODO(mswiech): try to use JDK9 api in future: http://download.java.net/jdk9/docs/api/java/lang/Process.html#getPid-- try { pid = getPidByRuntimeMXBean(); } catch (Exception e) { log.error("There is a problem with getting PID using RuntimeMXBean way.", e); } if (pid != null) { cachedPid = pid; } else { log.error("Could not obtain PID."); } } private static Long getPidByRuntimeMXBean() { final String processName; try { processName = ManagementFactory.getRuntimeMXBean().getName(); } catch (Exception e) { log.error("There is some problem with getting RuntimeMXBean name.", e); return null; } if (processName != null && processName.indexOf("@") > 0) { final String pid = processName.split("@")[0]; try { return Long.parseLong(pid); } catch (final NumberFormatException e) { log.error("Could not parse PID " + pid + " from " + processName); } } else { log.error("RuntimeMXBean name " + processName + " does not contain '@'."); } return null; } }
core/src/main/java/org/jboss/qa/jcontainer/util/PidUtils.java
package org.jboss.qa.jcontainer.util; import java.lang.management.ManagementFactory; import lombok.extern.slf4j.Slf4j; @Slf4j public class PidUtils { private static Long cachedPid; public static Long getPID() { if (cachedPid == null) { initPid(); } log.debug("My PID is {}", cachedPid); return cachedPid; } private static void initPid() { Long pid = null; //TODO try to use JDK9 api in future: http://download.java.net/jdk9/docs/api/java/lang/Process.html#getPid-- try { pid = getPidByRuntimeMXBean(); } catch (Exception e) { log.error("There is a problem with getting PID using RuntimeMXBean way.", e); } if (pid != null) { cachedPid = pid; } else { log.error("Could not obtain PID."); } } private static Long getPidByRuntimeMXBean() { final String processName; try { processName = ManagementFactory.getRuntimeMXBean().getName(); } catch (Exception e) { log.error("There is some problem with getting RuntimeMXBean name.", e); return null; } if (processName != null && processName.indexOf("@") > 0) { final String pid = processName.split("@")[0]; try { return Long.parseLong(pid); } catch (final NumberFormatException e) { log.error("Could not parse PID " + pid + " from " + processName); } } else { log.error("RuntimeMXBean name " + processName + " does not contain '@'."); } return null; } }
[relates #60] Fix checkstyle errors
core/src/main/java/org/jboss/qa/jcontainer/util/PidUtils.java
[relates #60] Fix checkstyle errors
<ide><path>ore/src/main/java/org/jboss/qa/jcontainer/util/PidUtils.java <add>/* <add> * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> package org.jboss.qa.jcontainer.util; <ide> <ide> import java.lang.management.ManagementFactory; <ide> import lombok.extern.slf4j.Slf4j; <ide> <ide> @Slf4j <del>public class PidUtils { <add>public final class PidUtils { <add> private PidUtils() { <add> } <ide> <ide> private static Long cachedPid; <ide> <ide> private static void initPid() { <ide> Long pid = null; <ide> <del> //TODO try to use JDK9 api in future: http://download.java.net/jdk9/docs/api/java/lang/Process.html#getPid-- <add> // TODO(mswiech): try to use JDK9 api in future: http://download.java.net/jdk9/docs/api/java/lang/Process.html#getPid-- <ide> <ide> try { <ide> pid = getPidByRuntimeMXBean(); <ide> log.error("Could not obtain PID."); <ide> } <ide> } <del> <ide> <ide> private static Long getPidByRuntimeMXBean() { <ide> final String processName;
Java
apache-2.0
fcd5ae6d95cd2fa4e25a324945d4b8cb0075309c
0
philbritton/dswarm,dswarm/dswarm,zazi/dswarm,janpolowinski/dswarm,knutwalker/dswarm,zazi/dswarm,dswarm/dswarm,dswarm/dswarm,philbritton/dswarm,janpolowinski/dswarm,knutwalker/dswarm,knutwalker/dswarm,philbritton/dswarm,zazi/dswarm
/** * Copyright (C) 2013, 2014 SLUB Dresden & Avantgarde Labs GmbH (<[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 org.dswarm.persistence.service.schema.test; import org.dswarm.persistence.GuicedTest; import org.dswarm.persistence.model.schema.Clasz; import org.dswarm.persistence.model.schema.proxy.ProxyClasz; import org.dswarm.persistence.service.schema.ClaszService; import org.dswarm.persistence.service.schema.test.utils.ClaszServiceTestUtils; import org.dswarm.persistence.service.test.AdvancedJPAServiceTest; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class ClaszServiceTest extends AdvancedJPAServiceTest<ProxyClasz, Clasz, ClaszService> { private static final Logger LOG = LoggerFactory.getLogger(ClaszServiceTest.class); private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class); private final ClaszServiceTestUtils claszServiceTestUtils; public ClaszServiceTest() { super("class", ClaszService.class); claszServiceTestUtils = new ClaszServiceTestUtils(); } @Test public void testSimpleAttribute() throws Exception { final Clasz clasz = claszServiceTestUtils.createClass( "http://purl.org/ontology/bibo/Document", "document" ); updateObjectTransactional(clasz); final Clasz updatedClass = getObject(clasz); Assert.assertNotNull("the attribute name of the updated resource shouldn't be null", updatedClass.getName()); Assert.assertEquals("the attribute's name are not equal", clasz.getName(), updatedClass.getName()); String json = null; try { json = objectMapper.writeValueAsString(updatedClass); } catch( final JsonProcessingException e ) { LOG.error( e.getMessage(), e ); } ClaszServiceTest.LOG.debug("class json: " + json); } @Test public void testUniquenessOfClasses() throws Exception { final Clasz clasz1 = createClass(); final Clasz clasz2 = createClass(); Assert.assertNotNull("attribute1 shouldn't be null", clasz1); Assert.assertNotNull("attribute2 shouldn't be null", clasz2); Assert.assertNotNull("attribute1 id shouldn't be null", clasz1.getId()); Assert.assertNotNull("attribute2 id shouldn't be null", clasz2.getId()); Assert.assertEquals("the attributes should be equal", clasz1, clasz2); Assert.assertNotNull("attribute1 uri shouldn't be null", clasz1.getUri()); Assert.assertNotNull("attribute2 uri shouldn't be null", clasz2.getUri()); Assert.assertNotNull("attribute1 uri shouldn't be empty", clasz1.getUri().trim().isEmpty()); Assert.assertNotNull("attribute2 uri shouldn't be empty", clasz2.getUri().trim().isEmpty()); Assert.assertEquals("the attribute uris should be equal", clasz1.getUri(), clasz2.getUri()); Assert.assertNotNull("attribute1 uri shouldn't be null", clasz1.getName()); Assert.assertNotNull("attribute2 uri shouldn't be null", clasz2.getName()); Assert.assertNotNull("attribute1 uri shouldn't be empty", clasz1.getName().trim().isEmpty()); Assert.assertNotNull("attribute2 uri shouldn't be empty", clasz2.getName().trim().isEmpty()); Assert.assertEquals("the attribute uris should be equal", clasz1.getName(), clasz2.getName()); } private Clasz createClass() throws Exception { final Clasz clasz = claszServiceTestUtils.createClass( "http://purl.org/ontology/bibo/Document", "document" ); updateObjectTransactional(clasz); final Clasz updatedClasz = getObject(clasz); return updatedClasz; } }
persistence/src/test/java/org/dswarm/persistence/service/schema/test/ClaszServiceTest.java
/** * Copyright (C) 2013, 2014 SLUB Dresden & Avantgarde Labs GmbH (<[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 org.dswarm.persistence.service.schema.test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.dswarm.persistence.GuicedTest; import org.dswarm.persistence.model.schema.Clasz; import org.dswarm.persistence.model.schema.proxy.ProxyClasz; import org.dswarm.persistence.service.schema.ClaszService; import org.dswarm.persistence.service.schema.test.utils.ClaszServiceTestUtils; import org.dswarm.persistence.service.test.AdvancedJPAServiceTest; public class ClaszServiceTest extends AdvancedJPAServiceTest<ProxyClasz, Clasz, ClaszService> { private static final Logger LOG = LoggerFactory.getLogger(ClaszServiceTest.class); private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class); private final ClaszServiceTestUtils claszServiceTestUtils; public ClaszServiceTest() { super("class", ClaszService.class); claszServiceTestUtils = new ClaszServiceTestUtils(); } @Test public void testSimpleAttribute() { final Clasz clasz = createObject("http://purl.org/ontology/bibo/Document").getObject(); clasz.setName("document"); updateObjectTransactional(clasz); final Clasz updatedClass = getObject(clasz); Assert.assertNotNull("the attribute name of the updated resource shouldn't be null", updatedClass.getName()); Assert.assertEquals("the attribute's name are not equal", clasz.getName(), updatedClass.getName()); String json = null; try { json = objectMapper.writeValueAsString(updatedClass); } catch (final JsonProcessingException e) { e.printStackTrace(); } ClaszServiceTest.LOG.debug("class json: " + json); // clean up DB claszServiceTestUtils.deleteObject(clasz); } @Test public void testUniquenessOfClasses() { final Clasz clasz1 = createClass(); final Clasz clasz2 = createClass(); Assert.assertNotNull("attribute1 shouldn't be null", clasz1); Assert.assertNotNull("attribute2 shouldn't be null", clasz2); Assert.assertNotNull("attribute1 id shouldn't be null", clasz1.getId()); Assert.assertNotNull("attribute2 id shouldn't be null", clasz2.getId()); Assert.assertEquals("the attributes should be equal", clasz1, clasz2); Assert.assertNotNull("attribute1 uri shouldn't be null", clasz1.getUri()); Assert.assertNotNull("attribute2 uri shouldn't be null", clasz2.getUri()); Assert.assertNotNull("attribute1 uri shouldn't be empty", clasz1.getUri().trim().isEmpty()); Assert.assertNotNull("attribute2 uri shouldn't be empty", clasz2.getUri().trim().isEmpty()); Assert.assertEquals("the attribute uris should be equal", clasz1.getUri(), clasz2.getUri()); Assert.assertNotNull("attribute1 uri shouldn't be null", clasz1.getName()); Assert.assertNotNull("attribute2 uri shouldn't be null", clasz2.getName()); Assert.assertNotNull("attribute1 uri shouldn't be empty", clasz1.getName().trim().isEmpty()); Assert.assertNotNull("attribute2 uri shouldn't be empty", clasz2.getName().trim().isEmpty()); Assert.assertEquals("the attribute uris should be equal", clasz1.getName(), clasz2.getName()); // clean up DB claszServiceTestUtils.deleteObject(clasz1); } private Clasz createClass() { final Clasz clasz = createObject("http://purl.org/ontology/bibo/Document").getObject(); clasz.setName("document"); updateObjectTransactional(clasz); final Clasz updatedClasz = getObject(clasz); return updatedClasz; } }
[DD-701] refactored to the usage of Utility and removed DB cleanup
persistence/src/test/java/org/dswarm/persistence/service/schema/test/ClaszServiceTest.java
[DD-701] refactored to the usage of Utility and removed DB cleanup
<ide><path>ersistence/src/test/java/org/dswarm/persistence/service/schema/test/ClaszServiceTest.java <ide> */ <ide> package org.dswarm.persistence.service.schema.test; <ide> <del>import com.fasterxml.jackson.core.JsonProcessingException; <del>import com.fasterxml.jackson.databind.ObjectMapper; <del>import org.junit.Assert; <del>import org.junit.Test; <del>import org.slf4j.Logger; <del>import org.slf4j.LoggerFactory; <del> <ide> import org.dswarm.persistence.GuicedTest; <ide> import org.dswarm.persistence.model.schema.Clasz; <ide> import org.dswarm.persistence.model.schema.proxy.ProxyClasz; <ide> import org.dswarm.persistence.service.schema.ClaszService; <ide> import org.dswarm.persistence.service.schema.test.utils.ClaszServiceTestUtils; <ide> import org.dswarm.persistence.service.test.AdvancedJPAServiceTest; <add>import org.junit.Assert; <add>import org.junit.Test; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add> <add>import com.fasterxml.jackson.core.JsonProcessingException; <add>import com.fasterxml.jackson.databind.ObjectMapper; <ide> <ide> public class ClaszServiceTest extends AdvancedJPAServiceTest<ProxyClasz, Clasz, ClaszService> { <ide> <del> private static final Logger LOG = LoggerFactory.getLogger(ClaszServiceTest.class); <add> private static final Logger LOG = LoggerFactory.getLogger(ClaszServiceTest.class); <ide> <del> private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class); <add> private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class); <ide> <del> private final ClaszServiceTestUtils claszServiceTestUtils; <add> private final ClaszServiceTestUtils claszServiceTestUtils; <add> <ide> <ide> public ClaszServiceTest() { <del> <ide> super("class", ClaszService.class); <del> <ide> claszServiceTestUtils = new ClaszServiceTestUtils(); <ide> } <ide> <add> <ide> @Test <del> public void testSimpleAttribute() { <add> public void testSimpleAttribute() throws Exception { <ide> <del> final Clasz clasz = createObject("http://purl.org/ontology/bibo/Document").getObject(); <del> <del> clasz.setName("document"); <add> final Clasz clasz = claszServiceTestUtils.createClass( "http://purl.org/ontology/bibo/Document", "document" ); <ide> <ide> updateObjectTransactional(clasz); <ide> <ide> Assert.assertEquals("the attribute's name are not equal", clasz.getName(), updatedClass.getName()); <ide> <ide> String json = null; <del> <ide> try { <ide> <ide> json = objectMapper.writeValueAsString(updatedClass); <del> } catch (final JsonProcessingException e) { <del> <del> e.printStackTrace(); <add> } catch( final JsonProcessingException e ) { <add> LOG.error( e.getMessage(), e ); <ide> } <ide> <ide> ClaszServiceTest.LOG.debug("class json: " + json); <del> <del> // clean up DB <del> claszServiceTestUtils.deleteObject(clasz); <ide> } <ide> <add> <ide> @Test <del> public void testUniquenessOfClasses() { <add> public void testUniquenessOfClasses() throws Exception { <ide> <ide> final Clasz clasz1 = createClass(); <ide> final Clasz clasz2 = createClass(); <ide> Assert.assertNotNull("attribute1 uri shouldn't be empty", clasz1.getName().trim().isEmpty()); <ide> Assert.assertNotNull("attribute2 uri shouldn't be empty", clasz2.getName().trim().isEmpty()); <ide> Assert.assertEquals("the attribute uris should be equal", clasz1.getName(), clasz2.getName()); <del> <del> // clean up DB <del> claszServiceTestUtils.deleteObject(clasz1); <ide> } <ide> <del> private Clasz createClass() { <ide> <del> final Clasz clasz = createObject("http://purl.org/ontology/bibo/Document").getObject(); <del> <del> clasz.setName("document"); <del> <add> private Clasz createClass() throws Exception { <add> final Clasz clasz = claszServiceTestUtils.createClass( "http://purl.org/ontology/bibo/Document", "document" ); <ide> updateObjectTransactional(clasz); <del> <ide> final Clasz updatedClasz = getObject(clasz); <del> <ide> return updatedClasz; <ide> } <ide> }
JavaScript
mit
0b255d8a93710f71357ac9273eca150df0dc632c
0
AlexanderLindsay/dailybudgeteer,AlexanderLindsay/dailybudgeteer,AlexanderLindsay/dailybudgeteer
var gulp = require('gulp'); var ts = require('gulp-typescript'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var ignore = require('gulp-ignore'); var rimraf = require('gulp-rimraf'); var packager = require('electron-packager'); var semanticBuild = require('./semantic/tasks/build'); gulp.task('clean', function () { return gulp.src(['compiled/*', 'test/client', 'test/test'], { read: false }) .pipe(rimraf()); }); gulp.task('client', ['clean'], function () { var compiled = gulp.src('client/**/*.ts') .pipe(ts({ noImplicitAny: true, sortOutput: true, module: "commonjs" })); var mithril = gulp.src('node_modules/mithril/mithril.min.js'); var jquery = gulp.src('node_modules/jquery/dist/jquery.min.js'); var semantic = gulp.src('semantic/dist/semantic.min.js'); var moment = gulp.src('node_modules/moment/min/moment.min.js'); var momentRange = gulp.src('node_modules/moment-range/dist/moment-range.min.js'); var d3 = gulp.src('node_modules/d3/d3.min.js'); return merge(mithril, jquery, semantic, moment, momentRange, d3, compiled) .pipe(gulp.dest('compiled/.')); }); gulp.task('main', ['clean'], function () { return gulp.src('main.ts') .pipe(ts({ noImplicitAny: true, out: 'main.js' })) .pipe(gulp.dest('.')); }); gulp.task('semantic-build', semanticBuild); gulp.task('build', ['main', 'client']); gulp.task('package', function () { packager({ arch: "x64", dir: ".", platform: "win32", name: "PerDay", version: "0.36.9", out: "builds", overwrite: true, ignore: "(\.gitignore)|(gulpfile\.js)|(\.vscode.*)|(typings.*)|(tsconfig.json)|(semantic.json)|(builds.*)|(client.*)|(test.*)|(node_modules.*)|(semantic/src.*)|(semantic/tasks.*)" }, function(err, appPath){}) });
gulpfile.js
var gulp = require('gulp'); var ts = require('gulp-typescript'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var ignore = require('gulp-ignore'); var rimraf = require('gulp-rimraf'); var packager = require('electron-packager'); var semanticBuild = require('./semantic/tasks/build'); gulp.task('clean', function () { return gulp.src(['compiled/*', 'test/client', 'test/test'], { read: false }) .pipe(rimraf()); }); gulp.task('client', ['clean'], function () { var compiled = gulp.src('client/**/*.ts') .pipe(ts({ noImplicitAny: true, sortOutput: true, module: "commonjs" })); var mithril = gulp.src('node_modules/mithril/mithril.min.js'); var jquery = gulp.src('node_modules/jquery/dist/jquery.min.js'); var semantic = gulp.src('semantic/dist/semantic.min.js'); var moment = gulp.src('node_modules/moment/min/moment.min.js'); var momentRange = gulp.src('node_modules/moment-range/dist/moment-range.min.js'); var d3 = gulp.src('node_modules/d3/d3.min.js'); return merge(mithril, jquery, semantic, moment, momentRange, d3, compiled) .pipe(gulp.dest('compiled/.')); }); gulp.task('main', ['clean'], function () { return gulp.src('main.ts') .pipe(ts({ noImplicitAny: true, out: 'main.js' })) .pipe(gulp.dest('.')); }); gulp.task('semantic-build', semanticBuild); gulp.task('build', ['main', 'client']); gulp.task('package', function () { packager({ arch: "x64", dir: ".", platform: "win32", name: "PerTurn", version: "0.36.9", out: "builds", overwrite: true, ignore: "(\.gitignore)|(gulpfile\.js)|(\.vscode.*)|(typings.*)|(tsconfig.json)|(semantic.json)|(builds.*)|(client.*)|(test.*)|(node_modules.*)|(semantic/src.*)|(semantic/tasks.*)" }, function(err, appPath){}) });
changed name of packaged app to PerDay
gulpfile.js
changed name of packaged app to PerDay
<ide><path>ulpfile.js <ide> arch: "x64", <ide> dir: ".", <ide> platform: "win32", <del> name: "PerTurn", <add> name: "PerDay", <ide> version: "0.36.9", <ide> out: "builds", <ide> overwrite: true,
Java
apache-2.0
193b44dca1a484a50d37b9a03633a81400488895
0
ahb0327/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ibinti/intellij-community,kool79/intellij-community,supersven/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,joewalnes/idea-community,kdwink/intellij-community,diorcety/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,da1z/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,diorcety/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,gnuhub/intellij-community,allotria/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,hurricup/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,robovm/robovm-studio,hurricup/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,signed/intellij-community,allotria/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,slisson/intellij-community,samthor/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,clumsy/intellij-community,da1z/intellij-community,adedayo/intellij-community,retomerz/intellij-community,vladmm/intellij-community,supersven/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ibinti/intellij-community,robovm/robovm-studio,FHannes/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,caot/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,slisson/intellij-community,jagguli/intellij-community,kool79/intellij-community,samthor/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,slisson/intellij-community,robovm/robovm-studio,ryano144/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,consulo/consulo,ahb0327/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,supersven/intellij-community,da1z/intellij-community,hurricup/intellij-community,retomerz/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,samthor/intellij-community,gnuhub/intellij-community,holmes/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,signed/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,izonder/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,izonder/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,slisson/intellij-community,izonder/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,retomerz/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,signed/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ernestp/consulo,apixandru/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,Lekanich/intellij-community,supersven/intellij-community,holmes/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,robovm/robovm-studio,apixandru/intellij-community,suncycheng/intellij-community,kool79/intellij-community,diorcety/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,caot/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,caot/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,adedayo/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,allotria/intellij-community,clumsy/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,FHannes/intellij-community,petteyg/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,adedayo/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,slisson/intellij-community,asedunov/intellij-community,joewalnes/idea-community,ibinti/intellij-community,dslomov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,amith01994/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,izonder/intellij-community,semonte/intellij-community,holmes/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,slisson/intellij-community,izonder/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,joewalnes/idea-community,xfournet/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,izonder/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,semonte/intellij-community,da1z/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,supersven/intellij-community,petteyg/intellij-community,retomerz/intellij-community,da1z/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,supersven/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,amith01994/intellij-community,samthor/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,clumsy/intellij-community,vladmm/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,petteyg/intellij-community,caot/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,adedayo/intellij-community,signed/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,consulo/consulo,joewalnes/idea-community,TangHao1987/intellij-community,semonte/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ibinti/intellij-community,allotria/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,fitermay/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,semonte/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,holmes/intellij-community,jagguli/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,supersven/intellij-community,apixandru/intellij-community,blademainer/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,apixandru/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,caot/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,signed/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,izonder/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,izonder/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,holmes/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,kdwink/intellij-community,ibinti/intellij-community,caot/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,allotria/intellij-community,fnouama/intellij-community,robovm/robovm-studio,diorcety/intellij-community,retomerz/intellij-community,clumsy/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,ernestp/consulo,adedayo/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,hurricup/intellij-community,da1z/intellij-community,semonte/intellij-community,blademainer/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,diorcety/intellij-community,samthor/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ryano144/intellij-community,da1z/intellij-community,Lekanich/intellij-community,signed/intellij-community,kool79/intellij-community,holmes/intellij-community,da1z/intellij-community,gnuhub/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,allotria/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ibinti/intellij-community,allotria/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,caot/intellij-community,ibinti/intellij-community,caot/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,consulo/consulo,petteyg/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,signed/intellij-community,fnouama/intellij-community,xfournet/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,signed/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,slisson/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,kool79/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,consulo/consulo,kdwink/intellij-community,alphafoobar/intellij-community,ernestp/consulo,diorcety/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,lucafavatella/intellij-community,consulo/consulo,ernestp/consulo,ernestp/consulo,fitermay/intellij-community,hurricup/intellij-community,slisson/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,caot/intellij-community,allotria/intellij-community,kdwink/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,gnuhub/intellij-community
<caret>// "Make 'a' extend 'b'" "true" class a extends b { void f(b b, Runnable r) { f(this, null); } } class b { }
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/after2.java
// "Make 'a' extend 'b'" "true" <caret>class a extends b { void f(b b, Runnable r) { f(this, null); } } class b { }
Empty import list placement and comment binding (test data fixed)
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/after2.java
Empty import list placement and comment binding (test data fixed)
<ide><path>ava/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/after2.java <del>// "Make 'a' extend 'b'" "true" <del><caret>class a extends b { <add><caret>// "Make 'a' extend 'b'" "true" <add>class a extends b { <ide> void f(b b, Runnable r) { <ide> f(this, null); <ide> }
Java
apache-2.0
baa6d3c7c23b33f2344f64f4aa332918061ca90c
0
cuba-platform/cuba,cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,dimone-kun/cuba
/* * Copyright (c) 2008-2015 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/license for details. */ package com.haulmont.cuba.core.sys; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.chile.core.model.MetaPropertyPath; import com.haulmont.chile.core.model.Range; import com.haulmont.cuba.core.entity.*; import com.haulmont.cuba.core.global.*; import org.apache.commons.lang.StringUtils; import org.eclipse.persistence.config.QueryHints; import org.eclipse.persistence.jpa.JpaQuery; import org.eclipse.persistence.queries.FetchGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; /** * @author krivopustov * @version $Id$ */ @Component("cuba_FetchGroupManager") public class FetchGroupManager { private Logger log = LoggerFactory.getLogger(FetchGroupManager.class); @Inject private Metadata metadata; @Inject private MetadataTools metadataTools; @Inject private ViewRepository viewRepository; public void setView(JpaQuery query, String queryString, @Nullable View view, boolean singleResultExpected) { Preconditions.checkNotNullArgument(query, "query is null"); if (view != null) { FetchGroup fg = new FetchGroup(); applyView(query, queryString, fg, view, singleResultExpected); } else { query.setHint(QueryHints.FETCH_GROUP, null); } } public void addView(JpaQuery query, String queryString, View view, boolean singleResultExpected) { Preconditions.checkNotNullArgument(query, "query is null"); Preconditions.checkNotNullArgument(view, "view is null"); Map<String, Object> hints = query.getHints(); FetchGroup fg = null; if (hints != null) fg = (FetchGroup) hints.get(QueryHints.FETCH_GROUP); if (fg == null) fg = new FetchGroup(); applyView(query, queryString, fg, view, singleResultExpected); } private void applyView(JpaQuery query, String queryString, FetchGroup fetchGroup, View view, boolean singleResultExpected) { Set<FetchGroupField> fetchGroupFields = new LinkedHashSet<>(); processView(view, null, fetchGroupFields); Set<String> fetchGroupAttributes = new TreeSet<>(); Map<String, String> fetchHints = new TreeMap<>(); // sort hints by attribute path for (FetchGroupField field : fetchGroupFields) { fetchGroupAttributes.add(field.path()); } fetchGroup.setShouldLoadAll(true); List<FetchGroupField> refFields = new ArrayList<>(); for (FetchGroupField field : fetchGroupFields) { if (field.metaProperty.getRange().isClass() && !metadataTools.isEmbedded(field.metaProperty)) refFields.add(field); } if (!refFields.isEmpty()) { MetaClass metaClass = metadata.getClassNN(view.getEntityClass()); String alias = QueryTransformerFactory.createParser(queryString).getEntityAlias(); List<FetchGroupField> batchFields = new ArrayList<>(); List<FetchGroupField> joinFields = new ArrayList<>(); for (FetchGroupField refField : refFields) { if (refField.fetchMode == FetchMode.UNDEFINED) { if (refField.metaProperty.getRange().getCardinality().isMany()) { List<String> masterAttributes = getMasterEntityAttributes(fetchGroup, fetchGroupFields, refField); fetchGroupAttributes.addAll(masterAttributes); } continue; } boolean selfRef = false; for (MetaProperty mp : refField.metaPropertyPath.getMetaProperties()) { if (metadataTools.isAssignableFrom(mp.getRange().asClass(), metaClass)) { batchFields.add(refField); selfRef = true; break; } } if (!selfRef) { if (refField.metaProperty.getRange().getCardinality().isMany()) { List<String> masterAttributes = getMasterEntityAttributes(fetchGroup, fetchGroupFields, refField); fetchGroupAttributes.addAll(masterAttributes); if (refField.fetchMode == FetchMode.JOIN) { joinFields.add(refField); } else { batchFields.add(refField); } } else { if (refField.fetchMode == FetchMode.BATCH) { batchFields.add(refField); } else { joinFields.add(refField); } } } } for (FetchGroupField joinField : new ArrayList<>(joinFields)) { if (joinField.fetchMode == FetchMode.AUTO) { Optional<FetchMode> parentMode = refFields.stream() .filter(f -> joinField.metaPropertyPath.startsWith(f.metaPropertyPath) && joinField.fetchMode != FetchMode.AUTO) .sorted((f1, f2) -> f1.metaPropertyPath.getPath().length - f2.metaPropertyPath.getPath().length) .findFirst() .map(f -> f.fetchMode); if (parentMode.isPresent()) { if (parentMode.get() == FetchMode.UNDEFINED) { joinFields.remove(joinField); } else if (parentMode.get() == FetchMode.BATCH) { joinFields.remove(joinField); batchFields.add(joinField); } } else { for (FetchGroupField batchField : new ArrayList<>(batchFields)) { if (joinField.metaPropertyPath.startsWith(batchField.metaPropertyPath)) { joinFields.remove(joinField); batchFields.add(joinField); } } } } } long toManyCount = refFields.stream() .filter(f -> f.metaProperty.getRange().getCardinality().isMany()).count(); // For query by ID, remove BATCH mode for to-many attributes that have no nested attributes if (singleResultExpected && toManyCount <= 1) { for (FetchGroupField batchField : new ArrayList<>(batchFields)) { if (batchField.metaProperty.getRange().getCardinality().isMany()) { boolean hasNested = refFields.stream() .anyMatch(f -> f != batchField && f.metaPropertyPath.startsWith(batchField.metaPropertyPath)); if (!hasNested && batchField.fetchMode != FetchMode.BATCH) { batchFields.remove(batchField); } } } } for (FetchGroupField joinField : joinFields) { String attr = alias + "." + joinField.path(); fetchHints.put(attr, QueryHints.LEFT_FETCH); } for (FetchGroupField batchField : batchFields) { if (batchField.fetchMode == FetchMode.BATCH || !singleResultExpected || batchFields.size() > 1) { String attr = alias + "." + batchField.path(); fetchHints.put(attr, QueryHints.BATCH); } } } if (log.isTraceEnabled()) log.trace("Fetch group for " + view + ":\n" + fetchGroupAttributes.stream().collect(Collectors.joining("\n"))); for (String attribute : fetchGroupAttributes) { fetchGroup.addAttribute(attribute); } query.setHint(QueryHints.FETCH_GROUP, fetchGroup); if (log.isDebugEnabled()) log.debug("Fetch modes for " + view + ": " + fetchHints.entrySet().stream() .map(e -> e.getKey() + "=" + (e.getValue().equals(QueryHints.LEFT_FETCH) ? "JOIN" : "BATCH")) .collect(Collectors.joining(", "))); for (Map.Entry<String, String> entry : fetchHints.entrySet()) { query.setHint(entry.getValue(), entry.getKey()); } query.setHint(QueryHints.BATCH_TYPE, "IN"); } private List<String> getMasterEntityAttributes(FetchGroup fetchGroup, Set<FetchGroupField> fetchGroupFields, FetchGroupField toManyField) { List<String> result = new ArrayList<>(); MetaClass propMetaClass = toManyField.metaProperty.getRange().asClass(); propMetaClass.getProperties().stream() .filter(mp -> mp.getRange().isClass() && metadataTools.isPersistent(mp) && metadataTools.isAssignableFrom(mp.getRange().asClass(), toManyField.metaClass)) .findFirst() .ifPresent(inverseProp -> { for (FetchGroupField fetchGroupField : fetchGroupFields) { if (fetchGroupField.metaClass.equals(toManyField.metaClass) // add only local properties && !fetchGroupField.metaProperty.getRange().isClass() // do not add properties from subclasses && fetchGroupField.metaProperty.getDomain().equals(inverseProp.getRange().asClass())) { String attribute = toManyField.path() + "." + inverseProp.getName() + "." + fetchGroupField.metaProperty.getName(); result.add(attribute); } } if (result.isEmpty()) { result.add(toManyField.path() + "." + inverseProp.getName() + ".id"); } }); return result; } private void processView(View view, FetchGroupField parentField, Set<FetchGroupField> fetchGroupFields) { if (view.isIncludeSystemProperties()) { includeSystemProperties(view, parentField, fetchGroupFields); } Class<? extends Entity> entityClass = view.getEntityClass(); // Always add SoftDelete properties to support EntityManager contract if (SoftDelete.class.isAssignableFrom(entityClass)) { for (String property : getInterfaceProperties(SoftDelete.class)) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, property)); } } // Always add uuid property if the entity has primary key not of type UUID if (!BaseUuidEntity.class.isAssignableFrom(entityClass) && !EmbeddableEntity.class.isAssignableFrom(entityClass)) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, "uuid")); } for (ViewProperty property : view.getProperties()) { String propertyName = property.getName(); MetaClass metaClass = metadata.getClassNN(entityClass); MetaProperty metaProperty = metaClass.getPropertyNN(propertyName); if (parentField != null && metaProperty.getRange().isClass() && metaProperty.getRange().asClass().equals(parentField.metaProperty.getDomain())) { // do not add immediate back references if (metaProperty.getRange().getCardinality().equals(Range.Cardinality.ONE_TO_ONE)) { // For ONE_TO_ONE, add the back reference. This leads to additional useless SELECTs but // saves from "Cannot get unfetched attribute" exception. FetchGroupField field = createFetchGroupField(entityClass, parentField, propertyName, property.getFetchMode()); fetchGroupFields.add(field); //noinspection unchecked Class<Entity> javaClass = metaProperty.getRange().asClass().getJavaClass(); fetchGroupFields.add(createFetchGroupField(javaClass, field, "id")); } continue; } if (metadataTools.isPersistent(metaProperty)) { FetchGroupField field = createFetchGroupField(entityClass, parentField, propertyName, property.getFetchMode()); fetchGroupFields.add(field); if (property.getView() != null) { processView(property.getView(), field, fetchGroupFields); } } List<String> relatedProperties = metadataTools.getRelatedProperties(entityClass, propertyName); for (String relatedProperty : relatedProperties) { if (!view.containsProperty(relatedProperty)) { FetchGroupField field = createFetchGroupField(entityClass, parentField, relatedProperty); fetchGroupFields.add(field); MetaProperty relatedMetaProp = metaClass.getPropertyNN(relatedProperty); if (relatedMetaProp.getRange().isClass()) { View relatedView = viewRepository.getView(relatedMetaProp.getRange().asClass(), View.MINIMAL); processView(relatedView, field, fetchGroupFields); } } } } } private void includeSystemProperties(View view, FetchGroupField parentField, Set<FetchGroupField> fetchGroupFields) { Class<? extends Entity> entityClass = view.getEntityClass(); MetaClass metaClass = metadata.getClassNN(entityClass); if (BaseEntity.class.isAssignableFrom(entityClass)) { for (String property : getInterfaceProperties(BaseEntity.class)) { if (metadataTools.isPersistent(metaClass.getPropertyNN(property))) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, property)); } } } if (Updatable.class.isAssignableFrom(entityClass)) { for (String property : getInterfaceProperties(Updatable.class)) { if (metadataTools.isPersistent(metaClass.getPropertyNN(property))) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, property)); } } } } private List<String> getInterfaceProperties(Class<?> intf) { List<String> result = new ArrayList<>(); for (Method method : intf.getDeclaredMethods()) { if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) { result.add(StringUtils.uncapitalize(method.getName().substring(3))); } } return result; } private FetchGroupField createFetchGroupField(Class<? extends Entity> entityClass, FetchGroupField parentField, String property) { return createFetchGroupField(entityClass, parentField, property, FetchMode.AUTO); } private FetchGroupField createFetchGroupField(Class<? extends Entity> entityClass, FetchGroupField parentField, String property, FetchMode fetchMode) { return new FetchGroupField(getRealClass(entityClass, property), parentField, property, fetchMode); } private MetaClass getRealClass(Class<? extends Entity> entityClass, String property) { // todo ? return metadata.getClassNN(entityClass); } protected static class FetchGroupField { private final MetaClass metaClass; private FetchMode fetchMode; private final MetaProperty metaProperty; private final MetaPropertyPath metaPropertyPath; public FetchGroupField(MetaClass metaClass, FetchGroupField parentField, String property, FetchMode fetchMode) { this.metaClass = metaClass; this.fetchMode = fetchMode; this.metaProperty = metaClass.getPropertyNN(property); this.metaPropertyPath = parentField == null ? new MetaPropertyPath(metaClass, metaProperty) : new MetaPropertyPath(parentField.metaPropertyPath, metaProperty); } public String path() { return metaPropertyPath.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FetchGroupField that = (FetchGroupField) o; if (!metaClass.equals(that.metaClass)) return false; if (!metaPropertyPath.equals(that.metaPropertyPath)) return false; return true; } @Override public int hashCode() { int result = metaClass.hashCode(); result = 31 * result + metaPropertyPath.hashCode(); return result; } @Override public String toString() { return path(); } } }
modules/core/src/com/haulmont/cuba/core/sys/FetchGroupManager.java
/* * Copyright (c) 2008-2015 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/license for details. */ package com.haulmont.cuba.core.sys; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.chile.core.model.MetaPropertyPath; import com.haulmont.cuba.core.entity.*; import com.haulmont.cuba.core.global.*; import org.apache.commons.lang.StringUtils; import org.eclipse.persistence.config.QueryHints; import org.eclipse.persistence.jpa.JpaQuery; import org.eclipse.persistence.queries.FetchGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; /** * @author krivopustov * @version $Id$ */ @Component("cuba_FetchGroupManager") public class FetchGroupManager { private Logger log = LoggerFactory.getLogger(FetchGroupManager.class); @Inject private Metadata metadata; @Inject private MetadataTools metadataTools; @Inject private ViewRepository viewRepository; public void setView(JpaQuery query, String queryString, @Nullable View view, boolean singleResultExpected) { Preconditions.checkNotNullArgument(query, "query is null"); if (view != null) { FetchGroup fg = new FetchGroup(); applyView(query, queryString, fg, view, singleResultExpected); } else { query.setHint(QueryHints.FETCH_GROUP, null); } } public void addView(JpaQuery query, String queryString, View view, boolean singleResultExpected) { Preconditions.checkNotNullArgument(query, "query is null"); Preconditions.checkNotNullArgument(view, "view is null"); Map<String, Object> hints = query.getHints(); FetchGroup fg = null; if (hints != null) fg = (FetchGroup) hints.get(QueryHints.FETCH_GROUP); if (fg == null) fg = new FetchGroup(); applyView(query, queryString, fg, view, singleResultExpected); } private void applyView(JpaQuery query, String queryString, FetchGroup fetchGroup, View view, boolean singleResultExpected) { Set<FetchGroupField> fetchGroupFields = new LinkedHashSet<>(); processView(view, null, fetchGroupFields); Set<String> fetchGroupAttributes = new TreeSet<>(); Map<String, String> fetchHints = new TreeMap<>(); // sort hints by attribute path for (FetchGroupField field : fetchGroupFields) { fetchGroupAttributes.add(field.path()); } fetchGroup.setShouldLoadAll(true); List<FetchGroupField> refFields = new ArrayList<>(); for (FetchGroupField field : fetchGroupFields) { if (field.metaProperty.getRange().isClass() && !metadataTools.isEmbedded(field.metaProperty)) refFields.add(field); } if (!refFields.isEmpty()) { MetaClass metaClass = metadata.getClassNN(view.getEntityClass()); String alias = QueryTransformerFactory.createParser(queryString).getEntityAlias(); List<FetchGroupField> batchFields = new ArrayList<>(); List<FetchGroupField> joinFields = new ArrayList<>(); for (FetchGroupField refField : refFields) { if (refField.fetchMode == FetchMode.UNDEFINED) { if (refField.metaProperty.getRange().getCardinality().isMany()) { List<String> masterAttributes = getMasterEntityAttributes(fetchGroup, fetchGroupFields, refField); fetchGroupAttributes.addAll(masterAttributes); } continue; } boolean selfRef = false; for (MetaProperty mp : refField.metaPropertyPath.getMetaProperties()) { if (metadataTools.isAssignableFrom(mp.getRange().asClass(), metaClass)) { batchFields.add(refField); selfRef = true; break; } } if (!selfRef) { if (refField.metaProperty.getRange().getCardinality().isMany()) { List<String> masterAttributes = getMasterEntityAttributes(fetchGroup, fetchGroupFields, refField); fetchGroupAttributes.addAll(masterAttributes); if (refField.fetchMode == FetchMode.JOIN) { joinFields.add(refField); } else { batchFields.add(refField); } } else { if (refField.fetchMode == FetchMode.BATCH) { batchFields.add(refField); } else { joinFields.add(refField); } } } } for (FetchGroupField joinField : new ArrayList<>(joinFields)) { if (joinField.fetchMode == FetchMode.AUTO) { Optional<FetchMode> parentMode = refFields.stream() .filter(f -> joinField.metaPropertyPath.startsWith(f.metaPropertyPath) && joinField.fetchMode != FetchMode.AUTO) .sorted((f1, f2) -> f1.metaPropertyPath.getPath().length - f2.metaPropertyPath.getPath().length) .findFirst() .map(f -> f.fetchMode); if (parentMode.isPresent()) { if (parentMode.get() == FetchMode.UNDEFINED) { joinFields.remove(joinField); } else if (parentMode.get() == FetchMode.BATCH) { joinFields.remove(joinField); batchFields.add(joinField); } } else { for (FetchGroupField batchField : new ArrayList<>(batchFields)) { if (joinField.metaPropertyPath.startsWith(batchField.metaPropertyPath)) { joinFields.remove(joinField); batchFields.add(joinField); } } } } } long toManyCount = refFields.stream() .filter(f -> f.metaProperty.getRange().getCardinality().isMany()).count(); // For query by ID, remove BATCH mode for to-many attributes that have no nested attributes if (singleResultExpected && toManyCount <= 1) { for (FetchGroupField batchField : new ArrayList<>(batchFields)) { if (batchField.metaProperty.getRange().getCardinality().isMany()) { boolean hasNested = refFields.stream() .anyMatch(f -> f != batchField && f.metaPropertyPath.startsWith(batchField.metaPropertyPath)); if (!hasNested && batchField.fetchMode != FetchMode.BATCH) { batchFields.remove(batchField); } } } } for (FetchGroupField joinField : joinFields) { String attr = alias + "." + joinField.path(); fetchHints.put(attr, QueryHints.LEFT_FETCH); } for (FetchGroupField batchField : batchFields) { if (batchField.fetchMode == FetchMode.BATCH || !singleResultExpected || batchFields.size() > 1) { String attr = alias + "." + batchField.path(); fetchHints.put(attr, QueryHints.BATCH); } } } if (log.isTraceEnabled()) log.trace("Fetch group for " + view + ":\n" + fetchGroupAttributes.stream().collect(Collectors.joining("\n"))); for (String attribute : fetchGroupAttributes) { fetchGroup.addAttribute(attribute); } query.setHint(QueryHints.FETCH_GROUP, fetchGroup); if (log.isDebugEnabled()) log.debug("Fetch modes for " + view + ": " + fetchHints.entrySet().stream() .map(e -> e.getKey() + "=" + (e.getValue().equals(QueryHints.LEFT_FETCH) ? "JOIN" : "BATCH")) .collect(Collectors.joining(", "))); for (Map.Entry<String, String> entry : fetchHints.entrySet()) { query.setHint(entry.getValue(), entry.getKey()); } query.setHint(QueryHints.BATCH_TYPE, "IN"); } private List<String> getMasterEntityAttributes(FetchGroup fetchGroup, Set<FetchGroupField> fetchGroupFields, FetchGroupField toManyField) { List<String> result = new ArrayList<>(); MetaClass propMetaClass = toManyField.metaProperty.getRange().asClass(); propMetaClass.getProperties().stream() .filter(mp -> mp.getRange().isClass() && metadataTools.isPersistent(mp) && metadataTools.isAssignableFrom(mp.getRange().asClass(), toManyField.metaClass)) .findFirst() .ifPresent(inverseProp -> { for (FetchGroupField fetchGroupField : fetchGroupFields) { if (fetchGroupField.metaClass.equals(toManyField.metaClass) // add only local properties && !fetchGroupField.metaProperty.getRange().isClass() // do not add properties from subclasses && fetchGroupField.metaProperty.getDomain().equals(inverseProp.getRange().asClass())) { String attribute = toManyField.path() + "." + inverseProp.getName() + "." + fetchGroupField.metaProperty.getName(); result.add(attribute); } } if (result.isEmpty()) { result.add(toManyField.path() + "." + inverseProp.getName() + ".id"); } }); return result; } private void processView(View view, FetchGroupField parentField, Set<FetchGroupField> fetchGroupFields) { if (view.isIncludeSystemProperties()) { includeSystemProperties(view, parentField, fetchGroupFields); } Class<? extends Entity> entityClass = view.getEntityClass(); // Always add SoftDelete properties to support EntityManager contract if (SoftDelete.class.isAssignableFrom(entityClass)) { for (String property : getInterfaceProperties(SoftDelete.class)) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, property)); } } // Always add uuid property if the entity has primary key not of type UUID if (!BaseUuidEntity.class.isAssignableFrom(entityClass) && !EmbeddableEntity.class.isAssignableFrom(entityClass)) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, "uuid")); } for (ViewProperty property : view.getProperties()) { String propertyName = property.getName(); MetaClass metaClass = metadata.getClassNN(entityClass); MetaProperty metaProperty = metaClass.getPropertyNN(propertyName); if (parentField != null && metaProperty.getRange().isClass() && metaProperty.getRange().asClass().equals(parentField.metaProperty.getDomain())) { // do not add immediate back references continue; } if (metadataTools.isPersistent(metaProperty)) { FetchGroupField field = createFetchGroupField(entityClass, parentField, propertyName, property.getFetchMode()); fetchGroupFields.add(field); if (property.getView() != null) { processView(property.getView(), field, fetchGroupFields); } } List<String> relatedProperties = metadataTools.getRelatedProperties(entityClass, propertyName); for (String relatedProperty : relatedProperties) { if (!view.containsProperty(relatedProperty)) { FetchGroupField field = createFetchGroupField(entityClass, parentField, relatedProperty); fetchGroupFields.add(field); MetaProperty relatedMetaProp = metaClass.getPropertyNN(relatedProperty); if (relatedMetaProp.getRange().isClass()) { View relatedView = viewRepository.getView(relatedMetaProp.getRange().asClass(), View.MINIMAL); processView(relatedView, field, fetchGroupFields); } } } } } private void includeSystemProperties(View view, FetchGroupField parentField, Set<FetchGroupField> fetchGroupFields) { Class<? extends Entity> entityClass = view.getEntityClass(); MetaClass metaClass = metadata.getClassNN(entityClass); if (BaseEntity.class.isAssignableFrom(entityClass)) { for (String property : getInterfaceProperties(BaseEntity.class)) { if (metadataTools.isPersistent(metaClass.getPropertyNN(property))) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, property)); } } } if (Updatable.class.isAssignableFrom(entityClass)) { for (String property : getInterfaceProperties(Updatable.class)) { if (metadataTools.isPersistent(metaClass.getPropertyNN(property))) { fetchGroupFields.add(createFetchGroupField(entityClass, parentField, property)); } } } } private List<String> getInterfaceProperties(Class<?> intf) { List<String> result = new ArrayList<>(); for (Method method : intf.getDeclaredMethods()) { if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) { result.add(StringUtils.uncapitalize(method.getName().substring(3))); } } return result; } private FetchGroupField createFetchGroupField(Class<? extends Entity> entityClass, FetchGroupField parentField, String property) { return createFetchGroupField(entityClass, parentField, property, FetchMode.AUTO); } private FetchGroupField createFetchGroupField(Class<? extends Entity> entityClass, FetchGroupField parentField, String property, FetchMode fetchMode) { return new FetchGroupField(getRealClass(entityClass, property), parentField, property, fetchMode); } private MetaClass getRealClass(Class<? extends Entity> entityClass, String property) { // todo ? return metadata.getClassNN(entityClass); } protected static class FetchGroupField { private final MetaClass metaClass; private FetchMode fetchMode; private final MetaProperty metaProperty; private final MetaPropertyPath metaPropertyPath; public FetchGroupField(MetaClass metaClass, FetchGroupField parentField, String property, FetchMode fetchMode) { this.metaClass = metaClass; this.fetchMode = fetchMode; this.metaProperty = metaClass.getPropertyNN(property); this.metaPropertyPath = parentField == null ? new MetaPropertyPath(metaClass, metaProperty) : new MetaPropertyPath(parentField.metaPropertyPath, metaProperty); } public String path() { return metaPropertyPath.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FetchGroupField that = (FetchGroupField) o; if (!metaClass.equals(that.metaClass)) return false; if (!metaPropertyPath.equals(that.metaPropertyPath)) return false; return true; } @Override public int hashCode() { int result = metaClass.hashCode(); result = 31 * result + metaPropertyPath.hashCode(); return result; } @Override public String toString() { return path(); } } }
"Cannot get unfetched attribute" when loading an object graph with one-to-many and one-to-one links. #PL-6405
modules/core/src/com/haulmont/cuba/core/sys/FetchGroupManager.java
"Cannot get unfetched attribute" when loading an object graph with one-to-many and one-to-one links. #PL-6405
<ide><path>odules/core/src/com/haulmont/cuba/core/sys/FetchGroupManager.java <ide> import com.haulmont.chile.core.model.MetaClass; <ide> import com.haulmont.chile.core.model.MetaProperty; <ide> import com.haulmont.chile.core.model.MetaPropertyPath; <add>import com.haulmont.chile.core.model.Range; <ide> import com.haulmont.cuba.core.entity.*; <ide> import com.haulmont.cuba.core.global.*; <ide> import org.apache.commons.lang.StringUtils; <ide> && metaProperty.getRange().isClass() <ide> && metaProperty.getRange().asClass().equals(parentField.metaProperty.getDomain())) { <ide> // do not add immediate back references <add> if (metaProperty.getRange().getCardinality().equals(Range.Cardinality.ONE_TO_ONE)) { <add> // For ONE_TO_ONE, add the back reference. This leads to additional useless SELECTs but <add> // saves from "Cannot get unfetched attribute" exception. <add> FetchGroupField field = createFetchGroupField(entityClass, parentField, propertyName, property.getFetchMode()); <add> fetchGroupFields.add(field); <add> //noinspection unchecked <add> Class<Entity> javaClass = metaProperty.getRange().asClass().getJavaClass(); <add> fetchGroupFields.add(createFetchGroupField(javaClass, field, "id")); <add> } <ide> continue; <ide> } <ide>
Java
apache-2.0
b718d4183bf2ff31de285e0b0f3f0b5c23099ccd
0
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
/** * * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.console.databasemanager.wizard; import java.io.IOException; import java.io.Serializable; import java.io.PrintWriter; import java.io.StringWriter; import java.io.File; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.StringReader; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import java.net.URISyntaxException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.MalformedURLException; import java.sql.Driver; import java.sql.SQLException; import java.sql.Connection; import java.sql.DatabaseMetaData; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; import javax.management.ObjectName; import javax.management.MalformedObjectNameException; import javax.enterprise.deploy.spi.DeploymentManager; import javax.enterprise.deploy.spi.DeploymentConfiguration; import javax.enterprise.deploy.spi.Target; import javax.enterprise.deploy.spi.TargetModuleID; import javax.enterprise.deploy.spi.status.ProgressObject; import javax.enterprise.deploy.model.DDBeanRoot; import javax.enterprise.deploy.model.DDBean; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.apache.geronimo.console.BasePortlet; import org.apache.geronimo.console.util.PortletManager; import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory; import org.apache.geronimo.management.geronimo.ResourceAdapterModule; import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; import org.apache.geronimo.kernel.repository.ListableRepository; import org.apache.geronimo.kernel.repository.Repository; import org.apache.geronimo.kernel.repository.WriteableRepository; import org.apache.geronimo.kernel.repository.FileWriteMonitor; import org.apache.geronimo.kernel.management.State; import org.apache.geronimo.kernel.proxy.GeronimoManagedBean; import org.apache.geronimo.deployment.tools.loader.ConnectorDeployable; import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot; import org.apache.geronimo.connector.deployment.jsr88.ConnectorDCB; import org.apache.geronimo.connector.deployment.jsr88.Dependency; import org.apache.geronimo.connector.deployment.jsr88.ResourceAdapter; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinition; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinitionInstance; import org.apache.geronimo.connector.deployment.jsr88.ConfigPropertySetting; import org.apache.geronimo.connector.deployment.jsr88.ConnectionManager; import org.apache.geronimo.connector.deployment.jsr88.SinglePool; import org.apache.geronimo.connector.outbound.PoolingAttributes; import org.apache.geronimo.converter.DatabaseConversionStatus; import org.apache.geronimo.converter.JDBCPool; import org.apache.geronimo.converter.bea.WebLogic81DatabaseConverter; import org.apache.geronimo.converter.jboss.JBoss4DatabaseConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.fileupload.portlet.PortletFileUpload; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.FileItem; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; /** * A portlet that lets you configure and deploy JDBC connection pools. * * @version $Rev$ $Date$ */ public class DatabasePoolPortlet extends BasePortlet { private final static Log log = LogFactory.getLog(DatabasePoolPortlet.class); private final static String[] SKIP_ENTRIES_WITH = new String[]{"geronimo", "tomcat", "tranql", "commons", "directory", "activemq"}; private final static String DRIVER_SESSION_KEY = "org.apache.geronimo.console.dbpool.Drivers"; private final static String CONFIG_SESSION_KEY = "org.apache.geronimo.console.dbpool.ConfigParam"; private final static String DRIVER_INFO_URL = "http://people.apache.org/~ammulder/driver-downloads.properties"; private static final String LIST_VIEW = "/WEB-INF/view/dbwizard/list.jsp"; private static final String EDIT_VIEW = "/WEB-INF/view/dbwizard/edit.jsp"; private static final String SELECT_RDBMS_VIEW = "/WEB-INF/view/dbwizard/selectDatabase.jsp"; private static final String BASIC_PARAMS_VIEW = "/WEB-INF/view/dbwizard/basicParams.jsp"; private static final String CONFIRM_URL_VIEW = "/WEB-INF/view/dbwizard/confirmURL.jsp"; private static final String TEST_CONNECTION_VIEW = "/WEB-INF/view/dbwizard/testConnection.jsp"; private static final String DOWNLOAD_VIEW = "/WEB-INF/view/dbwizard/selectDownload.jsp"; private static final String SHOW_PLAN_VIEW = "/WEB-INF/view/dbwizard/showPlan.jsp"; private static final String IMPORT_UPLOAD_VIEW = "/WEB-INF/view/dbwizard/importUpload.jsp"; private static final String IMPORT_STATUS_VIEW = "/WEB-INF/view/dbwizard/importStatus.jsp"; private static final String USAGE_VIEW = "/WEB-INF/view/dbwizard/usage.jsp"; private static final String LIST_MODE = "list"; private static final String EDIT_MODE = "edit"; private static final String SELECT_RDBMS_MODE = "rdbms"; private static final String BASIC_PARAMS_MODE = "params"; private static final String CONFIRM_URL_MODE = "url"; private static final String TEST_CONNECTION_MODE = "test"; private static final String SHOW_PLAN_MODE = "plan"; private static final String DOWNLOAD_MODE = "download"; private static final String EDIT_EXISTING_MODE = "editExisting"; private static final String SAVE_MODE = "save"; private static final String IMPORT_START_MODE = "startImport"; private static final String IMPORT_UPLOAD_MODE = "importUpload"; private static final String IMPORT_STATUS_MODE = "importStatus"; private static final String IMPORT_COMPLETE_MODE = "importComplete"; private static final String WEBLOGIC_IMPORT_MODE = "weblogicImport"; private static final String USAGE_MODE = "usage"; private static final String IMPORT_EDIT_MODE = "importEdit"; private static final String MODE_KEY = "mode"; private PortletRequestDispatcher listView; private PortletRequestDispatcher editView; private PortletRequestDispatcher selectRDBMSView; private PortletRequestDispatcher basicParamsView; private PortletRequestDispatcher confirmURLView; private PortletRequestDispatcher testConnectionView; private PortletRequestDispatcher downloadView; private PortletRequestDispatcher planView; private PortletRequestDispatcher importUploadView; private PortletRequestDispatcher importStatusView; private PortletRequestDispatcher usageView; public void init(PortletConfig portletConfig) throws PortletException { super.init(portletConfig); listView = portletConfig.getPortletContext().getRequestDispatcher(LIST_VIEW); editView = portletConfig.getPortletContext().getRequestDispatcher(EDIT_VIEW); selectRDBMSView = portletConfig.getPortletContext().getRequestDispatcher(SELECT_RDBMS_VIEW); basicParamsView = portletConfig.getPortletContext().getRequestDispatcher(BASIC_PARAMS_VIEW); confirmURLView = portletConfig.getPortletContext().getRequestDispatcher(CONFIRM_URL_VIEW); testConnectionView = portletConfig.getPortletContext().getRequestDispatcher(TEST_CONNECTION_VIEW); downloadView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_VIEW); planView = portletConfig.getPortletContext().getRequestDispatcher(SHOW_PLAN_VIEW); importUploadView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_UPLOAD_VIEW); importStatusView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_STATUS_VIEW); usageView = portletConfig.getPortletContext().getRequestDispatcher(USAGE_VIEW); } public void destroy() { listView = null; editView = null; selectRDBMSView = null; basicParamsView = null; confirmURLView = null; testConnectionView = null; downloadView = null; planView = null; importUploadView = null; importStatusView = null; usageView = null; super.destroy(); } public DriverDownloader.DriverInfo[] getDriverInfo(PortletRequest request) { PortletSession session = request.getPortletSession(true); DriverDownloader.DriverInfo[] results = (DriverDownloader.DriverInfo[]) session.getAttribute(DRIVER_SESSION_KEY, PortletSession.APPLICATION_SCOPE); if(results == null) { DriverDownloader downloader = new DriverDownloader(); try { results = downloader.loadDriverInfo(new URL(DRIVER_INFO_URL)); session.setAttribute(DRIVER_SESSION_KEY, results, PortletSession.APPLICATION_SCOPE); } catch (MalformedURLException e) { log.error("Unable to download driver data", e); results = new DriverDownloader.DriverInfo[0]; } } return results; } /** * Loads data about a resource adapter. Depending on what we already have, may load * the name and description, but always loads the config property descriptions. * @param request Pass it or die * @param rarPath If we're creating a new RA, the path to identify it * @param displayName If we're editing an existing RA, its name * @param adapterObjectName If we're editing an existing RA, its ObjectName */ public ResourceAdapterParams getRARConfiguration(PortletRequest request, String rarPath, String displayName, String adapterObjectName) { PortletSession session = request.getPortletSession(true); if(rarPath != null && !rarPath.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(CONFIG_SESSION_KEY+"-"+rarPath, PortletSession.APPLICATION_SCOPE); if(results == null) { results = loadConfigPropertiesByPath(request, rarPath); session.setAttribute(CONFIG_SESSION_KEY+"-"+rarPath, results, PortletSession.APPLICATION_SCOPE); session.setAttribute(CONFIG_SESSION_KEY+"-"+results.displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else if(displayName != null && !displayName.equals("") && adapterObjectName != null && !adapterObjectName.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(CONFIG_SESSION_KEY+"-"+displayName, PortletSession.APPLICATION_SCOPE); if(results == null) { results = loadConfigPropertiesByObjectName(request, adapterObjectName); session.setAttribute(CONFIG_SESSION_KEY+"-"+displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else { throw new IllegalArgumentException(); } } public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter(MODE_KEY); if(mode.equals(IMPORT_UPLOAD_MODE)) { processImportUpload(actionRequest, actionResponse); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); return; } PoolData data = new PoolData(); data.load(actionRequest); if(mode.equals("process-"+SELECT_RDBMS_MODE)) { DatabaseInfo info = null; info = getDatabaseInfo(data); if(info != null) { data.rarPath = info.getRarPath(); if(info.isXA()) { data.adapterDisplayName="Unknown"; // will pick these up when we process the RA type in the render request data.adapterDescription="Unknown"; actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { if(data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { data.driverClass = info.getDriverClass(); data.urlPrototype = info.getUrl(); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } } else { actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE); } } else if(mode.equals("process-"+DOWNLOAD_MODE)) { String name = actionRequest.getParameter("driverName"); DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest); DriverDownloader.DriverInfo found = null; for (int i = 0; i < drivers.length; i++) { DriverDownloader.DriverInfo driver = drivers[i]; if(driver.getName().equals(name)) { found = driver; break; } } if(found != null) { DriverDownloader downloader = new DriverDownloader(); WriteableRepository repo = PortletManager.getWritableRepositories(actionRequest)[0]; try { downloader.loadDriver(repo, found, new FileWriteMonitor() { public void writeStarted(String fileDescription) { System.out.println("Downloading "+fileDescription); } public void writeProgress(int bytes) { System.out.print("\rDownload progress: "+(bytes/1024)+"kB"); System.out.flush(); } public void writeComplete(int bytes) { System.out.println(); System.out.println("Finished downloading "+bytes+"b"); } }); data.jar1 = found.getRepositoryURI(); } catch (IOException e) { log.error("Unable to download JDBC driver", e); } } if(data.getDbtype() == null || data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if(mode.equals("process-"+BASIC_PARAMS_MODE)) { DatabaseInfo info = null; info = getDatabaseInfo(data); if(info != null) { data.url = populateURL(info.getUrl(), info.getUrlParameters(), data.getUrlProperties()); } if(attemptDriverLoad(actionRequest, data) != null) { actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE); } else { actionResponse.setRenderParameter("driverError", "Unable to load driver "+data.driverClass); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if(mode.equals("process-"+CONFIRM_URL_MODE)) { String test = actionRequest.getParameter("test"); if(test == null || test.equals("true")) { String result = null; String stack = null; try { result = attemptConnect(actionRequest, data); } catch (Exception e) { StringWriter writer = new StringWriter(); PrintWriter temp = new PrintWriter(writer); e.printStackTrace(temp); temp.flush(); temp.close(); stack = writer.getBuffer().toString(); } if(result != null) actionResponse.setRenderParameter("connectResult", result); actionRequest.getPortletSession(true).setAttribute("connectError", stack); actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE); } else { save(actionRequest, actionResponse, data, false); } } else if(mode.equals(SAVE_MODE)) { save(actionRequest, actionResponse, data, false); } else if(mode.equals(SHOW_PLAN_MODE)) { String plan = save(actionRequest, actionResponse, data, true); actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan); actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE); } else if(mode.equals(EDIT_EXISTING_MODE)) { final String name = actionRequest.getParameter("adapterObjectName"); loadConnectionFactory(actionRequest, name, data.getObjectName(), data); actionResponse.setRenderParameter("adapterObjectName", name); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if(mode.equals(SELECT_RDBMS_MODE)) { if(data.getAdapterDisplayName() == null) { // Set a default for a new pool data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; } actionResponse.setRenderParameter(MODE_KEY, mode); } else if(mode.equals(WEBLOGIC_IMPORT_MODE)) { String domainDir = actionRequest.getParameter("weblogicDomainDir"); String libDir = actionRequest.getParameter("weblogicLibDir"); try { DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir); actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } catch (Exception e) { log.error("Unable to import", e); actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE); } } else if(mode.equals(IMPORT_START_MODE)) { actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, mode); } else if(mode.equals(IMPORT_EDIT_MODE)) { ImportStatus status = getImportStatus(actionRequest); int index = Integer.parseInt(actionRequest.getParameter("importIndex")); status.setCurrentPoolIndex(index); loadImportedData(data, status.getCurrentPool()); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if(mode.equals(IMPORT_COMPLETE_MODE)) { ImportStatus status = getImportStatus(actionRequest); log.warn("Import Results:"); //todo: create a screen for this log.warn(" "+status.getSkippedCount()+" ignored"); log.warn(" "+status.getStartedCount()+" reviewed but not deployed"); log.warn(" "+status.getPendingCount()+" not reviewed"); log.warn(" "+status.getFinishedCount()+" deployed"); actionRequest.getPortletSession().removeAttribute("ImportStatus"); } else { actionResponse.setRenderParameter(MODE_KEY, mode); } data.store(actionResponse); } private void loadImportedData(PoolData data, ImportStatus.PoolProgress progress) { if(!progress.getType().equals(ImportStatus.PoolProgress.TYPE_XA)) { JDBCPool pool = (JDBCPool) progress.getPool(); data.dbtype = "Other"; data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; data.blockingTimeout = getImportString(pool.getBlockingTimeoutMillis()); data.driverClass = pool.getDriverClass(); data.idleTimeout = pool.getIdleTimeoutMillis() == null ? null : Integer.toString(pool.getIdleTimeoutMillis().intValue() / (60 * 1000)); data.maxSize = getImportString(pool.getMaxSize()); data.minSize = getImportString(pool.getMinSize()); data.name = pool.getName(); data.password = pool.getPassword(); data.url = pool.getJdbcURL(); data.user = pool.getUsername(); if(pool.getDriverClass() != null) { DatabaseInfo info = getDatabaseInfoFromDriver(data); if(info != null) { data.rarPath = info.getRarPath(); data.urlPrototype = info.getUrl(); } else { log.warn("Don't recognize database driver "+data.driverClass+"; Using default RAR file"); data.rarPath = DatabaseInfo.getDefaultRARPath(); } } } else { //todo: handle XA } } private static String getImportString(Integer value) { return value == null ? null : value.toString(); } private boolean processImportUpload(ActionRequest request, ActionResponse response) throws PortletException { String type = request.getParameter("importSource"); response.setRenderParameter("importSource", type); if (!PortletFileUpload.isMultipartContent(request)) { throw new PortletException("Expected file upload"); } PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory()); try { List items = uploader.parseRequest(request); for (Iterator i = items.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); if (!item.isFormField()) { File file = File.createTempFile("geronimo-import", ""); file.deleteOnExit(); log.debug("Writing database pool import file to "+file.getAbsolutePath()); item.write(file); DatabaseConversionStatus status = processImport(file, type); request.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); return true; } else { throw new PortletException("Not expecting any form fields"); } } } catch(PortletException e) { throw e; } catch(Exception e) { throw new PortletException(e); } return false; } private DatabaseConversionStatus processImport(File importFile, String type) throws PortletException, IOException { if(type.equals("JBoss 4")) { return JBoss4DatabaseConverter.convert(new FileReader(importFile)); } else if(type.equals("WebLogic 8.1")) { return WebLogic81DatabaseConverter.convert(new FileReader(importFile)); } else { throw new PortletException("Unknown import type '"+type+"'"); } } private ResourceAdapterParams loadConfigPropertiesByPath(PortletRequest request, String rarPath) { DeploymentManager mgr = PortletManager.getDeploymentManager(request); try { URL url = getRAR(request, rarPath); ConnectorDeployable deployable = new ConnectorDeployable(url); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); String adapterName = null, adapterDesc = null; String[] test = ddBeanRoot.getText("connector/display-name"); if(test != null && test.length > 0) { adapterName = test[0]; } test = ddBeanRoot.getText("connector/description"); if(test != null && test.length > 0) { adapterDesc = test[0]; } DDBean[] definitions = ddBeanRoot.getChildBean("connector/resourceadapter/outbound-resourceadapter/connection-definition"); List configs = new ArrayList(); if(definitions != null) { for (int i = 0; i < definitions.length; i++) { DDBean definition = definitions[i]; String iface = definition.getText("connectionfactory-interface")[0]; if(iface.equals("javax.sql.DataSource")) { DDBean[] beans = definition.getChildBean("config-property"); for (int j = 0; j < beans.length; j++) { DDBean bean = beans[j]; String name = bean.getText("config-property-name")[0].trim(); String type = bean.getText("config-property-type")[0].trim(); test = bean.getText("config-property-value"); String value = test == null || test.length == 0 ? null : test[0].trim(); test = bean.getText("description"); String desc = test == null || test.length == 0 ? null : test[0].trim(); configs.add(new ConfigParam(name, type, desc, value)); } } } } return new ResourceAdapterParams(adapterName, adapterDesc, (ConfigParam[]) configs.toArray(new ConfigParam[configs.size()])); } catch (Exception e) { log.error("Unable to read configuration properties", e); return null; } finally { if(mgr != null) mgr.release(); } } private ResourceAdapterParams loadConfigPropertiesByObjectName(PortletRequest request, String objectName) { ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request, objectName); String dd = module.getDeploymentDescriptor(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); final StringReader reader = new StringReader(dd); Document doc = builder.parse(new InputSource(reader)); reader.close(); Element elem = doc.getDocumentElement(); // connector String displayName = getFirstText(elem.getElementsByTagName("display-name")); String description = getFirstText(elem.getElementsByTagName("description")); elem = (Element) elem.getElementsByTagName("resourceadapter").item(0); elem = (Element) elem.getElementsByTagName("outbound-resourceadapter").item(0); NodeList defs = elem.getElementsByTagName("connection-definition"); List all = new ArrayList(); for(int i=0; i<defs.getLength(); i++) { final Element def = (Element)defs.item(i); String iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim(); if(iface.equals("javax.sql.DataSource")) { NodeList configs = def.getElementsByTagName("config-property"); for(int j=0; j<configs.getLength(); j++) { Element config = (Element) configs.item(j); String name = getFirstText(config.getElementsByTagName("config-property-name")).trim(); String type = getFirstText(config.getElementsByTagName("config-property-type")).trim(); String test = getFirstText(config.getElementsByTagName("config-property-value")); String value = test == null ? null : test.trim(); test = getFirstText(config.getElementsByTagName("description")); String desc = test == null ? null : test.trim(); all.add(new ConfigParam(name, type, desc, value)); } } } return new ResourceAdapterParams(displayName, description, (ConfigParam[]) all.toArray(new ConfigParam[all.size()])); } catch (Exception e) { log.error("Unable to read resource adapter DD", e); return null; } } private String getFirstText(NodeList list) { if(list.getLength() == 0) { return null; } Element first = (Element) list.item(0); StringBuffer buf = new StringBuffer(); NodeList all = first.getChildNodes(); for(int i=0; i<all.getLength(); i++) { Node node = all.item(i); if(node.getNodeType() == Node.TEXT_NODE) { buf.append(node.getNodeValue()); } } return buf.toString(); } private void loadConnectionFactory(ActionRequest actionRequest, String adapterName, String factoryName, PoolData data) { ResourceAdapterModule adapter = (ResourceAdapterModule) PortletManager.getManagedBean(actionRequest, adapterName); JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(actionRequest, factoryName); data.adapterDisplayName = adapter.getDisplayName(); data.adapterDescription = adapter.getDescription(); try { ObjectName oname = ObjectName.getInstance(factoryName); data.name = oname.getKeyProperty("name"); if(data.isGeneric()) { data.url = (String) factory.getConfigProperty("connectionURL"); data.driverClass = (String) factory.getConfigProperty("driver"); data.user = (String) factory.getConfigProperty("userName"); data.password = (String) factory.getConfigProperty("password"); } else { ResourceAdapterParams params = getRARConfiguration(actionRequest, data.getRarPath(), data.getAdapterDisplayName(), adapterName); for(int i=0; i<params.getConfigParams().length; i++) { ConfigParam cp = params.getConfigParams()[i]; Object value = factory.getConfigProperty(cp.getName()); data.properties.put("property-"+cp.getName(), value == null ? null : value.toString()); } } } catch (Exception e) { log.error("Unable to look up connection property", e); } //todo: push the lookup into ManagementHelper PoolingAttributes pool = (PoolingAttributes) PortletManager.getManagedBean(actionRequest, factory.getConnectionManager()); data.minSize = Integer.toString(pool.getPartitionMinSize()); data.maxSize = Integer.toString(pool.getPartitionMaxSize()); data.blockingTimeout = Integer.toString(pool.getBlockingTimeoutMilliseconds()); data.idleTimeout = Integer.toString(pool.getIdleTimeoutMinutes()); } protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) { return; } try { String mode = renderRequest.getParameter(MODE_KEY); PoolData data = new PoolData(); data.load(renderRequest); renderRequest.setAttribute("pool", data); // If not headed anywhere in particular, send to list if(mode == null || mode.equals("")) { mode = LIST_MODE; } // If headed to list but there's an import in progress, redirect to import status if(mode.equals(LIST_MODE) && getImportStatus(renderRequest) != null) { mode = IMPORT_STATUS_MODE; } if(mode.equals(LIST_MODE)) { renderList(renderRequest, renderResponse); } else if(mode.equals(EDIT_MODE)) { renderEdit(renderRequest, renderResponse, data); } else if(mode.equals(SELECT_RDBMS_MODE)) { renderSelectRDBMS(renderRequest, renderResponse); } else if(mode.equals(DOWNLOAD_MODE)) { renderDownload(renderRequest, renderResponse); } else if(mode.equals(BASIC_PARAMS_MODE)) { renderBasicParams(renderRequest, renderResponse, data); } else if(mode.equals(CONFIRM_URL_MODE)) { renderConfirmURL(renderRequest, renderResponse); } else if(mode.equals(TEST_CONNECTION_MODE)) { renderTestConnection(renderRequest, renderResponse); } else if(mode.equals(SHOW_PLAN_MODE)) { renderPlan(renderRequest, renderResponse); } else if(mode.equals(IMPORT_START_MODE)) { renderImportUploadForm(renderRequest, renderResponse); } else if(mode.equals(IMPORT_STATUS_MODE)) { renderImportStatus(renderRequest, renderResponse); } else if(mode.equals(USAGE_MODE)) { renderUsage(renderRequest, renderResponse); } } catch (Throwable e) { log.error("Unable to render portlet", e); } } private void renderUsage(RenderRequest request, RenderResponse response) throws IOException, PortletException { usageView.include(request, response); } private void renderImportStatus(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("status", getImportStatus(request)); populatePoolList(request); importStatusView.include(request, response); } private void renderImportUploadForm(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("from", request.getParameter("from")); importUploadView.include(request, response); } private void renderList(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { populatePoolList(renderRequest); listView.include(renderRequest, renderResponse); } private void populatePoolList(PortletRequest renderRequest) { ResourceAdapterModule[] modules = PortletManager.getOutboundRAModules(renderRequest, "javax.sql.DataSource"); List list = new ArrayList(); for (int i = 0; i < modules.length; i++) { ResourceAdapterModule module = modules[i]; JCAManagedConnectionFactory[] databases = PortletManager.getOutboundFactoriesForRA(renderRequest, module, "javax.sql.DataSource"); for (int j = 0; j < databases.length; j++) { JCAManagedConnectionFactory db = databases[j]; try { ObjectName name = ObjectName.getInstance(db.getObjectName()); list.add(new ConnectionPool(ObjectName.getInstance(module.getObjectName()), db.getObjectName(), name.getKeyProperty(NameFactory.J2EE_NAME), ((GeronimoManagedBean)db).getState())); } catch (MalformedObjectNameException e) { e.printStackTrace(); } } } Collections.sort(list); renderRequest.setAttribute("pools", list); } private void renderEdit(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { if(data.objectName == null || data.objectName.equals("")) { loadDriverJARList(renderRequest); } if(!data.isGeneric()) { ResourceAdapterParams params = getRARConfiguration(renderRequest, data.getRarPath(), data.getAdapterDisplayName(), renderRequest.getParameter("adapterObjectName")); data.adapterDisplayName = params.getDisplayName(); data.adapterDescription = params.getDescription(); Map map = new HashMap(); boolean more = false; for (int i = 0; i < params.getConfigParams().length; i++) { ConfigParam param = params.getConfigParams()[i]; if(!data.properties.containsKey("property-"+param.getName())) { data.properties.put("property-"+param.getName(), param.getDefaultValue()); more = true; } map.put("property-"+param.getName(), param); } if(more) { data.loadPropertyNames(); } renderRequest.setAttribute("ConfigParams", map); } editView.include(renderRequest, renderResponse); } private void renderSelectRDBMS(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("databases", DatabaseInfo.ALL_DATABASES); selectRDBMSView.include(renderRequest, renderResponse); } private void renderDownload(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("drivers", getDriverInfo(renderRequest)); downloadView.include(renderRequest, renderResponse); } private void renderBasicParams(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { loadDriverJARList(renderRequest); // Make sure all properties available for the DB are listed DatabaseInfo info = getDatabaseInfo(data); if(info != null) { String[] params = info.getUrlParameters(); for (int i = 0; i < params.length; i++) { String param = params[i]; final String key = "urlproperty-"+param; if(!data.getUrlProperties().containsKey(key)) { data.getUrlProperties().put(key, param.equalsIgnoreCase("port") && info.getDefaultPort() > 0 ? new Integer(info.getDefaultPort()) : null); } } } // Pass on errors renderRequest.setAttribute("driverError", renderRequest.getParameter("driverError")); basicParamsView.include(renderRequest, renderResponse); } private void loadDriverJARList(RenderRequest renderRequest) { // List the available JARs List list = new ArrayList(); ListableRepository[] repos = PortletManager.getListableRepositories(renderRequest); for (int i = 0; i < repos.length; i++) { ListableRepository repo = repos[i]; try { final URI[] uris = repo.listURIs(); outer: for (int j = 0; j < uris.length; j++) { String test = uris[j].toString(); for (int k = 0; k < SKIP_ENTRIES_WITH.length; k++) { String skip = SKIP_ENTRIES_WITH[k]; if(test.indexOf(skip) > -1) { continue outer; } } list.add(test); } } catch (URISyntaxException e) { e.printStackTrace(); } } Collections.sort(list); renderRequest.setAttribute("jars", list); } private void renderConfirmURL(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { confirmURLView.include(renderRequest, renderResponse); } private void renderTestConnection(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("connectResult", renderRequest.getParameter("connectResult")); renderRequest.setAttribute("connectError", renderRequest.getPortletSession().getAttribute("connectError")); testConnectionView.include(renderRequest, renderResponse); } private void renderPlan(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("deploymentPlan", renderRequest.getPortletSession().getAttribute("deploymentPlan")); planView.include(renderRequest, renderResponse); } private static String attemptConnect(PortletRequest request, PoolData data) throws SQLException, IllegalAccessException, InstantiationException { Class driverClass = attemptDriverLoad(request, data); Driver driver = (Driver) driverClass.newInstance(); if(driver.acceptsURL(data.url)) { Properties props = new Properties(); props.put("user", data.user); props.put("password", data.password); Connection con = null; try { con = driver.connect(data.url, props); final DatabaseMetaData metaData = con.getMetaData(); return metaData.getDatabaseProductName()+" "+metaData.getDatabaseProductVersion(); } finally { if(con != null) try{con.close();}catch(SQLException e) {} } } else throw new SQLException("Driver "+data.getDriverClass()+" does not accept URL "+data.url); } private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) { ImportStatus status = getImportStatus(request); if(data.objectName == null || data.objectName.equals("")) { // we're creating a new pool data.name = data.name.replaceAll("\\s", ""); DeploymentManager mgr = PortletManager.getDeploymentManager(request); try { URL url = getRAR(request, data.getRarPath()); ConnectorDeployable deployable = new ConnectorDeployable(url); DeploymentConfiguration config = mgr.createConfiguration(deployable); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot); ConnectorDCB connector = (ConnectorDCB) root.getDConfigBean(ddBeanRoot.getChildBean(root.getXpaths()[0])[0]); connector.setConfigID("user/database-pool"+data.getName() + "/1/car"); connector.setParentID("geronimo/j2ee-server/1.0-SNAPSHOT/car"); if(data.jar1 != null && !data.jar1.equals("")) { Dependency dep = new Dependency(); connector.setDependency(new Dependency[]{dep}); dep.setURI(data.jar1); } if(data.jar2 != null && !data.jar2.equals("")) { Dependency dep = new Dependency(); Dependency[] old = connector.getDependency(); Dependency[] longer = new Dependency[old.length+1]; System.arraycopy(old, 0, longer, 0, old.length); longer[old.length] = dep; connector.setDependency(longer); dep.setURI(data.jar2); } if(data.jar3 != null && !data.jar3.equals("")) { Dependency dep = new Dependency(); Dependency[] old = connector.getDependency(); Dependency[] longer = new Dependency[old.length+1]; System.arraycopy(old, 0, longer, 0, old.length); longer[old.length] = dep; connector.setDependency(longer); dep.setURI(data.jar3); } ResourceAdapter adapter = connector.getResourceAdapter()[0]; ConnectionDefinition definition = new ConnectionDefinition(); adapter.setConnectionDefinition(new ConnectionDefinition[]{definition}); definition.setConnectionFactoryInterface("javax.sql.DataSource"); ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance(); definition.setConnectionInstance(new ConnectionDefinitionInstance[]{instance}); instance.setName(data.getName()); ConfigPropertySetting[] settings = instance.getConfigPropertySetting(); if(data.isGeneric()) { // it's a generic TranQL JDBC pool for (int i = 0; i < settings.length; i++) { ConfigPropertySetting setting = settings[i]; if(setting.getName().equals("UserName")) { setting.setValue(data.user); } else if(setting.getName().equals("Password")) { setting.setValue(data.password); } else if(setting.getName().equals("ConnectionURL")) { setting.setValue(data.url); } else if(setting.getName().equals("Driver")) { setting.setValue(data.driverClass); } } } else { // it's an XA driver or non-TranQL RA for (int i = 0; i < settings.length; i++) { ConfigPropertySetting setting = settings[i]; String value = (String) data.properties.get("property-"+setting.getName()); setting.setValue(value == null ? "" : value); } } ConnectionManager manager = instance.getConnectionManager(); manager.setTransactionLocal(true); SinglePool pool = new SinglePool(); manager.setPoolSingle(pool); pool.setMatchOne(true); // Max Size needs to be set before the minimum. This is because // the connection manager will constrain the minimum based on the // current maximum value in the pool. We might consider adding a // setPoolConstraints method to allow specifying both at the same time. if(data.maxSize != null && !data.maxSize.equals("")) { pool.setMaxSize(new Integer(data.maxSize)); } if(data.minSize != null && !data.minSize.equals("")) { pool.setMinSize(new Integer(data.minSize)); } if(data.blockingTimeout != null && !data.blockingTimeout.equals("")) { pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout)); } if(data.idleTimeout != null && !data.idleTimeout.equals("")) { pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout)); } if(planOnly) { ByteArrayOutputStream out = new ByteArrayOutputStream(); config.save(out); out.close(); return new String(out.toByteArray(), "US-ASCII"); } else { File tempFile = File.createTempFile("console-deployment",".xml"); tempFile.deleteOnExit(); log.debug("Writing database pool deployment plan to "+tempFile.getAbsolutePath()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); config.save(out); out.flush(); out.close(); Target[] targets = mgr.getTargets(); ProgressObject po = mgr.distribute(targets, new File(url.getPath()), tempFile); waitForProgress(po); if(po.getDeploymentStatus().isCompleted()) { TargetModuleID[] ids = po.getResultTargetModuleIDs(); po = mgr.start(ids); waitForProgress(po); if(po.getDeploymentStatus().isCompleted()) { ids = po.getResultTargetModuleIDs(); if(status != null) { status.getCurrentPool().setName(data.getName()); status.getCurrentPool().setConfigurationName(ids[0].getModuleID()); status.getCurrentPool().setFinished(true); response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } System.out.println("Deployment completed successfully!"); } } } } catch (Exception e) { log.error("Unable to save connection pool", e); } finally { if(mgr != null) mgr.release(); } } else { // We're saving updates to an existing pool if(planOnly) { throw new UnsupportedOperationException("Can't update a plan for an existing deployment"); } try { JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(request, data.getObjectName()); if(data.isGeneric()) { factory.setConfigProperty("connectionURL", data.getUrl()); factory.setConfigProperty("userName", data.getUser()); factory.setConfigProperty("password", data.getPassword()); } else { for (Iterator it = data.getProperties().entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); factory.setConfigProperty(((String) entry.getKey()).substring("property-".length()), entry.getValue()); } } //todo: push the lookup into ManagementHelper PoolingAttributes pool = (PoolingAttributes) PortletManager.getManagedBean(request, factory.getConnectionManager()); pool.setPartitionMinSize(data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize)); pool.setPartitionMaxSize(data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize)); pool.setBlockingTimeoutMilliseconds(data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000 : Integer.parseInt(data.blockingTimeout)); pool.setIdleTimeoutMinutes(data.idleTimeout == null || data.idleTimeout.equals("") ? 15 : Integer.parseInt(data.idleTimeout)); } catch (Exception e) { log.error("Unable to save connection pool", e); } } return null; } private static void waitForProgress(ProgressObject po) { while(po.getDeploymentStatus().isRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private static ImportStatus getImportStatus(PortletRequest request) { return (ImportStatus) request.getPortletSession(true).getAttribute("ImportStatus"); } private static URL getRAR(PortletRequest request, String rarPath) { try { URI uri = new URI(rarPath); Repository[] repos = PortletManager.getRepositories(request); for (int i = 0; i < repos.length; i++) { Repository repo = repos[i]; URL url = repo.getURL(uri); if(url != null && url.getProtocol().equals("file")) { File file = new File(url.getPath()); if(file.exists() && file.canRead() && !file.isDirectory()) { return url; } } } } catch (URISyntaxException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } /** * WARNING: This method relies on having access to the same repository * URLs as the server uses. */ private static Class attemptDriverLoad(PortletRequest request, PoolData data) { List list = new ArrayList(); try { URI one = data.getJar1() == null ? null : new URI(data.getJar1()); URI two = data.getJar2() == null ? null : new URI(data.getJar2()); URI three = data.getJar3() == null ? null : new URI(data.getJar3()); ListableRepository[] repos = PortletManager.getListableRepositories(request); for (int i = 0; i < repos.length; i++) { ListableRepository repo = repos[i]; if(one != null) { URL url = repo.getURL(one); if(url != null) { list.add(url); one = null; } } if(two != null) { URL url = repo.getURL(two); if(url != null) { list.add(url); two = null; } } if(three != null) { URL url = repo.getURL(three); if(url != null) { list.add(url); three = null; } } } URLClassLoader loader = new URLClassLoader((URL[]) list.toArray(new URL[list.size()]), DatabasePoolPortlet.class.getClassLoader()); try { return loader.loadClass(data.driverClass); } catch (ClassNotFoundException e) { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } private static String populateURL(String url, String[] keys, Map properties) { for (int i = 0; i < keys.length; i++) { String key = keys[i]; String value = (String) properties.get("urlproperty-"+key); if(value == null || value.equals("")) { int begin = url.indexOf("<"+key+">"); int end = begin + key.length() + 2; for(int j=begin-1; j>=0; j--) { char c = url.charAt(j); if(c == ';' || c == ':') { begin = j; break; } else if(c == '/') { if(url.length() > end && url.charAt(end) == '/') { begin = j; // Don't leave // if foo is null for /<foo>/ } break; } } url = url.substring(0, begin)+url.substring(end); } else { url = url.replaceAll("<"+key+">", value); } } return url; } private static DatabaseInfo getDatabaseInfo(PoolData data) { DatabaseInfo info = null; for (int i = 0; i < DatabaseInfo.ALL_DATABASES.length; i++) { DatabaseInfo next = DatabaseInfo.ALL_DATABASES[i]; if(next.getName().equals(data.getDbtype())) { info = next; break; } } return info; } private static DatabaseInfo getDatabaseInfoFromDriver(PoolData data) { DatabaseInfo info = null; for (int i = 0; i < DatabaseInfo.ALL_DATABASES.length; i++) { DatabaseInfo next = DatabaseInfo.ALL_DATABASES[i]; if(next.getDriverClass() != null && next.getDriverClass().equals(data.getDriverClass())) { info = next; break; } } return info; } public static class PoolData implements Serializable { private String name; private String dbtype; private String user; private String password; private Map properties = new HashMap(); // Configuration for non-Generic drivers private Map urlProperties = new HashMap(); // URL substitution for Generic drivers private Map propertyNames; //todo: store these in the ConfigParam instead private String driverClass; private String url; private String urlPrototype; private String jar1; private String jar2; private String jar3; private String minSize; private String maxSize; private String blockingTimeout; private String idleTimeout; private String objectName; private String adapterDisplayName; private String adapterDescription; private String rarPath; private String importSource; private Map objectNameMap; // generated as needed, don't need to read/write it public void load(PortletRequest request) { name = request.getParameter("name"); if(name != null && name.equals("")) name = null; driverClass = request.getParameter("driverClass"); if(driverClass != null && driverClass.equals("")) driverClass = null; dbtype = request.getParameter("dbtype"); if(dbtype != null && dbtype.equals("")) dbtype = null; user = request.getParameter("user"); if(user != null && user.equals("")) user = null; password = request.getParameter("password"); if(password != null && password.equals("")) password = null; url = request.getParameter("url"); if(url != null && url.equals("")) url = null; urlPrototype = request.getParameter("urlPrototype"); if(urlPrototype != null && urlPrototype.equals("")) urlPrototype = null; jar1 = request.getParameter("jar1"); if(jar1 != null && jar1.equals("")) jar1 = null; jar2 = request.getParameter("jar2"); if(jar2 != null && jar2.equals("")) jar2 = null; jar3 = request.getParameter("jar3"); if(jar3 != null && jar3.equals("")) jar3 = null; minSize = request.getParameter("minSize"); if(minSize != null && minSize.equals("")) minSize = null; maxSize = request.getParameter("maxSize"); if(maxSize != null && maxSize.equals("")) maxSize = null; blockingTimeout = request.getParameter("blockingTimeout"); if(blockingTimeout != null && blockingTimeout.equals("")) blockingTimeout = null; idleTimeout = request.getParameter("idleTimeout"); if(idleTimeout != null && idleTimeout.equals("")) idleTimeout = null; objectName = request.getParameter("objectName"); if(objectName != null && objectName.equals("")) objectName = null; adapterDisplayName = request.getParameter("adapterDisplayName"); if(adapterDisplayName != null && adapterDisplayName.equals("")) adapterDisplayName = null; adapterDescription = request.getParameter("adapterDescription"); if(adapterDescription != null && adapterDescription.equals("")) adapterDescription = null; rarPath = request.getParameter("rarPath"); if(rarPath != null && rarPath.equals("")) rarPath = null; importSource = request.getParameter("importSource"); if(importSource != null && importSource.equals("")) importSource = null; Map map = request.getParameterMap(); propertyNames = new HashMap(); for (Iterator it = map.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); if(key.startsWith("urlproperty-")) { urlProperties.put(key, request.getParameter(key)); } else if(key.startsWith("property-")) { properties.put(key, request.getParameter(key)); propertyNames.put(key, getPropertyName(key)); } } } public void loadPropertyNames() { propertyNames = new HashMap(); for (Iterator it = properties.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); propertyNames.put(key, getPropertyName(key)); } } private static String getPropertyName(String key) { int pos = key.indexOf('-'); key = Character.toUpperCase(key.charAt(pos+1))+key.substring(pos+2); StringBuffer buf = new StringBuffer(); pos = 0; for(int i=1; i<key.length(); i++) { if(Character.isUpperCase(key.charAt(i))) { if(Character.isUpperCase(key.charAt(i-1))) { // ongoing capitalized word } else { // start of a new word buf.append(key.substring(pos, i)).append(" "); pos = i; } } else { if(Character.isUpperCase(key.charAt(i-1)) && i-pos > 1) { // first lower-case after a series of caps buf.append(key.substring(pos, i-1)).append(" "); pos = i-1; } } } buf.append(key.substring(pos)); return buf.toString(); } public void store(ActionResponse response) { if(name != null) response.setRenderParameter("name", name); if(dbtype != null) response.setRenderParameter("dbtype", dbtype); if(driverClass != null) response.setRenderParameter("driverClass", driverClass); if(user != null) response.setRenderParameter("user", user); if(password != null) response.setRenderParameter("password", password); if(url != null) response.setRenderParameter("url", url); if(urlPrototype != null) response.setRenderParameter("urlPrototype", urlPrototype); if(jar1 != null) response.setRenderParameter("jar1", jar1); if(jar2 != null) response.setRenderParameter("jar2", jar2); if(jar3 != null) response.setRenderParameter("jar3", jar3); if(minSize != null) response.setRenderParameter("minSize", minSize); if(maxSize != null) response.setRenderParameter("maxSize", maxSize); if(blockingTimeout != null) response.setRenderParameter("blockingTimeout", blockingTimeout); if(idleTimeout != null) response.setRenderParameter("idleTimeout", idleTimeout); if(objectName != null) response.setRenderParameter("objectName", objectName); if(adapterDisplayName != null) response.setRenderParameter("adapterDisplayName", adapterDisplayName); if(adapterDescription != null) response.setRenderParameter("adapterDescription", adapterDescription); if(importSource != null) response.setRenderParameter("importSource", importSource); if(rarPath != null) response.setRenderParameter("rarPath", rarPath); for (Iterator it = urlProperties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); if(entry.getValue() != null) { response.setRenderParameter((String)entry.getKey(), (String)entry.getValue()); } } for (Iterator it = properties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); if(entry.getValue() != null) { response.setRenderParameter((String)entry.getKey(), (String)entry.getValue()); } } } public String getName() { return name; } public String getDbtype() { return dbtype; } public String getUser() { return user; } public String getPassword() { return password; } public Map getProperties() { return properties; } public Map getPropertyNames() { return propertyNames; } public Map getUrlProperties() { return urlProperties; } public String getUrl() { return url; } public String getJar1() { return jar1; } public String getJar2() { return jar2; } public String getJar3() { return jar3; } public String getMinSize() { return minSize; } public String getMaxSize() { return maxSize; } public String getBlockingTimeout() { return blockingTimeout; } public String getIdleTimeout() { return idleTimeout; } public String getDriverClass() { return driverClass; } public String getUrlPrototype() { return urlPrototype; } public String getObjectName() { return objectName; } public String getAdapterDisplayName() { return adapterDisplayName; } public String getAdapterDescription() { return adapterDescription; } public String getRarPath() { return rarPath; } public boolean isGeneric() { //todo: is there any better way to tell? return adapterDisplayName == null || adapterDisplayName.equals("TranQL Generic JDBC Resource Adapter"); } public String getImportSource() { return importSource; } public Map getObjectNameMap() { if(objectName == null) return Collections.EMPTY_MAP; if(objectNameMap != null) return objectNameMap; try { ObjectName name = new ObjectName(objectName); objectNameMap = new HashMap(name.getKeyPropertyList()); objectNameMap.put("domain", name.getDomain()); return objectNameMap; } catch (MalformedObjectNameException e) { return Collections.EMPTY_MAP; } } } public static class ConnectionPool implements Serializable, Comparable { private final String adapterObjectName; private final String factoryObjectName; private final String name; private final String parentName; private final int state; public ConnectionPool(ObjectName adapterObjectName, String factoryObjectName, String name, int state) { this.adapterObjectName = adapterObjectName.getCanonicalName(); String parent = adapterObjectName.getKeyProperty(NameFactory.J2EE_APPLICATION); if(parent != null && parent.equals("null")) { parent = null; } parentName = parent; this.factoryObjectName = factoryObjectName; this.name = name; this.state = state; } public String getAdapterObjectName() { return adapterObjectName; } public String getFactoryObjectName() { return factoryObjectName; } public String getName() { return name; } public String getParentName() { return parentName; } public int getState() { return state; } public String getStateName() { return State.toString(state); } public int compareTo(Object o) { final ConnectionPool pool = (ConnectionPool)o; int names = name.compareTo(pool.name); if(parentName == null) { if(pool.parentName == null) { return names; } else { return -1; } } else { if(pool.parentName == null) { return 1; } else { int test = parentName.compareTo(pool.parentName); if(test != 0) { return test; } else { return names; } } } } } public static class ResourceAdapterParams { private String displayName; private String description; private ConfigParam[] configParams; public ResourceAdapterParams(String displayName, String description, ConfigParam[] configParams) { this.displayName = displayName; this.description = description; this.configParams = configParams; } public String getDisplayName() { return displayName; } public String getDescription() { return description; } public ConfigParam[] getConfigParams() { return configParams; } } public static class ConfigParam { private String name; private String type; private String description; private String defaultValue; public ConfigParam(String name, String type, String description, String defaultValue) { this.name = name; this.type = type; this.description = description; this.defaultValue = defaultValue; } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } public String getDefaultValue() { return defaultValue; } } }
applications/console-standard/src/java/org/apache/geronimo/console/databasemanager/wizard/DatabasePoolPortlet.java
/** * * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.console.databasemanager.wizard; import java.io.IOException; import java.io.Serializable; import java.io.PrintWriter; import java.io.StringWriter; import java.io.File; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.StringReader; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import java.net.URISyntaxException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.MalformedURLException; import java.sql.Driver; import java.sql.SQLException; import java.sql.Connection; import java.sql.DatabaseMetaData; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; import javax.management.ObjectName; import javax.management.MalformedObjectNameException; import javax.enterprise.deploy.spi.DeploymentManager; import javax.enterprise.deploy.spi.DeploymentConfiguration; import javax.enterprise.deploy.spi.Target; import javax.enterprise.deploy.spi.TargetModuleID; import javax.enterprise.deploy.spi.status.ProgressObject; import javax.enterprise.deploy.model.DDBeanRoot; import javax.enterprise.deploy.model.DDBean; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.apache.geronimo.console.BasePortlet; import org.apache.geronimo.console.util.PortletManager; import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory; import org.apache.geronimo.management.geronimo.ResourceAdapterModule; import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; import org.apache.geronimo.kernel.repository.ListableRepository; import org.apache.geronimo.kernel.repository.Repository; import org.apache.geronimo.kernel.repository.WriteableRepository; import org.apache.geronimo.kernel.repository.FileWriteMonitor; import org.apache.geronimo.kernel.management.State; import org.apache.geronimo.kernel.proxy.GeronimoManagedBean; import org.apache.geronimo.deployment.tools.loader.ConnectorDeployable; import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot; import org.apache.geronimo.connector.deployment.jsr88.ConnectorDCB; import org.apache.geronimo.connector.deployment.jsr88.Dependency; import org.apache.geronimo.connector.deployment.jsr88.ResourceAdapter; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinition; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinitionInstance; import org.apache.geronimo.connector.deployment.jsr88.ConfigPropertySetting; import org.apache.geronimo.connector.deployment.jsr88.ConnectionManager; import org.apache.geronimo.connector.deployment.jsr88.SinglePool; import org.apache.geronimo.connector.outbound.PoolingAttributes; import org.apache.geronimo.converter.DatabaseConversionStatus; import org.apache.geronimo.converter.JDBCPool; import org.apache.geronimo.converter.bea.WebLogic81DatabaseConverter; import org.apache.geronimo.converter.jboss.JBoss4DatabaseConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.fileupload.portlet.PortletFileUpload; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.FileItem; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; /** * A portlet that lets you configure and deploy JDBC connection pools. * * @version $Rev$ $Date$ */ public class DatabasePoolPortlet extends BasePortlet { private final static Log log = LogFactory.getLog(DatabasePoolPortlet.class); private final static String[] SKIP_ENTRIES_WITH = new String[]{"geronimo", "tomcat", "tranql", "commons", "directory", "activemq"}; private final static String DRIVER_SESSION_KEY = "org.apache.geronimo.console.dbpool.Drivers"; private final static String CONFIG_SESSION_KEY = "org.apache.geronimo.console.dbpool.ConfigParam"; private final static String DRIVER_INFO_URL = "http://people.apache.org/~ammulder/driver-downloads.properties"; private static final String LIST_VIEW = "/WEB-INF/view/dbwizard/list.jsp"; private static final String EDIT_VIEW = "/WEB-INF/view/dbwizard/edit.jsp"; private static final String SELECT_RDBMS_VIEW = "/WEB-INF/view/dbwizard/selectDatabase.jsp"; private static final String BASIC_PARAMS_VIEW = "/WEB-INF/view/dbwizard/basicParams.jsp"; private static final String CONFIRM_URL_VIEW = "/WEB-INF/view/dbwizard/confirmURL.jsp"; private static final String TEST_CONNECTION_VIEW = "/WEB-INF/view/dbwizard/testConnection.jsp"; private static final String DOWNLOAD_VIEW = "/WEB-INF/view/dbwizard/selectDownload.jsp"; private static final String SHOW_PLAN_VIEW = "/WEB-INF/view/dbwizard/showPlan.jsp"; private static final String IMPORT_UPLOAD_VIEW = "/WEB-INF/view/dbwizard/importUpload.jsp"; private static final String IMPORT_STATUS_VIEW = "/WEB-INF/view/dbwizard/importStatus.jsp"; private static final String USAGE_VIEW = "/WEB-INF/view/dbwizard/usage.jsp"; private static final String LIST_MODE = "list"; private static final String EDIT_MODE = "edit"; private static final String SELECT_RDBMS_MODE = "rdbms"; private static final String BASIC_PARAMS_MODE = "params"; private static final String CONFIRM_URL_MODE = "url"; private static final String TEST_CONNECTION_MODE = "test"; private static final String SHOW_PLAN_MODE = "plan"; private static final String DOWNLOAD_MODE = "download"; private static final String EDIT_EXISTING_MODE = "editExisting"; private static final String SAVE_MODE = "save"; private static final String IMPORT_START_MODE = "startImport"; private static final String IMPORT_UPLOAD_MODE = "importUpload"; private static final String IMPORT_STATUS_MODE = "importStatus"; private static final String IMPORT_COMPLETE_MODE = "importComplete"; private static final String WEBLOGIC_IMPORT_MODE = "weblogicImport"; private static final String USAGE_MODE = "usage"; private static final String IMPORT_EDIT_MODE = "importEdit"; private static final String MODE_KEY = "mode"; private PortletRequestDispatcher listView; private PortletRequestDispatcher editView; private PortletRequestDispatcher selectRDBMSView; private PortletRequestDispatcher basicParamsView; private PortletRequestDispatcher confirmURLView; private PortletRequestDispatcher testConnectionView; private PortletRequestDispatcher downloadView; private PortletRequestDispatcher planView; private PortletRequestDispatcher importUploadView; private PortletRequestDispatcher importStatusView; private PortletRequestDispatcher usageView; public void init(PortletConfig portletConfig) throws PortletException { super.init(portletConfig); listView = portletConfig.getPortletContext().getRequestDispatcher(LIST_VIEW); editView = portletConfig.getPortletContext().getRequestDispatcher(EDIT_VIEW); selectRDBMSView = portletConfig.getPortletContext().getRequestDispatcher(SELECT_RDBMS_VIEW); basicParamsView = portletConfig.getPortletContext().getRequestDispatcher(BASIC_PARAMS_VIEW); confirmURLView = portletConfig.getPortletContext().getRequestDispatcher(CONFIRM_URL_VIEW); testConnectionView = portletConfig.getPortletContext().getRequestDispatcher(TEST_CONNECTION_VIEW); downloadView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_VIEW); planView = portletConfig.getPortletContext().getRequestDispatcher(SHOW_PLAN_VIEW); importUploadView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_UPLOAD_VIEW); importStatusView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_STATUS_VIEW); usageView = portletConfig.getPortletContext().getRequestDispatcher(USAGE_VIEW); } public void destroy() { listView = null; editView = null; selectRDBMSView = null; basicParamsView = null; confirmURLView = null; testConnectionView = null; downloadView = null; planView = null; importUploadView = null; importStatusView = null; usageView = null; super.destroy(); } public DriverDownloader.DriverInfo[] getDriverInfo(PortletRequest request) { PortletSession session = request.getPortletSession(true); DriverDownloader.DriverInfo[] results = (DriverDownloader.DriverInfo[]) session.getAttribute(DRIVER_SESSION_KEY, PortletSession.APPLICATION_SCOPE); if(results == null) { DriverDownloader downloader = new DriverDownloader(); try { results = downloader.loadDriverInfo(new URL(DRIVER_INFO_URL)); session.setAttribute(DRIVER_SESSION_KEY, results, PortletSession.APPLICATION_SCOPE); } catch (MalformedURLException e) { log.error("Unable to download driver data", e); results = new DriverDownloader.DriverInfo[0]; } } return results; } /** * Loads data about a resource adapter. Depending on what we already have, may load * the name and description, but always loads the config property descriptions. * @param request Pass it or die * @param rarPath If we're creating a new RA, the path to identify it * @param displayName If we're editing an existing RA, its name * @param adapterObjectName If we're editing an existing RA, its ObjectName */ public ResourceAdapterParams getRARConfiguration(PortletRequest request, String rarPath, String displayName, String adapterObjectName) { PortletSession session = request.getPortletSession(true); if(rarPath != null && !rarPath.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(CONFIG_SESSION_KEY+"-"+rarPath, PortletSession.APPLICATION_SCOPE); if(results == null) { results = loadConfigPropertiesByPath(request, rarPath); session.setAttribute(CONFIG_SESSION_KEY+"-"+rarPath, results, PortletSession.APPLICATION_SCOPE); session.setAttribute(CONFIG_SESSION_KEY+"-"+results.displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else if(displayName != null && !displayName.equals("") && adapterObjectName != null && !adapterObjectName.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute(CONFIG_SESSION_KEY+"-"+displayName, PortletSession.APPLICATION_SCOPE); if(results == null) { results = loadConfigPropertiesByObjectName(request, adapterObjectName); session.setAttribute(CONFIG_SESSION_KEY+"-"+displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else { throw new IllegalArgumentException(); } } public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter(MODE_KEY); if(mode.equals(IMPORT_UPLOAD_MODE)) { processImportUpload(actionRequest, actionResponse); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); return; } PoolData data = new PoolData(); data.load(actionRequest); if(mode.equals("process-"+SELECT_RDBMS_MODE)) { DatabaseInfo info = null; info = getDatabaseInfo(data); if(info != null) { data.rarPath = info.getRarPath(); if(info.isXA()) { data.adapterDisplayName="Unknown"; // will pick these up when we process the RA type in the render request data.adapterDescription="Unknown"; actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { if(data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { data.driverClass = info.getDriverClass(); data.urlPrototype = info.getUrl(); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } } else { actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE); } } else if(mode.equals("process-"+DOWNLOAD_MODE)) { String name = actionRequest.getParameter("driverName"); DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest); DriverDownloader.DriverInfo found = null; for (int i = 0; i < drivers.length; i++) { DriverDownloader.DriverInfo driver = drivers[i]; if(driver.getName().equals(name)) { found = driver; break; } } if(found != null) { DriverDownloader downloader = new DriverDownloader(); WriteableRepository repo = PortletManager.getWritableRepositories(actionRequest)[0]; try { downloader.loadDriver(repo, found, new FileWriteMonitor() { public void writeStarted(String fileDescription) { System.out.println("Downloading "+fileDescription); } public void writeProgress(int bytes) { System.out.print("\rDownload progress: "+(bytes/1024)+"kB"); System.out.flush(); } public void writeComplete(int bytes) { System.out.println(); System.out.println("Finished downloading "+bytes+"b"); } }); data.jar1 = found.getRepositoryURI(); } catch (IOException e) { log.error("Unable to download JDBC driver", e); } } if(data.getDbtype() == null || data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if(mode.equals("process-"+BASIC_PARAMS_MODE)) { DatabaseInfo info = null; info = getDatabaseInfo(data); if(info != null) { data.url = populateURL(info.getUrl(), info.getUrlParameters(), data.getUrlProperties()); } if(attemptDriverLoad(actionRequest, data) != null) { actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE); } else { actionResponse.setRenderParameter("driverError", "Unable to load driver "+data.driverClass); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if(mode.equals("process-"+CONFIRM_URL_MODE)) { String test = actionRequest.getParameter("test"); if(test == null || test.equals("true")) { String result = null; String stack = null; try { result = attemptConnect(actionRequest, data); } catch (Exception e) { StringWriter writer = new StringWriter(); PrintWriter temp = new PrintWriter(writer); e.printStackTrace(temp); temp.flush(); temp.close(); stack = writer.getBuffer().toString(); } if(result != null) actionResponse.setRenderParameter("connectResult", result); actionRequest.getPortletSession(true).setAttribute("connectError", stack); actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE); } else { save(actionRequest, actionResponse, data, false); } } else if(mode.equals(SAVE_MODE)) { save(actionRequest, actionResponse, data, false); } else if(mode.equals(SHOW_PLAN_MODE)) { String plan = save(actionRequest, actionResponse, data, true); actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan); actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE); } else if(mode.equals(EDIT_EXISTING_MODE)) { final String name = actionRequest.getParameter("adapterObjectName"); loadConnectionFactory(actionRequest, name, data.getObjectName(), data); actionResponse.setRenderParameter("adapterObjectName", name); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if(mode.equals(SELECT_RDBMS_MODE)) { if(data.getAdapterDisplayName() == null) { // Set a default for a new pool data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; } actionResponse.setRenderParameter(MODE_KEY, mode); } else if(mode.equals(WEBLOGIC_IMPORT_MODE)) { String domainDir = actionRequest.getParameter("weblogicDomainDir"); String libDir = actionRequest.getParameter("weblogicLibDir"); try { DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir); actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } catch (Exception e) { log.error("Unable to import", e); actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE); } } else if(mode.equals(IMPORT_START_MODE)) { actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, mode); } else if(mode.equals(IMPORT_EDIT_MODE)) { ImportStatus status = getImportStatus(actionRequest); int index = Integer.parseInt(actionRequest.getParameter("importIndex")); status.setCurrentPoolIndex(index); loadImportedData(data, status.getCurrentPool()); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if(mode.equals(IMPORT_COMPLETE_MODE)) { ImportStatus status = getImportStatus(actionRequest); log.warn("Import Results:"); //todo: create a screen for this log.warn(" "+status.getSkippedCount()+" ignored"); log.warn(" "+status.getStartedCount()+" reviewed but not deployed"); log.warn(" "+status.getPendingCount()+" not reviewed"); log.warn(" "+status.getFinishedCount()+" deployed"); actionRequest.getPortletSession().removeAttribute("ImportStatus"); } else { actionResponse.setRenderParameter(MODE_KEY, mode); } data.store(actionResponse); } private void loadImportedData(PoolData data, ImportStatus.PoolProgress progress) { if(!progress.getType().equals(ImportStatus.PoolProgress.TYPE_XA)) { JDBCPool pool = (JDBCPool) progress.getPool(); data.dbtype = "Other"; data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; data.blockingTimeout = getImportString(pool.getBlockingTimeoutMillis()); data.driverClass = pool.getDriverClass(); data.idleTimeout = pool.getIdleTimeoutMillis() == null ? null : Integer.toString(pool.getIdleTimeoutMillis().intValue() / (60 * 1000)); data.maxSize = getImportString(pool.getMaxSize()); data.minSize = getImportString(pool.getMinSize()); data.name = pool.getName(); data.password = pool.getPassword(); data.url = pool.getJdbcURL(); data.user = pool.getUsername(); if(pool.getDriverClass() != null) { DatabaseInfo info = getDatabaseInfoFromDriver(data); if(info != null) { data.rarPath = info.getRarPath(); data.urlPrototype = info.getUrl(); } else { log.warn("Don't recognize database driver "+data.driverClass+"; Using default RAR file"); data.rarPath = DatabaseInfo.getDefaultRARPath(); } } } else { //todo: handle XA } } private static String getImportString(Integer value) { return value == null ? null : value.toString(); } private boolean processImportUpload(ActionRequest request, ActionResponse response) throws PortletException { String type = request.getParameter("importSource"); response.setRenderParameter("importSource", type); if (!PortletFileUpload.isMultipartContent(request)) { throw new PortletException("Expected file upload"); } PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory()); try { List items = uploader.parseRequest(request); for (Iterator i = items.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); if (!item.isFormField()) { File file = File.createTempFile("geronimo-import", ""); file.deleteOnExit(); log.debug("Writing database pool import file to "+file.getAbsolutePath()); item.write(file); DatabaseConversionStatus status = processImport(file, type); request.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); return true; } else { throw new PortletException("Not expecting any form fields"); } } } catch(PortletException e) { throw e; } catch(Exception e) { throw new PortletException(e); } return false; } private DatabaseConversionStatus processImport(File importFile, String type) throws PortletException, IOException { if(type.equals("JBoss 4")) { return JBoss4DatabaseConverter.convert(new FileReader(importFile)); } else if(type.equals("WebLogic 8.1")) { return WebLogic81DatabaseConverter.convert(new FileReader(importFile)); } else { throw new PortletException("Unknown import type '"+type+"'"); } } private ResourceAdapterParams loadConfigPropertiesByPath(PortletRequest request, String rarPath) { DeploymentManager mgr = PortletManager.getDeploymentManager(request); try { URL url = getRAR(request, rarPath); ConnectorDeployable deployable = new ConnectorDeployable(url); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); String adapterName = null, adapterDesc = null; String[] test = ddBeanRoot.getText("connector/display-name"); if(test != null && test.length > 0) { adapterName = test[0]; } test = ddBeanRoot.getText("connector/description"); if(test != null && test.length > 0) { adapterDesc = test[0]; } DDBean[] definitions = ddBeanRoot.getChildBean("connector/resourceadapter/outbound-resourceadapter/connection-definition"); List configs = new ArrayList(); if(definitions != null) { for (int i = 0; i < definitions.length; i++) { DDBean definition = definitions[i]; String iface = definition.getText("connectionfactory-interface")[0]; if(iface.equals("javax.sql.DataSource")) { DDBean[] beans = definition.getChildBean("config-property"); for (int j = 0; j < beans.length; j++) { DDBean bean = beans[j]; String name = bean.getText("config-property-name")[0].trim(); String type = bean.getText("config-property-type")[0].trim(); test = bean.getText("config-property-value"); String value = test == null || test.length == 0 ? null : test[0].trim(); test = bean.getText("description"); String desc = test == null || test.length == 0 ? null : test[0].trim(); configs.add(new ConfigParam(name, type, desc, value)); } } } } return new ResourceAdapterParams(adapterName, adapterDesc, (ConfigParam[]) configs.toArray(new ConfigParam[configs.size()])); } catch (Exception e) { log.error("Unable to read configuration properties", e); return null; } finally { if(mgr != null) mgr.release(); } } private ResourceAdapterParams loadConfigPropertiesByObjectName(PortletRequest request, String objectName) { ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request, objectName); String dd = module.getDeploymentDescriptor(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); final StringReader reader = new StringReader(dd); Document doc = builder.parse(new InputSource(reader)); reader.close(); Element elem = doc.getDocumentElement(); // connector String displayName = getFirstText(elem.getElementsByTagName("display-name")); String description = getFirstText(elem.getElementsByTagName("description")); elem = (Element) elem.getElementsByTagName("resourceadapter").item(0); elem = (Element) elem.getElementsByTagName("outbound-resourceadapter").item(0); NodeList defs = elem.getElementsByTagName("connection-definition"); List all = new ArrayList(); for(int i=0; i<defs.getLength(); i++) { final Element def = (Element)defs.item(i); String iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim(); if(iface.equals("javax.sql.DataSource")) { NodeList configs = def.getElementsByTagName("config-property"); for(int j=0; j<configs.getLength(); j++) { Element config = (Element) configs.item(j); String name = getFirstText(config.getElementsByTagName("config-property-name")).trim(); String type = getFirstText(config.getElementsByTagName("config-property-type")).trim(); String test = getFirstText(config.getElementsByTagName("config-property-value")); String value = test == null ? null : test.trim(); test = getFirstText(config.getElementsByTagName("description")); String desc = test == null ? null : test.trim(); all.add(new ConfigParam(name, type, desc, value)); } } } return new ResourceAdapterParams(displayName, description, (ConfigParam[]) all.toArray(new ConfigParam[all.size()])); } catch (Exception e) { log.error("Unable to read resource adapter DD", e); return null; } } private String getFirstText(NodeList list) { if(list.getLength() == 0) { return null; } Element first = (Element) list.item(0); StringBuffer buf = new StringBuffer(); NodeList all = first.getChildNodes(); for(int i=0; i<all.getLength(); i++) { Node node = all.item(i); if(node.getNodeType() == Node.TEXT_NODE) { buf.append(node.getNodeValue()); } } return buf.toString(); } private void loadConnectionFactory(ActionRequest actionRequest, String adapterName, String factoryName, PoolData data) { ResourceAdapterModule adapter = (ResourceAdapterModule) PortletManager.getManagedBean(actionRequest, adapterName); JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(actionRequest, factoryName); data.adapterDisplayName = adapter.getDisplayName(); data.adapterDescription = adapter.getDescription(); try { ObjectName oname = ObjectName.getInstance(factoryName); data.name = oname.getKeyProperty("name"); if(data.isGeneric()) { data.url = (String) factory.getConfigProperty("connectionURL"); data.driverClass = (String) factory.getConfigProperty("driver"); data.user = (String) factory.getConfigProperty("userName"); data.password = (String) factory.getConfigProperty("password"); } else { ResourceAdapterParams params = getRARConfiguration(actionRequest, data.getRarPath(), data.getAdapterDisplayName(), adapterName); for(int i=0; i<params.getConfigParams().length; i++) { ConfigParam cp = params.getConfigParams()[i]; Object value = factory.getConfigProperty(cp.getName()); data.properties.put("property-"+cp.getName(), value == null ? null : value.toString()); } } } catch (Exception e) { log.error("Unable to look up connection property", e); } //todo: push the lookup into ManagementHelper PoolingAttributes pool = (PoolingAttributes) PortletManager.getManagedBean(actionRequest, factory.getConnectionManager()); data.minSize = Integer.toString(pool.getPartitionMinSize()); data.maxSize = Integer.toString(pool.getPartitionMaxSize()); data.blockingTimeout = Integer.toString(pool.getBlockingTimeoutMilliseconds()); data.idleTimeout = Integer.toString(pool.getIdleTimeoutMinutes()); } protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) { return; } try { String mode = renderRequest.getParameter(MODE_KEY); PoolData data = new PoolData(); data.load(renderRequest); renderRequest.setAttribute("pool", data); // If not headed anywhere in particular, send to list if(mode == null || mode.equals("")) { mode = LIST_MODE; } // If headed to list but there's an import in progress, redirect to import status if(mode.equals(LIST_MODE) && getImportStatus(renderRequest) != null) { mode = IMPORT_STATUS_MODE; } if(mode.equals(LIST_MODE)) { renderList(renderRequest, renderResponse); } else if(mode.equals(EDIT_MODE)) { renderEdit(renderRequest, renderResponse, data); } else if(mode.equals(SELECT_RDBMS_MODE)) { renderSelectRDBMS(renderRequest, renderResponse); } else if(mode.equals(DOWNLOAD_MODE)) { renderDownload(renderRequest, renderResponse); } else if(mode.equals(BASIC_PARAMS_MODE)) { renderBasicParams(renderRequest, renderResponse, data); } else if(mode.equals(CONFIRM_URL_MODE)) { renderConfirmURL(renderRequest, renderResponse); } else if(mode.equals(TEST_CONNECTION_MODE)) { renderTestConnection(renderRequest, renderResponse); } else if(mode.equals(SHOW_PLAN_MODE)) { renderPlan(renderRequest, renderResponse); } else if(mode.equals(IMPORT_START_MODE)) { renderImportUploadForm(renderRequest, renderResponse); } else if(mode.equals(IMPORT_STATUS_MODE)) { renderImportStatus(renderRequest, renderResponse); } else if(mode.equals(USAGE_MODE)) { renderUsage(renderRequest, renderResponse); } } catch (Throwable e) { log.error("Unable to render portlet", e); } } private void renderUsage(RenderRequest request, RenderResponse response) throws IOException, PortletException { usageView.include(request, response); } private void renderImportStatus(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("status", getImportStatus(request)); populatePoolList(request); importStatusView.include(request, response); } private void renderImportUploadForm(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("from", request.getParameter("from")); importUploadView.include(request, response); } private void renderList(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { populatePoolList(renderRequest); listView.include(renderRequest, renderResponse); } private void populatePoolList(PortletRequest renderRequest) { ResourceAdapterModule[] modules = PortletManager.getOutboundRAModules(renderRequest, "javax.sql.DataSource"); List list = new ArrayList(); for (int i = 0; i < modules.length; i++) { ResourceAdapterModule module = modules[i]; JCAManagedConnectionFactory[] databases = PortletManager.getOutboundFactoriesForRA(renderRequest, module, "javax.sql.DataSource"); for (int j = 0; j < databases.length; j++) { JCAManagedConnectionFactory db = databases[j]; try { ObjectName name = ObjectName.getInstance(db.getObjectName()); list.add(new ConnectionPool(ObjectName.getInstance(module.getObjectName()), db.getObjectName(), name.getKeyProperty(NameFactory.J2EE_NAME), ((GeronimoManagedBean)db).getState())); } catch (MalformedObjectNameException e) { e.printStackTrace(); } } } Collections.sort(list); renderRequest.setAttribute("pools", list); } private void renderEdit(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { if(data.objectName == null || data.objectName.equals("")) { loadDriverJARList(renderRequest); } if(!data.isGeneric()) { ResourceAdapterParams params = getRARConfiguration(renderRequest, data.getRarPath(), data.getAdapterDisplayName(), renderRequest.getParameter("adapterObjectName")); data.adapterDisplayName = params.getDisplayName(); data.adapterDescription = params.getDescription(); Map map = new HashMap(); boolean more = false; for (int i = 0; i < params.getConfigParams().length; i++) { ConfigParam param = params.getConfigParams()[i]; if(!data.properties.containsKey("property-"+param.getName())) { data.properties.put("property-"+param.getName(), param.getDefaultValue()); more = true; } map.put("property-"+param.getName(), param); } if(more) { data.loadPropertyNames(); } renderRequest.setAttribute("ConfigParams", map); } editView.include(renderRequest, renderResponse); } private void renderSelectRDBMS(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("databases", DatabaseInfo.ALL_DATABASES); selectRDBMSView.include(renderRequest, renderResponse); } private void renderDownload(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("drivers", getDriverInfo(renderRequest)); downloadView.include(renderRequest, renderResponse); } private void renderBasicParams(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { loadDriverJARList(renderRequest); // Make sure all properties available for the DB are listed DatabaseInfo info = getDatabaseInfo(data); if(info != null) { String[] params = info.getUrlParameters(); for (int i = 0; i < params.length; i++) { String param = params[i]; final String key = "urlproperty-"+param; if(!data.getUrlProperties().containsKey(key)) { data.getUrlProperties().put(key, param.equalsIgnoreCase("port") && info.getDefaultPort() > 0 ? new Integer(info.getDefaultPort()) : null); } } } // Pass on errors renderRequest.setAttribute("driverError", renderRequest.getParameter("driverError")); basicParamsView.include(renderRequest, renderResponse); } private void loadDriverJARList(RenderRequest renderRequest) { // List the available JARs List list = new ArrayList(); ListableRepository[] repos = PortletManager.getListableRepositories(renderRequest); for (int i = 0; i < repos.length; i++) { ListableRepository repo = repos[i]; try { final URI[] uris = repo.listURIs(); outer: for (int j = 0; j < uris.length; j++) { String test = uris[j].toString(); for (int k = 0; k < SKIP_ENTRIES_WITH.length; k++) { String skip = SKIP_ENTRIES_WITH[k]; if(test.indexOf(skip) > -1) { continue outer; } } list.add(test); } } catch (URISyntaxException e) { e.printStackTrace(); } } Collections.sort(list); renderRequest.setAttribute("jars", list); } private void renderConfirmURL(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { confirmURLView.include(renderRequest, renderResponse); } private void renderTestConnection(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("connectResult", renderRequest.getParameter("connectResult")); renderRequest.setAttribute("connectError", renderRequest.getPortletSession().getAttribute("connectError")); testConnectionView.include(renderRequest, renderResponse); } private void renderPlan(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("deploymentPlan", renderRequest.getPortletSession().getAttribute("deploymentPlan")); planView.include(renderRequest, renderResponse); } private static String attemptConnect(PortletRequest request, PoolData data) throws SQLException, IllegalAccessException, InstantiationException { Class driverClass = attemptDriverLoad(request, data); Driver driver = (Driver) driverClass.newInstance(); if(driver.acceptsURL(data.url)) { Properties props = new Properties(); props.put("user", data.user); props.put("password", data.password); Connection con = null; try { con = driver.connect(data.url, props); final DatabaseMetaData metaData = con.getMetaData(); return metaData.getDatabaseProductName()+" "+metaData.getDatabaseProductVersion(); } finally { if(con != null) try{con.close();}catch(SQLException e) {} } } else throw new SQLException("Driver "+data.getDriverClass()+" does not accept URL "+data.url); } private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) { ImportStatus status = getImportStatus(request); if(data.objectName == null || data.objectName.equals("")) { // we're creating a new pool data.name = data.name.replaceAll("\\s", ""); DeploymentManager mgr = PortletManager.getDeploymentManager(request); try { URL url = getRAR(request, data.getRarPath()); ConnectorDeployable deployable = new ConnectorDeployable(url); DeploymentConfiguration config = mgr.createConfiguration(deployable); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot); ConnectorDCB connector = (ConnectorDCB) root.getDConfigBean(ddBeanRoot.getChildBean(root.getXpaths()[0])[0]); connector.setConfigID("user/database-pool"+data.getName() + "/1/car"); connector.setParentID("geronimo/j2ee-server/1.0-SNAPSHOT/car"); if(data.jar1 != null && !data.jar1.equals("")) { Dependency dep = new Dependency(); connector.setDependency(new Dependency[]{dep}); dep.setURI(data.jar1); } if(data.jar2 != null && !data.jar2.equals("")) { Dependency dep = new Dependency(); Dependency[] old = connector.getDependency(); Dependency[] longer = new Dependency[old.length+1]; System.arraycopy(old, 0, longer, 0, old.length); longer[old.length] = dep; connector.setDependency(longer); dep.setURI(data.jar2); } if(data.jar3 != null && !data.jar3.equals("")) { Dependency dep = new Dependency(); Dependency[] old = connector.getDependency(); Dependency[] longer = new Dependency[old.length+1]; System.arraycopy(old, 0, longer, 0, old.length); longer[old.length] = dep; connector.setDependency(longer); dep.setURI(data.jar3); } ResourceAdapter adapter = connector.getResourceAdapter()[0]; ConnectionDefinition definition = new ConnectionDefinition(); adapter.setConnectionDefinition(new ConnectionDefinition[]{definition}); definition.setConnectionFactoryInterface("javax.sql.DataSource"); ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance(); definition.setConnectionInstance(new ConnectionDefinitionInstance[]{instance}); instance.setName(data.getName()); ConfigPropertySetting[] settings = instance.getConfigPropertySetting(); if(data.isGeneric()) { // it's a generic TranQL JDBC pool for (int i = 0; i < settings.length; i++) { ConfigPropertySetting setting = settings[i]; if(setting.getName().equals("UserName")) { setting.setValue(data.user); } else if(setting.getName().equals("Password")) { setting.setValue(data.password); } else if(setting.getName().equals("ConnectionURL")) { setting.setValue(data.url); } else if(setting.getName().equals("Driver")) { setting.setValue(data.driverClass); } } } else { // it's an XA driver or non-TranQL RA for (int i = 0; i < settings.length; i++) { ConfigPropertySetting setting = settings[i]; String value = (String) data.properties.get("property-"+setting.getName()); setting.setValue(value == null ? "" : value); } } ConnectionManager manager = instance.getConnectionManager(); manager.setTransactionLocal(true); SinglePool pool = new SinglePool(); manager.setPoolSingle(pool); pool.setMatchOne(true); if(data.minSize != null && !data.minSize.equals("")) { pool.setMinSize(new Integer(data.minSize)); } if(data.maxSize != null && !data.maxSize.equals("")) { pool.setMaxSize(new Integer(data.maxSize)); } if(data.blockingTimeout != null && !data.blockingTimeout.equals("")) { pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout)); } if(data.idleTimeout != null && !data.idleTimeout.equals("")) { pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout)); } if(planOnly) { ByteArrayOutputStream out = new ByteArrayOutputStream(); config.save(out); out.close(); return new String(out.toByteArray(), "US-ASCII"); } else { File tempFile = File.createTempFile("console-deployment",".xml"); tempFile.deleteOnExit(); log.debug("Writing database pool deployment plan to "+tempFile.getAbsolutePath()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); config.save(out); out.flush(); out.close(); Target[] targets = mgr.getTargets(); ProgressObject po = mgr.distribute(targets, new File(url.getPath()), tempFile); waitForProgress(po); if(po.getDeploymentStatus().isCompleted()) { TargetModuleID[] ids = po.getResultTargetModuleIDs(); po = mgr.start(ids); waitForProgress(po); if(po.getDeploymentStatus().isCompleted()) { ids = po.getResultTargetModuleIDs(); if(status != null) { status.getCurrentPool().setName(data.getName()); status.getCurrentPool().setConfigurationName(ids[0].getModuleID()); status.getCurrentPool().setFinished(true); response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } System.out.println("Deployment completed successfully!"); } } } } catch (Exception e) { log.error("Unable to save connection pool", e); } finally { if(mgr != null) mgr.release(); } } else { // We're saving updates to an existing pool if(planOnly) { throw new UnsupportedOperationException("Can't update a plan for an existing deployment"); } try { JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(request, data.getObjectName()); if(data.isGeneric()) { factory.setConfigProperty("connectionURL", data.getUrl()); factory.setConfigProperty("userName", data.getUser()); factory.setConfigProperty("password", data.getPassword()); } else { for (Iterator it = data.getProperties().entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); factory.setConfigProperty(((String) entry.getKey()).substring("property-".length()), entry.getValue()); } } //todo: push the lookup into ManagementHelper PoolingAttributes pool = (PoolingAttributes) PortletManager.getManagedBean(request, factory.getConnectionManager()); pool.setPartitionMinSize(data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize)); pool.setPartitionMaxSize(data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize)); pool.setBlockingTimeoutMilliseconds(data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000 : Integer.parseInt(data.blockingTimeout)); pool.setIdleTimeoutMinutes(data.idleTimeout == null || data.idleTimeout.equals("") ? 15 : Integer.parseInt(data.idleTimeout)); } catch (Exception e) { log.error("Unable to save connection pool", e); } } return null; } private static void waitForProgress(ProgressObject po) { while(po.getDeploymentStatus().isRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private static ImportStatus getImportStatus(PortletRequest request) { return (ImportStatus) request.getPortletSession(true).getAttribute("ImportStatus"); } private static URL getRAR(PortletRequest request, String rarPath) { try { URI uri = new URI(rarPath); Repository[] repos = PortletManager.getRepositories(request); for (int i = 0; i < repos.length; i++) { Repository repo = repos[i]; URL url = repo.getURL(uri); if(url != null && url.getProtocol().equals("file")) { File file = new File(url.getPath()); if(file.exists() && file.canRead() && !file.isDirectory()) { return url; } } } } catch (URISyntaxException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } /** * WARNING: This method relies on having access to the same repository * URLs as the server uses. */ private static Class attemptDriverLoad(PortletRequest request, PoolData data) { List list = new ArrayList(); try { URI one = data.getJar1() == null ? null : new URI(data.getJar1()); URI two = data.getJar2() == null ? null : new URI(data.getJar2()); URI three = data.getJar3() == null ? null : new URI(data.getJar3()); ListableRepository[] repos = PortletManager.getListableRepositories(request); for (int i = 0; i < repos.length; i++) { ListableRepository repo = repos[i]; if(one != null) { URL url = repo.getURL(one); if(url != null) { list.add(url); one = null; } } if(two != null) { URL url = repo.getURL(two); if(url != null) { list.add(url); two = null; } } if(three != null) { URL url = repo.getURL(three); if(url != null) { list.add(url); three = null; } } } URLClassLoader loader = new URLClassLoader((URL[]) list.toArray(new URL[list.size()]), DatabasePoolPortlet.class.getClassLoader()); try { return loader.loadClass(data.driverClass); } catch (ClassNotFoundException e) { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } private static String populateURL(String url, String[] keys, Map properties) { for (int i = 0; i < keys.length; i++) { String key = keys[i]; String value = (String) properties.get("urlproperty-"+key); if(value == null || value.equals("")) { int begin = url.indexOf("<"+key+">"); int end = begin + key.length() + 2; for(int j=begin-1; j>=0; j--) { char c = url.charAt(j); if(c == ';' || c == ':') { begin = j; break; } else if(c == '/') { if(url.length() > end && url.charAt(end) == '/') { begin = j; // Don't leave // if foo is null for /<foo>/ } break; } } url = url.substring(0, begin)+url.substring(end); } else { url = url.replaceAll("<"+key+">", value); } } return url; } private static DatabaseInfo getDatabaseInfo(PoolData data) { DatabaseInfo info = null; for (int i = 0; i < DatabaseInfo.ALL_DATABASES.length; i++) { DatabaseInfo next = DatabaseInfo.ALL_DATABASES[i]; if(next.getName().equals(data.getDbtype())) { info = next; break; } } return info; } private static DatabaseInfo getDatabaseInfoFromDriver(PoolData data) { DatabaseInfo info = null; for (int i = 0; i < DatabaseInfo.ALL_DATABASES.length; i++) { DatabaseInfo next = DatabaseInfo.ALL_DATABASES[i]; if(next.getDriverClass() != null && next.getDriverClass().equals(data.getDriverClass())) { info = next; break; } } return info; } public static class PoolData implements Serializable { private String name; private String dbtype; private String user; private String password; private Map properties = new HashMap(); // Configuration for non-Generic drivers private Map urlProperties = new HashMap(); // URL substitution for Generic drivers private Map propertyNames; //todo: store these in the ConfigParam instead private String driverClass; private String url; private String urlPrototype; private String jar1; private String jar2; private String jar3; private String minSize; private String maxSize; private String blockingTimeout; private String idleTimeout; private String objectName; private String adapterDisplayName; private String adapterDescription; private String rarPath; private String importSource; private Map objectNameMap; // generated as needed, don't need to read/write it public void load(PortletRequest request) { name = request.getParameter("name"); if(name != null && name.equals("")) name = null; driverClass = request.getParameter("driverClass"); if(driverClass != null && driverClass.equals("")) driverClass = null; dbtype = request.getParameter("dbtype"); if(dbtype != null && dbtype.equals("")) dbtype = null; user = request.getParameter("user"); if(user != null && user.equals("")) user = null; password = request.getParameter("password"); if(password != null && password.equals("")) password = null; url = request.getParameter("url"); if(url != null && url.equals("")) url = null; urlPrototype = request.getParameter("urlPrototype"); if(urlPrototype != null && urlPrototype.equals("")) urlPrototype = null; jar1 = request.getParameter("jar1"); if(jar1 != null && jar1.equals("")) jar1 = null; jar2 = request.getParameter("jar2"); if(jar2 != null && jar2.equals("")) jar2 = null; jar3 = request.getParameter("jar3"); if(jar3 != null && jar3.equals("")) jar3 = null; minSize = request.getParameter("minSize"); if(minSize != null && minSize.equals("")) minSize = null; maxSize = request.getParameter("maxSize"); if(maxSize != null && maxSize.equals("")) maxSize = null; blockingTimeout = request.getParameter("blockingTimeout"); if(blockingTimeout != null && blockingTimeout.equals("")) blockingTimeout = null; idleTimeout = request.getParameter("idleTimeout"); if(idleTimeout != null && idleTimeout.equals("")) idleTimeout = null; objectName = request.getParameter("objectName"); if(objectName != null && objectName.equals("")) objectName = null; adapterDisplayName = request.getParameter("adapterDisplayName"); if(adapterDisplayName != null && adapterDisplayName.equals("")) adapterDisplayName = null; adapterDescription = request.getParameter("adapterDescription"); if(adapterDescription != null && adapterDescription.equals("")) adapterDescription = null; rarPath = request.getParameter("rarPath"); if(rarPath != null && rarPath.equals("")) rarPath = null; importSource = request.getParameter("importSource"); if(importSource != null && importSource.equals("")) importSource = null; Map map = request.getParameterMap(); propertyNames = new HashMap(); for (Iterator it = map.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); if(key.startsWith("urlproperty-")) { urlProperties.put(key, request.getParameter(key)); } else if(key.startsWith("property-")) { properties.put(key, request.getParameter(key)); propertyNames.put(key, getPropertyName(key)); } } } public void loadPropertyNames() { propertyNames = new HashMap(); for (Iterator it = properties.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); propertyNames.put(key, getPropertyName(key)); } } private static String getPropertyName(String key) { int pos = key.indexOf('-'); key = Character.toUpperCase(key.charAt(pos+1))+key.substring(pos+2); StringBuffer buf = new StringBuffer(); pos = 0; for(int i=1; i<key.length(); i++) { if(Character.isUpperCase(key.charAt(i))) { if(Character.isUpperCase(key.charAt(i-1))) { // ongoing capitalized word } else { // start of a new word buf.append(key.substring(pos, i)).append(" "); pos = i; } } else { if(Character.isUpperCase(key.charAt(i-1)) && i-pos > 1) { // first lower-case after a series of caps buf.append(key.substring(pos, i-1)).append(" "); pos = i-1; } } } buf.append(key.substring(pos)); return buf.toString(); } public void store(ActionResponse response) { if(name != null) response.setRenderParameter("name", name); if(dbtype != null) response.setRenderParameter("dbtype", dbtype); if(driverClass != null) response.setRenderParameter("driverClass", driverClass); if(user != null) response.setRenderParameter("user", user); if(password != null) response.setRenderParameter("password", password); if(url != null) response.setRenderParameter("url", url); if(urlPrototype != null) response.setRenderParameter("urlPrototype", urlPrototype); if(jar1 != null) response.setRenderParameter("jar1", jar1); if(jar2 != null) response.setRenderParameter("jar2", jar2); if(jar3 != null) response.setRenderParameter("jar3", jar3); if(minSize != null) response.setRenderParameter("minSize", minSize); if(maxSize != null) response.setRenderParameter("maxSize", maxSize); if(blockingTimeout != null) response.setRenderParameter("blockingTimeout", blockingTimeout); if(idleTimeout != null) response.setRenderParameter("idleTimeout", idleTimeout); if(objectName != null) response.setRenderParameter("objectName", objectName); if(adapterDisplayName != null) response.setRenderParameter("adapterDisplayName", adapterDisplayName); if(adapterDescription != null) response.setRenderParameter("adapterDescription", adapterDescription); if(importSource != null) response.setRenderParameter("importSource", importSource); if(rarPath != null) response.setRenderParameter("rarPath", rarPath); for (Iterator it = urlProperties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); if(entry.getValue() != null) { response.setRenderParameter((String)entry.getKey(), (String)entry.getValue()); } } for (Iterator it = properties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); if(entry.getValue() != null) { response.setRenderParameter((String)entry.getKey(), (String)entry.getValue()); } } } public String getName() { return name; } public String getDbtype() { return dbtype; } public String getUser() { return user; } public String getPassword() { return password; } public Map getProperties() { return properties; } public Map getPropertyNames() { return propertyNames; } public Map getUrlProperties() { return urlProperties; } public String getUrl() { return url; } public String getJar1() { return jar1; } public String getJar2() { return jar2; } public String getJar3() { return jar3; } public String getMinSize() { return minSize; } public String getMaxSize() { return maxSize; } public String getBlockingTimeout() { return blockingTimeout; } public String getIdleTimeout() { return idleTimeout; } public String getDriverClass() { return driverClass; } public String getUrlPrototype() { return urlPrototype; } public String getObjectName() { return objectName; } public String getAdapterDisplayName() { return adapterDisplayName; } public String getAdapterDescription() { return adapterDescription; } public String getRarPath() { return rarPath; } public boolean isGeneric() { //todo: is there any better way to tell? return adapterDisplayName == null || adapterDisplayName.equals("TranQL Generic JDBC Resource Adapter"); } public String getImportSource() { return importSource; } public Map getObjectNameMap() { if(objectName == null) return Collections.EMPTY_MAP; if(objectNameMap != null) return objectNameMap; try { ObjectName name = new ObjectName(objectName); objectNameMap = new HashMap(name.getKeyPropertyList()); objectNameMap.put("domain", name.getDomain()); return objectNameMap; } catch (MalformedObjectNameException e) { return Collections.EMPTY_MAP; } } } public static class ConnectionPool implements Serializable, Comparable { private final String adapterObjectName; private final String factoryObjectName; private final String name; private final String parentName; private final int state; public ConnectionPool(ObjectName adapterObjectName, String factoryObjectName, String name, int state) { this.adapterObjectName = adapterObjectName.getCanonicalName(); String parent = adapterObjectName.getKeyProperty(NameFactory.J2EE_APPLICATION); if(parent != null && parent.equals("null")) { parent = null; } parentName = parent; this.factoryObjectName = factoryObjectName; this.name = name; this.state = state; } public String getAdapterObjectName() { return adapterObjectName; } public String getFactoryObjectName() { return factoryObjectName; } public String getName() { return name; } public String getParentName() { return parentName; } public int getState() { return state; } public String getStateName() { return State.toString(state); } public int compareTo(Object o) { final ConnectionPool pool = (ConnectionPool)o; int names = name.compareTo(pool.name); if(parentName == null) { if(pool.parentName == null) { return names; } else { return -1; } } else { if(pool.parentName == null) { return 1; } else { int test = parentName.compareTo(pool.parentName); if(test != 0) { return test; } else { return names; } } } } } public static class ResourceAdapterParams { private String displayName; private String description; private ConfigParam[] configParams; public ResourceAdapterParams(String displayName, String description, ConfigParam[] configParams) { this.displayName = displayName; this.description = description; this.configParams = configParams; } public String getDisplayName() { return displayName; } public String getDescription() { return description; } public ConfigParam[] getConfigParams() { return configParams; } } public static class ConfigParam { private String name; private String type; private String description; private String defaultValue; public ConfigParam(String name, String type, String description, String defaultValue) { this.name = name; this.type = type; this.description = description; this.defaultValue = defaultValue; } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } public String getDefaultValue() { return defaultValue; } } }
Changed processing order for the max / min pool sizes in the DatabaseWizardPortlet git-svn-id: d69ffe4ccc4861bf06065bd0072b85c931fba7ed@356391 13f79535-47bb-0310-9956-ffa450edef68
applications/console-standard/src/java/org/apache/geronimo/console/databasemanager/wizard/DatabasePoolPortlet.java
Changed processing order for the max / min pool sizes in the DatabaseWizardPortlet
<ide><path>pplications/console-standard/src/java/org/apache/geronimo/console/databasemanager/wizard/DatabasePoolPortlet.java <ide> SinglePool pool = new SinglePool(); <ide> manager.setPoolSingle(pool); <ide> pool.setMatchOne(true); <add> // Max Size needs to be set before the minimum. This is because <add> // the connection manager will constrain the minimum based on the <add> // current maximum value in the pool. We might consider adding a <add> // setPoolConstraints method to allow specifying both at the same time. <add> if(data.maxSize != null && !data.maxSize.equals("")) { <add> pool.setMaxSize(new Integer(data.maxSize)); <add> } <ide> if(data.minSize != null && !data.minSize.equals("")) { <ide> pool.setMinSize(new Integer(data.minSize)); <del> } <del> if(data.maxSize != null && !data.maxSize.equals("")) { <del> pool.setMaxSize(new Integer(data.maxSize)); <ide> } <ide> if(data.blockingTimeout != null && !data.blockingTimeout.equals("")) { <ide> pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout));
Java
bsd-2-clause
25dc020a29b7f40124f58ce872017f7f6e10fb11
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
/* * Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the * names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package com.jme.input; import java.util.logging.Level; import com.jme.util.LoggingSystem; /** * <code>InputSystem</code> creates the required input objects (mouse and * keyboard) depending on the API desired for the handling of the input. This * will allow the client application to only deal with <code>KeyInput</code> * and <code>MouseInput</code> not having to worry about the API specifics. * @see com.jme.input.KeyInput * @see com.jme.input.MouseInput * @author Mark Powell * @version $Id: InputSystem.java,v 1.2 2003-10-26 17:48:56 mojomonkey Exp $ */ public class InputSystem { //the input devices. private static KeyInput keyInput; private static MouseInput mouseInput; /** * * <code>createInputSystem</code> initializes the input devices using the * provided API string. * @param system the input API to use, e.g. "LWJGL" or "JInput". */ public static void createInputSystem(String system) { if ("LWJGL".equalsIgnoreCase(system)) { keyInput = new LWJGLKeyInput(); mouseInput = new LWJGLMouseInput(); } } /** * * <code>getKeyInput</code> retrieves the key input device. * @return the key input device. */ public static KeyInput getKeyInput() { if (keyInput == null) { LoggingSystem.getLogger().log( Level.WARNING, "KeyInput is null," + " insure that a call to createInputSystem was made before" + " getting the devices."); } return keyInput; } /** * * <code>getMouseInput</code> retrieves the mouse input device. * @return the mouse input device. */ public static MouseInput getMouseInput() { if (mouseInput == null) { LoggingSystem.getLogger().log( Level.WARNING, "MouseInput is null," + " insure that a call to createInputSystem was made before" + " getting the devices."); } return mouseInput; } }
src/com/jme/input/InputSystem.java
/* * Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the * names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package com.jme.input; import java.util.logging.Level; import com.jme.util.LoggingSystem; /** * <code>InputSystem</code> creates the required input objects (mouse and * keyboard) depending on the API desired for the handling of the input. This * will allow the client application to only deal with <code>KeyInput</code> * and <code>MouseInput</code> not having to worry about the API specifics. * @see com.jme.input.KeyInput * @see com.jme.input.MouseInput * @author Mark Powell * @version $Id: InputSystem.java,v 1.1 2003-10-23 21:24:18 mojomonkey Exp $ */ public class InputSystem { //the input devices. private static KeyInput keyInput; private static MouseInput mouseInput; /** * * <code>createInputSystem</code> initializes the input devices using the * provided API string. * @param system the input API to use, e.g. "LWJGL" or "JInput". */ public static void createInputSystem(String system) { if ("LWJGL".equalsIgnoreCase(system)) { keyInput = new LWJGLKeyInput(); mouseInput = new LWJGLMouseInput(); } } /** * * <code>getKeyInput</code> retrieves the key input device. * @return the key input device. */ public static KeyInput getKeyInput() { if (keyInput == null) { LoggingSystem.getLogger().log( Level.WARNING, "KeyInput is null," + " insure that a call to createInputSystem was made before" + " getting the devices."); } return keyInput; } /** * * <code>getMouseInput</code> retrieves the mouse input device. * @return the mouse input device. */ public static MouseInput getMouseInput() { if (keyInput == null) { LoggingSystem.getLogger().log( Level.WARNING, "MouseInput is null," + " insure that a call to createInputSystem was made before" + " getting the devices."); } return mouseInput; } }
Fixed bug where checking null of keyboard rather than mouse for getMouseInput. git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@113 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/com/jme/input/InputSystem.java
Fixed bug where checking null of keyboard rather than mouse for getMouseInput.
<ide><path>rc/com/jme/input/InputSystem.java <ide> * @see com.jme.input.KeyInput <ide> * @see com.jme.input.MouseInput <ide> * @author Mark Powell <del> * @version $Id: InputSystem.java,v 1.1 2003-10-23 21:24:18 mojomonkey Exp $ <add> * @version $Id: InputSystem.java,v 1.2 2003-10-26 17:48:56 mojomonkey Exp $ <ide> */ <ide> public class InputSystem { <ide> //the input devices. <ide> * @return the mouse input device. <ide> */ <ide> public static MouseInput getMouseInput() { <del> if (keyInput == null) { <add> if (mouseInput == null) { <ide> LoggingSystem.getLogger().log( <ide> Level.WARNING, <ide> "MouseInput is null,"
Java
mit
e685b4d5d1073a3f6a59698410419b8adc7943b2
0
mrunde/Bachelor-Thesis,mrunde/Bachelor-Thesis
package de.mrunde.bachelorthesis.activities; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Locale; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.graphics.Color; import android.graphics.Paint; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.mapquest.android.maps.DefaultItemizedOverlay; import com.mapquest.android.maps.GeoPoint; import com.mapquest.android.maps.LineOverlay; import com.mapquest.android.maps.MapActivity; import com.mapquest.android.maps.MapView; import com.mapquest.android.maps.MyLocationOverlay; import com.mapquest.android.maps.OverlayItem; import com.mapquest.android.maps.RouteManager; import com.mapquest.android.maps.RouteResponse; import de.mrunde.bachelorthesis.R; import de.mrunde.bachelorthesis.basics.Landmark; import de.mrunde.bachelorthesis.basics.LandmarkCategory; import de.mrunde.bachelorthesis.basics.Maneuver; import de.mrunde.bachelorthesis.instructions.GlobalInstruction; import de.mrunde.bachelorthesis.instructions.Instruction; import de.mrunde.bachelorthesis.instructions.InstructionManager; import de.mrunde.bachelorthesis.instructions.LandmarkInstruction; /** * This is the navigational activity which is started by the MainActivity. It * navigates the user from his current location to the desired destination. * * @author Marius Runde */ public class NaviActivity extends MapActivity implements OnInitListener, LocationListener { // --- The indexes of the overlays --- /** * Index of the local landmark overlay */ private final int INDEX_OF_LANDMARK_OVERLAY = 3; // --- End of indexes --- // --- The graphical user interface (GUI) --- /** * Instruction view (verbal) */ private TextView tv_instruction; /** * Instruction view (image) */ private ImageView iv_instruction; /** * Map view */ private MapView map; /** * An overlay to display the user's location */ private MyLocationOverlay myLocationOverlay; // --- End of GUI --- // --- The route and instruction objects --- /** * Current location as String (for RouteManager only!) */ private String str_currentLocation; /** * Destination as String (for RouteManager and as title of destination * overlay) */ private String str_destination; /** * Latitude of the destination */ private double destination_lat; /** * Longitude of the destination */ private double destination_lng; /** * Route manager for route calculation */ private RouteManager rm; /** * Route options (already formatted as a String) */ private String routeOptions; /** * Instruction manager that creates instructions */ private InstructionManager im; /** * Location manager to monitor the user's location */ private LocationManager lm; /** * Location provider of the LocationManager */ private String provider; /** * Minimum distance for a route segment to use a NowInstruction */ private final int MIN_DISTANCE_FOR_NOW_INSTRUCTION = 1000; /** * The NowInstruction will be returned at this distance before reaching the * next decision point */ private final int DISTANCE_FOR_NOW_INSTRUCTION = 100; /** * Variable to control if the usage of a NowInstruction has been checked */ private boolean nowInstructionChecked = false; /** * Variable to control if a NowInstruction will be used */ private boolean nowInstructionUsed = false; /** * Maximum distance to a decision point when it is supposed to be reached */ private final int MAX_DISTANCE_TO_DECISION_POINT = 20; /** * Store the last distance between the next decision point and the current * location. Is set to 0 when the instruction is updated. */ private double lastDistanceDP1 = 0; /** * Store the last distance between the decision point after next and the * current location. Is set to 0 when the instruction is updated. */ private double lastDistanceDP2 = 0; /** * Counts the distance changes between the next decision point, the decision * point after next and the current location. Is set to 0 after the * instruction has been updated. The instruction is updated when the counter * reaches its maximum negative value (<code>(-1) * MAX_COUNTER_VALUE</code> * ) or the next decision point has been reached. If the counter reaches the * maximum positive value (<code>MAX_COUNTER_VALUE</code>), the whole * guidance will be updated. */ private int distanceCounter = 0; /** * Maximum value for the <code>distanceCounter</code>. */ private final int MAX_COUNTER_VALUE = 5; // --- End of route and instruction objects --- /** * TextToSpeech for audio output */ private TextToSpeech tts; /** * This method is called when the application has been started */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.navi); // Get the route information from the intent Intent intent = getIntent(); this.str_currentLocation = intent.getStringExtra("str_currentLocation"); this.str_destination = intent.getStringExtra("str_destination"); this.destination_lat = intent.getDoubleExtra("destination_lat", 0.0); this.destination_lng = intent.getDoubleExtra("destination_lng", 0.0); this.routeOptions = intent.getStringExtra("routeOptions"); // Initialize the TextToSpeech tts = new TextToSpeech(this, this); // Initialize the LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Choose the location provider Criteria criteria = new Criteria(); provider = lm.getBestProvider(criteria, false); Location location = lm.getLastKnownLocation(provider); if (location != null) { Log.e("Test", "Provider " + provider + " has been selected."); onLocationChanged(location); } else { Log.e("Test", "Location not available"); } // Setup the whole GUI and map setupGUI(); setupMapView(); setupMyLocation(); // Add the destination overlay to the map addDestinationOverlay(destination_lat, destination_lng); // Calculate the route calculateRoute(); // Get the guidance information and create the instructions getGuidance(); } /** * Set up the GUI */ private void setupGUI() { this.tv_instruction = (TextView) findViewById(R.id.tv_instruction); this.iv_instruction = (ImageView) findViewById(R.id.iv_instruction); } /** * Set up the map and disable user interaction */ private void setupMapView() { this.map = (MapView) findViewById(R.id.map); map.setBuiltInZoomControls(false); map.setClickable(true); map.setLongClickable(true); } /** * Set up a MyLocationOverlay and execute the runnable once a location has * been fixed */ private void setupMyLocation() { // Check if the GPS is enabled if (!((LocationManager) getSystemService(LOCATION_SERVICE)) .isProviderEnabled(LocationManager.GPS_PROVIDER)) { // Open dialog to inform the user that the GPS is disabled AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.gpsDisabled)); builder.setCancelable(false); builder.setPositiveButton(R.string.openSettings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Open the location settings if it is disabled Intent intent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Dismiss the dialog dialog.cancel(); } }); // Display the dialog AlertDialog dialog = builder.create(); dialog.show(); } // Set up the myLocationOverlay this.myLocationOverlay = new MyLocationOverlay(this, map); myLocationOverlay.enableMyLocation(); myLocationOverlay.setMarker( getResources().getDrawable(R.drawable.my_location), 0); myLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { GeoPoint currentLocation = myLocationOverlay.getMyLocation(); map.getController().animateTo(currentLocation); map.getController().setZoom(18); map.getOverlays().add(myLocationOverlay); myLocationOverlay.setFollowing(true); } }); } /** * Add the destination overlay to the map * * @param lat * Latitude of the destination * @param lng * Longitude of the destination */ private void addDestinationOverlay(double lat, double lng) { // Create a GeoPoint object of the destination GeoPoint destination = new GeoPoint(lat, lng); // Create the destination overlay OverlayItem oi_destination = new OverlayItem(destination, "Destination", str_destination); final DefaultItemizedOverlay destinationOverlay = new DefaultItemizedOverlay( getResources().getDrawable(R.drawable.destination_flag)); destinationOverlay.addItem(oi_destination); // Add the overlay to the map map.getOverlays().add(destinationOverlay); } /** * Calculate the route from the current location to the destination */ private void calculateRoute() { // Clear the previous route first if (rm != null) { rm.clearRoute(); } // Initialize a new RouteManager to calculate the route rm = new RouteManager(getBaseContext(), getResources().getString( R.string.apiKey)); // Set the route options (e.g. route type) rm.setOptions(routeOptions); // Set route callback rm.setRouteCallback(new RouteManager.RouteCallback() { @Override public void onSuccess(RouteResponse response) { // Route has been calculated successfully Log.i("NaviActivity", getResources().getString(R.string.routeCalculated)); } @Override public void onError(RouteResponse response) { // Route could not be calculated Log.e("NaviActivity", getResources().getString(R.string.routeNotCalculated)); } }); // Calculate the route and display it on the map rm.createRoute(str_currentLocation, str_destination); // Zoom to current location map.getController().animateTo(myLocationOverlay.getMyLocation()); map.getController().setZoom(18); } /** * Get the guidance information from MapQuest */ private void getGuidance() { // Create the URL to request the guidance from MapQuest String url; try { url = "https://open.mapquestapi.com/guidance/v1/route?key=" + getResources().getString(R.string.apiKey) + "&from=" + URLEncoder.encode(str_currentLocation, "UTF-8") + "&to=" + URLEncoder.encode(str_destination, "UTF-8") + "&narrativeType=text&fishbone=false&callback=renderBasicInformation"; } catch (UnsupportedEncodingException e) { Log.e("NaviActivity", "Could not encode the URL. This is the error message: " + e.getMessage()); return; } // Get the data. The instructions are created afterwards. GetJsonTask jsonTask = new GetJsonTask(); jsonTask.execute(url); } /** * This is a class to get the JSON file asynchronously from the given URL. * * @author Marius Runde */ private class GetJsonTask extends AsyncTask<String, Void, JSONObject> { /** * Progress dialog to inform the user about the download */ private ProgressDialog progressDialog = new ProgressDialog( NaviActivity.this); /** * Count the time needed for the data download */ private int downloadTimer; @Override protected void onPreExecute() { // Display progress dialog progressDialog.setMessage("Downloading guidance..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // Cancel the download when the "Cancel" button has been // clicked GetJsonTask.this.cancel(true); } }); // Set timer to current time downloadTimer = Calendar.getInstance().get(Calendar.SECOND); } @Override protected JSONObject doInBackground(String... url) { // Get the data from the URL String output = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; try { response = httpclient.execute(new HttpGet(url[0])); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); output = out.toString(); } else { // Close the connection response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (Exception e) { Log.e("GetJsonTask", "Could not get the data. This is the error message: " + e.getMessage()); return null; } // Delete the "renderBasicInformation" stuff at the beginning and // end of the output if needed to convert it to a JSONObject if (output.startsWith("renderBasicInformation(")) { output = output.substring(23, output.length()); } if (output.endsWith(");")) { output = output.substring(0, output.length() - 2); } // Convert the output to a JSONObject try { JSONObject result = new JSONObject(output); return result; } catch (JSONException e) { Log.e("GetJsonTask", "Could not convert output to JSONObject. This is the error message: " + e.getMessage()); return null; } } @Override protected void onPostExecute(JSONObject result) { // Dismiss progress dialog progressDialog.dismiss(); // Write the time needed for the download into the log downloadTimer = Calendar.getInstance().get(Calendar.SECOND) - downloadTimer; Log.i("GetJsonTask", "Completed guidance download in " + downloadTimer + " seconds"); // Check if the download was successful if (result == null) { // Could not receive the JSON Toast.makeText(NaviActivity.this, getResources().getString(R.string.routeNotCalculated), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } else { // Create the instructions createInstructions(result); // Draw the route and display the first instruction drawRoute(result); } } } /** * Create the instructions for the navigation * * @param guidance * The guidance information from MapQuest */ private void createInstructions(JSONObject guidance) { // Load the landmarks as a JSONObject from res/raw/landmarks.json InputStream is = getResources().openRawResource(R.raw.landmarks); JSONObject landmarks = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); landmarks = new JSONObject(rawJson); } catch (Exception e) { // Could not load landmarks Log.e("NaviActivity", "Could not load landmarks. This is the error message: " + e.getMessage()); } // Load the street furniture as a JSONArray from // res/raw/streetfurniture.json is = getResources().openRawResource(R.raw.streetfurniture); JSONArray streetFurniture = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); streetFurniture = new JSONArray(rawJson); } catch (Exception e) { // Could not load street furniture Log.e("NaviActivity", "Could not load street furniture. This is the error message: " + e.getMessage()); } // Load the intersections as a JSONArray from res/raw/intersections.json is = getResources().openRawResource(R.raw.intersections); JSONArray intersections = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); intersections = new JSONArray(rawJson); } catch (Exception e) { // Could not load intersections Log.e("NaviActivity", "Could not load intersections. This is the error message: " + e.getMessage()); } // Create the instruction manager im = new InstructionManager(guidance, landmarks, streetFurniture, intersections); // Check if the import was successful if (im.isImportSuccessful()) { // Create the instructions im.createInstructions(); } else { // Import was not successful Toast.makeText(this, getResources().getString(R.string.jsonImportNotSuccessful), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } } /** * Draw the route with the given shapePoints from the guidance information * * @param json * The guidance information from MapQuest */ private void drawRoute(JSONObject json) { // Set custom line style Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); // Initialize the route overlay List<GeoPoint> shapePoints = new ArrayList<GeoPoint>( Arrays.asList(this.im.getShapePoints())); LineOverlay drawnRoute = new LineOverlay(paint); drawnRoute.setData(shapePoints); // Add the drawn route to the map map.getOverlays().add(drawnRoute); Log.d("NaviActivity", "Route overlay added"); if (!im.isImportSuccessful()) { // Import was not successful Toast.makeText(NaviActivity.this, getResources().getString(R.string.jsonImportNotSuccessful), Toast.LENGTH_SHORT).show(); // Finish the activity to return to the MainActivity finish(); } else { do { // Route is not displayed yet } while (!this.isRouteDisplayed()); // Toast.makeText(NaviActivity.this, // getResources().getString(R.string.routeNotDisplayed), // Toast.LENGTH_SHORT).show(); // // Finish the activity to return to the MainActivity // finish(); // } else { // Get the first instruction and display it displayInstruction(im.getInstruction(0)); } } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.closeActivity_title) .setMessage(R.string.closeActivity_message) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setNegativeButton("No", null).show(); } @Override protected boolean isRouteDisplayed() { if (this.map.getOverlays().size() > 1) { return true; } else { return false; } } /** * Called when the OptionsMenu is created */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.navi, menu); return true; } /** * Called when an item of the OptionsMenu is clicked */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_allInstructions: // Create an array of all verbal instructions String[] allInstructions = im.getVerbalInstructions(); // Display all instructions in a list AlertDialog.Builder builder = new AlertDialog.Builder( NaviActivity.this); builder.setTitle(R.string.allInstructions); builder.setItems(allInstructions, null); AlertDialog alertDialog = builder.create(); alertDialog.show(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { // Enable features of the MyLocationOverlay myLocationOverlay.enableMyLocation(); // Request location updates at startup every 500ms for changes of 1m lm.requestLocationUpdates(provider, 500, 1, this); super.onResume(); } @Override protected void onPause() { super.onPause(); // Disable features of the MyLocationOverlay when in the background myLocationOverlay.disableMyLocation(); // Disable the LocationManager when in the background lm.removeUpdates(this); } @Override public void onInit(int status) { // Initialize the TextToSpeech engine if (status == TextToSpeech.SUCCESS) { tts.setLanguage(Locale.ENGLISH); } else { tts = null; Log.e("MainActivity", "Failed to initialize the TextToSpeech engine"); } } @Override public void onLocationChanged(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); // Check if the instruction manager has been initialized already if (im != null) { // Get the coordinates of the next decision point double dp1Lat = im.getCurrentInstruction().getDecisionPoint() .getLatitude(); double dp1Lng = im.getCurrentInstruction().getDecisionPoint() .getLongitude(); // Get the coordinates of the decision point after next double dp2Lat = im.getNextInstructionLocation().getLatitude(); double dp2Lng = im.getNextInstructionLocation().getLongitude(); // Calculate the distance to the next decision point float[] results = new float[1]; Location.distanceBetween(lat, lng, dp1Lat, dp1Lng, results); double distanceDP1 = results[0]; // Check whether a now instruction must be used (only once for each // route segment) if (nowInstructionChecked == false && distanceDP1 >= MIN_DISTANCE_FOR_NOW_INSTRUCTION) { nowInstructionUsed = true; } nowInstructionChecked = true; // Calculate the distance to the decision point after next Location.distanceBetween(lat, lng, dp2Lat, dp2Lng, results); double distanceDP2 = results[0]; // Check the distances with the stored ones if (distanceDP1 < MAX_DISTANCE_TO_DECISION_POINT) { // Distance to decision point is less than 20m so the // instruction is being updated updateInstruction(); } else if (distanceDP1 < DISTANCE_FOR_NOW_INSTRUCTION && nowInstructionUsed == true) { // Distance to updateNowInstruction(); } else if (distanceDP1 > lastDistanceDP1 && distanceDP2 < lastDistanceDP2) { // The distance to the next decision point has increased and the // distance to the decision point after next has decreased lastDistanceDP1 = distanceDP1; lastDistanceDP2 = distanceDP2; distanceCounter++; Log.v("NaviActivity.onLocationChanged", "distanceCounter: " + distanceCounter); } else if (distanceDP1 > lastDistanceDP1 && distanceDP2 > lastDistanceDP2) { // Distance to the next decision point and the decision point // after next has increased (can lead to a driving error) lastDistanceDP1 = distanceDP1; lastDistanceDP2 = distanceDP2; distanceCounter--; Log.v("NaviActivity.onLocationChanged", "distanceIncreaseCounter: " + distanceCounter); } // Check if the whole guidance needs to be reloaded due to a driving // error (user seems to go away from both the decision point and the // decision point after next) if (distanceCounter < (-1 * MAX_COUNTER_VALUE)) { updateGuidance(); } // Check if the instruction needs to be updated if (distanceCounter > MAX_COUNTER_VALUE) { updateInstruction(); } } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Do nothing here } @Override public void onProviderEnabled(String provider) { // Do nothing here } @Override public void onProviderDisabled(String provider) { // Do nothing here } /** * Called when the next decision point has been reached to update the * current instruction to the following instruction. */ private void updateInstruction() { Log.i("NaviActivity", "Updating Instruction..."); // Reset the distances, their counters, and the NowInstruction // controllers lastDistanceDP1 = 0; lastDistanceDP2 = 0; distanceCounter = 0; nowInstructionChecked = false; nowInstructionUsed = false; // Get the next instruction and display it Instruction nextInstruction = im.getNextInstruction(); displayInstruction(nextInstruction); } /** * Called when a new instruction shall be displayed. Also the map is being * updated so that the old landmarks are removed and the new ones are * displayed. * * @param instruction * The instruction to be displayed */ private void displayInstruction(Instruction instruction) { // --- Update the instruction view --- // Get the next verbal instruction String nextVerbalInstruction = instruction.toString(); // Display the verbal instruction this.tv_instruction.setText(nextVerbalInstruction); // Get the corresponding instruction image and display it this.iv_instruction.setImageDrawable(getResources().getDrawable( Maneuver.getDrawableId(instruction.getManeuverType()))); // --- Update the landmarks on the map (if available) --- // Remove previous landmark (if available) if (this.map.getOverlays().size() > this.INDEX_OF_LANDMARK_OVERLAY) { this.map.getOverlays().remove(this.INDEX_OF_LANDMARK_OVERLAY); } // Add new local landmark (if available) if (instruction.getClass().equals(LandmarkInstruction.class)) { Landmark newLocalLandmark = ((LandmarkInstruction) instruction) .getLocal(); OverlayItem oi_newLocalLandmark = new OverlayItem( newLocalLandmark.getCenter(), newLocalLandmark.getTitle(), newLocalLandmark.getCategory()); DefaultItemizedOverlay newLocalLandmarkOverlay = new DefaultItemizedOverlay( getResources().getDrawable( LandmarkCategory.getDrawableId(newLocalLandmark .getCategory()))); newLocalLandmarkOverlay.addItem(oi_newLocalLandmark); this.map.getOverlays().add(this.INDEX_OF_LANDMARK_OVERLAY, newLocalLandmarkOverlay); } // Add new global landmark (if available) if (instruction.getClass().equals(GlobalInstruction.class)) { Landmark newGlobalLandmark = ((GlobalInstruction) instruction) .getGlobal(); OverlayItem oi_newGlobalLandmark = new OverlayItem( newGlobalLandmark.getCenter(), newGlobalLandmark.getTitle(), newGlobalLandmark.getCategory()); DefaultItemizedOverlay newGlobalLandmarkOverlay = new DefaultItemizedOverlay( getResources().getDrawable( LandmarkCategory.getDrawableId(newGlobalLandmark .getCategory()))); newGlobalLandmarkOverlay.addItem(oi_newGlobalLandmark); this.map.getOverlays().add(this.INDEX_OF_LANDMARK_OVERLAY, newGlobalLandmarkOverlay); } // Speak out the verbal instruction speakInstruction(); } /** * Speak out the current instruction */ private void speakInstruction() { tts.setSpeechRate((float) 0.85); tts.speak(tv_instruction.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); } /** * Called when the next decision point will be reached in * <code>DISTANCE_FOR_NOW_INSTRUCTION</code> and a * <code>NowInstruction</code> is used to update the current instruction to * the instruction. The map is not changed as in the * <code>updateInstruction</code> method. */ private void updateNowInstruction() { // Get the now instruction Instruction nowInstruction = im.getNowInstruction(); // --- Update the instruction view --- // Get the verbal instruction String verbalInstruction = nowInstruction.toString(); // Display the verbal instruction this.tv_instruction.setText(verbalInstruction); // The instruction image stays the same // Speak out the verbal instruction speakInstruction(); } /** * Update the complete guidance. This method is called when a driving error * has occurred. */ private void updateGuidance() { // Inform the user about updating the guidance Log.i("NaviActivity", "Updating guidance..."); tts.setSpeechRate((float) 1); tts.speak("Updating guidance", TextToSpeech.QUEUE_FLUSH, null); // Restart the activity finish(); startActivity(getIntent()); } }
src/de/mrunde/bachelorthesis/activities/NaviActivity.java
package de.mrunde.bachelorthesis.activities; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Locale; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.graphics.Color; import android.graphics.Paint; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.mapquest.android.maps.DefaultItemizedOverlay; import com.mapquest.android.maps.GeoPoint; import com.mapquest.android.maps.LineOverlay; import com.mapquest.android.maps.MapActivity; import com.mapquest.android.maps.MapView; import com.mapquest.android.maps.MyLocationOverlay; import com.mapquest.android.maps.OverlayItem; import com.mapquest.android.maps.RouteManager; import com.mapquest.android.maps.RouteResponse; import de.mrunde.bachelorthesis.R; import de.mrunde.bachelorthesis.basics.Landmark; import de.mrunde.bachelorthesis.basics.LandmarkCategory; import de.mrunde.bachelorthesis.basics.Maneuver; import de.mrunde.bachelorthesis.instructions.Instruction; import de.mrunde.bachelorthesis.instructions.InstructionManager; import de.mrunde.bachelorthesis.instructions.LandmarkInstruction; /** * This is the navigational activity which is started by the MainActivity. It * navigates the user from his current location to the desired destination. * * @author Marius Runde */ public class NaviActivity extends MapActivity implements OnInitListener, LocationListener { // --- The indexes of the overlays --- /** * Index of the local landmark overlay */ private final int INDEX_OF_LOCAL_LANDMARK_OVERLAY = 3; /** * Index of the global landmark overlay */ private final int INDEX_OF_GLOBAL_LANDMARK_OVERLAY = 4; // --- End of indexes --- // --- The graphical user interface (GUI) --- /** * Instruction view (verbal) */ private TextView tv_instruction; /** * Instruction view (image) */ private ImageView iv_instruction; /** * Map view */ private MapView map; /** * An overlay to display the user's location */ private MyLocationOverlay myLocationOverlay; // --- End of GUI --- // --- The route and instruction objects --- /** * Current location as String (for RouteManager only!) */ private String str_currentLocation; /** * Destination as String (for RouteManager and as title of destination * overlay) */ private String str_destination; /** * Latitude of the destination */ private double destination_lat; /** * Longitude of the destination */ private double destination_lng; /** * Route manager for route calculation */ private RouteManager rm; /** * Route options (already formatted as a String) */ private String routeOptions; /** * Instruction manager that creates instructions */ private InstructionManager im; /** * Location manager to monitor the user's location */ private LocationManager lm; /** * Location provider of the LocationManager */ private String provider; /** * Minimum distance for a route segment to use a NowInstruction */ private final int MIN_DISTANCE_FOR_NOW_INSTRUCTION = 1000; /** * The NowInstruction will be returned at this distance before reaching the * next decision point */ private final int DISTANCE_FOR_NOW_INSTRUCTION = 100; /** * Variable to control if the usage of a NowInstruction has been checked */ private boolean nowInstructionChecked = false; /** * Variable to control if a NowInstruction will be used */ private boolean nowInstructionUsed = false; /** * Maximum distance to a decision point when it is supposed to be reached */ private final int MAX_DISTANCE_TO_DECISION_POINT = 20; /** * Store the last distance between the next decision point and the current * location. Is set to 0 when the instruction is updated. */ private double lastDistanceDP1 = 0; /** * Store the last distance between the decision point after next and the * current location. Is set to 0 when the instruction is updated. */ private double lastDistanceDP2 = 0; /** * Counts the distance changes between the next decision point, the decision * point after next and the current location. Is set to 0 after the * instruction has been updated. The instruction is updated when the counter * reaches its maximum negative value (<code>(-1) * MAX_COUNTER_VALUE</code> * ) or the next decision point has been reached. If the counter reaches the * maximum positive value (<code>MAX_COUNTER_VALUE</code>), the whole * guidance will be updated. */ private int distanceCounter = 0; /** * Maximum value for the <code>distanceCounter</code>. */ private final int MAX_COUNTER_VALUE = 5; // --- End of route and instruction objects --- /** * TextToSpeech for audio output */ private TextToSpeech tts; /** * This method is called when the application has been started */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.navi); // Get the route information from the intent Intent intent = getIntent(); this.str_currentLocation = intent.getStringExtra("str_currentLocation"); this.str_destination = intent.getStringExtra("str_destination"); this.destination_lat = intent.getDoubleExtra("destination_lat", 0.0); this.destination_lng = intent.getDoubleExtra("destination_lng", 0.0); this.routeOptions = intent.getStringExtra("routeOptions"); // Initialize the TextToSpeech tts = new TextToSpeech(this, this); // Initialize the LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Choose the location provider Criteria criteria = new Criteria(); provider = lm.getBestProvider(criteria, false); Location location = lm.getLastKnownLocation(provider); if (location != null) { Log.e("Test", "Provider " + provider + " has been selected."); onLocationChanged(location); } else { Log.e("Test", "Location not available"); } // Setup the whole GUI and map setupGUI(); setupMapView(); setupMyLocation(); // Add the destination overlay to the map addDestinationOverlay(destination_lat, destination_lng); // Calculate the route calculateRoute(); // Get the guidance information and create the instructions getGuidance(); } /** * Set up the GUI */ private void setupGUI() { this.tv_instruction = (TextView) findViewById(R.id.tv_instruction); this.iv_instruction = (ImageView) findViewById(R.id.iv_instruction); } /** * Set up the map and disable user interaction */ private void setupMapView() { this.map = (MapView) findViewById(R.id.map); map.setBuiltInZoomControls(false); map.setClickable(true); map.setLongClickable(true); } /** * Set up a MyLocationOverlay and execute the runnable once a location has * been fixed */ private void setupMyLocation() { // Check if the GPS is enabled if (!((LocationManager) getSystemService(LOCATION_SERVICE)) .isProviderEnabled(LocationManager.GPS_PROVIDER)) { // Open dialog to inform the user that the GPS is disabled AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.gpsDisabled)); builder.setCancelable(false); builder.setPositiveButton(R.string.openSettings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Open the location settings if it is disabled Intent intent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Dismiss the dialog dialog.cancel(); } }); // Display the dialog AlertDialog dialog = builder.create(); dialog.show(); } // Set up the myLocationOverlay this.myLocationOverlay = new MyLocationOverlay(this, map); myLocationOverlay.enableMyLocation(); myLocationOverlay.setMarker( getResources().getDrawable(R.drawable.my_location), 0); myLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { GeoPoint currentLocation = myLocationOverlay.getMyLocation(); map.getController().animateTo(currentLocation); map.getController().setZoom(18); map.getOverlays().add(myLocationOverlay); myLocationOverlay.setFollowing(true); } }); } /** * Add the destination overlay to the map * * @param lat * Latitude of the destination * @param lng * Longitude of the destination */ private void addDestinationOverlay(double lat, double lng) { // Create a GeoPoint object of the destination GeoPoint destination = new GeoPoint(lat, lng); // Create the destination overlay OverlayItem oi_destination = new OverlayItem(destination, "Destination", str_destination); final DefaultItemizedOverlay destinationOverlay = new DefaultItemizedOverlay( getResources().getDrawable(R.drawable.destination_flag)); destinationOverlay.addItem(oi_destination); // Add the overlay to the map map.getOverlays().add(destinationOverlay); } /** * Calculate the route from the current location to the destination */ private void calculateRoute() { // Clear the previous route first if (rm != null) { rm.clearRoute(); } // Initialize a new RouteManager to calculate the route rm = new RouteManager(getBaseContext(), getResources().getString( R.string.apiKey)); // Set the route options (e.g. route type) rm.setOptions(routeOptions); // Set route callback rm.setRouteCallback(new RouteManager.RouteCallback() { @Override public void onSuccess(RouteResponse response) { // Route has been calculated successfully Log.i("NaviActivity", getResources().getString(R.string.routeCalculated)); } @Override public void onError(RouteResponse response) { // Route could not be calculated Log.e("NaviActivity", getResources().getString(R.string.routeNotCalculated)); } }); // Calculate the route and display it on the map rm.createRoute(str_currentLocation, str_destination); // Zoom to current location map.getController().animateTo(myLocationOverlay.getMyLocation()); map.getController().setZoom(18); } /** * Get the guidance information from MapQuest */ private void getGuidance() { // Create the URL to request the guidance from MapQuest String url; try { url = "https://open.mapquestapi.com/guidance/v1/route?key=" + getResources().getString(R.string.apiKey) + "&from=" + URLEncoder.encode(str_currentLocation, "UTF-8") + "&to=" + URLEncoder.encode(str_destination, "UTF-8") + "&narrativeType=text&fishbone=false&callback=renderBasicInformation"; } catch (UnsupportedEncodingException e) { Log.e("NaviActivity", "Could not encode the URL. This is the error message: " + e.getMessage()); return; } // Get the data. The instructions are created afterwards. GetJsonTask jsonTask = new GetJsonTask(); jsonTask.execute(url); } /** * This is a class to get the JSON file asynchronously from the given URL. * * @author Marius Runde */ private class GetJsonTask extends AsyncTask<String, Void, JSONObject> { /** * Progress dialog to inform the user about the download */ private ProgressDialog progressDialog = new ProgressDialog( NaviActivity.this); /** * Count the time needed for the data download */ private int downloadTimer; @Override protected void onPreExecute() { // Display progress dialog progressDialog.setMessage("Downloading guidance..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // Cancel the download when the "Cancel" button has been // clicked GetJsonTask.this.cancel(true); } }); // Set timer to current time downloadTimer = Calendar.getInstance().get(Calendar.SECOND); } @Override protected JSONObject doInBackground(String... url) { // Get the data from the URL String output = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; try { response = httpclient.execute(new HttpGet(url[0])); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); output = out.toString(); } else { // Close the connection response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (Exception e) { Log.e("GetJsonTask", "Could not get the data. This is the error message: " + e.getMessage()); return null; } // Delete the "renderBasicInformation" stuff at the beginning and // end of the output if needed to convert it to a JSONObject if (output.startsWith("renderBasicInformation(")) { output = output.substring(23, output.length()); } if (output.endsWith(");")) { output = output.substring(0, output.length() - 2); } // Convert the output to a JSONObject try { JSONObject result = new JSONObject(output); return result; } catch (JSONException e) { Log.e("GetJsonTask", "Could not convert output to JSONObject. This is the error message: " + e.getMessage()); return null; } } @Override protected void onPostExecute(JSONObject result) { // Dismiss progress dialog progressDialog.dismiss(); // Write the time needed for the download into the log downloadTimer = Calendar.getInstance().get(Calendar.SECOND) - downloadTimer; Log.i("GetJsonTask", "Completed guidance download in " + downloadTimer + " seconds"); // Check if the download was successful if (result == null) { // Could not receive the JSON Toast.makeText(NaviActivity.this, getResources().getString(R.string.routeNotCalculated), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } else { // Create the instructions createInstructions(result); // Draw the route drawRoute(result); if (im.isImportSuccessful()) { // Get the first instruction and display it displayInstruction(im.getInstruction(0)); } else { // Import was not successful Toast.makeText( NaviActivity.this, getResources().getString( R.string.jsonImportNotSuccessful), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } } } } /** * Create the instructions for the navigation * * @param guidance * The guidance information from MapQuest */ private void createInstructions(JSONObject guidance) { // Load the landmarks as a JSONObject from res/raw/landmarks.json InputStream is = getResources().openRawResource(R.raw.landmarks); JSONObject landmarks = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); landmarks = new JSONObject(rawJson); } catch (Exception e) { // Could not load landmarks Log.e("NaviActivity", "Could not load landmarks. This is the error message: " + e.getMessage()); } // Load the street furniture as a JSONArray from // res/raw/streetfurniture.json is = getResources().openRawResource(R.raw.streetfurniture); JSONArray streetFurniture = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); streetFurniture = new JSONArray(rawJson); } catch (Exception e) { // Could not load street furniture Log.e("NaviActivity", "Could not load street furniture. This is the error message: " + e.getMessage()); } // Load the intersections as a JSONArray from res/raw/intersections.json is = getResources().openRawResource(R.raw.intersections); JSONArray intersections = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); intersections = new JSONArray(rawJson); } catch (Exception e) { // Could not load intersections Log.e("NaviActivity", "Could not load intersections. This is the error message: " + e.getMessage()); } // Create the instruction manager im = new InstructionManager(guidance, landmarks, streetFurniture, intersections); // Check if the import was successful if (im.isImportSuccessful()) { // Create the instructions im.createInstructions(); } else { // Import was not successful Toast.makeText(this, getResources().getString(R.string.jsonImportNotSuccessful), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } } /** * Draw the route with the given shapePoints from the guidance information * * @param json * The guidance information from MapQuest */ private void drawRoute(JSONObject json) { // Set custom line style Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); // Initialize the route overlay List<GeoPoint> shapePoints = new ArrayList<GeoPoint>( Arrays.asList(this.im.getShapePoints())); LineOverlay drawnRoute = new LineOverlay(paint); drawnRoute.setData(shapePoints); // Add the drawn route to the map map.getOverlays().add(drawnRoute); Log.d("NaviActivity", "Route overlay added"); } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.closeActivity_title) .setMessage(R.string.closeActivity_message) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setNegativeButton("No", null).show(); } @Override protected boolean isRouteDisplayed() { // Do nothing return false; } /** * Called when the OptionsMenu is created */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.navi, menu); return true; } /** * Called when an item of the OptionsMenu is clicked */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_allInstructions: // Create an array of all verbal instructions String[] allInstructions = im.getVerbalInstructions(); // Display all instructions in a list AlertDialog.Builder builder = new AlertDialog.Builder( NaviActivity.this); builder.setTitle(R.string.allInstructions); builder.setItems(allInstructions, null); AlertDialog alertDialog = builder.create(); alertDialog.show(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { // Enable features of the MyLocationOverlay myLocationOverlay.enableMyLocation(); // Request location updates at startup every 500ms for changes of 1m lm.requestLocationUpdates(provider, 500, 1, this); super.onResume(); } @Override protected void onPause() { super.onPause(); // Disable features of the MyLocationOverlay when in the background myLocationOverlay.disableMyLocation(); // Disable the LocationManager when in the background lm.removeUpdates(this); } @Override public void onInit(int status) { // Initialize the TextToSpeech engine if (status == TextToSpeech.SUCCESS) { tts.setLanguage(Locale.ENGLISH); } else { tts = null; Log.e("MainActivity", "Failed to initialize the TextToSpeech engine"); } } @Override public void onLocationChanged(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); // Check if the instruction manager has been initialized already if (im != null) { // Get the coordinates of the next decision point double dp1Lat = im.getCurrentInstruction().getDecisionPoint() .getLatitude(); double dp1Lng = im.getCurrentInstruction().getDecisionPoint() .getLongitude(); // Get the coordinates of the decision point after next double dp2Lat = im.getNextInstructionLocation().getLatitude(); double dp2Lng = im.getNextInstructionLocation().getLongitude(); // Calculate the distance to the next decision point float[] results = new float[1]; Location.distanceBetween(lat, lng, dp1Lat, dp1Lng, results); double distanceDP1 = results[0]; // Check whether a now instruction must be used (only once for each // route segment) if (nowInstructionChecked == false && distanceDP1 >= MIN_DISTANCE_FOR_NOW_INSTRUCTION) { nowInstructionUsed = true; } nowInstructionChecked = true; // Calculate the distance to the decision point after next Location.distanceBetween(lat, lng, dp2Lat, dp2Lng, results); double distanceDP2 = results[0]; // Check the distances with the stored ones if (distanceDP1 < MAX_DISTANCE_TO_DECISION_POINT) { // Distance to decision point is less than 20m so the // instruction is being updated updateInstruction(); } else if (distanceDP1 < DISTANCE_FOR_NOW_INSTRUCTION && nowInstructionUsed == true) { // Distance to updateNowInstruction(); } else if (distanceDP1 > lastDistanceDP1 && distanceDP2 < lastDistanceDP2) { // The distance to the next decision point has increased and the // distance to the decision point after next has decreased lastDistanceDP1 = distanceDP1; lastDistanceDP2 = distanceDP2; distanceCounter++; Log.v("NaviActivity.onLocationChanged", "distanceCounter: " + distanceCounter); } else if (distanceDP1 > lastDistanceDP1 && distanceDP2 > lastDistanceDP2) { // Distance to the next decision point and the decision point // after next has increased (can lead to a driving error) lastDistanceDP1 = distanceDP1; lastDistanceDP2 = distanceDP2; distanceCounter--; Log.v("NaviActivity.onLocationChanged", "distanceIncreaseCounter: " + distanceCounter); } // Check if the whole guidance needs to be reloaded due to a driving // error (user seems to go away from both the decision point and the // decision point after next) if (distanceCounter < (-1 * MAX_COUNTER_VALUE)) { updateGuidance(); } // Check if the instruction needs to be updated if (distanceCounter > MAX_COUNTER_VALUE) { updateInstruction(); } } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Do nothing here } @Override public void onProviderEnabled(String provider) { // Do nothing here } @Override public void onProviderDisabled(String provider) { // Do nothing here } /** * Called when the next decision point has been reached to update the * current instruction to the following instruction. */ private void updateInstruction() { Log.i("NaviActivity", "Updating Instruction..."); // Reset the distances, their counters, and the NowInstruction // controllers lastDistanceDP1 = 0; lastDistanceDP2 = 0; distanceCounter = 0; nowInstructionChecked = false; nowInstructionUsed = false; // Get the next instruction and display it Instruction nextInstruction = im.getNextInstruction(); displayInstruction(nextInstruction); } /** * Called when a new instruction shall be displayed. Also the map is being * updated so that the old landmarks are removed and the new ones are * displayed. * * @param instruction * The instruction to be displayed */ private void displayInstruction(Instruction instruction) { // --- Update the instruction view --- // Get the next verbal instruction String nextVerbalInstruction = instruction.toString(); // Display the verbal instruction this.tv_instruction.setText(nextVerbalInstruction); // Get the corresponding instruction image and display it this.iv_instruction.setImageDrawable(getResources().getDrawable( Maneuver.getDrawableId(instruction.getManeuverType()))); // --- Update the landmarks on the map (if available) --- // Remove previous landmarks (if available) // Remove global landmark if (this.map.getOverlays().size() > this.INDEX_OF_GLOBAL_LANDMARK_OVERLAY) { this.map.getOverlays() .remove(this.INDEX_OF_GLOBAL_LANDMARK_OVERLAY); } // Remove local landmark if (this.map.getOverlays().size() > this.INDEX_OF_LOCAL_LANDMARK_OVERLAY) { this.map.getOverlays().remove(this.INDEX_OF_LOCAL_LANDMARK_OVERLAY); } // Add new global landmark (if available) if (instruction.getGlobal() != null) { Landmark newGlobalLandmark = instruction.getGlobal(); OverlayItem oi_newGlobalLandmark = new OverlayItem( newGlobalLandmark.getCenter(), newGlobalLandmark.getTitle(), newGlobalLandmark.getCategory()); DefaultItemizedOverlay newGlobalLandmarkOverlay = new DefaultItemizedOverlay( getResources().getDrawable( LandmarkCategory.getDrawableId(newGlobalLandmark .getCategory()))); newGlobalLandmarkOverlay.addItem(oi_newGlobalLandmark); this.map.getOverlays().add(this.INDEX_OF_GLOBAL_LANDMARK_OVERLAY, newGlobalLandmarkOverlay); } // Add new local landmark (if available) if (instruction.getClass().equals(LandmarkInstruction.class)) { Landmark newLocalLandmark = ((LandmarkInstruction) instruction) .getLocal(); OverlayItem oi_newLocalLandmark = new OverlayItem( newLocalLandmark.getCenter(), newLocalLandmark.getTitle(), newLocalLandmark.getCategory()); DefaultItemizedOverlay newLocalLandmarkOverlay = new DefaultItemizedOverlay( getResources().getDrawable( LandmarkCategory.getDrawableId(newLocalLandmark .getCategory()))); newLocalLandmarkOverlay.addItem(oi_newLocalLandmark); this.map.getOverlays().add(this.INDEX_OF_LOCAL_LANDMARK_OVERLAY, newLocalLandmarkOverlay); } // Speak out the verbal instruction speakInstruction(); } /** * Speak out the current instruction */ private void speakInstruction() { tts.setSpeechRate((float) 0.85); tts.speak(tv_instruction.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); } /** * Called when the next decision point will be reached in * <code>DISTANCE_FOR_NOW_INSTRUCTION</code> and a * <code>NowInstruction</code> is used to update the current instruction to * the instruction. The map is not changed as in the * <code>updateInstruction</code> method. */ private void updateNowInstruction() { // Get the now instruction Instruction nowInstruction = im.getNowInstruction(); // --- Update the instruction view --- // Get the verbal instruction String verbalInstruction = nowInstruction.toString(); // Display the verbal instruction this.tv_instruction.setText(verbalInstruction); // The instruction image stays the same // Speak out the verbal instruction speakInstruction(); } /** * Update the complete guidance. This method is called when a driving error * has occurred. */ private void updateGuidance() { // Inform the user about updating the guidance Log.i("NaviActivity", "Updating guidance..."); tts.setSpeechRate((float) 1); tts.speak("Updating guidance", TextToSpeech.QUEUE_FLUSH, null); // Restart the activity finish(); startActivity(getIntent()); } }
Fix error of displaying instruction image at first instruction
src/de/mrunde/bachelorthesis/activities/NaviActivity.java
Fix error of displaying instruction image at first instruction
<ide><path>rc/de/mrunde/bachelorthesis/activities/NaviActivity.java <ide> import de.mrunde.bachelorthesis.basics.Landmark; <ide> import de.mrunde.bachelorthesis.basics.LandmarkCategory; <ide> import de.mrunde.bachelorthesis.basics.Maneuver; <add>import de.mrunde.bachelorthesis.instructions.GlobalInstruction; <ide> import de.mrunde.bachelorthesis.instructions.Instruction; <ide> import de.mrunde.bachelorthesis.instructions.InstructionManager; <ide> import de.mrunde.bachelorthesis.instructions.LandmarkInstruction; <ide> /** <ide> * Index of the local landmark overlay <ide> */ <del> private final int INDEX_OF_LOCAL_LANDMARK_OVERLAY = 3; <del> <del> /** <del> * Index of the global landmark overlay <del> */ <del> private final int INDEX_OF_GLOBAL_LANDMARK_OVERLAY = 4; <add> private final int INDEX_OF_LANDMARK_OVERLAY = 3; <add> <ide> // --- End of indexes --- <ide> <ide> // --- The graphical user interface (GUI) --- <ide> // Create the instructions <ide> createInstructions(result); <ide> <del> // Draw the route <add> // Draw the route and display the first instruction <ide> drawRoute(result); <del> <del> if (im.isImportSuccessful()) { <del> // Get the first instruction and display it <del> displayInstruction(im.getInstruction(0)); <del> } else { <del> // Import was not successful <del> Toast.makeText( <del> NaviActivity.this, <del> getResources().getString( <del> R.string.jsonImportNotSuccessful), <del> Toast.LENGTH_SHORT).show(); <del> // Finish the activity to return to MainActivity <del> finish(); <del> } <ide> } <ide> } <ide> } <ide> // Add the drawn route to the map <ide> map.getOverlays().add(drawnRoute); <ide> Log.d("NaviActivity", "Route overlay added"); <add> <add> if (!im.isImportSuccessful()) { <add> // Import was not successful <add> Toast.makeText(NaviActivity.this, <add> getResources().getString(R.string.jsonImportNotSuccessful), <add> Toast.LENGTH_SHORT).show(); <add> // Finish the activity to return to the MainActivity <add> finish(); <add> } else { <add> do { <add> // Route is not displayed yet <add> } while (!this.isRouteDisplayed()); <add> // Toast.makeText(NaviActivity.this, <add> // getResources().getString(R.string.routeNotDisplayed), <add> // Toast.LENGTH_SHORT).show(); <add> // // Finish the activity to return to the MainActivity <add> // finish(); <add> // } else { <add> // Get the first instruction and display it <add> displayInstruction(im.getInstruction(0)); <add> } <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> protected boolean isRouteDisplayed() { <del> // Do nothing <del> return false; <add> if (this.map.getOverlays().size() > 1) { <add> return true; <add> } else { <add> return false; <add> } <ide> } <ide> <ide> /** <ide> Maneuver.getDrawableId(instruction.getManeuverType()))); <ide> <ide> // --- Update the landmarks on the map (if available) --- <del> // Remove previous landmarks (if available) <del> // Remove global landmark <del> if (this.map.getOverlays().size() > this.INDEX_OF_GLOBAL_LANDMARK_OVERLAY) { <del> this.map.getOverlays() <del> .remove(this.INDEX_OF_GLOBAL_LANDMARK_OVERLAY); <del> } <del> // Remove local landmark <del> if (this.map.getOverlays().size() > this.INDEX_OF_LOCAL_LANDMARK_OVERLAY) { <del> this.map.getOverlays().remove(this.INDEX_OF_LOCAL_LANDMARK_OVERLAY); <del> } <del> <del> // Add new global landmark (if available) <del> if (instruction.getGlobal() != null) { <del> Landmark newGlobalLandmark = instruction.getGlobal(); <del> OverlayItem oi_newGlobalLandmark = new OverlayItem( <del> newGlobalLandmark.getCenter(), <del> newGlobalLandmark.getTitle(), <del> newGlobalLandmark.getCategory()); <del> DefaultItemizedOverlay newGlobalLandmarkOverlay = new DefaultItemizedOverlay( <del> getResources().getDrawable( <del> LandmarkCategory.getDrawableId(newGlobalLandmark <del> .getCategory()))); <del> newGlobalLandmarkOverlay.addItem(oi_newGlobalLandmark); <del> this.map.getOverlays().add(this.INDEX_OF_GLOBAL_LANDMARK_OVERLAY, <del> newGlobalLandmarkOverlay); <add> // Remove previous landmark (if available) <add> if (this.map.getOverlays().size() > this.INDEX_OF_LANDMARK_OVERLAY) { <add> this.map.getOverlays().remove(this.INDEX_OF_LANDMARK_OVERLAY); <ide> } <ide> <ide> // Add new local landmark (if available) <ide> LandmarkCategory.getDrawableId(newLocalLandmark <ide> .getCategory()))); <ide> newLocalLandmarkOverlay.addItem(oi_newLocalLandmark); <del> this.map.getOverlays().add(this.INDEX_OF_LOCAL_LANDMARK_OVERLAY, <add> this.map.getOverlays().add(this.INDEX_OF_LANDMARK_OVERLAY, <ide> newLocalLandmarkOverlay); <add> } <add> <add> // Add new global landmark (if available) <add> if (instruction.getClass().equals(GlobalInstruction.class)) { <add> Landmark newGlobalLandmark = ((GlobalInstruction) instruction) <add> .getGlobal(); <add> OverlayItem oi_newGlobalLandmark = new OverlayItem( <add> newGlobalLandmark.getCenter(), <add> newGlobalLandmark.getTitle(), <add> newGlobalLandmark.getCategory()); <add> DefaultItemizedOverlay newGlobalLandmarkOverlay = new DefaultItemizedOverlay( <add> getResources().getDrawable( <add> LandmarkCategory.getDrawableId(newGlobalLandmark <add> .getCategory()))); <add> newGlobalLandmarkOverlay.addItem(oi_newGlobalLandmark); <add> this.map.getOverlays().add(this.INDEX_OF_LANDMARK_OVERLAY, <add> newGlobalLandmarkOverlay); <ide> } <ide> <ide> // Speak out the verbal instruction
JavaScript
mit
0e10ec81c02df01d9fae13ab239d278e375a844d
0
armandocat/steemit-more-info,armandocat/steemit-more-info
(function(){ var makePostBottomBarFloating = function() { var tags = $('.TagList__horizontal'); var postFooter = $('.PostFull__footer'); if(tags.length && postFooter.length) { if(tags.closest('.smi-post-footer-wrapper-2').length){ return; } $('#post_overlay').on('scroll', function()ย { update(); }); var footer = $('<div class="smi-post-footer">\ <div class="smi-post-footer-wrapper-1">\ <div class="smi-post-footer-wrapper-2">\ </div>\ </div>\ </div>'); var footerWrapper = footer.find('.smi-post-footer-wrapper-2'); tags.replaceWith(footer); footerWrapper.append(tags); footerWrapper.append(postFooter); update(); } }; var update = function() { var footer = $('.smi-post-footer'); var footerWrapper = $('.smi-post-footer-wrapper-2'); if(footer.length && footerWrapper.length) { var h = footerWrapper.height(); var py = footer.position().top + h; var oy = footer.offset().top + h; var by = $(document).scrollTop() + $(window).height(); var isOverlay = $('#post_overlay').length > 0; // console.log('H= ' + h); // console.log('py= ' + py); // console.log('oy= ' + oy); // console.log('by= ' + by); footer.css('height', h + 'px'); if(oy > by) { if(!footer.hasClass('smi-post-floating-footer')){ footer.addClass('smi-post-floating-footer'); if(isOverlay) { footerWrapper.addClass('smi-post-floating-footer-on-body').addClass('row'); $('body').prepend(footerWrapper); } } if(isOverlay) { var ol = footer.offset().left; footerWrapper.css('left', ol + 'px'); } }else{ if(footer.hasClass('smi-post-floating-footer')){ footer.removeClass('smi-post-floating-footer'); if(isOverlay) { footerWrapper.removeClass('smi-post-floating-footer-on-body').removeClass('row'); footer.find('.smi-post-footer-wrapper-1').prepend(footerWrapper); } if(isOverlay) { footerWrapper.css('left', 'auto'); } } } } }; $(window).on('resize', function()ย { update(); }); $(document).on('scroll', function()ย { update(); }); $('body').attrchange(function(attrName) { if(attrName === 'class'){ if($('body').hasClass('with-post-overlay')) { makePostBottomBarFloating(); }else{ var footerWrapper = $('.smi-post-footer-wrapper-2'); if(footerWrapper.length && footerWrapper.parent().is('body')){ footerWrapper.remove(); } } } }); window.SteemMoreInfo.Events.addEventListener(window, 'changestate', function() { setTimeout(function() { makePostBottomBarFloating(); }, 100); }); makePostBottomBarFloating(); })();
src/post_floating_bottom_bar.js
(function(){ var makePostBottomBarFloating = function() { var tags = $('.TagList__horizontal'); var postFooter = $('.PostFull__footer'); if(tags.length && postFooter.length) { if(tags.parent().is('smi-post-footer-wrapper-2')){ return; } $('#post_overlay').on('scroll', function()ย { update(); }); var footer = $('<div class="smi-post-footer">\ <div class="smi-post-footer-wrapper-1">\ <div class="smi-post-footer-wrapper-2">\ </div>\ </div>\ </div>'); var footerWrapper = footer.find('.smi-post-footer-wrapper-2'); tags.replaceWith(footer); footerWrapper.append(tags); footerWrapper.append(postFooter); update(); } }; var update = function() { var footer = $('.smi-post-footer'); var footerWrapper = $('.smi-post-footer-wrapper-2'); if(footer.length && footerWrapper.length) { var h = footerWrapper.height(); var py = footer.position().top + h; var oy = footer.offset().top + h; var by = $(document).scrollTop() + $(window).height(); var isOverlay = $('#post_overlay').length > 0; // console.log('H= ' + h); // console.log('py= ' + py); // console.log('oy= ' + oy); // console.log('by= ' + by); footer.css('height', h + 'px'); if(oy > by) { if(!footer.hasClass('smi-post-floating-footer')){ footer.addClass('smi-post-floating-footer'); if(isOverlay) { footerWrapper.addClass('smi-post-floating-footer-on-body').addClass('row'); $('body').prepend(footerWrapper); } } if(isOverlay) { var ol = footer.offset().left; footerWrapper.css('left', ol + 'px'); } }else{ if(footer.hasClass('smi-post-floating-footer')){ footer.removeClass('smi-post-floating-footer'); if(isOverlay) { footerWrapper.removeClass('smi-post-floating-footer-on-body').removeClass('row'); footer.find('.smi-post-footer-wrapper-1').prepend(footerWrapper); } if(isOverlay) { footerWrapper.css('left', 'auto'); } } } } }; $(window).on('resize', function()ย { update(); }); $(document).on('scroll', function()ย { update(); }); $('body').attrchange(function(attrName) { if(attrName === 'class'){ if($('body').hasClass('with-post-overlay')) { makePostBottomBarFloating(); }else{ var footerWrapper = $('.smi-post-footer-wrapper-2'); if(footerWrapper.length && footerWrapper.parent().is('body')){ footerWrapper.remove(); } } } }); window.SteemMoreInfo.Events.addEventListener(window, 'changestate', function() { makePostBottomBarFloating(); }); makePostBottomBarFloating(); })();
Fix floating bar in posts
src/post_floating_bottom_bar.js
Fix floating bar in posts
<ide><path>rc/post_floating_bottom_bar.js <ide> <ide> if(tags.length && postFooter.length) { <ide> <del> if(tags.parent().is('smi-post-footer-wrapper-2')){ <add> if(tags.closest('.smi-post-footer-wrapper-2').length){ <ide> return; <ide> } <ide> <ide> }); <ide> <ide> window.SteemMoreInfo.Events.addEventListener(window, 'changestate', function() { <del> makePostBottomBarFloating(); <add> setTimeout(function() { <add> makePostBottomBarFloating(); <add> }, 100); <ide> }); <ide> <ide>
Java
bsd-3-clause
aadc0371ecf9b98845adb7d4a0b42983fac3aea6
0
NCIP/cagrid,NCIP/cagrid,NCIP/cagrid,NCIP/cagrid
/* * Created on Jun 11, 2006 */ package gov.nci.nih.cagrid.tests.core.steps; import gov.nci.nih.cagrid.tests.core.util.CaDSRExtractUtils; import gov.nih.nci.cadsr.umlproject.domain.Project; import gov.nih.nci.cadsr.umlproject.domain.SemanticMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLAttributeMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLClassMetadata; import gov.nih.nci.cagrid.cadsr.client.CaDSRServiceClient; import gov.nih.nci.cagrid.cadsr.common.CaDSRServiceI; import gov.nih.nci.cagrid.cadsr.domain.UMLAssociation; import gov.nih.nci.cagrid.metadata.common.UMLAttribute; import gov.nih.nci.cagrid.metadata.common.UMLClass; import gov.nih.nci.cagrid.metadata.dataservice.DomainModel; import java.io.File; import java.rmi.RemoteException; import org.apache.axis.message.addressing.Address; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.axis.types.URI.MalformedURIException; import com.atomicobject.haste.framework.Step; public class CheckCaDSRServiceStep extends Step { private EndpointReferenceType endpoint; private File extractFile; public CheckCaDSRServiceStep(int port, File extractFile) throws MalformedURIException { this(new EndpointReferenceType(new Address("http://localhost:" + port + "/wsrf/services/cagrid/CaDSRService")), extractFile); } public CheckCaDSRServiceStep(EndpointReferenceType endpoint, File extractFile) { super(); this.endpoint = endpoint; this.extractFile = extractFile; } public void runStep() throws Exception { CaDSRServiceI cadsr = new CaDSRServiceClient(endpoint.getAddress().toString()); DomainModel extract = null; if (extractFile == null) { extract = CaDSRExtractUtils.findExtract(cadsr, "Genomic Identifiers"); //extract = CaDSRExtractUtils.findExtract(cadsr, "caTIES"); } else { extract = CaDSRExtractUtils.readExtract(extractFile); } // find project Project[] projects = cadsr.findAllProjects(); Project project = null; for (Project myProject : projects) { if (myProject.longName.equals(extract.getProjectLongName())) { project = myProject; break; } } // assert everything looks good compareProject(extract, cadsr, project); } @SuppressWarnings("unchecked") private void compareProject(DomainModel extract, CaDSRServiceI cadsr, Project project) throws RemoteException { assertNotNull(project); assertEquals(extract.getProjectLongName(), project.longName); assertEquals(extract.getProjectShortName(), project.shortName); assertEquals(extract.getProjectDescription(), project.description); assertEquals(extract.getProjectVersion(), project.version); UMLClass[] extractCls = extract.getExposedUMLClassCollection().getUMLClass(); UMLClassMetadata[] cls = cadsr.findClassesInProject(project);//(UMLClassMetadata[]) project.getUMLClassMetadataCollection().toArray(new UMLClassMetadata[0]); assertEquals(extractCls.length, cls.length); compareClasses(cadsr, extractCls, project, cls); gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation[] extractAssocations = extract.getExposedUMLAssociationCollection().getUMLAssociation(); gov.nih.nci.cagrid.cadsr.domain.UMLAssociation[] assocations = cadsr.findAssociationsInProject(project); if (extractAssocations == null && assocations == null) { // some models don't have associations? } else { assertEquals(extractAssocations.length, assocations.length); compareAssociations(extractAssocations, assocations); } } private void compareClasses(CaDSRServiceI cadsr, UMLClass[] extractCls, Project project, UMLClassMetadata[] cls) throws RemoteException { for (UMLClass extractCl : extractCls) { UMLClassMetadata cl = findClass(extractCl, cls); assertNotNull(cl); assertEquals(extractCl.getPackageName() + "." + extractCl.getClassName(), cl.getFullyQualifiedName()); assertEquals(extractCl.getDescription(), cl.getDescription()); SemanticMetadata[] extractMetadata = extractCl.getSemanticMetadataCollection().getSemanticMetadata(); SemanticMetadata[] metadata = cadsr.findSemanticMetadataForClass(project, cl); assertEquals(extractMetadata.length, metadata.length); compareMetadata(cadsr, extractMetadata, metadata); UMLAttribute[] extractAtts = extractCl.getUmlAttributeCollection().getUMLAttribute(); UMLAttributeMetadata[] atts = cadsr.findAttributesInClass(project, cl); assertEquals(extractAtts.length, atts.length); compareAttributes(cadsr, extractAtts, atts); } } private void compareMetadata(CaDSRServiceI cadsr, SemanticMetadata[] extractMetadata, SemanticMetadata[] metadata) { for (SemanticMetadata em : extractMetadata) { assertNotNull(em); SemanticMetadata m = findSemanticMetadata(em, metadata); assertNotNull(m); assertEquals(m.conceptCode, em.conceptCode); assertEquals(m.conceptDefinition, em.conceptDefinition); assertEquals(m.conceptName, em.conceptName); assertEquals(m.id, em.id); assertEquals(m.isPrimaryConcept, em.isPrimaryConcept); assertEquals(m.order, em.order); assertEquals(m.orderLevel, em.orderLevel); } } private void compareAttributes(CaDSRServiceI cadsr, UMLAttribute[] extractAtts, UMLAttributeMetadata[] atts) throws RemoteException { for (UMLAttribute extractAtt : extractAtts) { assertNotNull(extractAtt); UMLAttributeMetadata att = findAttribute(extractAtt, atts); assertNotNull(att); assertTrue( (extractAtt.getDescription() == null && att.description == null) || (extractAtt.getDescription() == null && "".equals(att.description)) || ("".equals(extractAtt.getDescription()) && att.description == null) || extractAtt.getDescription().equals(att.description) ); //assertEquals(extractAtt.getDescription(), att.description); assertEquals(getExtractAttributeName(extractAtt), att.name); } } private void compareAssociations(gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation[] extractAssociations, gov.nih.nci.cagrid.cadsr.domain.UMLAssociation[] associations) { for (gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation extractAssociation : extractAssociations) { assertNotNull(extractAssociation); gov.nih.nci.cagrid.cadsr.domain.UMLAssociation association = findAssociation(extractAssociation, associations); assertNotNull(association); } } private UMLAssociation findAssociation(gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation extractAssociation, gov.nih.nci.cagrid.cadsr.domain.UMLAssociation[] associations) { for (gov.nih.nci.cagrid.cadsr.domain.UMLAssociation association : associations) { //String extractSourceClass = extractAssociation.getSourceUMLAssociationEdge().getUMLAssociationEdge().getUmlClass().getUMLClass().getClassName(); //String sourceClass = association.getSourceUMLClassMetadata().getUMLClassMetadata().fullyQualifiedName; //assertEquals(extractSourceClass, sourceClass); return association; } return null; } private UMLAttributeMetadata findAttribute(UMLAttribute extractAtt, UMLAttributeMetadata[] atts) { // extractAtt.getName()=Gene:ensemblgeneID // att.getName()=ensemblgeneID for (UMLAttributeMetadata att : atts) { if (getExtractAttributeName(extractAtt).equals(att.name)) return att; } return null; } private String getExtractAttributeName(UMLAttribute extractAtt) { String extractName = extractAtt.getName(); int index = extractName.indexOf(':'); if (index != -1) extractName = extractName.substring(index+1); return extractName; } private SemanticMetadata findSemanticMetadata(SemanticMetadata em, SemanticMetadata[] metadata) { for (SemanticMetadata m : metadata) { if (em.id.equals(m.id)) return m; } return null; } private UMLClassMetadata findClass(UMLClass extractCl, UMLClassMetadata[] cls) { String className = extractCl.getPackageName() + "." + extractCl.getClassName(); for (UMLClassMetadata cl : cls) { if (className.equals(cl.getFullyQualifiedName())) return cl; } return null; } public static void main(String[] args) throws Exception { CaDSRExtractUtils.setAxisConfig(new File("etc", "cadsr" + File.separator + "client-config.wsdd")); new CheckCaDSRServiceStep( new EndpointReferenceType(new Address("http://localhost:8080/wsrf/services/cagrid/CaDSRService")), new File("test", "resources" + File.separator + "CheckCaDSRServiceStep" + File.separator + "caTIES_extract.xml") ).runStep(); } }
cagrid-1-0/tests/projects/coretests/test/src/java/gov/nci/nih/cagrid/tests/core/steps/CheckCaDSRServiceStep.java
/* * Created on Jun 11, 2006 */ package gov.nci.nih.cagrid.tests.core.steps; import gov.nci.nih.cagrid.tests.core.util.CaDSRExtractUtils; import gov.nih.nci.cadsr.umlproject.domain.Project; import gov.nih.nci.cadsr.umlproject.domain.SemanticMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLAttributeMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLClassMetadata; import gov.nih.nci.cagrid.cadsr.client.CaDSRServiceClient; import gov.nih.nci.cagrid.cadsr.common.CaDSRServiceI; import gov.nih.nci.cagrid.cadsr.domain.UMLAssociation; import gov.nih.nci.cagrid.metadata.common.UMLAttribute; import gov.nih.nci.cagrid.metadata.common.UMLClass; import gov.nih.nci.cagrid.metadata.dataservice.DomainModel; import java.io.File; import java.rmi.RemoteException; import org.apache.axis.message.addressing.Address; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.axis.types.URI.MalformedURIException; import com.atomicobject.haste.framework.Step; public class CheckCaDSRServiceStep extends Step { private EndpointReferenceType endpoint; private File extractFile; public CheckCaDSRServiceStep(int port, File extractFile) throws MalformedURIException { this(new EndpointReferenceType(new Address("http://localhost:" + port + "/wsrf/services/cagrid/CaDSRService")), extractFile); } public CheckCaDSRServiceStep(EndpointReferenceType endpoint, File extractFile) { super(); this.endpoint = endpoint; this.extractFile = extractFile; } public void runStep() throws Exception { CaDSRServiceI cadsr = new CaDSRServiceClient(endpoint.getAddress().toString()); DomainModel extract = null; if (extractFile == null) { //extract = CaDSRExtractUtils.findExtract(cadsr, "Genomic Identifiers"); extract = CaDSRExtractUtils.findExtract(cadsr, "caTIES"); } else { extract = CaDSRExtractUtils.readExtract(extractFile); } // find project Project[] projects = cadsr.findAllProjects(); Project project = null; for (Project myProject : projects) { if (myProject.longName.equals(extract.getProjectLongName())) { project = myProject; break; } } // assert everything looks good compareProject(extract, cadsr, project); } @SuppressWarnings("unchecked") private void compareProject(DomainModel extract, CaDSRServiceI cadsr, Project project) throws RemoteException { assertNotNull(project); assertEquals(extract.getProjectLongName(), project.longName); assertEquals(extract.getProjectShortName(), project.shortName); assertEquals(extract.getProjectDescription(), project.description); assertEquals(extract.getProjectVersion(), project.version); UMLClass[] extractCls = extract.getExposedUMLClassCollection().getUMLClass(); UMLClassMetadata[] cls = cadsr.findClassesInProject(project);//(UMLClassMetadata[]) project.getUMLClassMetadataCollection().toArray(new UMLClassMetadata[0]); assertEquals(extractCls.length, cls.length); compareClasses(cadsr, extractCls, project, cls); gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation[] extractAssocations = extract.getExposedUMLAssociationCollection().getUMLAssociation(); gov.nih.nci.cagrid.cadsr.domain.UMLAssociation[] assocations = cadsr.findAssociationsInProject(project); if (extractAssocations == null && assocations == null) { // some models don't have associations? } else { assertEquals(extractAssocations.length, assocations.length); compareAssociations(extractAssocations, assocations); } } private void compareClasses(CaDSRServiceI cadsr, UMLClass[] extractCls, Project project, UMLClassMetadata[] cls) throws RemoteException { for (UMLClass extractCl : extractCls) { UMLClassMetadata cl = findClass(extractCl, cls); assertNotNull(cl); assertEquals(extractCl.getClassName(), cl.getFullyQualifiedName()); assertEquals(extractCl.getDescription(), cl.getDescription()); SemanticMetadata[] extractMetadata = extractCl.getSemanticMetadataCollection().getSemanticMetadata(); SemanticMetadata[] metadata = cadsr.findSemanticMetadataForClass(project, cl); assertEquals(extractMetadata.length, metadata.length); compareMetadata(cadsr, extractMetadata, metadata); UMLAttribute[] extractAtts = extractCl.getUmlAttributeCollection().getUMLAttribute(); UMLAttributeMetadata[] atts = cadsr.findAttributesInClass(project, cl); assertEquals(extractAtts.length, atts.length); compareAttributes(cadsr, extractAtts, atts); } } private void compareMetadata(CaDSRServiceI cadsr, SemanticMetadata[] extractMetadata, SemanticMetadata[] metadata) { for (SemanticMetadata em : extractMetadata) { assertNotNull(em); SemanticMetadata m = findSemanticMetadata(em, metadata); assertNotNull(m); assertEquals(m.conceptCode, em.conceptCode); assertEquals(m.conceptDefinition, em.conceptDefinition); assertEquals(m.conceptName, em.conceptName); assertEquals(m.id, em.id); assertEquals(m.isPrimaryConcept, em.isPrimaryConcept); assertEquals(m.order, em.order); assertEquals(m.orderLevel, em.orderLevel); } } private void compareAttributes(CaDSRServiceI cadsr, UMLAttribute[] extractAtts, UMLAttributeMetadata[] atts) throws RemoteException { for (UMLAttribute extractAtt : extractAtts) { assertNotNull(extractAtt); UMLAttributeMetadata att = findAttribute(extractAtt, atts); assertNotNull(att); assertEquals(extractAtt.getDescription(), att.description); assertEquals(getExtractAttributeName(extractAtt), att.name); } } private void compareAssociations(gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation[] extractAssociations, gov.nih.nci.cagrid.cadsr.domain.UMLAssociation[] associations) { for (gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation extractAssociation : extractAssociations) { assertNotNull(extractAssociation); gov.nih.nci.cagrid.cadsr.domain.UMLAssociation association = findAssociation(extractAssociation, associations); assertNotNull(association); } } private UMLAssociation findAssociation(gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation extractAssociation, gov.nih.nci.cagrid.cadsr.domain.UMLAssociation[] associations) { for (gov.nih.nci.cagrid.cadsr.domain.UMLAssociation association : associations) { //String extractSourceClass = extractAssociation.getSourceUMLAssociationEdge().getUMLAssociationEdge().getUmlClass().getUMLClass().getClassName(); //String sourceClass = association.getSourceUMLClassMetadata().getUMLClassMetadata().fullyQualifiedName; //assertEquals(extractSourceClass, sourceClass); return association; } return null; } private UMLAttributeMetadata findAttribute(UMLAttribute extractAtt, UMLAttributeMetadata[] atts) { // extractAtt.getName()=Gene:ensemblgeneID // att.getName()=ensemblgeneID for (UMLAttributeMetadata att : atts) { if (getExtractAttributeName(extractAtt).equals(att.name)) return att; } return null; } private String getExtractAttributeName(UMLAttribute extractAtt) { String extractName = extractAtt.getName(); int index = extractName.indexOf(':'); if (index != -1) extractName = extractName.substring(index+1); return extractName; } private SemanticMetadata findSemanticMetadata(SemanticMetadata em, SemanticMetadata[] metadata) { for (SemanticMetadata m : metadata) { if (em.id.equals(m.id)) return m; } return null; } private UMLClassMetadata findClass(UMLClass extractCl, UMLClassMetadata[] cls) { for (UMLClassMetadata cl : cls) { if (extractCl.getClassName().equals(cl.getFullyQualifiedName())) return cl; } return null; } public static void main(String[] args) throws Exception { new CheckCaDSRServiceStep( new EndpointReferenceType(new Address("http://cagrid05.bmi.ohio-state.edu:8080/wsrf/services/cagrid/CaDSRService")), null ).runStep(); } }
fixed a couple problems with package name checking and nulls
cagrid-1-0/tests/projects/coretests/test/src/java/gov/nci/nih/cagrid/tests/core/steps/CheckCaDSRServiceStep.java
fixed a couple problems with package name checking and nulls
<ide><path>agrid-1-0/tests/projects/coretests/test/src/java/gov/nci/nih/cagrid/tests/core/steps/CheckCaDSRServiceStep.java <ide> <ide> DomainModel extract = null; <ide> if (extractFile == null) { <del> //extract = CaDSRExtractUtils.findExtract(cadsr, "Genomic Identifiers"); <del> extract = CaDSRExtractUtils.findExtract(cadsr, "caTIES"); <add> extract = CaDSRExtractUtils.findExtract(cadsr, "Genomic Identifiers"); <add> //extract = CaDSRExtractUtils.findExtract(cadsr, "caTIES"); <ide> } else { <ide> extract = CaDSRExtractUtils.readExtract(extractFile); <ide> } <ide> for (UMLClass extractCl : extractCls) { <ide> UMLClassMetadata cl = findClass(extractCl, cls); <ide> assertNotNull(cl); <del> assertEquals(extractCl.getClassName(), cl.getFullyQualifiedName()); <add> assertEquals(extractCl.getPackageName() + "." + extractCl.getClassName(), cl.getFullyQualifiedName()); <ide> assertEquals(extractCl.getDescription(), cl.getDescription()); <ide> <ide> SemanticMetadata[] extractMetadata = extractCl.getSemanticMetadataCollection().getSemanticMetadata(); <ide> UMLAttributeMetadata att = findAttribute(extractAtt, atts); <ide> assertNotNull(att); <ide> <del> assertEquals(extractAtt.getDescription(), att.description); <add> assertTrue( <add> (extractAtt.getDescription() == null && att.description == null) || <add> (extractAtt.getDescription() == null && "".equals(att.description)) || <add> ("".equals(extractAtt.getDescription()) && att.description == null) || <add> extractAtt.getDescription().equals(att.description) <add> ); <add> //assertEquals(extractAtt.getDescription(), att.description); <ide> assertEquals(getExtractAttributeName(extractAtt), att.name); <ide> } <ide> } <ide> <ide> private UMLClassMetadata findClass(UMLClass extractCl, UMLClassMetadata[] cls) <ide> { <add> String className = extractCl.getPackageName() + "." + extractCl.getClassName(); <ide> for (UMLClassMetadata cl : cls) { <del> if (extractCl.getClassName().equals(cl.getFullyQualifiedName())) return cl; <add> if (className.equals(cl.getFullyQualifiedName())) return cl; <ide> } <ide> return null; <ide> } <ide> public static void main(String[] args) <ide> throws Exception <ide> { <add> CaDSRExtractUtils.setAxisConfig(new File("etc", "cadsr" + File.separator + "client-config.wsdd")); <ide> new CheckCaDSRServiceStep( <del> new EndpointReferenceType(new Address("http://cagrid05.bmi.ohio-state.edu:8080/wsrf/services/cagrid/CaDSRService")), <del> null <add> new EndpointReferenceType(new Address("http://localhost:8080/wsrf/services/cagrid/CaDSRService")), <add> new File("test", "resources" + File.separator + "CheckCaDSRServiceStep" + File.separator + "caTIES_extract.xml") <ide> ).runStep(); <ide> } <ide> }
Java
apache-2.0
aa46de674ee8b7b25c5ae65a0d8e0668eece8ca9
0
FlamingoIndustries/Calculator3.0
package formulator; import java.util.HashMap; import java.util.Vector; import javax.swing.SwingUtilities; public class GraphControl { public Vector<GraphFunction> graphlist = new Vector<GraphFunction>(); public HashMap<String, FormulaElement> formulas; public String text; public GraphControl(Vector<GraphFunction> graphs, HashMap<String, FormulaElement> map, String formulatext){ graphlist = graphs; formulas = map; text = formulatext; doGraph(); } public void doGraph() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CartesianFrame frame = new CartesianFrame(graphlist, false, true, true, true); frame.showUI(); frame.toFront(); frame.repaint(); } }); } }
Calc3/src/formulator/GraphControl.java
package formulator; import java.util.HashMap; import java.util.Vector; import javax.swing.SwingUtilities; public class GraphControl { public Vector<GraphFunction> graphlist = new Vector<GraphFunction>(); public HashMap<String, FormulaElement> formulas; public GraphControl(Vector<GraphFunction> graphs, HashMap<String, FormulaElement> map){ graphlist = graphs; formulas = map; doGraph(); } public void doGraph() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CartesianFrame frame = new CartesianFrame(graphlist, false, true, true, true); frame.showUI(); frame.toFront(); frame.repaint(); } }); } }
title thingy
Calc3/src/formulator/GraphControl.java
title thingy
<ide><path>alc3/src/formulator/GraphControl.java <ide> <ide> public Vector<GraphFunction> graphlist = new Vector<GraphFunction>(); <ide> public HashMap<String, FormulaElement> formulas; <del> public GraphControl(Vector<GraphFunction> graphs, HashMap<String, FormulaElement> map){ <add> public String text; <add> public GraphControl(Vector<GraphFunction> graphs, HashMap<String, FormulaElement> map, String formulatext){ <ide> graphlist = graphs; <ide> formulas = map; <add> text = formulatext; <ide> doGraph(); <ide> } <ide> <ide> <ide> SwingUtilities.invokeLater(new Runnable() { <ide> <del> <ide> @Override <ide> public void run() { <ide> CartesianFrame frame = new CartesianFrame(graphlist, false, true, true, true);
JavaScript
mit
395c3d524a0228244313093bbfa81bf795095b69
0
kovacsv/Online3DViewer,kovacsv/Online3DViewer,kovacsv/Online3DViewer,kovacsv/Online3DViewer
OV.ThreeImporter = class extends OV.ImporterBase { constructor () { super (); } CanImportExtension (extension) { return extension === 'fbx'; } GetKnownFileFormats () { return { 'fbx' : OV.FileFormat.Binary }; } GetUpDirection () { return OV.Direction.Z; } ClearContent () { } ResetContent () { } ImportContent (fileContent, onFinish) { const libraries = this.GetExternalLibraries (); if (libraries === null) { onFinish (); return; } Promise.all (libraries).then (() => { const loader = this.CreateLoader (); this.LoadModel (fileContent, loader, onFinish); }).catch (() => { onFinish (); }); } GetExternalLibraries () { if (this.extension === 'fbx') { return [ OV.LoadExternalLibrary ('three_loaders/FBXLoader.js'), OV.LoadExternalLibrary ('three_loaders/fflate.min.js') ]; } return null; } CreateLoader () { const manager = new THREE.LoadingManager (); manager.setURLModifier ((url) => { if (url.startsWith ('data:') || url.startsWith ('blob:')) { return url; } const fileBuffer = this.callbacks.getFileBuffer (url); const fileUrl = OV.CreateObjectUrl (fileBuffer); return fileUrl; }); let loader = null; if (this.extension === 'fbx') { loader = new THREE.FBXLoader (manager); } return loader; } LoadModel (fileContent, loader, onFinish) { function SetColor (color, threeColor) { color.Set ( parseInt (threeColor.r * 255.0, 10), parseInt (threeColor.g * 255.0, 10), parseInt (threeColor.b * 255.0, 10) ); } if (loader === null) { onFinish (); return; } // TODO: error handling const mainFileUrl = OV.CreateObjectUrl (fileContent); loader.load (mainFileUrl, (object) => { object.traverse ((child) => { if (child.isMesh) { // TODO: merge same materials // TODO: PBR materials console.log (child); let threeMaterial = child.material; let material = new OV.Material (OV.MaterialType.Phong); material.name = threeMaterial.name; SetColor (material.color, threeMaterial.color); if (threeMaterial.type === 'MeshPhongMaterial') { SetColor (material.specular, threeMaterial.specular); material.shininess = threeMaterial.shininess / 100.0; } const materialIndex = this.model.AddMaterial (material); let mesh = OV.ConvertThreeGeometryToMesh (child.geometry, materialIndex); if (child.matrixWorld !== undefined && child.matrixWorld !== null) { const matrix = new OV.Matrix (child.matrixWorld.elements); const transformation = new OV.Transformation (matrix); // TODO: flip to transform mesh let determinant = matrix.Determinant (); let mirrorByX = OV.IsNegative (determinant); if (mirrorByX) { OV.FlipMeshTrianglesOrientation (mesh); } OV.TransformMesh (mesh, transformation); } // TODO: transform this.model.AddMesh (mesh); } }); onFinish (); }); } };
source/threejs/threeimporter.js
OV.ThreeImporter = class extends OV.ImporterBase { constructor () { super (); } CanImportExtension (extension) { return extension === 'fbx'; } GetKnownFileFormats () { return { 'fbx' : OV.FileFormat.Binary }; } GetUpDirection () { return OV.Direction.Z; } ClearContent () { } ResetContent () { } ImportContent (fileContent, onFinish) { const libraries = this.GetExternalLibraries (); if (libraries === null) { onFinish (); return; } Promise.all (libraries).then (() => { const loader = this.CreateLoader (); this.LoadModel (fileContent, loader, onFinish); }).catch (() => { onFinish (); }); } GetExternalLibraries () { if (this.extension === 'fbx') { return [ OV.LoadExternalLibrary ('three_loaders/FBXLoader.js'), OV.LoadExternalLibrary ('three_loaders/fflate.min.js') ]; } return null; } CreateLoader () { const manager = new THREE.LoadingManager (); manager.setURLModifier ((url) => { if (url.startsWith ('data:') || url.startsWith ('blob:')) { return url; } const fileBuffer = this.callbacks.getFileBuffer (url); const fileUrl = OV.CreateObjectUrl (fileBuffer); return fileUrl; }); let loader = null; if (this.extension === 'fbx') { loader = new THREE.FBXLoader (manager); } return loader; } LoadModel (fileContent, loader, onFinish) { function SetColor (color, threeColor) { color.Set ( parseInt (threeColor.r * 255.0, 10), parseInt (threeColor.g * 255.0, 10), parseInt (threeColor.b * 255.0, 10) ); } if (loader === null) { onFinish (); return; } // TODO: error handling const mainFileUrl = OV.CreateObjectUrl (fileContent); loader.load (mainFileUrl, (object) => { object.traverse ((child) => { if (child.isMesh) { // TODO: merge same materials // TODO: PBR materials console.log (child); setTimeout (() => { console.log (child); }, 2000); let threeMaterial = child.material; let material = new OV.Material (OV.MaterialType.Phong); material.name = threeMaterial.name; SetColor (material.color, threeMaterial.color); if (threeMaterial.type === 'MeshPhongMaterial') { SetColor (material.specular, threeMaterial.specular); material.shininess = threeMaterial.shininess / 100.0; } const materialIndex = this.model.AddMaterial (material); let mesh = OV.ConvertThreeGeometryToMesh (child.geometry, materialIndex); // TODO: transform this.model.AddMesh (mesh); } }); onFinish (); }); } };
Transform meshes.
source/threejs/threeimporter.js
Transform meshes.
<ide><path>ource/threejs/threeimporter.js <ide> // TODO: merge same materials <ide> // TODO: PBR materials <ide> console.log (child); <del> setTimeout (() => { <del> console.log (child); <del> }, 2000); <ide> let threeMaterial = child.material; <ide> let material = new OV.Material (OV.MaterialType.Phong); <ide> material.name = threeMaterial.name; <ide> } <ide> const materialIndex = this.model.AddMaterial (material); <ide> let mesh = OV.ConvertThreeGeometryToMesh (child.geometry, materialIndex); <add> if (child.matrixWorld !== undefined && child.matrixWorld !== null) { <add> const matrix = new OV.Matrix (child.matrixWorld.elements); <add> const transformation = new OV.Transformation (matrix); <add> <add> // TODO: flip to transform mesh <add> let determinant = matrix.Determinant (); <add> let mirrorByX = OV.IsNegative (determinant); <add> if (mirrorByX) { <add> OV.FlipMeshTrianglesOrientation (mesh); <add> } <add> OV.TransformMesh (mesh, transformation); <add> } <ide> // TODO: transform <ide> this.model.AddMesh (mesh); <ide> }
JavaScript
mit
c8a685c800a9a40b936c84a2c94f10526bab6823
0
Medallyon/exambot,Medallyon/exambot
// import external modules necessary for this project var Discord = require("Discord.js") , colors = require("colors/safe") , fs = require("fs-extra") , wikijs = require("wikijs"); // import external files, such as the config var config = require("./config.json"); // initiate a new client from the Discord.js library var client = new Discord.Client({ forceFetchUsers: true }); // set the theme for the console to make it less confusing colors.setTheme({ log: 'cyan', output: 'green', info: 'yellow', warn: 'red', error: 'red' }); client.on("ready", function() { // the bot is logged in - time to console.log() console.log(colors.log("Logged in and ready to go!\nCurrently serving " + client.guilds.size + " guilds and " + client.users.size + " users.")); }) client.on("message", function(msg) { // define and then console.log() basic output based on if the message was sent on a public guild or in a private channel let output = (msg.guild ? `${new Date()}\n@${msg.author.username}: "${msg.content}"\n${msg.guild.name} #${msg.channel.name}` : `${new Date()}\n@${msg.author}: "${msg.content}"\nDM: #${msg.channel.recipient}`); console.log(colors.log("\n" + output)); // stop here - we don't want the bot to respond to itself! if (msg.author.id === client.user.id) return; }) client.login(config.token);
index.js
// import external modules necessary for this project var Discord = require("Discord.js") , colors = require("colors/safe") , fs = require("fs-extra") , wikijs = require("wikijs"); // import external files, such as the config var config = require("./config.json"); // initiate a new client from the Discord.js library var client = new Discord.Client({ forceFetchUsers: true }); // set the theme for the console to make it less confusing colors.setTheme({ log: 'cyan', output: 'green', info: 'yellow', warn: 'red', error: 'red' }); client.on("ready", function() { console.log(colors.log("Logged in and ready to go!\nCurrently serving " + client.guilds.size + " guilds and " + client.users.size + " users.")); }) client.on("message", function(msg) { let output = (msg.guild ? `${new Date()}\n@${msg.author.username}: "${msg.content}"\n${msg.guild.name} #${msg.channel.name}` : `${new Date()}\n@${msg.author}: "${msg.content}"\nDM: #${msg.channel.recipient}`); console.log(colors.log("\n" + output)); if (msg.author.id === client.user.id) return; }) client.login(config.token);
Added comments.
index.js
Added comments.
<ide><path>ndex.js <ide> <ide> client.on("ready", function() <ide> { <add> // the bot is logged in - time to console.log() <ide> console.log(colors.log("Logged in and ready to go!\nCurrently serving " + client.guilds.size + " guilds and " + client.users.size + " users.")); <ide> }) <ide> <ide> client.on("message", function(msg) <ide> { <add> // define and then console.log() basic output based on if the message was sent on a public guild or in a private channel <ide> let output = (msg.guild ? `${new Date()}\n@${msg.author.username}: "${msg.content}"\n${msg.guild.name} #${msg.channel.name}` : `${new Date()}\n@${msg.author}: "${msg.content}"\nDM: #${msg.channel.recipient}`); <ide> console.log(colors.log("\n" + output)); <ide> <add> // stop here - we don't want the bot to respond to itself! <ide> if (msg.author.id === client.user.id) return; <ide> }) <ide>
Java
apache-2.0
a6a99d1328fbf94725b11a349ed1d1f379ca5f9d
0
blademainer/intellij-community,semonte/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,semonte/intellij-community,ryano144/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,jexp/idea2,FHannes/intellij-community,caot/intellij-community,izonder/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,robovm/robovm-studio,da1z/intellij-community,vvv1559/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,hurricup/intellij-community,jexp/idea2,TangHao1987/intellij-community,da1z/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,da1z/intellij-community,signed/intellij-community,allotria/intellij-community,signed/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,kdwink/intellij-community,blademainer/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,samthor/intellij-community,caot/intellij-community,robovm/robovm-studio,consulo/consulo,dslomov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,joewalnes/idea-community,robovm/robovm-studio,diorcety/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,supersven/intellij-community,xfournet/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,semonte/intellij-community,kool79/intellij-community,blademainer/intellij-community,samthor/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,supersven/intellij-community,asedunov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,signed/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,xfournet/intellij-community,slisson/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,supersven/intellij-community,fnouama/intellij-community,caot/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,jagguli/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,adedayo/intellij-community,caot/intellij-community,ibinti/intellij-community,ernestp/consulo,hurricup/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,holmes/intellij-community,fnouama/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,holmes/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ernestp/consulo,retomerz/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,caot/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,signed/intellij-community,ibinti/intellij-community,adedayo/intellij-community,jexp/idea2,SerCeMan/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,holmes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,fitermay/intellij-community,retomerz/intellij-community,kool79/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,holmes/intellij-community,adedayo/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,joewalnes/idea-community,slisson/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,slisson/intellij-community,signed/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,clumsy/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,kdwink/intellij-community,amith01994/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,samthor/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,apixandru/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,vladmm/intellij-community,semonte/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,retomerz/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,FHannes/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,consulo/consulo,youdonghai/intellij-community,dslomov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,jexp/idea2,ftomassetti/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,blademainer/intellij-community,FHannes/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,izonder/intellij-community,diorcety/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,ftomassetti/intellij-community,fitermay/intellij-community,allotria/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,fitermay/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,kdwink/intellij-community,adedayo/intellij-community,slisson/intellij-community,apixandru/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,kool79/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,ernestp/consulo,SerCeMan/intellij-community,ryano144/intellij-community,semonte/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,petteyg/intellij-community,apixandru/intellij-community,adedayo/intellij-community,joewalnes/idea-community,ibinti/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,kdwink/intellij-community,supersven/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,kool79/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,semonte/intellij-community,jagguli/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,allotria/intellij-community,clumsy/intellij-community,hurricup/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,caot/intellij-community,diorcety/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,slisson/intellij-community,apixandru/intellij-community,semonte/intellij-community,caot/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,allotria/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,ernestp/consulo,lucafavatella/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,izonder/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,xfournet/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,supersven/intellij-community,FHannes/intellij-community,retomerz/intellij-community,caot/intellij-community,holmes/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kdwink/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,samthor/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,izonder/intellij-community,caot/intellij-community,supersven/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,jexp/idea2,izonder/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,jexp/idea2,salguarnieri/intellij-community,ernestp/consulo,allotria/intellij-community,petteyg/intellij-community,ernestp/consulo,robovm/robovm-studio,MER-GROUP/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,kool79/intellij-community,jagguli/intellij-community,ryano144/intellij-community,da1z/intellij-community,dslomov/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,jexp/idea2,vladmm/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,holmes/intellij-community,slisson/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,fnouama/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,kool79/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ibinti/intellij-community,da1z/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,diorcety/intellij-community,semonte/intellij-community,allotria/intellij-community,adedayo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,diorcety/intellij-community,holmes/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,allotria/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,vladmm/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,signed/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,signed/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,slisson/intellij-community,dslomov/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,signed/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,semonte/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,kool79/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,joewalnes/idea-community,consulo/consulo,samthor/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,samthor/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,izonder/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,kdwink/intellij-community,FHannes/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,supersven/intellij-community,suncycheng/intellij-community,consulo/consulo,idea4bsd/idea4bsd,Distrotech/intellij-community,caot/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,semonte/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,da1z/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ryano144/intellij-community,blademainer/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,apixandru/intellij-community,jagguli/intellij-community,da1z/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,adedayo/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,holmes/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community
package com.intellij.openapi.vcs.actions; import com.intellij.CommonBundle; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.diff.DiffProvider; import com.intellij.openapi.vcs.history.HistoryAsTreeProvider; import com.intellij.openapi.vcs.history.VcsFileRevision; import com.intellij.openapi.vcs.history.VcsHistoryProvider; import com.intellij.openapi.vcs.history.VcsHistorySession; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.SpeedSearchBase; import com.intellij.ui.TableUtil; import com.intellij.ui.dualView.TreeTableView; import com.intellij.ui.table.TableView; import com.intellij.util.Consumer; import com.intellij.util.TreeItem; import com.intellij.util.ui.ColumnInfo; import com.intellij.util.ui.ListTableModel; import com.intellij.util.ui.treetable.ListTreeTableModelOnColumns; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.util.List; public class CompareWithSelectedRevisionAction extends AbstractVcsAction { private static final ColumnInfo<TreeNodeAdapter,String> BRANCH_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revisions.list.branch")){ public String valueOf(final TreeNodeAdapter object) { return object.getRevision().getBranchName(); } }; private static final ColumnInfo<TreeNodeAdapter,String> REVISION_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revision.list.revision")){ public String valueOf(final TreeNodeAdapter object) { return object.getRevision().getRevisionNumber().asString(); } }; private static final ColumnInfo<TreeNodeAdapter,String> DATE_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revisions.list.filter")){ public String valueOf(final TreeNodeAdapter object) { return VcsRevisionListCellRenderer.DATE_FORMAT.format(object.getRevision().getRevisionDate()); } }; private static final ColumnInfo<TreeNodeAdapter,String> AUTHOR_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revision.list.author")){ public String valueOf(final TreeNodeAdapter object) { return object.getRevision().getAuthor(); } }; private static final ColumnInfo<VcsFileRevision, String> REVISION_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revision.list.revision")) { public String valueOf(final VcsFileRevision vcsFileRevision) { return vcsFileRevision.getRevisionNumber().asString(); } }; private static final ColumnInfo<VcsFileRevision, String> DATE_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revision.list.revision")) { public String valueOf(final VcsFileRevision vcsFileRevision) { return VcsRevisionListCellRenderer.DATE_FORMAT.format(vcsFileRevision.getRevisionDate()); } }; private static final ColumnInfo<VcsFileRevision,String> AUTHOR_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revision.list.author")){ public String valueOf(final VcsFileRevision vcsFileRevision) { return vcsFileRevision.getAuthor(); } }; private static final ColumnInfo<VcsFileRevision,String> BRANCH_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revisions.list.branch")){ public String valueOf(final VcsFileRevision vcsFileRevision) { return vcsFileRevision.getBranchName(); } }; public void update(VcsContext e, Presentation presentation) { AbstractShowDiffAction.updateDiffAction(presentation, e); } protected boolean forceSyncUpdate(final AnActionEvent e) { return true; } protected void actionPerformed(VcsContext vcsContext) { final VirtualFile file = vcsContext.getSelectedFiles()[0]; final Project project = vcsContext.getProject(); final AbstractVcs vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file); final VcsHistoryProvider vcsHistoryProvider = vcs.getVcsHistoryProvider(); try { final VcsHistorySession session = vcsHistoryProvider.createSessionFor(new FilePathImpl(file)); if (session == null) return; final List<VcsFileRevision> revisions = session.getRevisionList(); final HistoryAsTreeProvider treeHistoryProvider = vcsHistoryProvider.getTreeHistoryProvider(); if (treeHistoryProvider != null) { showTreePopup(treeHistoryProvider.createTreeOn(revisions), file, project, vcs.getDiffProvider()); } else { showListPopup(revisions, project, new Consumer<VcsFileRevision>() { public void consume(final VcsFileRevision revision) { DiffActionExecutor.showDiff(vcs.getDiffProvider(), revision.getRevisionNumber(), file, project); } }, true); } } catch (VcsException e1) { Messages.showErrorDialog(VcsBundle.message("message.text.cannot.show.differences", e1.getMessage()), CommonBundle.message("title.error")); } } private static void showTreePopup(final List<TreeItem<VcsFileRevision>> roots, final VirtualFile file, final Project project, final DiffProvider diffProvider) { final TreeTableView treeTable = new TreeTableView(new ListTreeTableModelOnColumns(new TreeNodeAdapter(null, null, roots), new ColumnInfo[]{BRANCH_COLUMN, REVISION_COLUMN, DATE_COLUMN, AUTHOR_COLUMN})); Runnable runnable = new Runnable() { public void run() { int index = treeTable.getSelectionModel().getMinSelectionIndex(); if (index == -1) { return; } VcsFileRevision revision = getRevisionAt(treeTable, index); if (revision != null) { DiffActionExecutor.showDiff(diffProvider, revision.getRevisionNumber(), file, project); } } }; treeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); new PopupChooserBuilder(treeTable). setTitle(VcsBundle.message("lookup.title.vcs.file.revisions")). setItemChoosenCallback(runnable). setSouthComponent(createCommentsPanel(treeTable)). setResizable(true). setDimensionServiceKey("Vcs.CompareWithSelectedRevision.Popup"). createPopup(). showCenteredInCurrentWindow(project); } @Nullable private static VcsFileRevision getRevisionAt(final TreeTableView treeTable, final int index) { final List items = treeTable.getItems(); if (items.size() <= index) { return null; } else { return ((TreeNodeAdapter)items.get(index)).getRevision(); } } private static JPanel createCommentsPanel(final TreeTableView treeTable) { JPanel panel = new JPanel(new BorderLayout()); final JTextArea textArea = createTextArea(); treeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { final int index = treeTable.getSelectionModel().getMinSelectionIndex(); if (index == -1) { textArea.setText(""); } else { final VcsFileRevision revision = getRevisionAt(treeTable, index); if (revision != null) { textArea.setText(revision.getCommitMessage()); } else { textArea.setText(""); } } } }); final JScrollPane textScrollPane = new JScrollPane(textArea); panel.add(textScrollPane, BorderLayout.CENTER); textScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.lightGray),VcsBundle.message("border.selected.revision.commit.message"))); return panel; } private static JTextArea createTextArea() { final JTextArea textArea = new JTextArea(); textArea.setRows(5); textArea.setEditable(false); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); return textArea; } public static void showListPopup(final List<VcsFileRevision> revisions, final Project project, final Consumer<VcsFileRevision> selectedRevisionConsumer, final boolean showComments) { ColumnInfo[] columns = new ColumnInfo[] { REVISION_TABLE_COLUMN, DATE_TABLE_COLUMN, AUTHOR_TABLE_COLUMN }; for(VcsFileRevision revision: revisions) { if (revision.getBranchName() != null) { columns = new ColumnInfo[] { REVISION_TABLE_COLUMN, BRANCH_TABLE_COLUMN, DATE_TABLE_COLUMN, AUTHOR_TABLE_COLUMN }; break; } } final TableView<VcsFileRevision> table = new TableView<VcsFileRevision>(new ListTableModel<VcsFileRevision>(columns, revisions, 0)); table.setShowHorizontalLines(false); table.setTableHeader(null); Runnable runnable = new Runnable() { public void run() { VcsFileRevision revision = table.getSelectedObject(); if (revision != null) { selectedRevisionConsumer.consume(revision); } } }; if (table.getModel().getRowCount() == 0) { table.clearSelection(); } new SpeedSearchBase<TableView>(table) { protected int getSelectedIndex() { return table.getSelectedRow(); } protected Object[] getAllElements() { return revisions.toArray(); } protected String getElementText(Object element) { VcsFileRevision revision = (VcsFileRevision) element; return revision.getRevisionNumber().asString() + " " + revision.getBranchName() + " " + revision.getAuthor(); } protected void selectElement(Object element, String selectedText) { VcsFileRevision revision = (VcsFileRevision) element; TableUtil.selectRows(myComponent, new int[] {revisions.indexOf(revision)}); TableUtil.scrollSelectionToVisible(myComponent); } }; table.setMinimumSize(new Dimension(300, 50)); final PopupChooserBuilder builder = new PopupChooserBuilder(table); if (showComments) { builder.setSouthComponent(createCommentsPanel(table)); } builder.setTitle(VcsBundle.message("lookup.title.vcs.file.revisions")). setItemChoosenCallback(runnable). setResizable(true). setDimensionServiceKey("Vcs.CompareWithSelectedRevision.Popup").setMinSize(new Dimension(300, 300)); final JBPopup popup = builder.createPopup(); popup.showCenteredInCurrentWindow(project); } private static JPanel createCommentsPanel(final TableView<VcsFileRevision> table) { final JTextArea textArea = createTextArea(); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { final VcsFileRevision revision = table.getSelectedObject(); if (revision == null) { textArea.setText(""); } else { textArea.setText(revision.getCommitMessage()); textArea.select(0, 0); } } }); JPanel jPanel = new JPanel(new BorderLayout()); final JScrollPane textScrollPane = new JScrollPane(textArea); textScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.lightGray),VcsBundle.message("border.selected.revision.commit.message"))); jPanel.add(textScrollPane, BorderLayout.SOUTH); jPanel.setPreferredSize(new Dimension(300, 100)); return jPanel; } private static class TreeNodeAdapter extends DefaultMutableTreeNode { private TreeItem<VcsFileRevision> myRevision; public TreeNodeAdapter(TreeNodeAdapter parent, TreeItem<VcsFileRevision> revision, List<TreeItem<VcsFileRevision>> children) { if (parent != null) { parent.add(this); } myRevision = revision; for (TreeItem<VcsFileRevision> treeItem : children) { new TreeNodeAdapter(this, treeItem, treeItem.getChildren()); } } public VcsFileRevision getRevision() { return myRevision.getData(); } } }
vcs-impl/src/com/intellij/openapi/vcs/actions/CompareWithSelectedRevisionAction.java
package com.intellij.openapi.vcs.actions; import com.intellij.CommonBundle; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.diff.DiffProvider; import com.intellij.openapi.vcs.history.HistoryAsTreeProvider; import com.intellij.openapi.vcs.history.VcsFileRevision; import com.intellij.openapi.vcs.history.VcsHistoryProvider; import com.intellij.openapi.vcs.history.VcsHistorySession; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.SpeedSearchBase; import com.intellij.ui.TableUtil; import com.intellij.ui.dualView.TreeTableView; import com.intellij.ui.table.TableView; import com.intellij.util.Consumer; import com.intellij.util.TreeItem; import com.intellij.util.ui.ColumnInfo; import com.intellij.util.ui.ListTableModel; import com.intellij.util.ui.treetable.ListTreeTableModelOnColumns; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.util.List; public class CompareWithSelectedRevisionAction extends AbstractVcsAction { private static final ColumnInfo<TreeNodeAdapter,String> BRANCH_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revisions.list.branch")){ public String valueOf(final TreeNodeAdapter object) { return object.getRevision().getBranchName(); } }; private static final ColumnInfo<TreeNodeAdapter,String> REVISION_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revision.list.revision")){ public String valueOf(final TreeNodeAdapter object) { return object.getRevision().getRevisionNumber().asString(); } }; private static final ColumnInfo<TreeNodeAdapter,String> DATE_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revisions.list.filter")){ public String valueOf(final TreeNodeAdapter object) { return VcsRevisionListCellRenderer.DATE_FORMAT.format(object.getRevision().getRevisionDate()); } }; private static final ColumnInfo<TreeNodeAdapter,String> AUTHOR_COLUMN = new ColumnInfo<TreeNodeAdapter, String>(VcsBundle.message("column.name.revision.list.author")){ public String valueOf(final TreeNodeAdapter object) { return object.getRevision().getAuthor(); } }; private static final ColumnInfo<VcsFileRevision, String> REVISION_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revision.list.revision")) { public String valueOf(final VcsFileRevision vcsFileRevision) { return vcsFileRevision.getRevisionNumber().asString(); } }; private static final ColumnInfo<VcsFileRevision, String> DATE_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revision.list.revision")) { public String valueOf(final VcsFileRevision vcsFileRevision) { return VcsRevisionListCellRenderer.DATE_FORMAT.format(vcsFileRevision.getRevisionDate()); } }; private static final ColumnInfo<VcsFileRevision,String> AUTHOR_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revision.list.author")){ public String valueOf(final VcsFileRevision vcsFileRevision) { return vcsFileRevision.getAuthor(); } }; private static final ColumnInfo<VcsFileRevision,String> BRANCH_TABLE_COLUMN = new ColumnInfo<VcsFileRevision, String>(VcsBundle.message("column.name.revisions.list.branch")){ public String valueOf(final VcsFileRevision vcsFileRevision) { return vcsFileRevision.getBranchName(); } }; public void update(VcsContext e, Presentation presentation) { AbstractShowDiffAction.updateDiffAction(presentation, e); } protected boolean forceSyncUpdate(final AnActionEvent e) { return true; } protected void actionPerformed(VcsContext vcsContext) { final VirtualFile file = vcsContext.getSelectedFiles()[0]; final Project project = vcsContext.getProject(); final AbstractVcs vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file); final VcsHistoryProvider vcsHistoryProvider = vcs.getVcsHistoryProvider(); try { final VcsHistorySession session = vcsHistoryProvider.createSessionFor(new FilePathImpl(file)); if (session == null) return; final List<VcsFileRevision> revisions = session.getRevisionList(); final HistoryAsTreeProvider treeHistoryProvider = vcsHistoryProvider.getTreeHistoryProvider(); if (treeHistoryProvider != null) { showTreePopup(treeHistoryProvider.createTreeOn(revisions), file, project, vcs.getDiffProvider()); } else { showListPopup(revisions, project, new Consumer<VcsFileRevision>() { public void consume(final VcsFileRevision revision) { DiffActionExecutor.showDiff(vcs.getDiffProvider(), revision.getRevisionNumber(), file, project); } }, true); } } catch (VcsException e1) { Messages.showErrorDialog(VcsBundle.message("message.text.cannot.show.differences"), CommonBundle.message("title.error")); } } private static void showTreePopup(final List<TreeItem<VcsFileRevision>> roots, final VirtualFile file, final Project project, final DiffProvider diffProvider) { final TreeTableView treeTable = new TreeTableView(new ListTreeTableModelOnColumns(new TreeNodeAdapter(null, null, roots), new ColumnInfo[]{BRANCH_COLUMN, REVISION_COLUMN, DATE_COLUMN, AUTHOR_COLUMN})); Runnable runnable = new Runnable() { public void run() { int index = treeTable.getSelectionModel().getMinSelectionIndex(); if (index == -1) { return; } VcsFileRevision revision = getRevisionAt(treeTable, index); if (revision != null) { DiffActionExecutor.showDiff(diffProvider, revision.getRevisionNumber(), file, project); } } }; treeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); new PopupChooserBuilder(treeTable). setTitle(VcsBundle.message("lookup.title.vcs.file.revisions")). setItemChoosenCallback(runnable). setSouthComponent(createCommentsPanel(treeTable)). setResizable(true). setDimensionServiceKey("Vcs.CompareWithSelectedRevision.Popup"). createPopup(). showCenteredInCurrentWindow(project); } @Nullable private static VcsFileRevision getRevisionAt(final TreeTableView treeTable, final int index) { final List items = treeTable.getItems(); if (items.size() <= index) { return null; } else { return ((TreeNodeAdapter)items.get(index)).getRevision(); } } private static JPanel createCommentsPanel(final TreeTableView treeTable) { JPanel panel = new JPanel(new BorderLayout()); final JTextArea textArea = createTextArea(); treeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { final int index = treeTable.getSelectionModel().getMinSelectionIndex(); if (index == -1) { textArea.setText(""); } else { final VcsFileRevision revision = getRevisionAt(treeTable, index); if (revision != null) { textArea.setText(revision.getCommitMessage()); } else { textArea.setText(""); } } } }); final JScrollPane textScrollPane = new JScrollPane(textArea); panel.add(textScrollPane, BorderLayout.CENTER); textScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.lightGray),VcsBundle.message("border.selected.revision.commit.message"))); return panel; } private static JTextArea createTextArea() { final JTextArea textArea = new JTextArea(); textArea.setRows(5); textArea.setEditable(false); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); return textArea; } public static void showListPopup(final List<VcsFileRevision> revisions, final Project project, final Consumer<VcsFileRevision> selectedRevisionConsumer, final boolean showComments) { ColumnInfo[] columns = new ColumnInfo[] { REVISION_TABLE_COLUMN, DATE_TABLE_COLUMN, AUTHOR_TABLE_COLUMN }; for(VcsFileRevision revision: revisions) { if (revision.getBranchName() != null) { columns = new ColumnInfo[] { REVISION_TABLE_COLUMN, BRANCH_TABLE_COLUMN, DATE_TABLE_COLUMN, AUTHOR_TABLE_COLUMN }; break; } } final TableView<VcsFileRevision> table = new TableView<VcsFileRevision>(new ListTableModel<VcsFileRevision>(columns, revisions, 0)); table.setShowHorizontalLines(false); table.setTableHeader(null); Runnable runnable = new Runnable() { public void run() { VcsFileRevision revision = table.getSelectedObject(); if (revision != null) { selectedRevisionConsumer.consume(revision); } } }; if (table.getModel().getRowCount() == 0) { table.clearSelection(); } new SpeedSearchBase<TableView>(table) { protected int getSelectedIndex() { return table.getSelectedRow(); } protected Object[] getAllElements() { return revisions.toArray(); } protected String getElementText(Object element) { VcsFileRevision revision = (VcsFileRevision) element; return revision.getRevisionNumber().asString() + " " + revision.getBranchName() + " " + revision.getAuthor(); } protected void selectElement(Object element, String selectedText) { VcsFileRevision revision = (VcsFileRevision) element; TableUtil.selectRows(myComponent, new int[] {revisions.indexOf(revision)}); TableUtil.scrollSelectionToVisible(myComponent); } }; table.setMinimumSize(new Dimension(300, 50)); final PopupChooserBuilder builder = new PopupChooserBuilder(table); if (showComments) { builder.setSouthComponent(createCommentsPanel(table)); } builder.setTitle(VcsBundle.message("lookup.title.vcs.file.revisions")). setItemChoosenCallback(runnable). setResizable(true). setDimensionServiceKey("Vcs.CompareWithSelectedRevision.Popup").setMinSize(new Dimension(300, 300)); final JBPopup popup = builder.createPopup(); popup.showCenteredInCurrentWindow(project); } private static JPanel createCommentsPanel(final TableView<VcsFileRevision> table) { final JTextArea textArea = createTextArea(); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { final VcsFileRevision revision = table.getSelectedObject(); if (revision == null) { textArea.setText(""); } else { textArea.setText(revision.getCommitMessage()); textArea.select(0, 0); } } }); JPanel jPanel = new JPanel(new BorderLayout()); final JScrollPane textScrollPane = new JScrollPane(textArea); textScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.lightGray),VcsBundle.message("border.selected.revision.commit.message"))); jPanel.add(textScrollPane, BorderLayout.SOUTH); jPanel.setPreferredSize(new Dimension(300, 100)); return jPanel; } private static class TreeNodeAdapter extends DefaultMutableTreeNode { private TreeItem<VcsFileRevision> myRevision; public TreeNodeAdapter(TreeNodeAdapter parent, TreeItem<VcsFileRevision> revision, List<TreeItem<VcsFileRevision>> children) { if (parent != null) { parent.add(this); } myRevision = revision; for (TreeItem<VcsFileRevision> treeItem : children) { new TreeNodeAdapter(this, treeItem, treeItem.getChildren()); } } public VcsFileRevision getRevision() { return myRevision.getData(); } } }
show full error message (IDEADEV-30906)
vcs-impl/src/com/intellij/openapi/vcs/actions/CompareWithSelectedRevisionAction.java
show full error message (IDEADEV-30906)
<ide><path>cs-impl/src/com/intellij/openapi/vcs/actions/CompareWithSelectedRevisionAction.java <ide> <ide> } <ide> catch (VcsException e1) { <del> Messages.showErrorDialog(VcsBundle.message("message.text.cannot.show.differences"), CommonBundle.message("title.error")); <add> Messages.showErrorDialog(VcsBundle.message("message.text.cannot.show.differences", e1.getMessage()), <add> CommonBundle.message("title.error")); <ide> } <ide> <ide>
JavaScript
mit
f9c12c154cd4aedd4e6b0903099f17bd6e80d6fc
0
viralpatel/jquery.shorten,gdseller/jquery.shorten,cookiespam/terratrix.github.io
๏ปฟ/* * jQuery Shorten plugin 1.0.0 * * Copyright (c) 2013 Viral Patel * http://viralpatel.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php */ /* ** updated by Jeff Richardson ** Updated to use strict, ** IE 7 has a "bug" It is returning underfined when trying to reference string characters in this format ** content[i]. IE 7 allows content.charAt(i) This works fine in all modern browsers. ** I've also added brackets where they werent added just for readability (mostly for me). */ (function($) { $.fn.shorten = function (settings) { "use strict"; if ($(this).data('jquery.shorten')){ return false; } $(this).data('jquery.shorten', true); var config = { showChars: 100, ellipsesText: "...", moreText: "more", lessText: "less", errMsg: null }; if (settings) { $.extend(config, settings); } $(document).off("click", '.morelink'); $(document).on({click: function () { var $this = $(this); if ($this.hasClass('less')) { $this.removeClass('less'); $this.html(config.moreText); $this.parent().prev().prev().show(); // shortcontent $this.parent().prev().hide(); // allcontent } else { $this.addClass('less'); $this.html(config.lessText); $this.parent().prev().prev().hide(); // shortcontent $this.parent().prev().show(); // allcontent } return false; } }, '.morelink'); return this.each(function () { var $this = $(this); var content = $this.html(); var contentlen = $this.text().length; if (contentlen > config.showChars) { var c = content.substr(0, config.showChars); if (c.indexOf('<') >= 0) // If there's HTML don't want to cut it { var inTag = false; // I'm in a tag? var bag = ''; // Put the characters to be shown here var countChars = 0; // Current bag size var openTags = []; // Stack for opened tags, so I can close them later var tagName = null; for (var i = 0, r=0; r <= config.showChars; i++) { if (content[i] == '<' && !inTag) { inTag = true; // This could be "tag" or "/tag" tagName = content.substring(i + 1, content.indexOf('>', i)); // If its a closing tag if (tagName[0] == '/') { if (tagName != '/' + openTags[0]) { config.errMsg = 'ERROR en HTML: the top of the stack should be the tag that closes'; } else { openTags.shift(); // Pops the last tag from the open tag stack (the tag is closed in the retult HTML!) } } else { // There are some nasty tags that don't have a close tag like <br/> if (tagName.toLowerCase() != 'br') { openTags.unshift(tagName); // Add to start the name of the tag that opens } } } if (inTag && content[i] == '>') { inTag = false; } if (inTag) { bag += content.charAt(i); } // Add tag name chars to the result else { r++; if (countChars <= config.showChars) { bag += content.charAt(i); // Fix to ie 7 not allowing you to reference string characters using the [] countChars++; } else // Now I have the characters needed { if (openTags.length > 0) // I have unclosed tags { //console.log('They were open tags'); //console.log(openTags); for (j = 0; j < openTags.length; j++) { //console.log('Cierro tag ' + openTags[j]); bag += '</' + openTags[j] + '>'; // Close all tags that were opened // You could shift the tag from the stack to check if you end with an empty stack, that means you have closed all open tags } break; } } } } c = bag; } var html = '<span class="shortcontent">' + c + '&nbsp;' + config.ellipsesText + '</span><span class="allcontent">' + content + '</span>&nbsp;&nbsp;<span><a href="javascript://nop/" class="morelink">' + config.moreText + '</a></span>'; $this.html(html); $this.find(".allcontent").hide(); // Esconde el contenido completo para todos los textos } }); }; })(jQuery);
src/jquery.shorten.js
๏ปฟ/* * jQuery Shorten plugin 1.0.0 * * Copyright (c) 2013 Viral Patel * http://viralpatel.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php */ /* ** updated by Jeff Richardson ** Updated to use strict, ** IE 7 has a "bug" It is returning underfined when trying to reference string characters in this format ** content[i]. IE 7 allows content.charAt(i) This works fine in all modern browsers. ** I've also added brackets where they werent added just for readability (mostly for me). */ (function($) { $.fn.shorten = function (settings) { "use strict"; var config = { showChars: 100, ellipsesText: "...", moreText: "more", lessText: "less", errMsg: null }; if (settings) { $.extend(config, settings); } $(document).off("click", '.morelink'); $(document).on({click: function () { var $this = $(this); if ($this.hasClass('less')) { $this.removeClass('less'); $this.html(config.moreText); $this.parent().prev().prev().show(); // shortcontent $this.parent().prev().hide(); // allcontent } else { $this.addClass('less'); $this.html(config.lessText); $this.parent().prev().prev().hide(); // shortcontent $this.parent().prev().show(); // allcontent } return false; } }, '.morelink'); return this.each(function () { var $this = $(this); var content = $this.html(); var contentlen = $this.text().length; if (contentlen > config.showChars) { var c = content.substr(0, config.showChars); if (c.indexOf('<') >= 0) // If there's HTML don't want to cut it { var inTag = false; // I'm in a tag? var bag = ''; // Put the characters to be shown here var countChars = 0; // Current bag size var openTags = []; // Stack for opened tags, so I can close them later var tagName = null; for (var i = 0, r=0; r <= config.showChars; i++) { if (content[i] == '<' && !inTag) { inTag = true; // This could be "tag" or "/tag" tagName = content.substring(i + 1, content.indexOf('>', i)); // If its a closing tag if (tagName[0] == '/') { if (tagName != '/' + openTags[0]) { config.errMsg = 'ERROR en HTML: the top of the stack should be the tag that closes'; } else { openTags.shift(); // Pops the last tag from the open tag stack (the tag is closed in the retult HTML!) } } else { // There are some nasty tags that don't have a close tag like <br/> if (tagName.toLowerCase() != 'br') { openTags.unshift(tagName); // Add to start the name of the tag that opens } } } if (inTag && content[i] == '>') { inTag = false; } if (inTag) { bag += content.charAt(i); } // Add tag name chars to the result else { r++; if (countChars <= config.showChars) { bag += content.charAt(i); // Fix to ie 7 not allowing you to reference string characters using the [] countChars++; } else // Now I have the characters needed { if (openTags.length > 0) // I have unclosed tags { //console.log('They were open tags'); //console.log(openTags); for (j = 0; j < openTags.length; j++) { //console.log('Cierro tag ' + openTags[j]); bag += '</' + openTags[j] + '>'; // Close all tags that were opened // You could shift the tag from the stack to check if you end with an empty stack, that means you have closed all open tags } break; } } } } c = bag; } var html = '<span class="shortcontent">' + c + '&nbsp;' + config.ellipsesText + '</span><span class="allcontent">' + content + '</span>&nbsp;&nbsp;<span><a href="javascript://nop/" class="morelink">' + config.moreText + '</a></span>'; $this.html(html); $this.find(".allcontent").hide(); // Esconde el contenido completo para todos los textos } }); }; })(jQuery);
Prevent the plugin to be attached more than once to an element.
src/jquery.shorten.js
Prevent the plugin to be attached more than once to an element.
<ide><path>rc/jquery.shorten.js <ide> $.fn.shorten = function (settings) { <ide> <ide> "use strict"; <del> <add> if ($(this).data('jquery.shorten')){ <add> return false; <add> } <add> $(this).data('jquery.shorten', true); <add> <ide> var config = { <ide> showChars: 100, <ide> ellipsesText: "...",
JavaScript
mit
ec49cc6effeebed643ddd705dc8021eadec44deb
0
Xiphe/grunt-codeclimate-reporter,MrBoolean/grunt-codeclimate-reporter
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js' ], options: { jshintrc: '.jshintrc' } }, eslint: { target: ['tasks/**/*.js', 'lib/**/*.js', 'Gruntfile.js'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-eslint'); grunt.loadNpmTasks('grunt-mocha'); grunt.registerTask('default', ['eslint']); };
Gruntfile.js
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js' ], options: { jshintrc: '.jshintrc' } }, eslint: { target: ['tasks/**/*.js', 'lib/**/*.js', 'Gruntfile.js'] }, mocha: { test: { src: ['test/**/*.test.js'] } } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-eslint'); grunt.loadNpmTasks('grunt-mocha'); grunt.registerTask('test', ['mocha:test']); grunt.registerTask('default', ['eslint', 'test']); };
Cleanup gruntfile
Gruntfile.js
Cleanup gruntfile
<ide><path>runtfile.js <ide> }, <ide> eslint: { <ide> target: ['tasks/**/*.js', 'lib/**/*.js', 'Gruntfile.js'] <del> }, <del> mocha: { <del> test: { <del> src: ['test/**/*.test.js'] <del> } <ide> } <ide> }); <ide> <ide> grunt.loadNpmTasks('grunt-eslint'); <ide> grunt.loadNpmTasks('grunt-mocha'); <ide> <del> grunt.registerTask('test', ['mocha:test']); <del> grunt.registerTask('default', ['eslint', 'test']); <add> grunt.registerTask('default', ['eslint']); <ide> };
Java
mit
3d03d668a97c24e028bc11eea34da0e153064b38
0
venkatramanm/swf-all,venkatramanm/swf-all,venkatramanm/swf-all
package com.venky.swf.plugins.mail.core; import com.venky.core.io.ByteArrayInputStream; import com.venky.core.io.StringReader; import com.venky.core.util.ObjectUtil; import com.venky.swf.db.Database; import com.venky.swf.db.annotations.column.ui.mimes.MimeType; import com.venky.swf.db.model.UserEmail; import com.venky.swf.db.model.reflection.ModelReflector; import com.venky.swf.plugins.attachment.db.model.Attachment; import com.venky.swf.plugins.background.core.Task; import com.venky.swf.plugins.mail.db.model.Mail; import com.venky.swf.plugins.mail.db.model.MailAttachment; import com.venky.swf.plugins.mail.db.model.User; import com.venky.swf.pm.DataSecurityFilter; import com.venky.swf.routing.Config; import com.venky.swf.sql.Expression; import com.venky.swf.sql.Operator; import com.venky.swf.sql.Select; import org.codemonkey.simplejavamail.Email; import javax.mail.Message.RecipientType; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class MailerTask implements Task{ private static final long serialVersionUID = 8083486775891668308L; long toUserId ; String toEmail; String subject; String text; boolean isHtml = false; List<Long> cc; List<Long> bcc; List<AttachedElement> attachedElements; public static class AttachedElement implements Serializable { public AttachedElement(){ } public AttachedElement(MimeType mimeType, String name, byte[] bytes){ this.bytes = bytes; this.name = name; this.mimeType = mimeType; } byte[] bytes; String name; MimeType mimeType; } @Deprecated public MailerTask(){ } public MailerTask(User to,String subject, String text){ this(to,null, subject,text); } public MailerTask(User to,String toEmail,String subject, String text){ this(to,toEmail,subject,text,null,null,null); } public MailerTask(User to, String toEmail, String subject, String text, List<User> cc , List<User> bcc, List<AttachedElement> attachedElements){ this.toUserId = to.getId(); this.toEmail = toEmail; this.subject = subject; this.text = text; if (!ObjectUtil.isVoid(text)){ String trim = text.trim(); int len = trim.length(); if (len > 5 ) { this.isHtml = trim.substring(0, 5).equalsIgnoreCase("<html") || (len > 14 && trim.substring(0,14).equalsIgnoreCase("<!DOCTYPE html")); } } if (cc != null){ this.cc = DataSecurityFilter.getIds(cc); } if (bcc != null){ this.bcc = DataSecurityFilter.getIds(bcc); } if (attachedElements != null){ this.attachedElements = new ArrayList<>(attachedElements); } } public void execute() { User to = Database.getTable(User.class).get(toUserId); if (to == null){ return; } List<User> cc = this.cc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this.cc.toArray())).execute(); List<User> bcc = this.bcc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this. bcc.toArray())).execute(); Map<RecipientType,List<User>> map = new HashMap<>(); map.put(RecipientType.TO, Collections.singletonList(to)); map.put(RecipientType.CC,cc); map.put(RecipientType.BCC,bcc); List<UserEmail> emails = to.getUserEmails(); if (!ObjectUtil.isVoid(this.toEmail)){ emails = emails.stream().filter(e->ObjectUtil.equals(e.getEmail(),this.toEmail)).collect(Collectors.toList()); } if (emails.isEmpty()){ throw new RuntimeException("No toEmail available for " + to.getName()); } String emailId = Config.instance().getProperty("swf.sendmail.user"); String userName = Config.instance().getProperty("swf.sendmail.user.name"); if( ObjectUtil.isVoid(emailId)) { throw new RuntimeException("Plugin not configured :swf.sendmail.user" ); } final Email email = new Email(); email.setFromAddress(userName, emailId); email.setSubject(subject); StringBuilder emailString = new StringBuilder(); for (RecipientType type : map.keySet()){ List<User> users = map.get(type); if (!users.isEmpty()){ emailString.append(type.toString()).append(": "); for (User user : users){ for (UserEmail useremail : user.getUserEmails()){ email.addRecipient(useremail.getAlias() + "(" + useremail.getEmail() + ")" , useremail.getEmail(), type); emailString.append(useremail.getEmail()).append(";"); } } } } if (isHtml){ email.setTextHTML(text); }else { email.setText(text); } Mail mail = Database.getTable(Mail.class).newRecord(); mail.setUserId(toUserId); mail.setEmail(emailString.toString()); mail.setSubject(subject); mail.setBody(new StringReader(text)); mail.save(); if (attachedElements != null && !attachedElements.isEmpty()){ for (AttachedElement element : attachedElements){ email.addAttachment(element.name, element.bytes, element.mimeType.toString()); MailAttachment mailAttachment = Database.getTable(MailAttachment.class).newRecord(); mailAttachment.setMailId(mail.getId()); Attachment attachment = Attachment.find(element.name); if (attachment == null){ attachment = Database.getTable(Attachment.class).newRecord() ; attachment.setAttachment(new ByteArrayInputStream(element.bytes)); attachment.setAttachmentContentName(element.name); attachment.setAttachmentContentSize(element.bytes.length); attachment.setAttachmentContentType(element.mimeType.toString()); attachment.save(); } mailAttachment.setAttachmentId(attachment.getId()); mailAttachment = Database.getTable(MailAttachment.class).getRefreshed(mailAttachment); mailAttachment.save(); } } AsyncMailer.instance().addEmail(email); } }
swf-plugin-mail/src/main/java/com/venky/swf/plugins/mail/core/MailerTask.java
package com.venky.swf.plugins.mail.core; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.mail.Message.RecipientType; import com.venky.core.io.ByteArrayInputStream; import com.venky.swf.db.annotations.column.ui.mimes.MimeType; import com.venky.swf.db.model.reflection.ModelReflector; import com.venky.swf.plugins.attachment.db.model.Attachment; import com.venky.swf.plugins.mail.db.model.MailAttachment; import com.venky.swf.pm.DataSecurityFilter; import com.venky.swf.sql.Expression; import com.venky.swf.sql.Operator; import com.venky.swf.sql.Select; import org.codemonkey.simplejavamail.Email; import com.venky.core.io.StringReader; import com.venky.core.util.ObjectUtil; import com.venky.swf.db.Database; import com.venky.swf.db.model.UserEmail; import com.venky.swf.plugins.background.core.Task; import com.venky.swf.plugins.mail.db.model.Mail; import com.venky.swf.plugins.mail.db.model.User; import com.venky.swf.routing.Config; public class MailerTask implements Task{ private static final long serialVersionUID = 8083486775891668308L; long toUserId ; String toEmail; String subject; String text; boolean isHtml = false; List<Long> cc; List<Long> bcc; List<AttachedElement> attachedElements; public static class AttachedElement implements Serializable { public AttachedElement(){ } public AttachedElement(MimeType mimeType, String name, byte[] bytes){ this.bytes = bytes; this.name = name; this.mimeType = mimeType; } byte[] bytes; String name; MimeType mimeType; } @Deprecated public MailerTask(){ } public MailerTask(User to,String subject, String text){ this(to,null, subject,text); } public MailerTask(User to,String toEmail,String subject, String text){ this(to,toEmail,subject,text,null,null,null); } public MailerTask(User to, String toEmail, String subject, String text, List<User> cc , List<User> bcc, List<AttachedElement> attachedElements){ this.toUserId = to.getId(); this.toEmail = toEmail; this.subject = subject; this.text = text; if (!ObjectUtil.isVoid(text)){ String trim = text.trim(); int len = trim.length(); if (len > 5 ) { this.isHtml = trim.substring(0, 5).equalsIgnoreCase("<html") || (len > 14 && trim.substring(0,14).equalsIgnoreCase("<!DOCTYPE html")); } } if (cc != null){ this.cc = DataSecurityFilter.getIds(cc); } if (bcc != null){ this.bcc = DataSecurityFilter.getIds(bcc); } if (attachedElements != null){ this.attachedElements = new ArrayList<>(attachedElements); } } public void execute() { User to = Database.getTable(User.class).get(toUserId); if (to == null){ return; } List<User> cc = this.cc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this.cc)).execute(); List<User> bcc = this.bcc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this. bcc)).execute(); Map<RecipientType,List<User>> map = new HashMap<>(); map.put(RecipientType.TO,Arrays.asList(to)); map.put(RecipientType.CC,cc); map.put(RecipientType.BCC,bcc); List<UserEmail> emails = to.getUserEmails(); if (!ObjectUtil.isVoid(this.toEmail)){ emails = emails.stream().filter(e->ObjectUtil.equals(e.getEmail(),this.toEmail)).collect(Collectors.toList()); } if (emails.isEmpty()){ throw new RuntimeException("No toEmail available for " + to.getName()); } String emailId = Config.instance().getProperty("swf.sendmail.user"); String userName = Config.instance().getProperty("swf.sendmail.user.name"); if( ObjectUtil.isVoid(emailId)) { throw new RuntimeException("Plugin not configured :swf.sendmail.user" ); } final Email email = new Email(); email.setFromAddress(userName, emailId); email.setSubject(subject); StringBuilder emailString = new StringBuilder(); for (RecipientType type : map.keySet()){ List<User> users = map.get(type); if (!users.isEmpty()){ emailString.append(type.toString()).append(": "); for (User user : users){ for (UserEmail useremail : user.getUserEmails()){ email.addRecipient(useremail.getAlias() + "(" + useremail.getEmail() + ")" , useremail.getEmail(), type); emailString.append(useremail.getEmail()).append(";"); } } } } if (isHtml){ email.setTextHTML(text); }else { email.setText(text); } Mail mail = Database.getTable(Mail.class).newRecord(); mail.setUserId(toUserId); mail.setEmail(emailString.toString()); mail.setSubject(subject); mail.setBody(new StringReader(text)); mail.save(); if (attachedElements != null && !attachedElements.isEmpty()){ for (AttachedElement element : attachedElements){ email.addAttachment(element.name, element.bytes, element.mimeType.toString()); MailAttachment mailAttachment = Database.getTable(MailAttachment.class).newRecord(); mailAttachment.setMailId(mail.getId()); Attachment attachment = Attachment.find(element.name); if (attachment == null){ attachment = Database.getTable(Attachment.class).newRecord() ; attachment.setAttachment(new ByteArrayInputStream(element.bytes)); attachment.setAttachmentContentName(element.name); attachment.setAttachmentContentSize(element.bytes.length); attachment.setAttachmentContentType(element.mimeType.toString()); attachment.save(); } mailAttachment.setAttachmentId(attachment.getId()); mailAttachment = Database.getTable(MailAttachment.class).getRefreshed(mailAttachment); mailAttachment.save(); } } AsyncMailer.instance().addEmail(email); } }
Mailer error
swf-plugin-mail/src/main/java/com/venky/swf/plugins/mail/core/MailerTask.java
Mailer error
<ide><path>wf-plugin-mail/src/main/java/com/venky/swf/plugins/mail/core/MailerTask.java <ide> package com.venky.swf.plugins.mail.core; <ide> <del>import java.io.Serializable; <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <del>import java.util.stream.Collectors; <del> <del>import javax.mail.Message.RecipientType; <del> <ide> import com.venky.core.io.ByteArrayInputStream; <add>import com.venky.core.io.StringReader; <add>import com.venky.core.util.ObjectUtil; <add>import com.venky.swf.db.Database; <ide> import com.venky.swf.db.annotations.column.ui.mimes.MimeType; <add>import com.venky.swf.db.model.UserEmail; <ide> import com.venky.swf.db.model.reflection.ModelReflector; <ide> import com.venky.swf.plugins.attachment.db.model.Attachment; <add>import com.venky.swf.plugins.background.core.Task; <add>import com.venky.swf.plugins.mail.db.model.Mail; <ide> import com.venky.swf.plugins.mail.db.model.MailAttachment; <add>import com.venky.swf.plugins.mail.db.model.User; <ide> import com.venky.swf.pm.DataSecurityFilter; <add>import com.venky.swf.routing.Config; <ide> import com.venky.swf.sql.Expression; <ide> import com.venky.swf.sql.Operator; <ide> import com.venky.swf.sql.Select; <ide> import org.codemonkey.simplejavamail.Email; <ide> <del>import com.venky.core.io.StringReader; <del>import com.venky.core.util.ObjectUtil; <del>import com.venky.swf.db.Database; <del>import com.venky.swf.db.model.UserEmail; <del>import com.venky.swf.plugins.background.core.Task; <del>import com.venky.swf.plugins.mail.db.model.Mail; <del>import com.venky.swf.plugins.mail.db.model.User; <del>import com.venky.swf.routing.Config; <add>import javax.mail.Message.RecipientType; <add>import java.io.Serializable; <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.stream.Collectors; <ide> <ide> public class MailerTask implements Task{ <ide> <ide> return; <ide> } <ide> <del> List<User> cc = this.cc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this.cc)).execute(); <del> List<User> bcc = this.bcc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this. bcc)).execute(); <add> List<User> cc = this.cc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this.cc.toArray())).execute(); <add> List<User> bcc = this.bcc == null ? new ArrayList<>() : new Select().from(User.class).where(new Expression(ModelReflector.instance(User.class).getPool(),"ID", Operator.IN,this. bcc.toArray())).execute(); <ide> <ide> Map<RecipientType,List<User>> map = new HashMap<>(); <ide> <del> map.put(RecipientType.TO,Arrays.asList(to)); <add> map.put(RecipientType.TO, Collections.singletonList(to)); <ide> map.put(RecipientType.CC,cc); <ide> map.put(RecipientType.BCC,bcc); <ide>
Java
apache-2.0
51a30322d1c24eba39811accbeb77c5d18d75c94
0
DavidWhitlock/PortlandStateJava,DavidWhitlock/PortlandStateJava
package edu.pdx.cs410J.grader; import com.google.common.base.Function; import com.google.common.collect.Maps; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.jar.Attributes; /** * This class is used to submit assignments in CS410J. The user * specified his or her email address as well as the base directory * for his/her source files on the command line. The directory is * searched recursively for files ending in .java. Those files are * placed in a jar file and emailed to the grader. A confirmation * email is sent to the submitter. * <p/> * <p/> * <p/> * More information about the JavaMail API can be found at: * <p/> * <center><a href="http://java.sun.com/products/javamail"> * http://java.sun.com/products/javamail</a></center> * * @author David Whitlock * @since Fall 2000 (Refactored to use fewer static methods in Spring 2006) */ public class Submit { private static final PrintWriter out = new PrintWriter(System.out, true); private static final PrintWriter err = new PrintWriter(System.err, true); /** * The grader's email address */ private static final String TA_EMAIL = "[email protected]"; /** * A URL containing a list of files that should not be submitted */ private static final String NO_SUBMIT_LIST_URL = "http://www.cs.pdx.edu/~whitlock/no-submit"; private static final String PROJECT_NAMES_LIST_URL = "http://www.cs.pdx.edu/~whitlock/project-names"; ///////////////////// Instance Fields ////////////////////////// /** * The name of the project being submitted */ private String projName = null; /** * The name of the user (student) submits the project */ private String userName = null; /** * The submitter's email address */ private String userEmail = null; /** * The submitter's user id */ private String userId = null; /** * The name of the SMTP server that is used to send email */ private String serverName = "mailhost.cs.pdx.edu"; /** * A comment describing the project */ private String comment = null; /** * Should the execution of this program be logged? */ private boolean debug = false; /** * Should the generated jar file be saved? */ private boolean saveJar = false; /** * The time at which the project was submitted */ private Date submitTime = null; /** * The names of the files to be submitted */ private Set<String> fileNames = new HashSet<>(); /////////////////////// Constructors ///////////////////////// /** * Creates a new <code>Submit</code> program */ public Submit() { } ///////////////////// Instance Methods /////////////////////// /** * Sets the name of the SMTP server that is used to send emails */ public void setServerName(String serverName) { this.serverName = serverName; } /** * Sets whether or not the progress of the submission should be logged. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Sets whether or not the jar file generated by the submission * should be saved. */ public void setSaveJar(boolean saveJar) { this.saveJar = saveJar; } /** * Sets the comment for this submission */ public void setComment(String comment) { this.comment = comment; } /** * Sets the name of project being submitted */ public void setProjectName(String projName) { this.projName = projName; } /** * Sets the name of the user who is submitting the project */ public void setUserName(String userName) { this.userName = userName; } /** * Sets the id of the user who is submitting the project */ public void setUserId(String userId) { this.userId = userId; } /** * Sets the email address of the user who is submitting the project */ public void setUserEmail(String userEmail) { this.userEmail = userEmail; } /** * Adds the file with the given name to the list of files to be * submitted. */ public void addFile(String fileName) { this.fileNames.add(fileName); } /** * Validates the state of this submission * * @throws IllegalStateException If any state is incorrect or missing */ public void validate() { validateProjectName(); if (projName == null) { throw new IllegalStateException("Missing project name"); } if (userName == null) { throw new IllegalStateException("Missing student name"); } if (userId == null) { throw new IllegalStateException("Missing login id"); } if (userEmail == null) { throw new IllegalStateException("Missing email address"); } else { // Make sure user's email is okay try { new InternetAddress(userEmail); } catch (AddressException ex) { String s = "Invalid email address: " + userEmail; IllegalStateException ex2 = new IllegalStateException(s); ex2.initCause(ex); throw ex2; } } } private void validateProjectName() { List<String> validProjectNames = fetchListOfValidProjectNames(); if (!validProjectNames.contains(projName)) { String message = "\"" + projName + "\" is not in the list of valid project names: " + validProjectNames; throw new IllegalStateException(message); } } private List<String> fetchListOfValidProjectNames() { return fetchListOfStringsFromUrl(PROJECT_NAMES_LIST_URL); } /** * Submits the project to the grader * * @param verify Should the user be prompted to verify his submission? * @return Whether or not the submission actually occurred * @throws IllegalStateException If no source files were found */ public boolean submit(boolean verify) throws IOException, MessagingException { // Recursively search the source directory for .java files Set<File> sourceFiles = searchForSourceFiles(fileNames); db(sourceFiles.size() + " source files found"); if (sourceFiles.size() == 0) { String s = "No source files were found."; throw new IllegalStateException(s); } // Verify submission with user if (verify && !verifySubmission(sourceFiles)) { // User does not want to submit return false; } // Timestamp this.submitTime = new Date(); // Create a temporary jar file to hold the source files File jarFile = makeJarFileWith(sourceFiles); // Send the jar file as an email attachment to the TA mailTA(jarFile, sourceFiles); // Send a receipt to the user mailReceipt(sourceFiles); return true; } /** * Prints debugging output. */ private void db(String s) { if (this.debug) { err.println("++ " + s); } } /** * Searches for the files given on the command line. Ignores files * that do not end in .java, or that appear on the "no submit" list. * Files must reside in a directory named * edu/pdx/cs410J/<studentId>. */ private Set<File> searchForSourceFiles(Set<String> fileNames) { List<String> noSubmit = fetchListOfFilesThatCanNotBeSubmitted(); // Files should be sorted by name SortedSet<File> files = new TreeSet<>(new Comparator<File>() { @Override public int compare(File o1, File o2) { String name1 = o1.toString(); String name2 = o2.toString(); return name1.compareTo(name2); } }); for (String fileName : fileNames) { File file = new File(fileName); file = file.getAbsoluteFile(); // Full path // Does the file exist? if (!file.exists()) { err.println("** Not submitting file " + fileName + " because it does not exist"); continue; } // Is the file on the "no submit" list? String name = file.getName(); if (noSubmit.contains(name)) { err.println("** Not submitting file " + fileName + " because it is on the \"no submit\" list"); continue; } // Does the file name end in .java? if (!name.endsWith(".java")) { err.println("** No submitting file " + fileName + " because does end in \".java\""); continue; } // Verify that file is in the correct directory. File parent = file.getParentFile(); if (parent == null || !parent.getName().equals(userId)) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("cs410J")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "cs410J" + File.separator + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("pdx")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "pdx" + File.separator + "cs410J" + File.separator + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("edu")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "edu" + File.separator + "pdx" + File.separator + "cs410J" + File.separator + userId); continue; } // We like this file files.add(file); } return files; } private List<String> fetchListOfFilesThatCanNotBeSubmitted() { return fetchListOfStringsFromUrl(NO_SUBMIT_LIST_URL); } private List<String> fetchListOfStringsFromUrl(String listUrl) { List<String> noSubmit = new ArrayList<>(); try { URL url = new URL(listUrl); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); while (br.ready()) { noSubmit.add(br.readLine().trim()); } } catch (MalformedURLException ex) { err.println("** WARNING: Cannot access " + listUrl + ": " + ex.getMessage()); } catch (IOException ex) { err.println("** WARNING: Problems while reading " + listUrl + ": " + ex.getMessage()); } return noSubmit; } /** * Prints a summary of what is about to be submitted and prompts the * user to verify that it is correct. * * @return <code>true</code> if the user wants to submit */ private boolean verifySubmission(Set<File> sourceFiles) { // Print out what is going to be submitted out.print("\n" + userName); out.print("'s submission for "); out.println(projName); for (File file : sourceFiles) { out.println(" " + file); } if (comment != null) { out.println("\nComment: " + comment + "\n\n"); } out.println("A receipt will be sent to: " + userEmail + "\n"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); while (true) { out.print("Do you wish to continue with the submission? (yes/no) "); out.flush(); try { String line = in.readLine().trim(); switch (line) { case "yes": return true; case "no": return false; default: err.println("** Please enter yes or no"); break; } } catch (IOException ex) { err.println("** Exception while reading from System.in: " + ex); } } } /** * Returns the name of a <code>File</code> relative to the source * directory. */ private String getRelativeName(File file) { // We already know that the file is in the correct directory return "edu/pdx/cs410J/" + userId + "/" + file.getName(); } /** * Creates a Jar file that contains the source files. The Jar File * is temporary and is deleted when the program exits. */ private File makeJarFileWith(Set<File> sourceFiles) throws IOException { String jarFileName = userName.replace(' ', '_') + "-TEMP"; File jarFile = File.createTempFile(jarFileName, ".jar"); if (!saveJar) { jarFile.deleteOnExit(); } else { out.println("Saving temporary Jar file: " + jarFile); } db("Created Jar file: " + jarFile); Map<File, String> sourceFilesWithNames = Maps.toMap(sourceFiles, new Function<File, String>() { @Override public String apply(File file) { return getRelativeName(file); } }); return new JarMaker(sourceFilesWithNames, jarFile, getManifestEntries()).makeJar(); } private Map<Attributes.Name, String> getManifestEntries() { Map<Attributes.Name, String> manifestEntries = new HashMap<>(); manifestEntries.put(ManifestAttributes.USER_NAME, userName); manifestEntries.put(ManifestAttributes.USER_ID, userId); manifestEntries.put(ManifestAttributes.USER_EMAIL, userEmail); manifestEntries.put(ManifestAttributes.PROJECT_NAME, projName); manifestEntries.put(ManifestAttributes.SUBMISSION_COMMENT, comment); manifestEntries.put(ManifestAttributes.SUBMISSION_TIME, ManifestAttributes.formatSubmissionTime(submitTime)); return manifestEntries; } /** * Sends the Jar file to the TA as a MIME attachment. Also includes * a textual summary of the contents of the Jar file. */ private void mailTA(File jarFile, Set<File> sourceFiles) throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(), TA_EMAIL, "CS410J-SUBMIT " + userName + "'s " + projName); MimeBodyPart textPart = createTextPartOfTAEmail(sourceFiles); MimeBodyPart filePart = createJarAttachment(jarFile); Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(filePart); message.setContent(mp); out.println("Submitting project to Grader"); Transport.send(message); } private MimeBodyPart createJarAttachment(File jarFile) throws MessagingException { // Now attach the Jar file DataSource ds = new FileDataSource(jarFile); DataHandler dh = new DataHandler(ds); MimeBodyPart filePart = new MimeBodyPart(); String jarFileTitle = userName.replace(' ', '_') + ".jar"; filePart.setDataHandler(dh); filePart.setFileName(jarFileTitle); filePart.setDescription(userName + "'s " + projName); return filePart; } private MimeBodyPart createTextPartOfTAEmail(Set<File> sourceFiles) throws MessagingException { // Create the text portion of the message StringBuilder text = new StringBuilder(); text.append("Student name: ").append(userName).append(" (").append(userEmail).append(")\n"); text.append("Project name: ").append(projName).append("\n"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); text.append("Submitted on: ").append(df.format(submitTime)).append("\n"); if (comment != null) { text.append("\nComment: ").append(comment).append("\n\n"); } text.append("Contents:\n"); for (File file : sourceFiles) { text.append(" ").append(getRelativeName(file)).append("\n"); } text.append("\n\n"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(text.toString(), "text/plain"); // Try not to display text as separate attachment textPart.setDisposition("inline"); return textPart; } private MimeMessage newEmailTo(Session session, String recipient, String subject) throws MessagingException { // Make a new email message MimeMessage message = new MimeMessage(session); InternetAddress[] to = {new InternetAddress(recipient)}; message.setRecipients(Message.RecipientType.TO, to); message.setSubject(subject); return message; } private Session newEmailSession() { // Obtain a Session for sending email Properties props = new Properties(); props.put("mail.smtp.host", serverName); db("Establishing session on " + serverName); Session session = Session.getDefaultInstance(props, null); session.setDebug(this.debug); return session; } /** * Sends a email to the user as a receipt of the submission. */ private void mailReceipt(Set<File> sourceFiles) throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(), userEmail, "CS410J " + projName + " submission"); // Create the contents of the message DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); StringBuilder text = new StringBuilder(); text.append("On ").append(df.format(submitTime)).append("\n"); text.append(userName).append(" (").append(userEmail).append(")\n"); text.append("submitted the following files for ").append(projName).append(":\n"); for (File file : sourceFiles) { text.append(" ").append(file.getAbsolutePath()).append("\n"); } if (comment != null) { text.append("\nComment: ").append(comment).append("\n\n"); } text.append("\n\n"); text.append("Have a nice day."); // Add the text to the message and send it message.setText(text.toString()); message.setDisposition("inline"); out.println("Sending receipt to you"); Transport.send(message); } ///////////////////////// Main Program /////////////////////////// /** * Prints usage information about this program. */ private static void usage(String s) { err.println("\n** " + s + "\n"); err.println("usage: java Submit [options] args file+"); err.println(" args are (in this order):"); err.println(" project What project is being submitted (Project1, Project2, etc.)"); err.println(" student Who is submitting the project?"); err.println(" loginId UNIX login id"); err.println(" email Student's email address"); err.println(" file Java source file to submit"); err.println(" options are (options may appear in any order):"); err.println(" -savejar Saves temporary Jar file"); err.println(" -smtp serverName Name of SMTP server"); err.println(" -verbose Log debugging output"); err.println(" -comment comment Info for the Grader"); err.println(""); err.println("Submits Java source code to the CS410J grader."); System.exit(1); } /** * Parses the command line, finds the source files, prompts the user * to verify whether or not the settings are correct, and then sends * an email to the Grader. */ public static void main(String[] args) throws IOException, MessagingException { Submit submit = new Submit(); // Parse the command line for (int i = 0; i < args.length; i++) { // Check for options first if (args[i].equals("-smtp")) { if (++i >= args.length) { usage("No SMTP server specified"); } submit.setServerName(args[i]); } else if (args[i].equals("-verbose")) { submit.setDebug(true); } else if (args[i].equals("-savejar")) { submit.setSaveJar(true); } else if (args[i].equals("-comment")) { if (++i >= args.length) { usage("No comment specified"); } submit.setComment(args[i]); } else if (submit.projName == null) { submit.setProjectName(args[i]); } else if (submit.userName == null) { submit.setUserName(args[i]); } else if (submit.userId == null) { submit.setUserId(args[i]); } else if (submit.userEmail == null) { submit.setUserEmail(args[i]); } else { // The name of a source file submit.addFile(args[i]); } } boolean submitted; try { // Make sure that user entered enough information submit.validate(); submit.db("Command line successfully parsed."); submitted = submit.submit(true); } catch (IllegalStateException ex) { usage(ex.getMessage()); return; } // All done. if (submitted) { out.println(submit.projName + " submitted successfully. Thank you."); } else { out.println(submit.projName + " not submitted."); } } static class ManifestAttributes { public static final Attributes.Name USER_NAME = new Attributes.Name("Submitter-User-Name"); public static final Attributes.Name USER_ID = new Attributes.Name("Submitter-User-Id"); public static final Attributes.Name USER_EMAIL = new Attributes.Name("Submitter-Email"); public static final Attributes.Name PROJECT_NAME = new Attributes.Name("Project-Name"); public static final Attributes.Name SUBMISSION_TIME = new Attributes.Name("Submission-Time"); public static final Attributes.Name SUBMISSION_COMMENT = new Attributes.Name("Submission-Comment"); public static String formatSubmissionTime(Date submitTime) { DateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); return format.format(submitTime); } } }
grader/src/main/java/edu/pdx/cs410J/grader/Submit.java
package edu.pdx.cs410J.grader; import com.google.common.base.Function; import com.google.common.collect.Maps; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.jar.Attributes; /** * This class is used to submit assignments in CS410J. The user * specified his or her email address as well as the base directory * for his/her source files on the command line. The directory is * searched recursively for files ending in .java. Those files are * placed in a jar file and emailed to the grader. A confirmation * email is sent to the submitter. * <p/> * <p/> * <p/> * More information about the JavaMail API can be found at: * <p/> * <center><a href="http://java.sun.com/products/javamail"> * http://java.sun.com/products/javamail</a></center> * * @author David Whitlock * @since Fall 2000 (Refactored to use fewer static methods in Spring 2006) */ public class Submit { private static final PrintWriter out = new PrintWriter(System.out, true); private static final PrintWriter err = new PrintWriter(System.err, true); /** * The grader's email address */ private static final String TA_EMAIL = "[email protected]"; /** * A URL containing a list of files that should not be submitted */ private static final String NO_SUBMIT_LIST_URL = "http://www.cs.pdx.edu/~whitlock/no-submit"; ///////////////////// Instance Fields ////////////////////////// /** * The name of the project being submitted */ private String projName = null; /** * The name of the user (student) submits the project */ private String userName = null; /** * The submitter's email address */ private String userEmail = null; /** * The submitter's user id */ private String userId = null; /** * The name of the SMTP server that is used to send email */ private String serverName = "mailhost.cs.pdx.edu"; /** * A comment describing the project */ private String comment = null; /** * Should the execution of this program be logged? */ private boolean debug = false; /** * Should the generated jar file be saved? */ private boolean saveJar = false; /** * The time at which the project was submitted */ private Date submitTime = null; /** * The names of the files to be submitted */ private Set<String> fileNames = new HashSet<>(); /////////////////////// Constructors ///////////////////////// /** * Creates a new <code>Submit</code> program */ public Submit() { } ///////////////////// Instance Methods /////////////////////// /** * Sets the name of the SMTP server that is used to send emails */ public void setServerName(String serverName) { this.serverName = serverName; } /** * Sets whether or not the progress of the submission should be logged. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Sets whether or not the jar file generated by the submission * should be saved. */ public void setSaveJar(boolean saveJar) { this.saveJar = saveJar; } /** * Sets the comment for this submission */ public void setComment(String comment) { this.comment = comment; } /** * Sets the name of project being submitted */ public void setProjectName(String projName) { this.projName = projName; } /** * Sets the name of the user who is submitting the project */ public void setUserName(String userName) { this.userName = userName; } /** * Sets the id of the user who is submitting the project */ public void setUserId(String userId) { this.userId = userId; } /** * Sets the email address of the user who is submitting the project */ public void setUserEmail(String userEmail) { this.userEmail = userEmail; } /** * Adds the file with the given name to the list of files to be * submitted. */ public void addFile(String fileName) { this.fileNames.add(fileName); } /** * Validates the state of this submission * * @throws IllegalStateException If any state is incorrect or missing */ public void validate() { if (projName == null) { throw new IllegalStateException("Missing project name"); } if (userName == null) { throw new IllegalStateException("Missing student name"); } if (userId == null) { throw new IllegalStateException("Missing login id"); } if (userEmail == null) { throw new IllegalStateException("Missing email address"); } else { // Make sure user's email is okay try { new InternetAddress(userEmail); } catch (AddressException ex) { String s = "Invalid email address: " + userEmail; IllegalStateException ex2 = new IllegalStateException(s); ex2.initCause(ex); throw ex2; } } } /** * Submits the project to the grader * * @param verify Should the user be prompted to verify his submission? * @return Whether or not the submission actually occurred * @throws IllegalStateException If no source files were found */ public boolean submit(boolean verify) throws IOException, MessagingException { // Recursively search the source directory for .java files Set<File> sourceFiles = searchForSourceFiles(fileNames); db(sourceFiles.size() + " source files found"); if (sourceFiles.size() == 0) { String s = "No source files were found."; throw new IllegalStateException(s); } // Verify submission with user if (verify && !verifySubmission(sourceFiles)) { // User does not want to submit return false; } // Timestamp this.submitTime = new Date(); // Create a temporary jar file to hold the source files File jarFile = makeJarFileWith(sourceFiles); // Send the jar file as an email attachment to the TA mailTA(jarFile, sourceFiles); // Send a receipt to the user mailReceipt(sourceFiles); return true; } /** * Prints debugging output. */ private void db(String s) { if (this.debug) { err.println("++ " + s); } } /** * Searches for the files given on the command line. Ignores files * that do not end in .java, or that appear on the "no submit" list. * Files must reside in a directory named * edu/pdx/cs410J/<studentId>. */ private Set<File> searchForSourceFiles(Set<String> fileNames) { Set<String> noSubmit = fetchListOfFilesThatCanNotBeSubmitted(); // Files should be sorted by name SortedSet<File> files = new TreeSet<>(new Comparator<File>() { @Override public int compare(File o1, File o2) { String name1 = o1.toString(); String name2 = o2.toString(); return name1.compareTo(name2); } }); for (String fileName : fileNames) { File file = new File(fileName); file = file.getAbsoluteFile(); // Full path // Does the file exist? if (!file.exists()) { err.println("** Not submitting file " + fileName + " because it does not exist"); continue; } // Is the file on the "no submit" list? String name = file.getName(); if (noSubmit.contains(name)) { err.println("** Not submitting file " + fileName + " because it is on the \"no submit\" list"); continue; } // Does the file name end in .java? if (!name.endsWith(".java")) { err.println("** No submitting file " + fileName + " because does end in \".java\""); continue; } // Verify that file is in the correct directory. File parent = file.getParentFile(); if (parent == null || !parent.getName().equals(userId)) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("cs410J")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "cs410J" + File.separator + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("pdx")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "pdx" + File.separator + "cs410J" + File.separator + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("edu")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "edu" + File.separator + "pdx" + File.separator + "cs410J" + File.separator + userId); continue; } // We like this file files.add(file); } return files; } private Set<String> fetchListOfFilesThatCanNotBeSubmitted() { Set<String> noSubmit = new HashSet<>(); try { URL url = new URL(NO_SUBMIT_LIST_URL); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); while (br.ready()) { noSubmit.add(br.readLine().trim()); } } catch (MalformedURLException ex) { err.println("** WARNING: Cannot access \"no submit\" list: " + ex.getMessage()); } catch (IOException ex) { err.println("** WARNING: Problems while reading " + "\"no submit\" list: " + ex); } return noSubmit; } /** * Prints a summary of what is about to be submitted and prompts the * user to verify that it is correct. * * @return <code>true</code> if the user wants to submit */ private boolean verifySubmission(Set<File> sourceFiles) { // Print out what is going to be submitted out.print("\n" + userName); out.print("'s submission for "); out.println(projName); for (File file : sourceFiles) { out.println(" " + file); } if (comment != null) { out.println("\nComment: " + comment + "\n\n"); } out.println("A receipt will be sent to: " + userEmail + "\n"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); while (true) { out.print("Do you wish to continue with the submission? (yes/no) "); out.flush(); try { String line = in.readLine().trim(); switch (line) { case "yes": return true; case "no": return false; default: err.println("** Please enter yes or no"); break; } } catch (IOException ex) { err.println("** Exception while reading from System.in: " + ex); } } } /** * Returns the name of a <code>File</code> relative to the source * directory. */ private String getRelativeName(File file) { // We already know that the file is in the correct directory return "edu/pdx/cs410J/" + userId + "/" + file.getName(); } /** * Creates a Jar file that contains the source files. The Jar File * is temporary and is deleted when the program exits. */ private File makeJarFileWith(Set<File> sourceFiles) throws IOException { String jarFileName = userName.replace(' ', '_') + "-TEMP"; File jarFile = File.createTempFile(jarFileName, ".jar"); if (!saveJar) { jarFile.deleteOnExit(); } else { out.println("Saving temporary Jar file: " + jarFile); } db("Created Jar file: " + jarFile); Map<File, String> sourceFilesWithNames = Maps.toMap(sourceFiles, new Function<File, String>() { @Override public String apply(File file) { return getRelativeName(file); } }); return new JarMaker(sourceFilesWithNames, jarFile, getManifestEntries()).makeJar(); } private Map<Attributes.Name, String> getManifestEntries() { Map<Attributes.Name, String> manifestEntries = new HashMap<>(); manifestEntries.put(ManifestAttributes.USER_NAME, userName); manifestEntries.put(ManifestAttributes.USER_ID, userId); manifestEntries.put(ManifestAttributes.USER_EMAIL, userEmail); manifestEntries.put(ManifestAttributes.PROJECT_NAME, projName); manifestEntries.put(ManifestAttributes.SUBMISSION_COMMENT, comment); manifestEntries.put(ManifestAttributes.SUBMISSION_TIME, ManifestAttributes.formatSubmissionTime(submitTime)); return manifestEntries; } /** * Sends the Jar file to the TA as a MIME attachment. Also includes * a textual summary of the contents of the Jar file. */ private void mailTA(File jarFile, Set<File> sourceFiles) throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(), TA_EMAIL, "CS410J-SUBMIT " + userName + "'s " + projName); MimeBodyPart textPart = createTextPartOfTAEmail(sourceFiles); MimeBodyPart filePart = createJarAttachment(jarFile); Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(filePart); message.setContent(mp); out.println("Submitting project to Grader"); Transport.send(message); } private MimeBodyPart createJarAttachment(File jarFile) throws MessagingException { // Now attach the Jar file DataSource ds = new FileDataSource(jarFile); DataHandler dh = new DataHandler(ds); MimeBodyPart filePart = new MimeBodyPart(); String jarFileTitle = userName.replace(' ', '_') + ".jar"; filePart.setDataHandler(dh); filePart.setFileName(jarFileTitle); filePart.setDescription(userName + "'s " + projName); return filePart; } private MimeBodyPart createTextPartOfTAEmail(Set<File> sourceFiles) throws MessagingException { // Create the text portion of the message StringBuilder text = new StringBuilder(); text.append("Student name: ").append(userName).append(" (").append(userEmail).append(")\n"); text.append("Project name: ").append(projName).append("\n"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); text.append("Submitted on: ").append(df.format(submitTime)).append("\n"); if (comment != null) { text.append("\nComment: ").append(comment).append("\n\n"); } text.append("Contents:\n"); for (File file : sourceFiles) { text.append(" ").append(getRelativeName(file)).append("\n"); } text.append("\n\n"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(text.toString(), "text/plain"); // Try not to display text as separate attachment textPart.setDisposition("inline"); return textPart; } private MimeMessage newEmailTo(Session session, String recipient, String subject) throws MessagingException { // Make a new email message MimeMessage message = new MimeMessage(session); InternetAddress[] to = {new InternetAddress(recipient)}; message.setRecipients(Message.RecipientType.TO, to); message.setSubject(subject); return message; } private Session newEmailSession() { // Obtain a Session for sending email Properties props = new Properties(); props.put("mail.smtp.host", serverName); db("Establishing session on " + serverName); Session session = Session.getDefaultInstance(props, null); session.setDebug(this.debug); return session; } /** * Sends a email to the user as a receipt of the submission. */ private void mailReceipt(Set<File> sourceFiles) throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(), userEmail, "CS410J " + projName + " submission"); // Create the contents of the message DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); StringBuilder text = new StringBuilder(); text.append("On ").append(df.format(submitTime)).append("\n"); text.append(userName).append(" (").append(userEmail).append(")\n"); text.append("submitted the following files for ").append(projName).append(":\n"); for (File file : sourceFiles) { text.append(" ").append(file.getAbsolutePath()).append("\n"); } if (comment != null) { text.append("\nComment: ").append(comment).append("\n\n"); } text.append("\n\n"); text.append("Have a nice day."); // Add the text to the message and send it message.setText(text.toString()); message.setDisposition("inline"); out.println("Sending receipt to you"); Transport.send(message); } ///////////////////////// Main Program /////////////////////////// /** * Prints usage information about this program. */ private static void usage(String s) { err.println("\n** " + s + "\n"); err.println("usage: java Submit [options] args file+"); err.println(" args are (in this order):"); err.println(" project What project is being submitted"); err.println(" student Who is submitting the project?"); err.println(" loginId UNIX login id"); err.println(" email Student's email address"); err.println(" file Java source file to submit"); err.println(" options are (options may appear in any order):"); err.println(" -savejar Saves temporary Jar file"); err.println(" -smtp serverName Name of SMTP server"); err.println(" -verbose Log debugging output"); err.println(" -comment comment Info for the Grader"); err.println(""); err.println("Submits Java source code to the CS410J grader."); System.exit(1); } /** * Parses the command line, finds the source files, prompts the user * to verify whether or not the settings are correct, and then sends * an email to the Grader. */ public static void main(String[] args) throws IOException, MessagingException { Submit submit = new Submit(); // Parse the command line for (int i = 0; i < args.length; i++) { // Check for options first if (args[i].equals("-smtp")) { if (++i >= args.length) { usage("No SMTP server specified"); } submit.setServerName(args[i]); } else if (args[i].equals("-verbose")) { submit.setDebug(true); } else if (args[i].equals("-savejar")) { submit.setSaveJar(true); } else if (args[i].equals("-comment")) { if (++i >= args.length) { usage("No comment specified"); } submit.setComment(args[i]); } else if (submit.projName == null) { submit.setProjectName(args[i]); } else if (submit.userName == null) { submit.setUserName(args[i]); } else if (submit.userId == null) { submit.setUserId(args[i]); } else if (submit.userEmail == null) { submit.setUserEmail(args[i]); } else { // The name of a source file submit.addFile(args[i]); } } boolean submitted; try { // Make sure that user entered enough information submit.validate(); submit.db("Command line successfully parsed."); submitted = submit.submit(true); } catch (IllegalStateException ex) { usage(ex.getMessage()); return; } // All done. if (submitted) { out.println(submit.projName + " submitted successfully. Thank you."); } else { out.println(submit.projName + " not submitted."); } } static class ManifestAttributes { public static final Attributes.Name USER_NAME = new Attributes.Name("Submitter-User-Name"); public static final Attributes.Name USER_ID = new Attributes.Name("Submitter-User-Id"); public static final Attributes.Name USER_EMAIL = new Attributes.Name("Submitter-Email"); public static final Attributes.Name PROJECT_NAME = new Attributes.Name("Project-Name"); public static final Attributes.Name SUBMISSION_TIME = new Attributes.Name("Submission-Time"); public static final Attributes.Name SUBMISSION_COMMENT = new Attributes.Name("Submission-Comment"); public static String formatSubmissionTime(Date submitTime) { DateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); return format.format(submitTime); } } }
Make sure that the project name is one of the expected project names. This way, we can make sure that the project name matches the name of the one assignments in the grade book.
grader/src/main/java/edu/pdx/cs410J/grader/Submit.java
Make sure that the project name is one of the expected project names. This way, we can make sure that the project name matches the name of the one assignments in the grade book.
<ide><path>rader/src/main/java/edu/pdx/cs410J/grader/Submit.java <ide> private static final String NO_SUBMIT_LIST_URL = <ide> "http://www.cs.pdx.edu/~whitlock/no-submit"; <ide> <add> private static final String PROJECT_NAMES_LIST_URL = <add> "http://www.cs.pdx.edu/~whitlock/project-names"; <add> <ide> ///////////////////// Instance Fields ////////////////////////// <ide> <ide> /** <ide> * @throws IllegalStateException If any state is incorrect or missing <ide> */ <ide> public void validate() { <add> validateProjectName(); <add> <ide> if (projName == null) { <ide> throw new IllegalStateException("Missing project name"); <ide> } <ide> } <ide> } <ide> <add> private void validateProjectName() { <add> List<String> validProjectNames = fetchListOfValidProjectNames(); <add> if (!validProjectNames.contains(projName)) { <add> String message = "\"" + projName + "\" is not in the list of valid project names: " + validProjectNames; <add> throw new IllegalStateException(message); <add> } <add> } <add> <add> private List<String> fetchListOfValidProjectNames() { <add> return fetchListOfStringsFromUrl(PROJECT_NAMES_LIST_URL); <add> } <add> <ide> /** <ide> * Submits the project to the grader <ide> * <ide> * edu/pdx/cs410J/<studentId>. <ide> */ <ide> private Set<File> searchForSourceFiles(Set<String> fileNames) { <del> Set<String> noSubmit = fetchListOfFilesThatCanNotBeSubmitted(); <add> List<String> noSubmit = fetchListOfFilesThatCanNotBeSubmitted(); <ide> <ide> // Files should be sorted by name <ide> SortedSet<File> files = new TreeSet<>(new Comparator<File>() { <ide> return files; <ide> } <ide> <del> private Set<String> fetchListOfFilesThatCanNotBeSubmitted() { <del> Set<String> noSubmit = new HashSet<>(); <add> private List<String> fetchListOfFilesThatCanNotBeSubmitted() { <add> return fetchListOfStringsFromUrl(NO_SUBMIT_LIST_URL); <add> } <add> <add> private List<String> fetchListOfStringsFromUrl(String listUrl) { <add> List<String> noSubmit = new ArrayList<>(); <ide> <ide> try { <del> URL url = new URL(NO_SUBMIT_LIST_URL); <add> URL url = new URL(listUrl); <ide> InputStreamReader isr = new InputStreamReader(url.openStream()); <ide> BufferedReader br = new BufferedReader(isr); <ide> while (br.ready()) { <ide> } <ide> <ide> } catch (MalformedURLException ex) { <del> err.println("** WARNING: Cannot access \"no submit\" list: " + <add> err.println("** WARNING: Cannot access " + listUrl + ": " + <ide> ex.getMessage()); <ide> <ide> } catch (IOException ex) { <del> err.println("** WARNING: Problems while reading " + <del> "\"no submit\" list: " + ex); <add> err.println("** WARNING: Problems while reading " + listUrl + ": " + ex.getMessage()); <ide> } <ide> return noSubmit; <ide> } <ide> err.println("\n** " + s + "\n"); <ide> err.println("usage: java Submit [options] args file+"); <ide> err.println(" args are (in this order):"); <del> err.println(" project What project is being submitted"); <add> err.println(" project What project is being submitted (Project1, Project2, etc.)"); <ide> err.println(" student Who is submitting the project?"); <ide> err.println(" loginId UNIX login id"); <ide> err.println(" email Student's email address");
Java
apache-2.0
72288bd54c4cc7010d22d60e161646dc8ab5188c
0
apache/tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,Lab41/tinkerpop3,apache/tinkerpop,n-tran/incubator-tinkerpop,samiunn/incubator-tinkerpop,vtslab/incubator-tinkerpop,apache/tinkerpop,mpollmeier/tinkerpop3,krlohnes/tinkerpop,artem-aliev/tinkerpop,samiunn/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,vtslab/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,rmagen/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,n-tran/incubator-tinkerpop,velo/incubator-tinkerpop,robertdale/tinkerpop,BrynCooke/incubator-tinkerpop,dalaro/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,rmagen/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,artem-aliev/tinkerpop,krlohnes/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,newkek/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,mpollmeier/tinkerpop3,newkek/incubator-tinkerpop,apache/tinkerpop,newkek/incubator-tinkerpop,robertdale/tinkerpop,RedSeal-co/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,edgarRd/incubator-tinkerpop,apache/tinkerpop,PommeVerte/incubator-tinkerpop,pluradj/incubator-tinkerpop,dalaro/incubator-tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,dalaro/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,jorgebay/tinkerpop,BrynCooke/incubator-tinkerpop,velo/incubator-tinkerpop,edgarRd/incubator-tinkerpop,n-tran/incubator-tinkerpop,jorgebay/tinkerpop,jorgebay/tinkerpop,pluradj/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,apache/incubator-tinkerpop,edgarRd/incubator-tinkerpop,robertdale/tinkerpop,mike-tr-adamson/incubator-tinkerpop,krlohnes/tinkerpop,velo/incubator-tinkerpop,artem-aliev/tinkerpop,rmagen/incubator-tinkerpop,artem-aliev/tinkerpop,Lab41/tinkerpop3,vtslab/incubator-tinkerpop,samiunn/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,PommeVerte/incubator-tinkerpop
package com.tinkerpop.gremlin.driver; import com.tinkerpop.gremlin.driver.message.RequestMessage; import io.netty.channel.ChannelPromise; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class Client { private final Cluster cluster; private volatile boolean initialized; // todo: each host gets a connection pool? private ConcurrentMap<Host, Connection> connections = new ConcurrentHashMap<>(); Client(final Cluster cluster) { this.cluster = cluster; } public synchronized Client init() { if (initialized) return this; cluster.init(); // todo: connection pooling final Cluster.Factory factory = cluster.getFactory(); cluster.getClusterInfo().allHosts().forEach(host -> connections.put(host, new Connection(host.getWebSocketUri(), factory))); initialized = true; return this; } public ResultSet submit(final String gremlin) { try { return submitAsync(gremlin).get(); } catch (Exception ex) { throw new RuntimeException(ex); } } public CompletableFuture<ResultSet> submitAsync(final String gremlin) { if (!initialized) init(); final CompletableFuture<ResultSet> future = new CompletableFuture<>(); // todo: choose a connection smartly. final Connection connection = connections.values().iterator().next(); final RequestMessage request = RequestMessage.create("eval") .add(Tokens.ARGS_GREMLIN, gremlin, Tokens.ARGS_ACCEPT, "application/json").build(); connection.write(request, future); return future; } }
gremlin-driver/src/main/java/com/tinkerpop/gremlin/driver/Client.java
package com.tinkerpop.gremlin.driver; import com.tinkerpop.gremlin.driver.message.RequestMessage; import io.netty.channel.ChannelPromise; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class Client { private final Cluster cluster; private volatile boolean initialized; // todo: each host gets a connection pool? private ConcurrentMap<Host, Connection> connections = new ConcurrentHashMap<>(); public Client(final Cluster cluster) { this.cluster = cluster; } public synchronized Client init() { if (initialized) return this; cluster.init(); // todo: connection pooling final Cluster.Factory factory = cluster.getFactory(); cluster.getClusterInfo().allHosts().forEach(host -> connections.put(host, new Connection(host.getWebSocketUri(), factory))); initialized = true; return this; } public ResultSet submit(final String gremlin) { try { return submitAsync(gremlin).get(); } catch (Exception ex) { throw new RuntimeException(ex); } } public CompletableFuture<ResultSet> submitAsync(final String gremlin) { if (!initialized) init(); final CompletableFuture<ResultSet> future = new CompletableFuture<>(); // todo: choose a connection smartly. final Connection connection = connections.values().iterator().next(); final RequestMessage request = RequestMessage.create("eval") .add(Tokens.ARGS_GREMLIN, gremlin, Tokens.ARGS_ACCEPT, "application/json").build(); connection.write(request, future); return future; } }
A Client can only be constructed internally by a Cluster.
gremlin-driver/src/main/java/com/tinkerpop/gremlin/driver/Client.java
A Client can only be constructed internally by a Cluster.
<ide><path>remlin-driver/src/main/java/com/tinkerpop/gremlin/driver/Client.java <ide> // todo: each host gets a connection pool? <ide> private ConcurrentMap<Host, Connection> connections = new ConcurrentHashMap<>(); <ide> <del> public Client(final Cluster cluster) { <add> Client(final Cluster cluster) { <ide> this.cluster = cluster; <ide> <ide> }
JavaScript
mit
a152aab8bc5a928726b1f37fb00359966f4e8a03
0
grantila/awesome-phonenumber,grantila/awesome-phonenumber,grantila/awesome-phonenumber
const gulp = require( 'gulp' ); const child = require( 'child_process' ); const fs = require( 'fs' ); const rimraf = require( 'rimraf-promise' ); const mkdirp = require( 'mkdirp' ); const replace = require( 'replace' ); const libphonenumberVersion = fs.readFileSync( 'libphonenumber.version', 'utf8' ).toString( ).trim( ); const buildRoot = './build'; const libphonenumberUrl = 'https://github.com/google/libphonenumber/'; const closureLibraryUrl = 'https://github.com/google/closure-library/'; const closureLinterUrl = 'https://github.com/google/closure-linter'; const pythonGflagsUrl = 'https://github.com/google/python-gflags.git'; const antName = 'apache-ant-1.10.8'; const antTar = `${antName}.tar.gz`; const antUrl = `http://apache.mirrors.spacedump.net/ant/binaries/${antName}-bin.tar.gz`; const isDebug = process.env.DEBUG && process.env.DEBUG !== '0'; gulp.task( 'clean', ( ) => rimraf( buildRoot ) ); gulp.task( 'make-build-dir', async ( ) => await mkdirp( buildRoot ) ); gulp.task( 'clone-libphonenumber', gulp.series( 'make-build-dir', ( ) => gitClone( libphonenumberUrl, 'libphonenumber', libphonenumberVersion ) ) ); gulp.task( 'clone-closure-library', gulp.series( 'make-build-dir', ( ) => gitClone( closureLibraryUrl, 'closure-library', 'v20171112' ) ) ); gulp.task( 'checkout-closure-linter', gulp.series( 'make-build-dir', ( ) => gitClone( closureLinterUrl, 'closure-linter' ) ) ); gulp.task( 'checkout-python-gflags', gulp.series( 'make-build-dir', ( ) => gitClone( pythonGflagsUrl, 'python-gflags' ) ) ); gulp.task( 'download-ant', gulp.series( 'make-build-dir', ( ) => runCommand( 'curl', [ '-L', '-o', antTar, antUrl ], { cwd: buildRoot } ), ( ) => runCommand( 'tar', [ 'zxf', antTar ], { cwd: buildRoot } ) ) ); gulp.task( 'download-deps', gulp.parallel( 'clone-libphonenumber', 'clone-closure-library', 'checkout-closure-linter', 'checkout-python-gflags', 'download-ant' ) ); gulp.task( 'build-deps', gulp.series( 'download-deps' ) ); gulp.task( 'build-libphonenumber', ( ) => { var args = [ '-f', 'build.xml', 'compile-exports' ]; return runCommand( `${buildRoot}/${antName}/bin/ant`, args, { cwd: '.' } ); } ); gulp.task( 'build', gulp.series( 'build-deps', 'build-libphonenumber' ) ); gulp.task( 'update-readme', ( ) => updateReadme( ) ); gulp.task( 'default', gulp.series( 'clean', 'build', 'update-readme' ) ); async function updateReadme( ) { replace( { regex: 'Uses libphonenumber ([A-Za-z.0-9]+)', replacement: `Uses libphonenumber ${libphonenumberVersion}`, paths: [ 'README.md' ], silent: true, } ); } function gitClone( url, name, branch ) { const args = [ '--depth=1' ]; if ( branch ) args.push( '--branch=' + branch ); return runCommand( 'git', [ 'clone', ...args, url, name ] ); } function runCommand( cmd, args, opts ) { opts = opts ||ย { cwd : './build', stdio : [ null, null, isDebug ? process.stderr : null ] }; return new Promise( function( resolve, reject ) { var cp = child.spawn( cmd, args, opts ); cp.stdout.on( 'data', data => { if ( isDebug ) console.log( data.toString( ) ); } ); cp.on( 'close', code => { if ( code === 0 ) return resolve( ); reject( new Error( `${cmd} exited with exitcode ${code}. Args: ${args}` ) ); } ); cp.on( 'error', err => reject( err ) ); } ); }
gulpfile.js
const gulp = require( 'gulp' ); const child = require( 'child_process' ); const fs = require( 'fs' ); const rimraf = require( 'rimraf-promise' ); const mkdirp = require( 'mkdirp' ); const replace = require( 'replace' ); const libphonenumberVersion = fs.readFileSync( 'libphonenumber.version', 'utf8' ).toString( ).trim( ); const buildRoot = './build'; const libphonenumberUrl = 'https://github.com/googlei18n/libphonenumber/'; const closureLibraryUrl = 'https://github.com/google/closure-library/'; const closureLinterUrl = 'https://github.com/google/closure-linter'; const pythonGflagsUrl = 'https://github.com/google/python-gflags.git'; const antName = 'apache-ant-1.10.8'; const antTar = `${antName}.tar.gz`; const antUrl = `http://apache.mirrors.spacedump.net/ant/binaries/${antName}-bin.tar.gz`; const isDebug = process.env.DEBUG && process.env.DEBUG !== '0'; gulp.task( 'clean', ( ) => rimraf( buildRoot ) ); gulp.task( 'make-build-dir', async ( ) => await mkdirp( buildRoot ) ); gulp.task( 'clone-libphonenumber', gulp.series( 'make-build-dir', ( ) => gitClone( libphonenumberUrl, 'libphonenumber', libphonenumberVersion ) ) ); gulp.task( 'clone-closure-library', gulp.series( 'make-build-dir', ( ) => gitClone( closureLibraryUrl, 'closure-library', 'v20171112' ) ) ); gulp.task( 'checkout-closure-linter', gulp.series( 'make-build-dir', ( ) => gitClone( closureLinterUrl, 'closure-linter' ) ) ); gulp.task( 'checkout-python-gflags', gulp.series( 'make-build-dir', ( ) => gitClone( pythonGflagsUrl, 'python-gflags' ) ) ); gulp.task( 'download-ant', gulp.series( 'make-build-dir', ( ) => runCommand( 'curl', [ '-L', '-o', antTar, antUrl ], { cwd: buildRoot } ), ( ) => runCommand( 'tar', [ 'zxf', antTar ], { cwd: buildRoot } ) ) ); gulp.task( 'download-deps', gulp.parallel( 'clone-libphonenumber', 'clone-closure-library', 'checkout-closure-linter', 'checkout-python-gflags', 'download-ant' ) ); gulp.task( 'build-deps', gulp.series( 'download-deps' ) ); gulp.task( 'build-libphonenumber', ( ) => { var args = [ '-f', 'build.xml', 'compile-exports' ]; return runCommand( `${buildRoot}/${antName}/bin/ant`, args, { cwd: '.' } ); } ); gulp.task( 'build', gulp.series( 'build-deps', 'build-libphonenumber' ) ); gulp.task( 'update-readme', ( ) => updateReadme( ) ); gulp.task( 'default', gulp.series( 'clean', 'build', 'update-readme' ) ); async function updateReadme( ) { replace( { regex: 'Uses libphonenumber ([A-Za-z.0-9]+)', replacement: `Uses libphonenumber ${libphonenumberVersion}`, paths: [ 'README.md' ], silent: true, } ); } function gitClone( url, name, branch ) { const args = [ '--depth=1' ]; if ( branch ) args.push( '--branch=' + branch ); return runCommand( 'git', [ 'clone', ...args, url, name ] ); } function runCommand( cmd, args, opts ) { opts = opts ||ย { cwd : './build', stdio : [ null, null, isDebug ? process.stderr : null ] }; return new Promise( function( resolve, reject ) { var cp = child.spawn( cmd, args, opts ); cp.stdout.on( 'data', data => { if ( isDebug ) console.log( data.toString( ) ); } ); cp.on( 'close', code => { if ( code === 0 ) return resolve( ); reject( new Error( `${cmd} exited with exitcode ${code}. Args: ${args}` ) ); } ); cp.on( 'error', err => reject( err ) ); } ); }
build(upstream): libphonenumber has moved to a new upstream location
gulpfile.js
build(upstream): libphonenumber has moved to a new upstream location
<ide><path>ulpfile.js <ide> fs.readFileSync( 'libphonenumber.version', 'utf8' ).toString( ).trim( ); <ide> <ide> const buildRoot = './build'; <del>const libphonenumberUrl = 'https://github.com/googlei18n/libphonenumber/'; <add>const libphonenumberUrl = 'https://github.com/google/libphonenumber/'; <ide> const closureLibraryUrl = 'https://github.com/google/closure-library/'; <ide> const closureLinterUrl = 'https://github.com/google/closure-linter'; <ide> const pythonGflagsUrl = 'https://github.com/google/python-gflags.git';
JavaScript
mit
2a23f9408f09bcee51e6c53430ba39d590045095
0
melonjs/melonJS,melonjs/melonJS
import Vector2d from "./../math/vector2.js"; import timer from "./../system/timer.js"; import { randomFloat, clamp } from "./../math/math.js"; import Renderable from "./../renderable/renderable.js"; /** * @classdesc * Single Particle Object. * @augments Renderable */ class Particle extends Renderable { /** * @param {ParticleEmitter} particle emitter */ constructor(emitter) { // Call the super constructor super( emitter.getRandomPointX(), emitter.getRandomPointY(), emitter.image ? emitter.image.width : emitter.width || 1, emitter.image ? emitter.image.height : emitter.height || 1 ); // particle velocity this.vel = new Vector2d(); this.onResetEvent(emitter, true); } /** * @ignore */ onResetEvent(emitter, newInstance = false) { if (newInstance === false) { this.pos.set( emitter.getRandomPointX(), emitter.getRandomPointY() ); this.resize( emitter.image ? emitter.image.width : emitter.width || 1, emitter.image ? emitter.image.height : emitter.height || 1 ); } this.image = emitter.image; // Particle will always update this.alwaysUpdate = true; if (typeof emitter.tint === "string") { this.tint.parseCSS(emitter.tint); } // Set the start particle Angle and Speed as defined in emitter var angle = emitter.angle + ((emitter.angleVariation > 0) ? (randomFloat(0, 2) - 1) * emitter.angleVariation : 0); var speed = emitter.speed + ((emitter.speedVariation > 0) ? (randomFloat(0, 2) - 1) * emitter.speedVariation : 0); // Set the start particle Velocity this.vel.set(speed * Math.cos(angle), -speed * Math.sin(angle)); // Set the start particle Time of Life as defined in emitter this.life = randomFloat(emitter.minLife, emitter.maxLife); this.startLife = this.life; // Set the start and end particle Scale as defined in emitter // clamp the values as minimum and maximum scales range this.startScale = clamp( randomFloat(emitter.minStartScale, emitter.maxStartScale), emitter.minStartScale, emitter.maxStartScale ); this.endScale = clamp( randomFloat(emitter.minEndScale, emitter.maxEndScale), emitter.minEndScale, emitter.maxEndScale ); // Set the particle Gravity and Wind (horizontal gravity) as defined in emitter this.gravity = emitter.gravity; this.wind = emitter.wind; // Set if the particle update the rotation in accordance the trajectory this.followTrajectory = emitter.followTrajectory; // Set if the particle update only in Viewport this.onlyInViewport = emitter.onlyInViewport; // Set the particle Z Order this.pos.z = emitter.z; // cache inverse of the expected delta time this._deltaInv = timer.maxfps / 1000; // Set the start particle rotation as defined in emitter // if the particle not follow trajectory if (!emitter.followTrajectory) { this.angle = randomFloat(emitter.minRotation, emitter.maxRotation); } } /** * Update the Particle <br> * This is automatically called by the game manager {@link game} * @ignore * @param {number} dt time since the last update in milliseconds */ update(dt) { // move things forward independent of the current frame rate var skew = dt * this._deltaInv; // Decrease particle life this.life = this.life > dt ? this.life - dt : 0; // Calculate the particle Age Ratio var ageRatio = this.life / this.startLife; // Resize the particle as particle Age Ratio var scale = this.startScale; if (this.startScale > this.endScale) { scale *= ageRatio; scale = (scale < this.endScale) ? this.endScale : scale; } else if (this.startScale < this.endScale) { scale /= ageRatio; scale = (scale > this.endScale) ? this.endScale : scale; } // Set the particle opacity as Age Ratio this.alpha = ageRatio; // Adjust the particle velocity this.vel.x += this.wind * skew; this.vel.y += this.gravity * skew; // If necessary update the rotation of particle in accordance the particle trajectory var angle = this.followTrajectory ? Math.atan2(this.vel.y, this.vel.x) : this.angle; this.pos.x += this.vel.x * skew; this.pos.y += this.vel.y * skew; // Update particle transform this.currentTransform.setTransform( scale, 0, 0, 0, scale, 0, this.pos.x, this.pos.y, 1 ).rotate(angle); // Return true if the particle is not dead yet return (this.inViewport || !this.onlyInViewport) && (this.life > 0); } /** * @ignore */ preDraw(renderer) { // restore is called in postDraw renderer.save(); // particle alpha value renderer.setGlobalAlpha(renderer.globalAlpha() * this.alpha); // translate to the defined anchor point and scale it renderer.transform(this.currentTransform); // apply the current tint and opacity renderer.setTint(this.tint, this.getOpacity()); } /** * @ignore */ draw(renderer) { var w = this.width, h = this.height; renderer.drawImage( this.image, 0, 0, w, h, -w / 2, -h / 2, w, h ); } }; export default Particle;
src/particles/particle.js
import Vector2d from "./../math/vector2.js"; import timer from "./../system/timer.js"; import { randomFloat, clamp } from "./../math/math.js"; import Renderable from "./../renderable/renderable.js"; /** * @classdesc * Single Particle Object. * @augments Renderable */ class Particle extends Renderable { /** * @param {ParticleEmitter} particle emitter */ constructor(emitter) { // Call the super constructor super( emitter.getRandomPointX(), emitter.getRandomPointY(), emitter.image ? emitter.image.width : emitter.width || 1, emitter.image ? emitter.image.height : emitter.height || 1 ); // particle velocity this.vel = new Vector2d(); this.onResetEvent(emitter, true); } /** * @ignore */ onResetEvent(emitter, newInstance = false) { if (newInstance === false) { super.onResetEvent( emitter.getRandomPointX(), emitter.getRandomPointY(), emitter.image ? emitter.image.width : emitter.width || 1, emitter.image ? emitter.image.height : emitter.height || 1 ); } this.image = emitter.image; // Particle will always update this.alwaysUpdate = true; if (typeof emitter.tint === "string") { this.tint.parseCSS(emitter.tint); } // Set the start particle Angle and Speed as defined in emitter var angle = emitter.angle + ((emitter.angleVariation > 0) ? (randomFloat(0, 2) - 1) * emitter.angleVariation : 0); var speed = emitter.speed + ((emitter.speedVariation > 0) ? (randomFloat(0, 2) - 1) * emitter.speedVariation : 0); // Set the start particle Velocity this.vel.set(speed * Math.cos(angle), -speed * Math.sin(angle)); // Set the start particle Time of Life as defined in emitter this.life = randomFloat(emitter.minLife, emitter.maxLife); this.startLife = this.life; // Set the start and end particle Scale as defined in emitter // clamp the values as minimum and maximum scales range this.startScale = clamp( randomFloat(emitter.minStartScale, emitter.maxStartScale), emitter.minStartScale, emitter.maxStartScale ); this.endScale = clamp( randomFloat(emitter.minEndScale, emitter.maxEndScale), emitter.minEndScale, emitter.maxEndScale ); // Set the particle Gravity and Wind (horizontal gravity) as defined in emitter this.gravity = emitter.gravity; this.wind = emitter.wind; // Set if the particle update the rotation in accordance the trajectory this.followTrajectory = emitter.followTrajectory; // Set if the particle update only in Viewport this.onlyInViewport = emitter.onlyInViewport; // Set the particle Z Order this.pos.z = emitter.z; // cache inverse of the expected delta time this._deltaInv = timer.maxfps / 1000; // Set the start particle rotation as defined in emitter // if the particle not follow trajectory if (!emitter.followTrajectory) { this.angle = randomFloat(emitter.minRotation, emitter.maxRotation); } } /** * Update the Particle <br> * This is automatically called by the game manager {@link game} * @ignore * @param {number} dt time since the last update in milliseconds */ update(dt) { // move things forward independent of the current frame rate var skew = dt * this._deltaInv; // Decrease particle life this.life = this.life > dt ? this.life - dt : 0; // Calculate the particle Age Ratio var ageRatio = this.life / this.startLife; // Resize the particle as particle Age Ratio var scale = this.startScale; if (this.startScale > this.endScale) { scale *= ageRatio; scale = (scale < this.endScale) ? this.endScale : scale; } else if (this.startScale < this.endScale) { scale /= ageRatio; scale = (scale > this.endScale) ? this.endScale : scale; } // Set the particle opacity as Age Ratio this.alpha = ageRatio; // Adjust the particle velocity this.vel.x += this.wind * skew; this.vel.y += this.gravity * skew; // If necessary update the rotation of particle in accordance the particle trajectory var angle = this.followTrajectory ? Math.atan2(this.vel.y, this.vel.x) : this.angle; this.pos.x += this.vel.x * skew; this.pos.y += this.vel.y * skew; // Update particle transform this.currentTransform.setTransform( scale, 0, 0, 0, scale, 0, this.pos.x, this.pos.y, 1 ).rotate(angle); // Return true if the particle is not dead yet return (this.inViewport || !this.onlyInViewport) && (this.life > 0); } /** * @ignore */ preDraw(renderer) { // restore is called in postDraw renderer.save(); // particle alpha value renderer.setGlobalAlpha(renderer.globalAlpha() * this.alpha); // translate to the defined anchor point and scale it renderer.transform(this.currentTransform); // apply the current tint and opacity renderer.setTint(this.tint, this.getOpacity()); } /** * @ignore */ draw(renderer) { var w = this.width, h = this.height; renderer.drawImage( this.image, 0, 0, w, h, -w / 2, -h / 2, w, h ); } }; export default Particle;
fix particle pooling/recycling Renderable have no onResetEvent function by default, so calling the super function would not work
src/particles/particle.js
fix particle pooling/recycling
<ide><path>rc/particles/particle.js <ide> */ <ide> onResetEvent(emitter, newInstance = false) { <ide> if (newInstance === false) { <del> super.onResetEvent( <add> this.pos.set( <ide> emitter.getRandomPointX(), <del> emitter.getRandomPointY(), <add> emitter.getRandomPointY() <add> ); <add> this.resize( <ide> emitter.image ? emitter.image.width : emitter.width || 1, <ide> emitter.image ? emitter.image.height : emitter.height || 1 <ide> );
Java
apache-2.0
efd6ec96bf4470c174dd8ec0f3b18cd65fa68aa5
0
linkedin/parseq,linkedin/parseq,linkedin/parseq,linkedin/parseq
/* * Copyright 2016 LinkedIn, 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.linkedin.restli.client; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.Collection; import org.testng.annotations.Test; import com.linkedin.parseq.Task; import com.linkedin.r2.message.RequestContext; import com.linkedin.restli.client.config.RequestConfigOverridesBuilder; import com.linkedin.restli.common.ResourceMethod; import com.linkedin.restli.examples.greetings.api.Greeting; import com.linkedin.restli.examples.greetings.client.GreetingsBuilders; public class TestRequestContextProvider extends ParSeqRestClientIntegrationTest { private CapturingRestClient _capturingRestClient; @Override public ParSeqRestliClientConfig getParSeqRestClientConfig() { return new ParSeqRestliClientConfigBuilder() .addTimeoutMs("*.*/greetings.GET", 9999L) .addTimeoutMs("*.*/greetings.*", 10001L) .addTimeoutMs("*.*/*.GET", 10002L) .addTimeoutMs("foo.*/greetings.GET", 10003L) .addTimeoutMs("foo.GET/greetings.GET", 10004L) .addTimeoutMs("foo.ACTION-*/greetings.GET", 10005L) .addTimeoutMs("foo.ACTION-bar/greetings.GET", 10006L) .addBatchingEnabled("withBatching.*/*.*", true) .addMaxBatchSize("withBatching.*/*.*", 3) .build(); } @Override protected RestClient createRestClient() { _capturingRestClient = new CapturingRestClient(null, null, super.createRestClient()); return _capturingRestClient; } private <T> RequestContext createRequestContext(Request<T> request) { RequestContext requestContext = new RequestContext(); requestContext.putLocalAttr("method", request.getMethod()); return requestContext; } @Override protected void customizeParSeqRestliClient(ParSeqRestliClientBuilder parSeqRestliClientBuilder) { parSeqRestliClientBuilder.setRequestContextProvider(this::createRequestContext); } @Test public void testNonBatchableRequest() { try { GetRequest<Greeting> request = new GreetingsBuilders().get().id(1L).build(); Task<?> task = _parseqClient.createTask(request); runAndWait(getTestClassName() + ".testNonBatchableRequest", task); verifyRequestContext(request); } finally { _capturingRestClient.clearCapturedRequestContexts(); } } @Test public void testBatchableRequestNotBatched() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); GetRequest<Greeting> request = new GreetingsBuilders().get().id(1L).build(); Task<?> task = _parseqClient.createTask(request); runAndWait(getTestClassName() + ".testBatchableRequestNotBatched", task); verifyRequestContext(request); } finally { _capturingRestClient.clearCapturedRequestContexts(); } } @Test public void testBatchableRequestBatched() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); GetRequest<Greeting> request1 = new GreetingsBuilders().get().id(1L).build(); GetRequest<Greeting> request2 = new GreetingsBuilders().get().id(2L).build(); Task<?> task = Task.par(_parseqClient.createTask(request1), _parseqClient.createTask(request2)); runAndWait(getTestClassName() + ".testBatchableRequestBatched", task); Collection<RequestContext> contexts = _capturingRestClient.getCapturedRequestContexts().values(); assertEquals(contexts.size(), 1); RequestContext context = contexts.iterator().next(); assertNotNull(context.getLocalAttr("method")); assertEquals(context.getLocalAttr("method"), ResourceMethod.BATCH_GET); } finally { _capturingRestClient.clearCapturedRequestContexts(); } } private void verifyRequestContext(Request<?> request) { assertTrue(_capturingRestClient.getCapturedRequestContexts().containsKey(request)); assertNotNull(_capturingRestClient.getCapturedRequestContexts().get(request).getLocalAttr("method")); assertEquals(_capturingRestClient.getCapturedRequestContexts().get(request).getLocalAttr("method"), request.getMethod()); } }
contrib/parseq-restli-client/src/test/java/com/linkedin/restli/client/TestRequestContextProvider.java
/* * Copyright 2016 LinkedIn, 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.linkedin.restli.client; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.Collection; import org.testng.annotations.Test; import com.linkedin.parseq.Task; import com.linkedin.r2.message.RequestContext; import com.linkedin.restli.client.config.RequestConfigOverridesBuilder; import com.linkedin.restli.common.ResourceMethod; import com.linkedin.restli.examples.greetings.api.Greeting; import com.linkedin.restli.examples.greetings.client.GreetingsBuilders; public class TestRequestContextProvider extends ParSeqRestClientIntegrationTest { private CapturingRestClient _capturingRestClient; @Override public ParSeqRestliClientConfig getParSeqRestClientConfig() { return new ParSeqRestliClientConfigBuilder() .addTimeoutMs("*.*/greetings.GET", 9999L) .addTimeoutMs("*.*/greetings.*", 10001L) .addTimeoutMs("*.*/*.GET", 10002L) .addTimeoutMs("foo.*/greetings.GET", 10003L) .addTimeoutMs("foo.GET/greetings.GET", 10004L) .addTimeoutMs("foo.ACTION-*/greetings.GET", 10005L) .addTimeoutMs("foo.ACTION-bar/greetings.GET", 10006L) .addBatchingEnabled("withBatching.*/*.*", true) .addMaxBatchSize("withBatching.*/*.*", 3) .build(); } @Override protected RestClient createRestClient() { _capturingRestClient = new CapturingRestClient(null, null, super.createRestClient()); return _capturingRestClient; } private <T> RequestContext createRequestContext(Request<T> request) { RequestContext requestContext = new RequestContext(); requestContext.putLocalAttr("method", request.getMethod()); return requestContext; } @Override protected void customizeParSeqRestliClient(ParSeqRestliClientBuilder parSeqRestliClientBuilder) { parSeqRestliClientBuilder.setRequestContextProvider(this::createRequestContext); } @Test public void testNonBatchableRequest() { try { GetRequest<Greeting> request = new GreetingsBuilders().get().id(1L).build(); Task<?> task = _parseqClient.createTask(request); runAndWait(getTestClassName() + ".testNonBatchableRequest", task); verifyRequestContext(request); } finally { _capturingRestClient.clearCapturedRequestContexts(); } } @Test public void testBatchableRequestNotBatched() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); GetRequest<Greeting> request = new GreetingsBuilders().get().id(1L).build(); Task<?> task = _parseqClient.createTask(request); runAndWait(getTestClassName() + ".testNonBatchableRequest", task); verifyRequestContext(request); } finally { _capturingRestClient.clearCapturedRequestContexts(); } } @Test public void testBatchableRequestBatched() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); GetRequest<Greeting> request1 = new GreetingsBuilders().get().id(1L).build(); GetRequest<Greeting> request2 = new GreetingsBuilders().get().id(2L).build(); Task<?> task = Task.par(_parseqClient.createTask(request1), _parseqClient.createTask(request2)); runAndWait(getTestClassName() + ".testNonBatchableRequest", task); Collection<RequestContext> contexts = _capturingRestClient.getCapturedRequestContexts().values(); assertEquals(contexts.size(), 1); RequestContext context = contexts.iterator().next(); assertNotNull(context.getLocalAttr("method")); assertEquals(context.getLocalAttr("method"), ResourceMethod.BATCH_GET); } finally { _capturingRestClient.clearCapturedRequestContexts(); } } private void verifyRequestContext(Request<?> request) { assertTrue(_capturingRestClient.getCapturedRequestContexts().containsKey(request)); assertNotNull(_capturingRestClient.getCapturedRequestContexts().get(request).getLocalAttr("method")); assertEquals(_capturingRestClient.getCapturedRequestContexts().get(request).getLocalAttr("method"), request.getMethod()); } @Test public void testConfiguredTimeoutOutboundOverride() { Task<?> task = greetingGet(1L, new RequestConfigOverridesBuilder() .setTimeoutMs(5555L, "overriden") .build()); runAndWait(getTestClassName() + ".testConfiguredTimeoutOutbound", task); assertTrue(hasTask("withTimeout 5555ms src: overriden", task.getTrace())); } @Test public void testConfiguredTimeoutOutboundOverrideNoSrc() { Task<?> task = greetingGet(1L, new RequestConfigOverridesBuilder() .setTimeoutMs(5555L) .build()); runAndWait(getTestClassName() + ".testConfiguredTimeoutOutbound", task); assertTrue(hasTask("withTimeout 5555ms", task.getTrace())); } @Test public void testConfiguredTimeoutInboundAndOutbound() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("foo") .setMethod("GET") .build()); Task<?> task = greetingGet(1L); runAndWait(getTestClassName() + ".testConfiguredTimeoutInboundAndOutbound", task); assertTrue(hasTask("withTimeout 10004ms src: foo.GET/greetings.GET", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testConfiguredTimeoutMismatchedInboundOutbound() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("blah") .setMethod("GET") .build()); Task<?> task = greetingGet(1L); runAndWait(getTestClassName() + ".testConfiguredTimeoutMismatchedInboundOutbound", task); assertTrue(hasTask("withTimeout 9999ms src: *.*/greetings.GET", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testConfiguredTimeoutFullActionAndOutbound() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("foo") .setMethod("ACTION") .setActionName("bar") .build()); Task<?> task = greetingGet(1L); runAndWait(getTestClassName() + ".testConfiguredTimeoutFullActionAndOutbound", task); assertTrue(hasTask("withTimeout 10006ms src: foo.ACTION-bar/greetings.GET", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testConfiguredTimeoutPartialActionAndOutbound() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("foo") .setMethod("ACTION") .build()); Task<?> task = greetingGet(1L); runAndWait(getTestClassName() + ".testConfiguredTimeoutPartialActionAndOutbound", task); assertTrue(hasTask("withTimeout 10005ms src: foo.ACTION-*/greetings.GET", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testConfiguredTimeoutOutboundOp() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("blah") .setMethod("GET") .build()); Task<?> task = greetingDel(9999L).toTry(); runAndWait(getTestClassName() + ".testConfiguredTimeoutOutboundOp", task); assertTrue(hasTask("withTimeout 10001ms src: *.*/greetings.*", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testBatchingGetRequests() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); Task<?> task = Task.par(greetingGet(1L), greetingGet(2L), greetingGet(3L)); runAndWait(getTestClassName() + ".testBatchingGetRequests", task); assertTrue(hasTask("greetings batch_get(reqs: 3, ids: 3)", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testBatchingGetRequestsMaxExceeded() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); Task<?> task = Task.par(greetingGet(1L), greetingGet(2L), greetingGet(3L), greetingGet(4L)); runAndWait(getTestClassName() + ".testBatchingGetRequestsMaxExceeded", task); assertTrue(hasTask("greetings batch_get(reqs: 3, ids: 3)", task.getTrace())); } finally { clearInboundRequestContext(); } } @Test public void testBatchGetLargerThanMaxBatchSize() { try { setInboundRequestContext(new InboundRequestContextBuilder() .setName("withBatching") .build()); Task<?> task = greetings(1L, 2L, 3L, 4L); runAndWait(getTestClassName() + ".testBatchGetLargerThanMaxBatchSize", task); assertFalse(hasTask("greetings batch_get(reqs: 3, ids: 3)", task.getTrace())); } finally { clearInboundRequestContext(); } } }
fixing test in TestRequestContextProvider (#107)
contrib/parseq-restli-client/src/test/java/com/linkedin/restli/client/TestRequestContextProvider.java
fixing test in TestRequestContextProvider (#107)
<ide><path>ontrib/parseq-restli-client/src/test/java/com/linkedin/restli/client/TestRequestContextProvider.java <ide> .build()); <ide> GetRequest<Greeting> request = new GreetingsBuilders().get().id(1L).build(); <ide> Task<?> task = _parseqClient.createTask(request); <del> runAndWait(getTestClassName() + ".testNonBatchableRequest", task); <add> runAndWait(getTestClassName() + ".testBatchableRequestNotBatched", task); <ide> verifyRequestContext(request); <ide> } finally { <ide> _capturingRestClient.clearCapturedRequestContexts(); <ide> GetRequest<Greeting> request2 = new GreetingsBuilders().get().id(2L).build(); <ide> Task<?> task = Task.par(_parseqClient.createTask(request1), _parseqClient.createTask(request2)); <ide> <del> runAndWait(getTestClassName() + ".testNonBatchableRequest", task); <add> runAndWait(getTestClassName() + ".testBatchableRequestBatched", task); <ide> <ide> Collection<RequestContext> contexts = _capturingRestClient.getCapturedRequestContexts().values(); <ide> assertEquals(contexts.size(), 1); <ide> assertEquals(_capturingRestClient.getCapturedRequestContexts().get(request).getLocalAttr("method"), request.getMethod()); <ide> } <ide> <del> @Test <del> public void testConfiguredTimeoutOutboundOverride() { <del> Task<?> task = greetingGet(1L, new RequestConfigOverridesBuilder() <del> .setTimeoutMs(5555L, "overriden") <del> .build()); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutOutbound", task); <del> assertTrue(hasTask("withTimeout 5555ms src: overriden", task.getTrace())); <del> } <del> <del> @Test <del> public void testConfiguredTimeoutOutboundOverrideNoSrc() { <del> Task<?> task = greetingGet(1L, new RequestConfigOverridesBuilder() <del> .setTimeoutMs(5555L) <del> .build()); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutOutbound", task); <del> assertTrue(hasTask("withTimeout 5555ms", task.getTrace())); <del> } <del> <del> @Test <del> public void testConfiguredTimeoutInboundAndOutbound() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("foo") <del> .setMethod("GET") <del> .build()); <del> Task<?> task = greetingGet(1L); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutInboundAndOutbound", task); <del> assertTrue(hasTask("withTimeout 10004ms src: foo.GET/greetings.GET", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testConfiguredTimeoutMismatchedInboundOutbound() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("blah") <del> .setMethod("GET") <del> .build()); <del> Task<?> task = greetingGet(1L); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutMismatchedInboundOutbound", task); <del> assertTrue(hasTask("withTimeout 9999ms src: *.*/greetings.GET", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testConfiguredTimeoutFullActionAndOutbound() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("foo") <del> .setMethod("ACTION") <del> .setActionName("bar") <del> .build()); <del> Task<?> task = greetingGet(1L); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutFullActionAndOutbound", task); <del> assertTrue(hasTask("withTimeout 10006ms src: foo.ACTION-bar/greetings.GET", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testConfiguredTimeoutPartialActionAndOutbound() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("foo") <del> .setMethod("ACTION") <del> .build()); <del> Task<?> task = greetingGet(1L); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutPartialActionAndOutbound", task); <del> assertTrue(hasTask("withTimeout 10005ms src: foo.ACTION-*/greetings.GET", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testConfiguredTimeoutOutboundOp() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("blah") <del> .setMethod("GET") <del> .build()); <del> Task<?> task = greetingDel(9999L).toTry(); <del> runAndWait(getTestClassName() + ".testConfiguredTimeoutOutboundOp", task); <del> assertTrue(hasTask("withTimeout 10001ms src: *.*/greetings.*", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testBatchingGetRequests() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("withBatching") <del> .build()); <del> Task<?> task = Task.par(greetingGet(1L), greetingGet(2L), greetingGet(3L)); <del> runAndWait(getTestClassName() + ".testBatchingGetRequests", task); <del> assertTrue(hasTask("greetings batch_get(reqs: 3, ids: 3)", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testBatchingGetRequestsMaxExceeded() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("withBatching") <del> .build()); <del> Task<?> task = Task.par(greetingGet(1L), greetingGet(2L), greetingGet(3L), greetingGet(4L)); <del> runAndWait(getTestClassName() + ".testBatchingGetRequestsMaxExceeded", task); <del> assertTrue(hasTask("greetings batch_get(reqs: 3, ids: 3)", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <del> @Test <del> public void testBatchGetLargerThanMaxBatchSize() { <del> try { <del> setInboundRequestContext(new InboundRequestContextBuilder() <del> .setName("withBatching") <del> .build()); <del> Task<?> task = greetings(1L, 2L, 3L, 4L); <del> runAndWait(getTestClassName() + ".testBatchGetLargerThanMaxBatchSize", task); <del> assertFalse(hasTask("greetings batch_get(reqs: 3, ids: 3)", task.getTrace())); <del> } finally { <del> clearInboundRequestContext(); <del> } <del> } <del> <ide> }
JavaScript
mit
ade3d46d08bc92eb070fd1033d8030158aaf0398
0
cramhead/meteor-autoform,mizzao/meteor-autoform,andrerpena/meteor-autoform,abecks/meteor-autoform,aldeed/meteor-autoform,devgrok/meteor-autoform,Chun-Yang/meteor-autoform,challett/meteor-autoform,poetic/meteor-autoform,vimes1984/meteor-autoform,aldeed/meteor-autoform,mrphu3074/meteor-react-autoform,poetic/meteor-autoform,maher-samir/meteor-autoform,abecks/meteor-autoform,jimmiebtlr/meteor-autoform,jg3526/meteor-autoform,Chun-Yang/meteor-autoform,gregory/meteor-autoform,TamarAmit/meteor-autoform,TamarAmit/meteor-autoform,awatson1978/clinical-autoform,jimmiebtlr/meteor-autoform,Nieziemski/meteor-autoform,mindfront/meteor-autoform,vimes1984/meteor-autoform,devgrok/meteor-autoform,aramk/meteor-autoform,cramhead/meteor-autoform,mrphu3074/meteor-react-autoform,chrisbutler/meteor-autoform,chrisbutler/meteor-autoform,aramk/meteor-autoform,awatson1978/clinical-autoform,maher-samir/meteor-autoform,Q42/meteor-autoform,mshekera/meteor-autoform,jg3526/meteor-autoform,jmptrader/meteor-autoform,mshekera/meteor-autoform,andrerpena/meteor-autoform,calvinfroedge/meteor-autoform,gregory/meteor-autoform,calvinfroedge/meteor-autoform,mindfront/meteor-autoform,Q42/meteor-autoform,lukemadera/meteor-autoform,mizzao/meteor-autoform,jimmiebtlr/meteor-autoform,challett/meteor-autoform,Nieziemski/meteor-autoform,jmptrader/meteor-autoform,lukemadera/meteor-autoform
/* global AutoForm:true, SimpleSchema, Utility, Hooks, deps, globalDefaultTemplate:true, defaultTypeTemplates:true, getFormValues, formValues, _validateForm, validateField, arrayTracker, getInputType, ReactiveVar */ // This file defines the public, exported API AutoForm = AutoForm || {}; //exported AutoForm.Utility = Utility; /** * @method AutoForm.addHooks * @public * @param {String[]|String|null} formIds Form `id` or array of form IDs to which these hooks apply. Specify `null` to add hooks that will run for every form. * @param {Object} hooks Hooks to add, where supported names are "before", "after", "formToDoc", "docToForm", "onSubmit", "onSuccess", and "onError". * @returns {undefined} * * Defines hooks to be used by one or more forms. Extends hooks lists if called multiple times for the same * form. */ AutoForm.addHooks = function autoFormAddHooks(formIds, hooks, replace) { if (typeof formIds === "string") { formIds = [formIds]; } // If formIds is null, add global hooks if (!formIds) { Hooks.addHooksToList(Hooks.global, hooks, replace); } else { _.each(formIds, function (formId) { // Init the hooks object if not done yet Hooks.form[formId] = Hooks.form[formId] || { before: {}, after: {}, formToDoc: [], docToForm: [], onSubmit: [], onSuccess: [], onError: [], beginSubmit: [], endSubmit: [] }; Hooks.addHooksToList(Hooks.form[formId], hooks, replace); }); } }; /** * @method AutoForm.hooks * @public * @param {Object} hooks * @returns {undefined} * * Defines hooks by form id. Extends hooks lists if called multiple times for the same * form. */ AutoForm.hooks = function autoFormHooks(hooks, replace) { _.each(hooks, function(hooksObj, formId) { AutoForm.addHooks(formId, hooksObj, replace); }); }; // Expose the hooks references to aid with automated testing AutoForm._hooks = Hooks.form; AutoForm._globalHooks = Hooks.global; /** * @method AutoForm._forceResetFormValues * @public * @param {String} formId * @returns {undefined} * * Forces an AutoForm's values to properly update. * See https://github.com/meteor/meteor/issues/2431 */ AutoForm._forceResetFormValues = function autoFormForceResetFormValues(formId) { AutoForm._destroyForm[formId] = AutoForm._destroyForm[formId] || new ReactiveVar(false); AutoForm._destroyForm[formId].set(true); setTimeout(function () { AutoForm._destroyForm[formId].set(false); }, 0); }; /** * @method AutoForm.resetForm * @public * @param {String} formId * @param {TemplateInstance} [template] Looked up if not provided. Pass in for efficiency. * @returns {undefined} * * Resets an autoform, including resetting validation errors. The same as clicking the reset button for an autoform. */ AutoForm.resetForm = function autoFormResetForm(formId, template) { template = template || AutoForm.templateInstanceForForm(formId); if (template && template.view._domrange && !template.view.isDestroyed) { template.$("form")[0].reset(); } }; /** * @method AutoForm.setDefaultTemplate * @public * @param {String} template */ AutoForm.setDefaultTemplate = function autoFormSetDefaultTemplate(template) { globalDefaultTemplate = template; deps.defaultTemplate.changed(); }; /** * @method AutoForm.getDefaultTemplate * @public * * Reactive. */ AutoForm.getDefaultTemplate = function autoFormGetDefaultTemplate() { deps.defaultTemplate.depend(); return globalDefaultTemplate; }; /** * @method AutoForm.setDefaultTemplateForType * @public * @param {String} type * @param {String} template */ AutoForm.setDefaultTemplateForType = function autoFormSetDefaultTemplateForType(type, template) { if (!deps.defaultTypeTemplates[type]) { deps.defaultTypeTemplates[type] = new Tracker.Dependency(); } if (template !== null && !Template[type + "_" + template]) { throw new Error("setDefaultTemplateForType can't set default template to \"" + template + "\" for type \"" + type + "\" because there is no defined template with the name \"" + type + "_" + template + "\""); } defaultTypeTemplates[type] = template; deps.defaultTypeTemplates[type].changed(); }; /** * @method AutoForm.getDefaultTemplateForType * @public * @param {String} type * @return {String} Template name * * Reactive. */ AutoForm.getDefaultTemplateForType = function autoFormGetDefaultTemplateForType(type) { if (!deps.defaultTypeTemplates[type]) { deps.defaultTypeTemplates[type] = new Tracker.Dependency(); } deps.defaultTypeTemplates[type].depend(); return defaultTypeTemplates[type]; }; /** * @method AutoForm.getTemplateName * @public * @param {String} templateType * @param {String} templateName * @param {String} [fieldName] * @param {Boolean} [skipExistsCheck] Pass `true` to return a template name even if that template hasn't been defined. * @return {String} Template name * * Returns the full template name. In the simplest scenario, this is templateType_templateName * as passed in. However, if templateName is not provided, it is looked up in the following * manner: * * 1. autoform.<componentType>.template from the schema (field+type override for all forms) * 2. autoform.template from the schema (field override for all forms) * 3. template-<componentType> attribute on an ancestor component within the same form (form+type for all fields) * 4. template attribute on an ancestor component within the same form (form specificity for all types and fields) * 5. Default template for component type, as set by AutoForm.setDefaultTemplateForType * 6. Default template, as set by AutoForm.setDefaultTemplate. * 7. Built-in default template, currently bootstrap-3. */ AutoForm.getTemplateName = function autoFormGetTemplateName(templateType, templateName, fieldName, skipExistsCheck) { var schemaAutoFormDefs, templateFromAncestor, defaultTemplate; function templateExists(t) { return !!(skipExistsCheck || Template[t]); } // Default case: use the `template` attribute provided if (templateName && templateExists(templateType + '_' + templateName)) { return templateType + '_' + templateName; } // If the attributes provided a templateName but that template didn't exist, show a warning if (templateName && AutoForm._debug) { console.warn(templateType + ': "' + templateName + '" is not a valid template name. Falling back to a different template.'); } // Get `autoform` object from the schema, if present. // Skip for quickForm because it renders a form and not a field. if (templateType !== 'quickForm' && fieldName) { schemaAutoFormDefs = AutoForm.getSchemaForField(fieldName).autoform; } // Fallback #1: autoform.<componentType>.template from the schema if (schemaAutoFormDefs && schemaAutoFormDefs[templateType] && schemaAutoFormDefs[templateType].template && templateExists(templateType + '_' + schemaAutoFormDefs[templateType].template)) { return templateType + '_' + schemaAutoFormDefs[templateType].template; } // Fallback #2: autoform.template from the schema if (schemaAutoFormDefs && schemaAutoFormDefs.template && templateExists(templateType + '_' + schemaAutoFormDefs.template)) { return templateType + '_' + schemaAutoFormDefs.template; } // Fallback #3: template-<componentType> attribute on an ancestor component within the same form templateFromAncestor = AutoForm.findAttribute("template-" + templateType); if (templateFromAncestor && templateExists(templateType + '_' + templateFromAncestor)) { return templateType + '_' + templateFromAncestor; } // Fallback #4: template attribute on an ancestor component within the same form templateFromAncestor = AutoForm.findAttribute("template"); if (templateFromAncestor && templateExists(templateType + '_' + templateFromAncestor)) { return templateType + '_' + templateFromAncestor; } // Fallback #5: Default template for component type, as set by AutoForm.setDefaultTemplateForType defaultTemplate = AutoForm.getDefaultTemplateForType(templateType); if (defaultTemplate && templateExists(templateType + '_' + defaultTemplate)) { return templateType + '_' + defaultTemplate; } // Fallback #6: Default template, as set by AutoForm.setDefaultTemplate defaultTemplate = AutoForm.getDefaultTemplate(); if (defaultTemplate && templateExists(templateType + '_' + defaultTemplate)) { return templateType + '_' + defaultTemplate; } // Found nothing. Return undefined return; }; /** * @method AutoForm.getFormValues * @public * @param {String} formId The `id` attribute of the `autoForm` you want current values for. * @return {Object} * * Returns an object representing the current values of all schema-based fields in the form. * The returned object contains two properties, "insertDoc" and "updateDoc", which represent * the field values as a normal object and as a MongoDB modifier, respectively. */ AutoForm.getFormValues = function autoFormGetFormValues(formId) { var template = AutoForm.templateInstanceForForm(formId); if (!template || !template.view._domrange || template.view.isDestroyed) { throw new Error("getFormValues: There is currently no autoForm template rendered for the form with id " + formId); } // Get a reference to the SimpleSchema instance that should be used for // determining what types we want back for each field. var context = template.data; var ss = AutoForm.Utility.getSimpleSchemaFromContext(context, formId); return getFormValues(template, formId, ss); }; /** * @method AutoForm.getFieldValue * @public * @param {String} formId The `id` attribute of the `autoForm` you want current values for. * @param {String} fieldName The name of the field for which you want the current value. * @return {Any} * * Returns the value of the field (the value that would be used if the form were submitted right now). * This is a reactive method that will rerun whenever the current value of the requested field changes. */ AutoForm.getFieldValue = function autoFormGetFieldValue(formId, fieldName) { // reactive dependency formValues[formId] = formValues[formId] || {}; formValues[formId][fieldName] = formValues[formId][fieldName] || new Tracker.Dependency(); formValues[formId][fieldName].depend(); // find AutoForm template var template = AutoForm.templateInstanceForForm(formId); if (!template || !template.view._domrange || template.view.isDestroyed) { return; } // find AutoForm schema var ss = AutoForm.getFormSchema(formId); // get element reference var element = template.$('[data-schema-key="' + fieldName + '"]')[0]; return AutoForm.getInputValue(element, ss); }; /** * @method AutoForm.getInputTypeTemplateNameForElement * @public * @param {DOMElement} element The input DOM element, generated by an autoform input control * @return {String} * * Returns the name of the template used to render the element. */ AutoForm.getInputTypeTemplateNameForElement = function autoFormGetInputTypeTemplateNameForElement(element) { // get the enclosing view var view = Blaze.getView(element); // if the enclosing view is not a template, perhaps because // the template contains a block helper like if, with, each, // then look up the view chain until we arrive at a template while (view && view.name.slice(0, 9) !== "Template.") { view = view.parentView; } if (!view) { throw new Error("The element does not appear to be in a template view"); } // View names have "Template." at the beginning so we slice that off. return view.name.slice(9); }; /** * @method AutoForm.getInputValue * @public * @param {DOMElement} element The input DOM element, generated by an autoform input control, which must have a `data-schema-key` attribute set to the correct schema key name. * @param {SimpleSchema} [ss] Provide the SimpleSchema instance if you already have it. * @return {Any} * * Returns the value of the field (the value that would be used if the form were submitted right now). * Unlike `AutoForm.getFieldValue`, this function is not reactive. */ AutoForm.getInputValue = function autoFormGetInputValue(element, ss) { var field, fieldName, fieldType, arrayItemFieldType, val, typeDef, inputTypeTemplate, dataContext, autoConvert; dataContext = Blaze.getData(element); if (dataContext && dataContext.atts) { autoConvert = dataContext.atts.autoConvert; } // Get jQuery field reference field = $(element); // Get the field/schema key name fieldName = field.attr("data-schema-key"); // If we have a schema, we can autoconvert to the correct data type if (ss) { fieldType = ss.schema(fieldName).type; } // Get the name of the input type template used to render the input element inputTypeTemplate = AutoForm.getInputTypeTemplateNameForElement(element); // Slice off the potential theme template, after the underscore. inputTypeTemplate = inputTypeTemplate.split("_")[0]; // Figure out what registered input type was used to render this element typeDef = _.where(AutoForm._inputTypeDefinitions, {template: inputTypeTemplate})[0]; // If field has a "data-null-value" attribute, value should always be null if (field.attr("data-null-value") !== void 0) { val = null; } // Otherwise get the field's value using the input type's `valueOut` function if provided else if (typeDef && typeDef.valueOut) { val = typeDef.valueOut.call(field); } // Otherwise get the field's value in a default way else { val = field.val(); } // run through input's type converter if provided if (val !== void 0 && autoConvert !== false && typeDef && typeDef.valueConverters && fieldType) { var converterFunc; if (fieldType === String) { converterFunc = typeDef.valueConverters.string; } else if (fieldType === Number) { converterFunc = typeDef.valueConverters.number; } else if (fieldType === Boolean) { converterFunc = typeDef.valueConverters.boolean; } else if (fieldType === Date) { converterFunc = typeDef.valueConverters.date; } else if (fieldType === Array) { arrayItemFieldType = ss.schema(fieldName + ".$").type; if (arrayItemFieldType === String) { converterFunc = typeDef.valueConverters.stringArray; } else if (arrayItemFieldType === Number) { converterFunc = typeDef.valueConverters.numberArray; } else if (arrayItemFieldType === Boolean) { converterFunc = typeDef.valueConverters.booleanArray; } else if (arrayItemFieldType === Date) { converterFunc = typeDef.valueConverters.dateArray; } } if (typeof converterFunc === "function") { val = converterFunc.call(field, val); } } return val; }; /** * @method AutoForm.addInputType * @public * @param {String} name The type string that this definition is for. * @param {Object} definition Defines how the input type should be rendered. * @param {String} definition.componentName The component name. A template with the name <componentName>_bootstrap3, and potentially others, must be defined. * @return {undefined} * * Use this method to add custom input components. */ AutoForm.addInputType = function afAddInputType(name, definition) { var obj = {}; obj[name] = definition; _.extend(AutoForm._inputTypeDefinitions, obj); }; /** * @method AutoForm.addFormType * @public * @param {String} name The type string that this definition is for. * @param {Object} definition Defines how the submit type should work * @param {String} definition.componentName The component name. A template with the name <componentName>_bootstrap3, and potentially others, must be defined. * @return {undefined} * * Use this method to add custom input components. */ AutoForm.addFormType = function afAddFormType(name, definition) { var obj = {}; obj[name] = definition; _.extend(AutoForm._formTypeDefinitions, obj); }; /** * @method AutoForm.validateField * @public * @param {String} formId The `id` attribute of the `autoForm` you want to validate. * @param {String} fieldName The name of the field within the `autoForm` you want to validate. * @param {Boolean} [skipEmpty=false] Set to `true` to skip validation if the field has no value. Useful for preventing `required` errors in form fields that the user has not yet filled out. * @return {Boolean} Is it valid? * * In addition to returning a boolean that indicates whether the field is currently valid, * this method causes the reactive validation messages to appear. */ AutoForm.validateField = function autoFormValidateField(formId, fieldName, skipEmpty) { var template = AutoForm.templateInstanceForForm(formId); if (!template || !template.view._domrange || template.view.isDestroyed) { throw new Error("validateField: There is currently no autoForm template rendered for the form with id " + formId); } var ss = AutoForm.getFormSchema(formId); return validateField(fieldName, template, ss, skipEmpty, false); }; /** * @method AutoForm.validateForm * @public * @param {String} formId The `id` attribute of the `autoForm` you want to validate. * @return {Boolean} Is it valid? * * In addition to returning a boolean that indicates whether the form is currently valid, * this method causes the reactive validation messages to appear. */ AutoForm.validateForm = function autoFormValidateForm(formId) { // Gather all form values var formDocs = AutoForm.getFormValues(formId); return _validateForm(formId, formDocs); }; /** * @method AutoForm.getValidationContext * @public * @param {String} formId The `id` attribute of the `autoForm` for which you want the validation context * @return {SimpleSchemaValidationContext} The SimpleSchema validation context object. * * Use this method to get the validation context, which can be used to check * the current invalid fields, manually invalidate fields, etc. */ AutoForm.getValidationContext = function autoFormGetValidationContext(formId) { var ss = AutoForm.getFormSchema(formId); return ss && ss.namedContext(formId); }; /** * @method AutoForm.findAttribute * @param {String} attrName Attribute name * @public * @return {Any|undefined} Searches for the given attribute, looking up the parent context tree until the closest autoform is reached. * * Call this method from a UI helper. Might return undefined. */ AutoForm.findAttribute = function autoFormFindAttribute(attrName) { var val, view, viewData; var instance = Template.instance(); if (!instance) { return val; } function checkView() { // Is the attribute we're looking for on here? // If so, stop searching viewData = Blaze.getData(view); if (viewData && viewData.atts && viewData.atts[attrName] !== void 0) { val = viewData.atts[attrName]; } else if (viewData && viewData[attrName] !== void 0) { // When searching for "template", make sure we didn't just // find the one that's on Template.dynamic if (attrName !== 'template' || !('data' in viewData)) { val = viewData[attrName]; } } } // Loop view = instance.view; while (val === undefined && view && view.name !== 'Template.autoForm') { checkView(); view = view.originalParentView || view.parentView; } // If we've reached the form, check there, too if (val === undefined && view && view.name === 'Template.autoForm') { checkView(); } return val; }; /** * @method AutoForm.findAttributesWithPrefix * @param {String} prefix Attribute prefix * @public * @return {Object} An object containing all of the found attributes and their values, with the prefix removed from the keys. * * Call this method from a UI helper. Searches for attributes that start with the given prefix, looking up the parent context tree until the closest autoform is reached. * * TODO change this to use logic like AutoForm.findAttribute */ AutoForm.findAttributesWithPrefix = function autoFormFindAttributesWithPrefix(prefix) { var n = 0, af, searchObj, stopAt = -1, obj = {}; // we go one level past _af so that we get the original autoForm or quickForm attributes, too do { af = Template.parentData(n++); if (af) { if (af.atts) { searchObj = af.atts; } else { searchObj = af; } if (_.isObject(searchObj)) { _.each(searchObj, function (v, k) { if (k.indexOf(prefix) === 0) { obj[k.slice(prefix.length)] = v; } }); } if (af._af) { stopAt = n + 1; } } } while (af && stopAt < n); return obj; }; /** * @method AutoForm.debug * @public * * Call this method in client code while developing to turn on extra logging. */ AutoForm.debug = function autoFormDebug() { SimpleSchema.debug = true; AutoForm._debug = true; AutoForm.addHooks(null, { onError: function (operation, error) { console.log("Error in " + this.formId, operation, error); } }); }; /** * @property AutoForm.arrayTracker * @public */ AutoForm.arrayTracker = arrayTracker; /** * @method AutoForm.getInputType * @param {Object} atts The attributes provided to afFieldInput. * @public * @return {String} The input type. Most are the same as the `type` attributes for HTML input elements, but some are special strings that autoform interprets. * * Call this method from a UI helper to get the type string for the input control. */ AutoForm.getInputType = getInputType; /** * @method AutoForm.getSchemaForField * @public * @param {String} name The field name attribute / schema key. * @return {Object} * * Call this method from a UI helper to get the field definitions based on the schema used by the closest containing autoForm. * Always throws an error or returns the schema object. */ AutoForm.getSchemaForField = function autoFormGetSchemaForField(name) { var ss = AutoForm.getFormSchema(); return AutoForm.Utility.getDefs(ss, name); }; /** * @method AutoForm.getLabelForField * @public * @param {String} name The field name attribute / schema key. * @return {Object} * * Call this method from a UI helper to get the field definitions based on the schema used by the closest containing autoForm. * Always throws an error or returns the schema object. */ AutoForm.getLabelForField = function autoFormGetSchemaForField(name) { var ss = AutoForm.getFormSchema(), label = ss.label(name); // for array items we don't want to inflect the label because // we will end up with a number; // TODO this check should probably be in the SimpleSchema code if (SimpleSchema._makeGeneric(name).slice(-1) === "$" && !isNaN(parseInt(label, 10))) { label = null; } return label; }; /** * Gets the template instance for the form. The form * must be currently rendered. If not, returns `undefined`. * @param {String} formId The form's `id` attribute * @returns {TemplateInstance|undefined} The template instance. */ AutoForm.templateInstanceForForm = function (formId) { var formElement = document.getElementById(formId); if (!formElement) { return; } var view = Blaze.getView(formElement); if (!view) { return; } // Currently we have an #unless wrapping the form, // so we need to go up a level. This should continue to // work even if we remove that #unless or add other wrappers. while (typeof view.templateInstance !== 'function' && view.parentView) { view = view.parentView; } return view.templateInstance(); }; /** * Looks in the document attached to the form to see if the * requested field exists and is an array. If so, returns the * length (count) of the array. Otherwise returns undefined. * @param {String} formId The form's `id` attribute * @param {String} field The field name (schema key) * @returns {Number|undefined} Array count in the attached document. */ AutoForm.getArrayCountFromDocForField = function (formId, field) { var mDoc = AutoForm.reactiveFormData.sourceDoc(formId); var docCount; if (mDoc) { var keyInfo = mDoc.getInfoForKey(field); if (keyInfo && _.isArray(keyInfo.value)) { docCount = keyInfo.value.length; } } return docCount; }; /** * Returns the current data context for a form. Always returns an object * or throws an error. * You can call this without a formId from within a helper and * the data for the nearest containing form will be returned. * @param {String} formId The form's `id` attribute * @returns {Object} Current data context for the form, or an empty object. */ AutoForm.getCurrentDataForForm = function (formId) { var formElement; // get data for form with formId if passed if (formId) { formElement = document.getElementById(formId); if (!formElement) { throw new Error('No form with ID ' + formId + ' is currently rendered. If you are calling AutoForm.getCurrentDataForForm, or something that calls it, from within a template helper, try calling without passing a formId'); } return Blaze.getData(formElement) || {}; } // otherwise get data for nearest form from within helper var instance = Template.instance(); if (!instance) { return {}; } var view = instance.view; while (view && view.name !== 'Template.autoForm') { view = view.originalParentView || view.parentView; } if (view && view.name === 'Template.autoForm') { return Blaze.getData(view) || {}; } return {}; }; /** * Returns the current data context for a form plus some extra properties. * Always returns an object or throws an error. * You can call this without a formId from within a helper and * the data for the nearest containing form will be returned. * @param {String} [formId] The form's `id` attribute * @returns {Object} Current data context for the form, or an empty object. */ AutoForm.getCurrentDataPlusExtrasForForm = function (formId) { var data = AutoForm.getCurrentDataForForm(formId); data = _.clone(data); // add form type definition var formType = data.type || 'normal'; data.formTypeDef = AutoForm._formTypeDefinitions[formType]; if (!data.formTypeDef) { throw new Error('AutoForm: Form type "' + formType + '" has not been defined'); } return data; }; AutoForm.getFormCollection = function (formId) { var data = AutoForm.getCurrentDataForForm(formId); return AutoForm.Utility.lookup(data.collection); }; /** * Gets the schema for a form, from the `schema` attribute if * provided, or from the schema attached to the `Mongo.Collection` * specified in the `collection` attribute. The form must be * currently rendered. * @param {String} formId The form's `id` attribute * @returns {SimpleSchema|undefined} The SimpleSchema instance */ AutoForm.getFormSchema = function (formId) { var schema = AutoForm.getCurrentDataForForm(formId).schema; if (schema) { return AutoForm.Utility.lookup(schema); } else { var collection = AutoForm.getFormCollection(formId); if (collection && typeof collection.simpleSchema === 'function') { return collection.simpleSchema(); } } }; /** * Call in a helper to get the containing form's `id` attribute. Reactive. * @returns {String} The containing form's `id` attribute value */ AutoForm.getFormId = function () { return AutoForm.getCurrentDataForForm().id; };
autoform-api.js
/* global AutoForm:true, SimpleSchema, Utility, Hooks, deps, globalDefaultTemplate:true, defaultTypeTemplates:true, getFormValues, formValues, _validateForm, validateField, arrayTracker, getInputType, ReactiveVar */ // This file defines the public, exported API AutoForm = AutoForm || {}; //exported AutoForm.Utility = Utility; /** * @method AutoForm.addHooks * @public * @param {String[]|String|null} formIds Form `id` or array of form IDs to which these hooks apply. Specify `null` to add hooks that will run for every form. * @param {Object} hooks Hooks to add, where supported names are "before", "after", "formToDoc", "docToForm", "onSubmit", "onSuccess", and "onError". * @returns {undefined} * * Defines hooks to be used by one or more forms. Extends hooks lists if called multiple times for the same * form. */ AutoForm.addHooks = function autoFormAddHooks(formIds, hooks, replace) { if (typeof formIds === "string") { formIds = [formIds]; } // If formIds is null, add global hooks if (!formIds) { Hooks.addHooksToList(Hooks.global, hooks, replace); } else { _.each(formIds, function (formId) { // Init the hooks object if not done yet Hooks.form[formId] = Hooks.form[formId] || { before: {}, after: {}, formToDoc: [], docToForm: [], onSubmit: [], onSuccess: [], onError: [], beginSubmit: [], endSubmit: [] }; Hooks.addHooksToList(Hooks.form[formId], hooks, replace); }); } }; /** * @method AutoForm.hooks * @public * @param {Object} hooks * @returns {undefined} * * Defines hooks by form id. Extends hooks lists if called multiple times for the same * form. */ AutoForm.hooks = function autoFormHooks(hooks, replace) { _.each(hooks, function(hooksObj, formId) { AutoForm.addHooks(formId, hooksObj, replace); }); }; // Expose the hooks references to aid with automated testing AutoForm._hooks = Hooks.form; AutoForm._globalHooks = Hooks.global; /** * @method AutoForm._forceResetFormValues * @public * @param {String} formId * @returns {undefined} * * Forces an AutoForm's values to properly update. * See https://github.com/meteor/meteor/issues/2431 */ AutoForm._forceResetFormValues = function autoFormForceResetFormValues(formId) { AutoForm._destroyForm[formId] = AutoForm._destroyForm[formId] || new ReactiveVar(false); AutoForm._destroyForm[formId].set(true); setTimeout(function () { AutoForm._destroyForm[formId].set(false); }, 0); }; /** * @method AutoForm.resetForm * @public * @param {String} formId * @param {TemplateInstance} [template] Looked up if not provided. Pass in for efficiency. * @returns {undefined} * * Resets an autoform, including resetting validation errors. The same as clicking the reset button for an autoform. */ AutoForm.resetForm = function autoFormResetForm(formId, template) { template = template || AutoForm.templateInstanceForForm(formId); if (template && template.view._domrange && !template.view.isDestroyed) { template.$("form")[0].reset(); } }; /** * @method AutoForm.setDefaultTemplate * @public * @param {String} template */ AutoForm.setDefaultTemplate = function autoFormSetDefaultTemplate(template) { globalDefaultTemplate = template; deps.defaultTemplate.changed(); }; /** * @method AutoForm.getDefaultTemplate * @public * * Reactive. */ AutoForm.getDefaultTemplate = function autoFormGetDefaultTemplate() { deps.defaultTemplate.depend(); return globalDefaultTemplate; }; /** * @method AutoForm.setDefaultTemplateForType * @public * @param {String} type * @param {String} template */ AutoForm.setDefaultTemplateForType = function autoFormSetDefaultTemplateForType(type, template) { if (!deps.defaultTypeTemplates[type]) { deps.defaultTypeTemplates[type] = new Tracker.Dependency(); } if (template !== null && !Template[type + "_" + template]) { throw new Error("setDefaultTemplateForType can't set default template to \"" + template + "\" for type \"" + type + "\" because there is no defined template with the name \"" + type + "_" + template + "\""); } defaultTypeTemplates[type] = template; deps.defaultTypeTemplates[type].changed(); }; /** * @method AutoForm.getDefaultTemplateForType * @public * @param {String} type * @return {String} Template name * * Reactive. */ AutoForm.getDefaultTemplateForType = function autoFormGetDefaultTemplateForType(type) { if (!deps.defaultTypeTemplates[type]) { deps.defaultTypeTemplates[type] = new Tracker.Dependency(); } deps.defaultTypeTemplates[type].depend(); return defaultTypeTemplates[type]; }; /** * @method AutoForm.getTemplateName * @public * @param {String} templateType * @param {String} templateName * @param {String} [fieldName] * @param {Boolean} [skipExistsCheck] Pass `true` to return a template name even if that template hasn't been defined. * @return {String} Template name * * Returns the full template name. In the simplest scenario, this is templateType_templateName * as passed in. However, if templateName is not provided, it is looked up in the following * manner: * * 1. autoform.<componentType>.template from the schema (field+type override for all forms) * 2. autoform.template from the schema (field override for all forms) * 3. template-<componentType> attribute on an ancestor component within the same form (form+type for all fields) * 4. template attribute on an ancestor component within the same form (form specificity for all types and fields) * 5. Default template for component type, as set by AutoForm.setDefaultTemplateForType * 6. Default template, as set by AutoForm.setDefaultTemplate. * 7. Built-in default template, currently bootstrap-3. */ AutoForm.getTemplateName = function autoFormGetTemplateName(templateType, templateName, fieldName, skipExistsCheck) { var schemaAutoFormDefs, templateFromAncestor, defaultTemplate; function templateExists(t) { return !!(skipExistsCheck || Template[t]); } // Default case: use the `template` attribute provided if (templateName && templateExists(templateType + '_' + templateName)) { return templateType + '_' + templateName; } // If the attributes provided a templateName but that template didn't exist, show a warning if (templateName && AutoForm._debug) { console.warn(templateType + ': "' + templateName + '" is not a valid template name. Falling back to a different template.'); } // Get `autoform` object from the schema, if present. // Skip for quickForm because it renders a form and not a field. if (templateType !== 'quickForm' && fieldName) { schemaAutoFormDefs = AutoForm.getSchemaForField(fieldName).autoform; } // Fallback #1: autoform.<componentType>.template from the schema if (schemaAutoFormDefs && schemaAutoFormDefs[templateType] && schemaAutoFormDefs[templateType].template && templateExists(templateType + '_' + schemaAutoFormDefs[templateType].template)) { return templateType + '_' + schemaAutoFormDefs[templateType].template; } // Fallback #2: autoform.template from the schema if (schemaAutoFormDefs && schemaAutoFormDefs.template && templateExists(templateType + '_' + schemaAutoFormDefs.template)) { return templateType + '_' + schemaAutoFormDefs.template; } // Fallback #3: template-<componentType> attribute on an ancestor component within the same form templateFromAncestor = AutoForm.findAttribute("template-" + templateType); if (templateFromAncestor && templateExists(templateType + '_' + templateFromAncestor)) { return templateType + '_' + templateFromAncestor; } // Fallback #4: template attribute on an ancestor component within the same form templateFromAncestor = AutoForm.findAttribute("template"); if (templateFromAncestor && templateExists(templateType + '_' + templateFromAncestor)) { return templateType + '_' + templateFromAncestor; } // Fallback #5: Default template for component type, as set by AutoForm.setDefaultTemplateForType defaultTemplate = AutoForm.getDefaultTemplateForType(templateType); if (defaultTemplate && templateExists(templateType + '_' + defaultTemplate)) { return templateType + '_' + defaultTemplate; } // Fallback #6: Default template, as set by AutoForm.setDefaultTemplate defaultTemplate = AutoForm.getDefaultTemplate(); if (defaultTemplate && templateExists(templateType + '_' + defaultTemplate)) { return templateType + '_' + defaultTemplate; } // Found nothing. Return undefined return; }; /** * @method AutoForm.getFormValues * @public * @param {String} formId The `id` attribute of the `autoForm` you want current values for. * @return {Object} * * Returns an object representing the current values of all schema-based fields in the form. * The returned object contains two properties, "insertDoc" and "updateDoc", which represent * the field values as a normal object and as a MongoDB modifier, respectively. */ AutoForm.getFormValues = function autoFormGetFormValues(formId) { var template = AutoForm.templateInstanceForForm(formId); if (!template || !template.view._domrange || template.view.isDestroyed) { throw new Error("getFormValues: There is currently no autoForm template rendered for the form with id " + formId); } // Get a reference to the SimpleSchema instance that should be used for // determining what types we want back for each field. var context = template.data; var ss = AutoForm.Utility.getSimpleSchemaFromContext(context, formId); return getFormValues(template, formId, ss); }; /** * @method AutoForm.getFieldValue * @public * @param {String} formId The `id` attribute of the `autoForm` you want current values for. * @param {String} fieldName The name of the field for which you want the current value. * @return {Any} * * Returns the value of the field (the value that would be used if the form were submitted right now). * This is a reactive method that will rerun whenever the current value of the requested field changes. */ AutoForm.getFieldValue = function autoFormGetFieldValue(formId, fieldName) { // reactive dependency formValues[formId] = formValues[formId] || {}; formValues[formId][fieldName] = formValues[formId][fieldName] || new Tracker.Dependency(); formValues[formId][fieldName].depend(); // find AutoForm template var template = AutoForm.templateInstanceForForm(formId); if (!template || !template.view._domrange || template.view.isDestroyed) { return; } // find AutoForm schema var ss = AutoForm.getFormSchema(formId); // get element reference var element = template.$('[data-schema-key="' + fieldName + '"]')[0]; return AutoForm.getInputValue(element, ss); }; /** * @method AutoForm.getInputTypeTemplateNameForElement * @public * @param {DOMElement} element The input DOM element, generated by an autoform input control * @return {String} * * Returns the name of the template used to render the element. */ AutoForm.getInputTypeTemplateNameForElement = function autoFormGetInputTypeTemplateNameForElement(element) { // get the enclosing view var view = Blaze.getView(element); // if the enclosing view is not a template, perhaps because // the template contains a block helper like if, with, each, // then look up the view chain until we arrive at a template while (view && view.name.slice(0, 9) !== "Template.") { view = view.parentView; } if (!view) { throw new Error("The element does not appear to be in a template view"); } // View names have "Template." at the beginning so we slice that off. return view.name.slice(9); }; /** * @method AutoForm.getInputValue * @public * @param {DOMElement} element The input DOM element, generated by an autoform input control, which must have a `data-schema-key` attribute set to the correct schema key name. * @param {SimpleSchema} [ss] Provide the SimpleSchema instance if you already have it. * @return {Any} * * Returns the value of the field (the value that would be used if the form were submitted right now). * Unlike `AutoForm.getFieldValue`, this function is not reactive. */ AutoForm.getInputValue = function autoFormGetInputValue(element, ss) { var field, fieldName, fieldType, arrayItemFieldType, val, typeDef, inputTypeTemplate, dataContext, autoConvert; dataContext = Blaze.getData(element); if (dataContext && dataContext.atts) { autoConvert = dataContext.atts.autoConvert; } // Get jQuery field reference field = $(element); // Get the field/schema key name fieldName = field.attr("data-schema-key"); // If we have a schema, we can autoconvert to the correct data type if (ss) { fieldType = ss.schema(fieldName).type; } // Get the name of the input type template used to render the input element inputTypeTemplate = AutoForm.getInputTypeTemplateNameForElement(element); // Slice off the potential theme template, after the underscore. inputTypeTemplate = inputTypeTemplate.split("_")[0]; // Figure out what registered input type was used to render this element typeDef = _.where(AutoForm._inputTypeDefinitions, {template: inputTypeTemplate})[0]; // If field has a "data-null-value" attribute, value should always be null if (field.attr("data-null-value") !== void 0) { val = null; } // Otherwise get the field's value using the input type's `valueOut` function if provided else if (typeDef && typeDef.valueOut) { val = typeDef.valueOut.call(field); } // Otherwise get the field's value in a default way else { val = field.val(); } // run through input's type converter if provided if (val !== void 0 && autoConvert !== false && typeDef && typeDef.valueConverters && fieldType) { var converterFunc; if (fieldType === String) { converterFunc = typeDef.valueConverters.string; } else if (fieldType === Number) { converterFunc = typeDef.valueConverters.number; } else if (fieldType === Boolean) { converterFunc = typeDef.valueConverters.boolean; } else if (fieldType === Date) { converterFunc = typeDef.valueConverters.date; } else if (fieldType === Array) { arrayItemFieldType = ss.schema(fieldName + ".$").type; if (arrayItemFieldType === String) { converterFunc = typeDef.valueConverters.stringArray; } else if (arrayItemFieldType === Number) { converterFunc = typeDef.valueConverters.numberArray; } else if (arrayItemFieldType === Boolean) { converterFunc = typeDef.valueConverters.booleanArray; } else if (arrayItemFieldType === Date) { converterFunc = typeDef.valueConverters.dateArray; } } if (typeof converterFunc === "function") { val = converterFunc.call(field, val); } } return val; }; /** * @method AutoForm.addInputType * @public * @param {String} name The type string that this definition is for. * @param {Object} definition Defines how the input type should be rendered. * @param {String} definition.componentName The component name. A template with the name <componentName>_bootstrap3, and potentially others, must be defined. * @return {undefined} * * Use this method to add custom input components. */ AutoForm.addInputType = function afAddInputType(name, definition) { var obj = {}; obj[name] = definition; _.extend(AutoForm._inputTypeDefinitions, obj); }; /** * @method AutoForm.addFormType * @public * @param {String} name The type string that this definition is for. * @param {Object} definition Defines how the submit type should work * @param {String} definition.componentName The component name. A template with the name <componentName>_bootstrap3, and potentially others, must be defined. * @return {undefined} * * Use this method to add custom input components. */ AutoForm.addFormType = function afAddFormType(name, definition) { var obj = {}; obj[name] = definition; _.extend(AutoForm._formTypeDefinitions, obj); }; /** * @method AutoForm.validateField * @public * @param {String} formId The `id` attribute of the `autoForm` you want to validate. * @param {String} fieldName The name of the field within the `autoForm` you want to validate. * @param {Boolean} [skipEmpty=false] Set to `true` to skip validation if the field has no value. Useful for preventing `required` errors in form fields that the user has not yet filled out. * @return {Boolean} Is it valid? * * In addition to returning a boolean that indicates whether the field is currently valid, * this method causes the reactive validation messages to appear. */ AutoForm.validateField = function autoFormValidateField(formId, fieldName, skipEmpty) { var template = AutoForm.templateInstanceForForm(formId); if (!template || !template.view._domrange || template.view.isDestroyed) { throw new Error("validateField: There is currently no autoForm template rendered for the form with id " + formId); } var ss = AutoForm.getFormSchema(formId); return validateField(fieldName, template, ss, skipEmpty, false); }; /** * @method AutoForm.validateForm * @public * @param {String} formId The `id` attribute of the `autoForm` you want to validate. * @return {Boolean} Is it valid? * * In addition to returning a boolean that indicates whether the form is currently valid, * this method causes the reactive validation messages to appear. */ AutoForm.validateForm = function autoFormValidateForm(formId) { // Gather all form values var formDocs = AutoForm.getFormValues(formId); return _validateForm(formId, formDocs); }; /** * @method AutoForm.getValidationContext * @public * @param {String} formId The `id` attribute of the `autoForm` for which you want the validation context * @return {SimpleSchemaValidationContext} The SimpleSchema validation context object. * * Use this method to get the validation context, which can be used to check * the current invalid fields, manually invalidate fields, etc. */ AutoForm.getValidationContext = function autoFormGetValidationContext(formId) { var ss = AutoForm.getFormSchema(formId); return ss && ss.namedContext(formId); }; /** * @method AutoForm.findAttribute * @param {String} attrName Attribute name * @public * @return {Any|undefined} Searches for the given attribute, looking up the parent context tree until the closest autoform is reached. * * Call this method from a UI helper. Might return undefined. */ AutoForm.findAttribute = function autoFormFindAttribute(attrName) { var val, view, viewData; var instance = Template.instance(); if (!instance) { return val; } function checkView() { // Is the attribute we're looking for on here? // If so, stop searching viewData = Blaze.getData(view); if (viewData && viewData.atts && viewData.atts[attrName] !== void 0) { val = viewData.atts[attrName]; } else if (viewData && viewData[attrName] !== void 0) { // When searching for "template", make sure we didn't just // find the one that's on Template.dynamic if (attrName !== 'template' || !('data' in viewData)) { val = viewData[attrName]; } } } // Loop view = instance.view; while (val === undefined && view && view.name !== 'Template.autoForm') { checkView(); view = view.originalParentView || view.parentView; } // If we've reached the form, check there, too if (val === undefined && view && view.name === 'Template.autoForm') { checkView(); } return val; }; /** * @method AutoForm.findAttributesWithPrefix * @param {String} prefix Attribute prefix * @public * @return {Object} An object containing all of the found attributes and their values, with the prefix removed from the keys. * * Call this method from a UI helper. Searches for attributes that start with the given prefix, looking up the parent context tree until the closest autoform is reached. * * TODO change this to use logic like AutoForm.findAttribute */ AutoForm.findAttributesWithPrefix = function autoFormFindAttributesWithPrefix(prefix) { var n = 0, af, searchObj, stopAt = -1, obj = {}; // we go one level past _af so that we get the original autoForm or quickForm attributes, too do { af = Template.parentData(n++); if (af) { if (af.atts) { searchObj = af.atts; } else { searchObj = af; } if (_.isObject(searchObj)) { _.each(searchObj, function (v, k) { if (k.indexOf(prefix) === 0) { obj[k.slice(prefix.length)] = v; } }); } if (af._af) { stopAt = n + 1; } } } while (af && stopAt < n); return obj; }; /** * @method AutoForm.debug * @public * * Call this method in client code while developing to turn on extra logging. */ AutoForm.debug = function autoFormDebug() { SimpleSchema.debug = true; AutoForm._debug = true; AutoForm.addHooks(null, { onError: function (operation, error) { console.log("Error in " + this.formId, operation, error); } }); }; /** * @property AutoForm.arrayTracker * @public */ AutoForm.arrayTracker = arrayTracker; /** * @method AutoForm.getInputType * @param {Object} atts The attributes provided to afFieldInput. * @public * @return {String} The input type. Most are the same as the `type` attributes for HTML input elements, but some are special strings that autoform interprets. * * Call this method from a UI helper to get the type string for the input control. */ AutoForm.getInputType = getInputType; /** * @method AutoForm.getSchemaForField * @public * @param {String} name The field name attribute / schema key. * @return {Object} * * Call this method from a UI helper to get the field definitions based on the schema used by the closest containing autoForm. * Always throws an error or returns the schema object. */ AutoForm.getSchemaForField = function autoFormGetSchemaForField(name) { var ss = AutoForm.getFormSchema(); return AutoForm.Utility.getDefs(ss, name); }; /** * @method AutoForm.getLabelForField * @public * @param {String} name The field name attribute / schema key. * @return {Object} * * Call this method from a UI helper to get the field definitions based on the schema used by the closest containing autoForm. * Always throws an error or returns the schema object. */ AutoForm.getLabelForField = function autoFormGetSchemaForField(name) { var ss = AutoForm.getFormSchema(), label = ss.label(name); // for array items we don't want to inflect the label because // we will end up with a number; // TODO this check should probably be in the SimpleSchema code if (SimpleSchema._makeGeneric(name).slice(-1) === "$" && !isNaN(parseInt(label, 10))) { label = null; } return label; }; /** * Gets the template instance for the form. The form * must be currently rendered. If not, returns `undefined`. * @param {String} formId The form's `id` attribute * @returns {TemplateInstance|undefined} The template instance. */ AutoForm.templateInstanceForForm = function (formId) { var formElement = document.getElementById(formId); if (!formElement) { return; } var view = Blaze.getView(formElement); if (!view) { return; } // Currently we have an #unless wrapping the form, // so we need to go up a level. This should continue to // work even if we remove that #unless or add other wrappers. while (typeof view.templateInstance !== 'function' && view.parentView) { view = view.parentView; } return view.templateInstance(); }; /** * Looks in the document attached to the form to see if the * requested field exists and is an array. If so, returns the * length (count) of the array. Otherwise returns undefined. * @param {String} formId The form's `id` attribute * @param {String} field The field name (schema key) * @returns {Number|undefined} Array count in the attached document. */ AutoForm.getArrayCountFromDocForField = function (formId, field) { var mDoc = AutoForm.reactiveFormData.sourceDoc(formId); var docCount; if (mDoc) { var keyInfo = mDoc.getInfoForKey(field); if (keyInfo && _.isArray(keyInfo.value)) { docCount = keyInfo.value.length; } } return docCount; }; /** * Returns the current data context for a form. Always returns an object * or throws an error. * You can call this without a formId from within a helper and * the data for the nearest containing form will be returned. * @param {String} formId The form's `id` attribute * @returns {Object} Current data context for the form, or an empty object. */ AutoForm.getCurrentDataForForm = function (formId) { var formElement; // get data for form with formId if passed if (formId) { formElement = document.getElementById(formId); if (!formElement) { throw new Error('No form with ID ' + formId + ' is currently rendered. If you are calling AutoForm.getCurrentDataForForm, or something that calls it, from within a template helper, try calling without passing a formId'); } return Blaze.getData(formElement) || {}; } // otherwise get data for nearest form from within helper var instance = Template.instance(); if (!instance) { return {}; } var view = instance.view; while (view && view.name !== 'Template.autoForm') { view = view.originalParentView || view.parentView; } if (view && view.name === 'Template.autoForm') { return Blaze.getData(view) || {}; } return {}; }; /** * Returns the current data context for a form plus some extra properties. * Always returns an object or throws an error. * You can call this without a formId from within a helper and * the data for the nearest containing form will be returned. * @param {String} [formId] The form's `id` attribute * @returns {Object} Current data context for the form, or an empty object. */ AutoForm.getCurrentDataPlusExtrasForForm = function (formId) { var data = AutoForm.getCurrentDataForForm(formId); data = _.clone(data); // add form type definition var formType = data.type || 'normal'; data.formTypeDef = AutoForm._formTypeDefinitions[formType]; if (!data.formTypeDef) { throw new Error('AutoForm: Form type "' + formType + '" has not been defined'); } return data; }; AutoForm.getFormCollection = function (formId) { var data = AutoForm.getCurrentDataForForm(formId); return AutoForm.Utility.lookup(data.collection); }; /** * Gets the schema for a form, from the `schema` attribute if * provided, or from the schema attached to the `Mongo.Collection` * specified in the `collection` attribute. The form must be * currently rendered. * @param {String} formId The form's `id` attribute * @returns {SimpleSchema|undefined} The SimpleSchema instance */ AutoForm.getFormSchema = function (formId) { var schema = AutoForm.getCurrentDataForForm(formId).schema; if (schema) { return schema; } else { var collection = AutoForm.getFormCollection(formId); if (collection && typeof collection.simpleSchema === 'function') { return collection.simpleSchema(); } } }; /** * Call in a helper to get the containing form's `id` attribute. Reactive. * @returns {String} The containing form's `id` attribute value */ AutoForm.getFormId = function () { return AutoForm.getCurrentDataForForm().id; };
fix for string schema attribute
autoform-api.js
fix for string schema attribute
<ide><path>utoform-api.js <ide> AutoForm.getFormSchema = function (formId) { <ide> var schema = AutoForm.getCurrentDataForForm(formId).schema; <ide> if (schema) { <del> return schema; <add> return AutoForm.Utility.lookup(schema); <ide> } else { <ide> var collection = AutoForm.getFormCollection(formId); <ide> if (collection && typeof collection.simpleSchema === 'function') {
Java
mit
a0721b159938a449543ea54ed6dc20e6ab517d61
0
instructure/CanvasAPI
package com.instructure.canvasapi.api; import android.content.Context; import android.util.Log; import com.instructure.canvasapi.model.Attachment; import com.instructure.canvasapi.model.CanvasColor; import com.instructure.canvasapi.model.CanvasContext; import com.instructure.canvasapi.model.Enrollment; import com.instructure.canvasapi.model.FileUploadParams; import com.instructure.canvasapi.model.User; import com.instructure.canvasapi.utilities.APIHelpers; import com.instructure.canvasapi.utilities.CanvasCallback; import com.instructure.canvasapi.utilities.ExhaustiveBridgeCallback; import com.instructure.canvasapi.utilities.Masquerading; import com.instructure.canvasapi.utilities.UserCallback; import java.io.File; import java.util.LinkedHashMap; import retrofit.Callback; import retrofit.client.Response; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.Multipart; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Part; import retrofit.http.PartMap; import retrofit.http.Path; import retrofit.http.Query; import retrofit.mime.TypedFile; /** * Copyright (c) 2015 Instructure. All rights reserved. */ public class UserAPI extends BuildInterfaceAPI { public enum ENROLLMENT_TYPE {STUDENT, TEACHER, TA, OBSERVER, DESIGNER} interface UsersInterface { @GET("/users/self/profile") void getSelf(Callback<User> callback); // TODO: We probably need to create a helper that does each of these individually @GET("/users/self/enrollments?state[]=active&state[]=invited&state[]=completed") void getSelfEnrollments(Callback<Enrollment[]> callback); @GET("/users/self") void getSelfWithPermission(CanvasCallback<User> callback); @PUT("/users/self") void updateShortName(@Query("user[short_name]") String shortName, @Body String body, Callback<User> callback); @GET("/users/{userid}/profile") void getUserById(@Path("userid")long userId, Callback<User> userCallback); @GET("/{context_id}/users/{userId}?include[]=avatar_url&include[]=user_id&include[]=email&include[]=bio") void getUserById(@Path("context_id") long context_id, @Path("userId")long userId, Callback<User> userCallback); @GET("/{context_id}/users?include[]=enrollments&include[]=avatar_url&include[]=user_id&include[]=email&include[]=bio") void getFirstPagePeopleList(@Path("context_id") long context_id, Callback<User[]> callback); @GET("/{context_id}/users?include[]=enrollments&include[]=avatar_url&include[]=user_id&include[]=email") void getFirstPagePeopleListWithEnrollmentType(@Path("context_id") long context_id, @Query("enrollment_type") String enrollmentType, Callback<User[]> callback); @GET("/{next}") void getNextPagePeopleList(@Path(value = "next", encode = false) String nextURL, Callback<User[]> callback); @POST("/users/self/file") void uploadUserFileURL( @Query("url") String fileURL, @Query("name") String fileName, @Query("size") long size, @Query("content_type") String content_type, @Query("parent_folder_path") String parentFolderPath, @Body String body, Callback<String> callback); @POST("/users/self/files") FileUploadParams getFileUploadParams( @Query("size") long size, @Query("name") String fileName, @Query("content_type") String content_type, @Query("parent_folder_id") Long parentFolderId, @Body String body); @POST("/users/self/files") FileUploadParams getFileUploadParams( @Query("size") long size, @Query("name") String fileName, @Query("content_type") String content_type, @Query("parent_folder_path") String parentFolderPath, @Body String body); @Multipart @POST("/") Attachment uploadUserFile(@PartMap LinkedHashMap<String, String> params, @Part("file") TypedFile file); //Colors @GET("/users/self/colors") void getColors(CanvasCallback<CanvasColor> callback); @PUT("/users/self/colors/{context_id}") void setColor(@Path("context_id") String context_id, @Query(value = "hexcode", encodeValue = false) String color, @Body String body, CanvasCallback<CanvasColor> callback); @POST("/accounts/{account_id}/self_registration") void createSelfRegistrationUser(@Path("account_id") long account_id, @Query("user[name]") String userName, @Query("pseudonym[unique_id]") String emailAddress, @Query("user[terms_of_use]") int acceptsTerms, @Body String body, Callback<User> callback); @POST("/users/self/observees") void addObserveeWithToken(@Query("access_token") String token, @Body String body, CanvasCallback<User> callback); @GET("/users/self/observees?include[]=avatar_url") void getObservees(CanvasCallback<User[]> callback); @DELETE("/users/self/observees/{observee_id}") void removeObservee(@Path("observee_id") long observee_id, Callback<User> callback); @DELETE("/student/{observer_id}/{student_id}") void removeStudent(@Path("observer_id") long observer_id, @Path("student_id") long student_id, Callback<Response> callback); } ///////////////////////////////////////////////////////////////////////// // API Calls ///////////////////////////////////////////////////////////////////////// public static void getSelf(UserCallback callback) { if (APIHelpers.paramIsNull(callback)) { return; } //Read cache callback.cache(APIHelpers.getCacheUser(callback.getContext()), null, null); //Don't allow this API call to be made while masquerading. //It causes the current user to be overridden with the masqueraded one. if (Masquerading.isMasquerading(callback.getContext())) { Log.w(APIHelpers.LOG_TAG,"No API call for /users/self/profile can be made while masquerading."); return; } buildInterface(UsersInterface.class, callback, null).getSelf(callback); } public static void getSelfWithPermissions(CanvasCallback<User> callback) { if (APIHelpers.paramIsNull(callback)) { return; } //Don't allow this API call to be made while masquerading. //It causes the current user to be overriden with the masqueraded one. if (Masquerading.isMasquerading(callback.getContext())) { Log.w(APIHelpers.LOG_TAG,"No API call for /users/self can be made while masquerading."); return; } buildCacheInterface(UsersInterface.class, callback, null).getSelfWithPermission(callback); buildInterface(UsersInterface.class, callback, null).getSelfWithPermission(callback); } public static void getSelfEnrollments(CanvasCallback<Enrollment[]> callback) { if(APIHelpers.paramIsNull(callback)) return; buildCacheInterface(UsersInterface.class, callback, null).getSelfEnrollments(callback); buildInterface(UsersInterface.class, callback, null).getSelfEnrollments(callback); } public static void updateShortName(String shortName, CanvasCallback<User> callback) { if (APIHelpers.paramIsNull(callback, shortName)) { return; } buildInterface(UsersInterface.class, callback, null).updateShortName(shortName, "", callback); } public static void getUserById(long userId, CanvasCallback<User> userCanvasCallback){ if(APIHelpers.paramIsNull(userCanvasCallback)){return;} buildCacheInterface(UsersInterface.class, userCanvasCallback, null).getUserById(userId, userCanvasCallback); //Passing UserCallback here will break OUR cache. if(userCanvasCallback instanceof UserCallback){ Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self.."); return; } buildInterface(UsersInterface.class, userCanvasCallback, null).getUserById(userId, userCanvasCallback); } public static void getUserByIdNoCache(long userId, CanvasCallback<User> userCanvasCallback){ if(APIHelpers.paramIsNull(userCanvasCallback)){return;} //Passing UserCallback here will break OUR cache. if(userCanvasCallback instanceof UserCallback){ Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self.."); return; } buildInterface(UsersInterface.class, userCanvasCallback, null).getUserById(userId, userCanvasCallback); } public static void getCourseUserById(CanvasContext canvasContext, long userId, CanvasCallback<User> userCanvasCallback){ if(APIHelpers.paramIsNull(userCanvasCallback)){return;} buildCacheInterface(UsersInterface.class, userCanvasCallback, canvasContext).getUserById(canvasContext.getId(), userId, userCanvasCallback); //Passing UserCallback here will break OUR cache. if(userCanvasCallback instanceof UserCallback){ Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self.."); return; } buildInterface(UsersInterface.class, userCanvasCallback, canvasContext).getUserById(canvasContext.getId(), userId, userCanvasCallback); } public static void getFirstPagePeople(CanvasContext canvasContext, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); } public static void getFirstPagePeopleChained(CanvasContext canvasContext, boolean isCached, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } if(isCached) { buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); } else { buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); } } public static void getNextPagePeople(String nextURL, CanvasCallback<User[]> callback){ if (APIHelpers.paramIsNull(callback, nextURL)) { return; } callback.setIsNextPage(true); buildCacheInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); buildInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); } public static void getNextPagePeopleChained(String nextURL, CanvasCallback<User[]> callback, boolean isCached){ if (APIHelpers.paramIsNull(callback, nextURL)) { return; } callback.setIsNextPage(true); if (isCached) { buildCacheInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); } else { buildInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); } } public static void getAllUsersForCourseByEnrollmentType(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, final CanvasCallback<User[]> callback){ if(APIHelpers.paramIsNull(callback, canvasContext)){return;} CanvasCallback<User[]> bridge = new ExhaustiveBridgeCallback<>(User.class, callback, new ExhaustiveBridgeCallback.ExhaustiveBridgeEvents() { @Override public void performApiCallWithExhaustiveCallback(CanvasCallback bridgeCallback, String nextURL, boolean isCached) { if(callback.isCancelled()) { return; } UserAPI.getNextPagePeopleChained(nextURL, bridgeCallback, isCached); } }); buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), bridge); buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), bridge); } public static void getFirstPagePeople(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); } public static void getFirstPagePeopleChained(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, boolean isCached, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } if(isCached) { buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); } else { buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); } } public static void getColors(Context context, CanvasCallback<CanvasColor> callback) { buildCacheInterface(UsersInterface.class, context, false).getColors(callback); buildInterface(UsersInterface.class, context, false).getColors(callback); } public static void setColor(Context context, CanvasContext canvasContext, int color, CanvasCallback<CanvasColor> callback) { if (APIHelpers.paramIsNull(context, canvasContext, callback)) { return; } setColor(context, canvasContext.getContextId(), color, callback); } public static void setColor(Context context, String context_id, int color, CanvasCallback<CanvasColor> callback) { if (APIHelpers.paramIsNull(context, context_id, callback)) { return; } //Modifies a color into a RRGGBB color string with no #. String hexColor = Integer.toHexString(color); hexColor = hexColor.substring(hexColor.length() - 6); if(hexColor.contains("#")) { hexColor = hexColor.replaceAll("#", ""); } buildInterface(UsersInterface.class, context, false).setColor(context_id, hexColor, "", callback); } public static void createSelfRegistrationUser(long accountId, String userName, String emailAddress, CanvasCallback<User> callback) { if (APIHelpers.paramIsNull(userName, emailAddress, callback)) { return; } buildInterface(UsersInterface.class, callback, false).createSelfRegistrationUser(accountId, userName, emailAddress, 1, "", callback); } public static void addObserveeByToken(String token, CanvasCallback<User> callback) { if(APIHelpers.paramIsNull(token, callback)) { return; } buildInterface(UsersInterface.class, callback, false).addObserveeWithToken(token, "", callback); } public static void getObservees(CanvasCallback<User[]> callback) { if(APIHelpers.paramIsNull(callback)) { return; } buildCacheInterface(UsersInterface.class, callback).getObservees(callback); buildInterface(UsersInterface.class, callback).getObservees(callback); } public static void removeObservee(long observeeId, CanvasCallback<User> callback) { if(APIHelpers.paramIsNull(callback)) { return; } buildInterface(UsersInterface.class, callback).removeObservee(observeeId, callback); } /** * Remove student from Airwolf. Currently only used in the parent app * * @param observerId * @param studentId * @param callback - 200 if successful */ public static void removeStudent(long observerId, long studentId, CanvasCallback<Response> callback) { if(APIHelpers.paramIsNull(callback)) { return; } buildInterface(UsersInterface.class, AlertAPI.AIRWOLF_DOMAIN, callback).removeStudent(observerId, studentId, callback); } ///////////////////////////////////////////////////////////////////////// // Synchronous Calls ///////////////////////////////////////////////////////////////////////// public static FileUploadParams getFileUploadParams(Context context, String fileName, long size, String contentType, Long parentFolderId){ return buildInterface(UsersInterface.class, context).getFileUploadParams(size, fileName, contentType, parentFolderId, ""); } public static FileUploadParams getFileUploadParams(Context context, String fileName, long size, String contentType, String parentFolderPath){ return buildInterface(UsersInterface.class, context).getFileUploadParams(size, fileName, contentType, parentFolderPath, ""); } public static Attachment uploadUserFile(String uploadUrl, LinkedHashMap<String,String> uploadParams, String mimeType, File file){ return buildUploadInterface(UsersInterface.class, uploadUrl).uploadUserFile(uploadParams, new TypedFile(mimeType, file)); } ///////////////////////////////////////////////////////////////////////// // Helpers ///////////////////////////////////////////////////////////////////////// private static String getEnrollmentTypeString(ENROLLMENT_TYPE enrollment_type){ String enrollmentType = ""; switch (enrollment_type){ case DESIGNER: enrollmentType = "designer"; break; case OBSERVER: enrollmentType = "observer"; break; case STUDENT: enrollmentType = "student"; break; case TA: enrollmentType = "ta"; break; case TEACHER: enrollmentType = "teacher"; break; } return enrollmentType; } }
src/main/java/com/instructure/canvasapi/api/UserAPI.java
package com.instructure.canvasapi.api; import android.content.Context; import android.util.Log; import com.instructure.canvasapi.model.Attachment; import com.instructure.canvasapi.model.CanvasColor; import com.instructure.canvasapi.model.CanvasContext; import com.instructure.canvasapi.model.Enrollment; import com.instructure.canvasapi.model.FileUploadParams; import com.instructure.canvasapi.model.User; import com.instructure.canvasapi.utilities.APIHelpers; import com.instructure.canvasapi.utilities.CanvasCallback; import com.instructure.canvasapi.utilities.ExhaustiveBridgeCallback; import com.instructure.canvasapi.utilities.Masquerading; import com.instructure.canvasapi.utilities.UserCallback; import java.io.File; import java.util.LinkedHashMap; import retrofit.Callback; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.Multipart; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Part; import retrofit.http.PartMap; import retrofit.http.Path; import retrofit.http.Query; import retrofit.mime.TypedFile; /** * Copyright (c) 2015 Instructure. All rights reserved. */ public class UserAPI extends BuildInterfaceAPI { public enum ENROLLMENT_TYPE {STUDENT, TEACHER, TA, OBSERVER, DESIGNER} interface UsersInterface { @GET("/users/self/profile") void getSelf(Callback<User> callback); // TODO: We probably need to create a helper that does each of these individually @GET("/users/self/enrollments?state[]=active&state[]=invited&state[]=completed") void getSelfEnrollments(Callback<Enrollment[]> callback); @GET("/users/self") void getSelfWithPermission(CanvasCallback<User> callback); @PUT("/users/self") void updateShortName(@Query("user[short_name]") String shortName, @Body String body, Callback<User> callback); @GET("/users/{userid}/profile") void getUserById(@Path("userid")long userId, Callback<User> userCallback); @GET("/{context_id}/users/{userId}?include[]=avatar_url&include[]=user_id&include[]=email&include[]=bio") void getUserById(@Path("context_id") long context_id, @Path("userId")long userId, Callback<User> userCallback); @GET("/{context_id}/users?include[]=enrollments&include[]=avatar_url&include[]=user_id&include[]=email&include[]=bio") void getFirstPagePeopleList(@Path("context_id") long context_id, Callback<User[]> callback); @GET("/{context_id}/users?include[]=enrollments&include[]=avatar_url&include[]=user_id&include[]=email") void getFirstPagePeopleListWithEnrollmentType(@Path("context_id") long context_id, @Query("enrollment_type") String enrollmentType, Callback<User[]> callback); @GET("/{next}") void getNextPagePeopleList(@Path(value = "next", encode = false) String nextURL, Callback<User[]> callback); @POST("/users/self/file") void uploadUserFileURL( @Query("url") String fileURL, @Query("name") String fileName, @Query("size") long size, @Query("content_type") String content_type, @Query("parent_folder_path") String parentFolderPath, @Body String body, Callback<String> callback); @POST("/users/self/files") FileUploadParams getFileUploadParams( @Query("size") long size, @Query("name") String fileName, @Query("content_type") String content_type, @Query("parent_folder_id") Long parentFolderId, @Body String body); @POST("/users/self/files") FileUploadParams getFileUploadParams( @Query("size") long size, @Query("name") String fileName, @Query("content_type") String content_type, @Query("parent_folder_path") String parentFolderPath, @Body String body); @Multipart @POST("/") Attachment uploadUserFile(@PartMap LinkedHashMap<String, String> params, @Part("file") TypedFile file); //Colors @GET("/users/self/colors") void getColors(CanvasCallback<CanvasColor> callback); @PUT("/users/self/colors/{context_id}") void setColor(@Path("context_id") String context_id, @Query(value = "hexcode", encodeValue = false) String color, @Body String body, CanvasCallback<CanvasColor> callback); @POST("/accounts/{account_id}/self_registration") void createSelfRegistrationUser(@Path("account_id") long account_id, @Query("user[name]") String userName, @Query("pseudonym[unique_id]") String emailAddress, @Query("user[terms_of_use]") int acceptsTerms, @Body String body, Callback<User> callback); @POST("/users/self/observees") void addObserveeWithToken(@Query("access_token") String token, @Body String body, CanvasCallback<User> callback); @GET("/users/self/observees?include[]=avatar_url") void getObservees(CanvasCallback<User[]> callback); @DELETE("/users/self/observees/{observee_id}") void removeObservee(@Path("observee_id") long observee_id, Callback<User> callback); } ///////////////////////////////////////////////////////////////////////// // API Calls ///////////////////////////////////////////////////////////////////////// public static void getSelf(UserCallback callback) { if (APIHelpers.paramIsNull(callback)) { return; } //Read cache callback.cache(APIHelpers.getCacheUser(callback.getContext()), null, null); //Don't allow this API call to be made while masquerading. //It causes the current user to be overridden with the masqueraded one. if (Masquerading.isMasquerading(callback.getContext())) { Log.w(APIHelpers.LOG_TAG,"No API call for /users/self/profile can be made while masquerading."); return; } buildInterface(UsersInterface.class, callback, null).getSelf(callback); } public static void getSelfWithPermissions(CanvasCallback<User> callback) { if (APIHelpers.paramIsNull(callback)) { return; } //Don't allow this API call to be made while masquerading. //It causes the current user to be overriden with the masqueraded one. if (Masquerading.isMasquerading(callback.getContext())) { Log.w(APIHelpers.LOG_TAG,"No API call for /users/self can be made while masquerading."); return; } buildCacheInterface(UsersInterface.class, callback, null).getSelfWithPermission(callback); buildInterface(UsersInterface.class, callback, null).getSelfWithPermission(callback); } public static void getSelfEnrollments(CanvasCallback<Enrollment[]> callback) { if(APIHelpers.paramIsNull(callback)) return; buildCacheInterface(UsersInterface.class, callback, null).getSelfEnrollments(callback); buildInterface(UsersInterface.class, callback, null).getSelfEnrollments(callback); } public static void updateShortName(String shortName, CanvasCallback<User> callback) { if (APIHelpers.paramIsNull(callback, shortName)) { return; } buildInterface(UsersInterface.class, callback, null).updateShortName(shortName, "", callback); } public static void getUserById(long userId, CanvasCallback<User> userCanvasCallback){ if(APIHelpers.paramIsNull(userCanvasCallback)){return;} buildCacheInterface(UsersInterface.class, userCanvasCallback, null).getUserById(userId, userCanvasCallback); //Passing UserCallback here will break OUR cache. if(userCanvasCallback instanceof UserCallback){ Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self.."); return; } buildInterface(UsersInterface.class, userCanvasCallback, null).getUserById(userId, userCanvasCallback); } public static void getUserByIdNoCache(long userId, CanvasCallback<User> userCanvasCallback){ if(APIHelpers.paramIsNull(userCanvasCallback)){return;} //Passing UserCallback here will break OUR cache. if(userCanvasCallback instanceof UserCallback){ Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self.."); return; } buildInterface(UsersInterface.class, userCanvasCallback, null).getUserById(userId, userCanvasCallback); } public static void getCourseUserById(CanvasContext canvasContext, long userId, CanvasCallback<User> userCanvasCallback){ if(APIHelpers.paramIsNull(userCanvasCallback)){return;} buildCacheInterface(UsersInterface.class, userCanvasCallback, canvasContext).getUserById(canvasContext.getId(), userId, userCanvasCallback); //Passing UserCallback here will break OUR cache. if(userCanvasCallback instanceof UserCallback){ Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self.."); return; } buildInterface(UsersInterface.class, userCanvasCallback, canvasContext).getUserById(canvasContext.getId(), userId, userCanvasCallback); } public static void getFirstPagePeople(CanvasContext canvasContext, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); } public static void getFirstPagePeopleChained(CanvasContext canvasContext, boolean isCached, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } if(isCached) { buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); } else { buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback); } } public static void getNextPagePeople(String nextURL, CanvasCallback<User[]> callback){ if (APIHelpers.paramIsNull(callback, nextURL)) { return; } callback.setIsNextPage(true); buildCacheInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); buildInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); } public static void getNextPagePeopleChained(String nextURL, CanvasCallback<User[]> callback, boolean isCached){ if (APIHelpers.paramIsNull(callback, nextURL)) { return; } callback.setIsNextPage(true); if (isCached) { buildCacheInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); } else { buildInterface(UsersInterface.class, callback, false).getNextPagePeopleList(nextURL, callback); } } public static void getAllUsersForCourseByEnrollmentType(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, final CanvasCallback<User[]> callback){ if(APIHelpers.paramIsNull(callback, canvasContext)){return;} CanvasCallback<User[]> bridge = new ExhaustiveBridgeCallback<>(User.class, callback, new ExhaustiveBridgeCallback.ExhaustiveBridgeEvents() { @Override public void performApiCallWithExhaustiveCallback(CanvasCallback bridgeCallback, String nextURL, boolean isCached) { if(callback.isCancelled()) { return; } UserAPI.getNextPagePeopleChained(nextURL, bridgeCallback, isCached); } }); buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), bridge); buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), bridge); } public static void getFirstPagePeople(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); } public static void getFirstPagePeopleChained(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, boolean isCached, CanvasCallback<User[]> callback) { if (APIHelpers.paramIsNull(callback, canvasContext)) { return; } if(isCached) { buildCacheInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); } else { buildInterface(UsersInterface.class, callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback); } } public static void getColors(Context context, CanvasCallback<CanvasColor> callback) { buildCacheInterface(UsersInterface.class, context, false).getColors(callback); buildInterface(UsersInterface.class, context, false).getColors(callback); } public static void setColor(Context context, CanvasContext canvasContext, int color, CanvasCallback<CanvasColor> callback) { if (APIHelpers.paramIsNull(context, canvasContext, callback)) { return; } setColor(context, canvasContext.getContextId(), color, callback); } public static void setColor(Context context, String context_id, int color, CanvasCallback<CanvasColor> callback) { if (APIHelpers.paramIsNull(context, context_id, callback)) { return; } //Modifies a color into a RRGGBB color string with no #. String hexColor = Integer.toHexString(color); hexColor = hexColor.substring(hexColor.length() - 6); if(hexColor.contains("#")) { hexColor = hexColor.replaceAll("#", ""); } buildInterface(UsersInterface.class, context, false).setColor(context_id, hexColor, "", callback); } public static void createSelfRegistrationUser(long accountId, String userName, String emailAddress, CanvasCallback<User> callback) { if (APIHelpers.paramIsNull(userName, emailAddress, callback)) { return; } buildInterface(UsersInterface.class, callback, false).createSelfRegistrationUser(accountId, userName, emailAddress, 1, "", callback); } public static void addObserveeByToken(String token, CanvasCallback<User> callback) { if(APIHelpers.paramIsNull(token, callback)) { return; } buildInterface(UsersInterface.class, callback, false).addObserveeWithToken(token, "", callback); } public static void getObservees(CanvasCallback<User[]> callback) { if(APIHelpers.paramIsNull(callback)) { return; } buildCacheInterface(UsersInterface.class, callback).getObservees(callback); buildInterface(UsersInterface.class, callback).getObservees(callback); } public static void removeObservee(long observeeId, CanvasCallback<User> callback) { if(APIHelpers.paramIsNull(callback)) { return; } buildInterface(UsersInterface.class, callback).removeObservee(observeeId, callback); } ///////////////////////////////////////////////////////////////////////// // Synchronous Calls ///////////////////////////////////////////////////////////////////////// public static FileUploadParams getFileUploadParams(Context context, String fileName, long size, String contentType, Long parentFolderId){ return buildInterface(UsersInterface.class, context).getFileUploadParams(size, fileName, contentType, parentFolderId, ""); } public static FileUploadParams getFileUploadParams(Context context, String fileName, long size, String contentType, String parentFolderPath){ return buildInterface(UsersInterface.class, context).getFileUploadParams(size, fileName, contentType, parentFolderPath, ""); } public static Attachment uploadUserFile(String uploadUrl, LinkedHashMap<String,String> uploadParams, String mimeType, File file){ return buildUploadInterface(UsersInterface.class, uploadUrl).uploadUserFile(uploadParams, new TypedFile(mimeType, file)); } ///////////////////////////////////////////////////////////////////////// // Helpers ///////////////////////////////////////////////////////////////////////// private static String getEnrollmentTypeString(ENROLLMENT_TYPE enrollment_type){ String enrollmentType = ""; switch (enrollment_type){ case DESIGNER: enrollmentType = "designer"; break; case OBSERVER: enrollmentType = "observer"; break; case STUDENT: enrollmentType = "student"; break; case TA: enrollmentType = "ta"; break; case TEACHER: enrollmentType = "teacher"; break; } return enrollmentType; } }
Add api to remove student from airwolf databases. Change-Id: Ic6a3d7dfdc7db4a7485cc7ef19aa75da87bec977
src/main/java/com/instructure/canvasapi/api/UserAPI.java
Add api to remove student from airwolf databases.
<ide><path>rc/main/java/com/instructure/canvasapi/api/UserAPI.java <ide> import java.util.LinkedHashMap; <ide> <ide> import retrofit.Callback; <add>import retrofit.client.Response; <ide> import retrofit.http.Body; <ide> import retrofit.http.DELETE; <ide> import retrofit.http.GET; <ide> <ide> @DELETE("/users/self/observees/{observee_id}") <ide> void removeObservee(@Path("observee_id") long observee_id, Callback<User> callback); <add> <add> @DELETE("/student/{observer_id}/{student_id}") <add> void removeStudent(@Path("observer_id") long observer_id, @Path("student_id") long student_id, Callback<Response> callback); <ide> } <ide> <ide> ///////////////////////////////////////////////////////////////////////// <ide> <ide> buildInterface(UsersInterface.class, callback).removeObservee(observeeId, callback); <ide> } <add> <add> /** <add> * Remove student from Airwolf. Currently only used in the parent app <add> * <add> * @param observerId <add> * @param studentId <add> * @param callback - 200 if successful <add> */ <add> public static void removeStudent(long observerId, long studentId, CanvasCallback<Response> callback) { <add> if(APIHelpers.paramIsNull(callback)) { return; } <add> <add> buildInterface(UsersInterface.class, AlertAPI.AIRWOLF_DOMAIN, callback).removeStudent(observerId, studentId, callback); <add> } <ide> ///////////////////////////////////////////////////////////////////////// <ide> // Synchronous Calls <ide> /////////////////////////////////////////////////////////////////////////
Java
apache-2.0
2939e4c219263b7f2ebd94f7369150dc48d4a5cc
0
rprabhat/orientdb,rprabhat/orientdb,cstamas/orientdb,tempbottle/orientdb,intfrr/orientdb,joansmith/orientdb,alonsod86/orientdb,jdillon/orientdb,mbhulin/orientdb,joansmith/orientdb,giastfader/orientdb,sanyaade-g2g-repos/orientdb,mbhulin/orientdb,giastfader/orientdb,orientechnologies/orientdb,mmacfadden/orientdb,wyzssw/orientdb,allanmoso/orientdb,cstamas/orientdb,joansmith/orientdb,tempbottle/orientdb,wyzssw/orientdb,rprabhat/orientdb,allanmoso/orientdb,allanmoso/orientdb,allanmoso/orientdb,mbhulin/orientdb,giastfader/orientdb,sanyaade-g2g-repos/orientdb,mbhulin/orientdb,wouterv/orientdb,wyzssw/orientdb,intfrr/orientdb,intfrr/orientdb,wouterv/orientdb,intfrr/orientdb,wouterv/orientdb,jdillon/orientdb,tempbottle/orientdb,alonsod86/orientdb,joansmith/orientdb,orientechnologies/orientdb,cstamas/orientdb,cstamas/orientdb,mmacfadden/orientdb,sanyaade-g2g-repos/orientdb,giastfader/orientdb,orientechnologies/orientdb,wyzssw/orientdb,wouterv/orientdb,mmacfadden/orientdb,orientechnologies/orientdb,tempbottle/orientdb,rprabhat/orientdb,mmacfadden/orientdb,alonsod86/orientdb,alonsod86/orientdb,sanyaade-g2g-repos/orientdb,jdillon/orientdb
/* * Copyright 1999-2005 Luca Garulli (l.garulli--at-orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.profiler; import java.io.File; import com.orientechnologies.common.profiler.OProfiler; import com.orientechnologies.orient.core.memory.OMemoryWatchDog; /** * Profiling utility class. Handles chronos (times), statistics and counters. By default it's used as Singleton but you can create * any instances you want for separate profiling contexts. * * To start the recording use call startRecording(). By default record is turned off to avoid a run-time execution cost. * * @author Luca Garulli * @copyrights Orient Technologies.com */ public class OJVMProfiler extends OProfiler implements OMemoryWatchDog.Listener { private final int metricProcessors = Runtime.getRuntime().availableProcessors(); public OJVMProfiler() { registerHookValue(getSystemMetric("config.cpus"), new OProfilerHookValue() { @Override public Object getValue() { return metricProcessors; } }); registerHookValue(getSystemMetric("config.os.name"), new OProfilerHookValue() { @Override public Object getValue() { return System.getProperty("os.name"); } }); registerHookValue(getSystemMetric("config.os.version"), new OProfilerHookValue() { @Override public Object getValue() { return System.getProperty("os.version"); } }); registerHookValue(getSystemMetric("config.os.arch"), new OProfilerHookValue() { @Override public Object getValue() { return System.getProperty("os.arch"); } }); registerHookValue(getSystemMetric("config.java.vendor"), new OProfilerHookValue() { @Override public Object getValue() { return System.getProperty("java.vendor"); } }); registerHookValue(getSystemMetric("config.java.version"), new OProfilerHookValue() { @Override public Object getValue() { return System.getProperty("java.version"); } }); registerHookValue(getProcessMetric("runtime.availableMemory"), new OProfilerHookValue() { @Override public Object getValue() { return Runtime.getRuntime().freeMemory(); } }); registerHookValue(getProcessMetric("runtime.maxMemory"), new OProfilerHookValue() { @Override public Object getValue() { return Runtime.getRuntime().maxMemory(); } }); registerHookValue(getProcessMetric("runtime.totalMemory"), new OProfilerHookValue() { @Override public Object getValue() { return Runtime.getRuntime().totalMemory(); } }); final File[] roots = File.listRoots(); for (final File root : roots) { String volumeName = root.getAbsolutePath(); int pos = volumeName.indexOf(":\\"); if (pos > -1) volumeName = volumeName.substring(0, pos); final String metricPrefix = "system.disk." + volumeName; registerHookValue(metricPrefix + ".totalSpace", new OProfilerHookValue() { @Override public Object getValue() { return root.getTotalSpace(); } }); registerHookValue(metricPrefix + ".freeSpace", new OProfilerHookValue() { @Override public Object getValue() { return root.getFreeSpace(); } }); registerHookValue(metricPrefix + ".usableSpace", new OProfilerHookValue() { @Override public Object getValue() { return root.getUsableSpace(); } }); } } public String getSystemMetric(final String iMetricName) { final StringBuilder buffer = new StringBuilder(); buffer.append("system."); buffer.append(iMetricName); return buffer.toString(); } public String getProcessMetric(final String iMetricName) { final StringBuilder buffer = new StringBuilder(); buffer.append("process."); buffer.append(iMetricName); return buffer.toString(); } public String getDatabaseMetric(final String iDatabaseName, final String iMetricName) { final StringBuilder buffer = new StringBuilder(); buffer.append("db."); buffer.append(iDatabaseName); buffer.append('.'); buffer.append(iMetricName); return buffer.toString(); } /** * Frees the memory removing profiling information */ public void memoryUsageLow(final long iFreeMemory, final long iFreeMemoryPercentage) { synchronized (snapshots) { snapshots.clear(); } synchronized (summaries) { summaries.clear(); } } }
core/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java
/* * Copyright 1999-2005 Luca Garulli (l.garulli--at-orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.profiler; import java.io.File; import com.orientechnologies.common.profiler.OProfiler; import com.orientechnologies.orient.core.memory.OMemoryWatchDog; /** * Profiling utility class. Handles chronos (times), statistics and counters. By default it's used as Singleton but you can create * any instances you want for separate profiling contexts. * * To start the recording use call startRecording(). By default record is turned off to avoid a run-time execution cost. * * @author Luca Garulli * @copyrights Orient Technologies.com */ public class OJVMProfiler extends OProfiler implements OMemoryWatchDog.Listener { private final int metricProcessors = Runtime.getRuntime().availableProcessors(); public OJVMProfiler() { registerHookValue(getSystemMetric("config.cpus"), new OProfilerHookValue() { @Override public Object getValue() { return metricProcessors; } }); registerHookValue(getProcessMetric("runtime.availableMemory"), new OProfilerHookValue() { @Override public Object getValue() { return Runtime.getRuntime().freeMemory(); } }); registerHookValue(getProcessMetric("runtime.maxMemory"), new OProfilerHookValue() { @Override public Object getValue() { return Runtime.getRuntime().maxMemory(); } }); registerHookValue(getProcessMetric("runtime.totalMemory"), new OProfilerHookValue() { @Override public Object getValue() { return Runtime.getRuntime().totalMemory(); } }); final File[] roots = File.listRoots(); for (final File root : roots) { String volumeName = root.getAbsolutePath(); int pos = volumeName.indexOf(":\\"); if (pos > -1) volumeName = volumeName.substring(0, pos); final String metricPrefix = "system.disk." + volumeName; registerHookValue(metricPrefix + ".totalSpace", new OProfilerHookValue() { @Override public Object getValue() { return root.getTotalSpace(); } }); registerHookValue(metricPrefix + ".freeSpace", new OProfilerHookValue() { @Override public Object getValue() { return root.getFreeSpace(); } }); registerHookValue(metricPrefix + ".usableSpace", new OProfilerHookValue() { @Override public Object getValue() { return root.getUsableSpace(); } }); } } public String getSystemMetric(final String iMetricName) { final StringBuilder buffer = new StringBuilder(); buffer.append("system."); buffer.append(iMetricName); return buffer.toString(); } public String getProcessMetric(final String iMetricName) { final StringBuilder buffer = new StringBuilder(); buffer.append("process."); buffer.append(iMetricName); return buffer.toString(); } public String getDatabaseMetric(final String iDatabaseName, final String iMetricName) { final StringBuilder buffer = new StringBuilder(); buffer.append("db."); buffer.append(iDatabaseName); buffer.append('.'); buffer.append(iMetricName); return buffer.toString(); } /** * Frees the memory removing profiling information */ public void memoryUsageLow(final long iFreeMemory, final long iFreeMemoryPercentage) { synchronized (snapshots) { snapshots.clear(); } synchronized (summaries) { summaries.clear(); } } }
Profiler: created new metrics about OS information
core/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java
Profiler: created new metrics about OS information
<ide><path>ore/src/main/java/com/orientechnologies/orient/core/profiler/OJVMProfiler.java <ide> @Override <ide> public Object getValue() { <ide> return metricProcessors; <add> } <add> }); <add> registerHookValue(getSystemMetric("config.os.name"), new OProfilerHookValue() { <add> @Override <add> public Object getValue() { <add> return System.getProperty("os.name"); <add> } <add> }); <add> registerHookValue(getSystemMetric("config.os.version"), new OProfilerHookValue() { <add> @Override <add> public Object getValue() { <add> return System.getProperty("os.version"); <add> } <add> }); <add> registerHookValue(getSystemMetric("config.os.arch"), new OProfilerHookValue() { <add> @Override <add> public Object getValue() { <add> return System.getProperty("os.arch"); <add> } <add> }); <add> registerHookValue(getSystemMetric("config.java.vendor"), new OProfilerHookValue() { <add> @Override <add> public Object getValue() { <add> return System.getProperty("java.vendor"); <add> } <add> }); <add> registerHookValue(getSystemMetric("config.java.version"), new OProfilerHookValue() { <add> @Override <add> public Object getValue() { <add> return System.getProperty("java.version"); <ide> } <ide> }); <ide> registerHookValue(getProcessMetric("runtime.availableMemory"), new OProfilerHookValue() {
JavaScript
bsd-3-clause
b0dfe1d509ba7779cd568da8fdb7692b0c98b564
0
CartoDB/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var fs = require('fs'); var path = require('path'); var argv = require('yargs') .usage('Usage: $0 <environment> [options]') .help('h') .example( '$0 production -c /etc/sql-api/config.js', 'start server in production environment with /etc/sql-api/config.js as config file' ) .alias('h', 'help') .alias('c', 'config') .nargs('c', 1) .describe('c', 'Load configuration from path') .argv; var environmentArg = argv._[0] || process.env.NODE_ENV || 'development'; var configurationFile = path.resolve(argv.config || './config/environments/' + environmentArg + '.js'); if (!fs.existsSync(configurationFile)) { console.error('Configuration file "%s" does not exist', configurationFile); process.exit(1); } global.settings = require(configurationFile); var ENVIRONMENT = argv._[0] || process.env.NODE_ENV || global.settings.environment; process.env.NODE_ENV = ENVIRONMENT; var availableEnvironments = ['development', 'production', 'test', 'staging']; // sanity check arguments if (availableEnvironments.indexOf(ENVIRONMENT) === -1) { console.error("node app.js [environment]"); console.error("Available environments: " + availableEnvironments.join(', ')); process.exit(1); } global.settings.api_hostname = require('os').hostname().split('.')[0]; global.log4js = require('log4js'); var log4jsConfig = { appenders: [], replaceConsole: true }; if ( global.settings.log_filename ) { var logFilename = path.resolve(global.settings.log_filename); var logDirectory = path.dirname(logFilename); if (!fs.existsSync(logDirectory)) { console.error("Log filename directory does not exist: " + logDirectory); process.exit(1); } console.log("Logs will be written to " + logFilename); log4jsConfig.appenders.push( { type: "file", absolute: true, filename: logFilename } ); } else { log4jsConfig.appenders.push( { type: "console", layout: { type:'basic' } } ); } global.log4js.configure(log4jsConfig); global.logger = global.log4js.getLogger(); // kick off controller if ( ! global.settings.base_url ) { global.settings.base_url = '/api/*'; } var version = require("./package").version; var server = require('./app/server')(); server.listen(global.settings.node_port, global.settings.node_host, function() { console.info('Using configuration file "%s"', configurationFile); console.log( "CartoDB SQL API %s listening on %s:%s PID=%d (%s)", version, global.settings.node_host, global.settings.node_port, process.pid, ENVIRONMENT ); }); process.on('uncaughtException', function(err) { global.logger.error('Uncaught exception: ' + err.stack); }); process.on('SIGHUP', function() { global.log4js.clearAndShutdownAppenders(function() { global.log4js.configure(log4jsConfig); global.logger = global.log4js.getLogger(); console.log('Log files reloaded'); }); if (server.batch && server.batch.logger) { server.batch.logger.reopenFileStreams(); } }); process.on('SIGTERM', function () { server.batch.stop(); server.batch.drain(function (err) { if (err) { console.log('Exit with error'); return process.exit(1); } console.log('Exit gracefully'); process.exit(0); }); });
app.js
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var fs = require('fs'); var path = require('path'); var argv = require('yargs') .usage('Usage: $0 <environment> [options]') .help('h') .example( '$0 production -c /etc/sql-api/config.js', 'start server in production environment with /etc/sql-api/config.js as config file' ) .alias('h', 'help') .alias('c', 'config') .nargs('c', 1) .describe('c', 'Load configuration from path') .argv; var environmentArg = argv._[0] || process.env.NODE_ENV || 'development'; var configurationFile = path.resolve(argv.config || './config/environments/' + environmentArg + '.js'); if (!fs.existsSync(configurationFile)) { console.error('Configuration file "%s" does not exist', configurationFile); process.exit(1); } global.settings = require(configurationFile); var ENVIRONMENT = argv._[0] || process.env.NODE_ENV || global.settings.environment; process.env.NODE_ENV = ENVIRONMENT; var availableEnvironments = ['development', 'production', 'test', 'staging']; // sanity check arguments if (availableEnvironments.indexOf(ENVIRONMENT) === -1) { console.error("node app.js [environment]"); console.error("Available environments: " + availableEnvironments.join(', ')); process.exit(1); } global.settings.api_hostname = require('os').hostname().split('.')[0]; global.log4js = require('log4js'); var log4jsConfig = { appenders: [], replaceConsole: true }; if ( global.settings.log_filename ) { var logFilename = path.resolve(global.settings.log_filename); var logDirectory = path.dirname(logFilename); if (!fs.existsSync(logDirectory)) { console.error("Log filename directory does not exist: " + logDirectory); process.exit(1); } console.log("Logs will be written to " + logFilename); log4jsConfig.appenders.push( { type: "file", absolute: true, filename: logFilename } ); } else { log4jsConfig.appenders.push( { type: "console", layout: { type:'basic' } } ); } global.log4js.configure(log4jsConfig); global.logger = global.log4js.getLogger(); // kick off controller if ( ! global.settings.base_url ) { global.settings.base_url = '/api/*'; } var version = require("./package").version; var server = require('./app/server')(); server.listen(global.settings.node_port, global.settings.node_host, function() { console.info('Using configuration file "%s"', configurationFile); console.log( "CartoDB SQL API %s listening on %s:%s PID=%d (%s)", version, global.settings.node_host, global.settings.node_port, process.pid, ENVIRONMENT ); }); process.on('uncaughtException', function(err) { global.logger.error('Uncaught exception: ' + err.stack); }); process.on('SIGHUP', function() { global.log4js.clearAndShutdownAppenders(function() { global.log4js.configure(log4jsConfig); global.logger = global.log4js.getLogger(); console.log('Log files reloaded'); }); server.batch.logger.reopenFileStreams(); }); process.on('SIGTERM', function () { server.batch.stop(); server.batch.drain(function (err) { if (err) { console.log('Exit with error'); return process.exit(1); } console.log('Exit gracefully'); process.exit(0); }); });
Only reload log files if logger exists
app.js
Only reload log files if logger exists
<ide><path>pp.js <ide> console.log('Log files reloaded'); <ide> }); <ide> <del> server.batch.logger.reopenFileStreams(); <add> if (server.batch && server.batch.logger) { <add> server.batch.logger.reopenFileStreams(); <add> } <ide> }); <ide> <ide> process.on('SIGTERM', function () {
JavaScript
mit
c0648728e9bb5fb103a5c581552d83b251eaf681
0
UniSiegenCSCW/remotino,UniSiegenCSCW/remotino,UniSiegenCSCW/remotino
import path from 'path'; export default { module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.html$/, loader: 'html' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'commonjs2' }, resolve: { extensions: ['', '.js', '.jsx'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [ ], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] };
webpack.config.base.js
import path from 'path'; export default { module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'commonjs2' }, resolve: { extensions: ['', '.js', '.jsx'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [ ], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] };
add html loader to webpack
webpack.config.base.js
add html loader to webpack
<ide><path>ebpack.config.base.js <ide> }, { <ide> test: /\.json$/, <ide> loader: 'json-loader' <add> }, { <add> test: /\.html$/, <add> loader: 'html' <ide> }] <ide> }, <ide> output: {
Java
lgpl-2.1
316a10f9a08a29fd43e8361f009a13df40ff3811
0
RockManJoe64/swingx,RockManJoe64/swingx
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Random; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.RowFilter; import javax.swing.SortOrder; import javax.swing.SwingUtilities; import javax.swing.RowSorter.SortKey; import javax.swing.event.RowSorterEvent; import javax.swing.event.RowSorterListener; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.RowSorterEvent.Type; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.search.SearchFactory; import org.jdesktop.swingx.sort.DefaultSortController; import org.jdesktop.swingx.sort.SortUtils; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.DatePickerCellEditor; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; import org.junit.Test; /** * Split from old JXTableUnitTest - contains "interactive" * methods only. <p> * * PENDING: too many frames to fit all on screen - either split into different * tests or change positioning algo to start on top again if hidden. <p> * @author Jeanette Winzenburg */ public class JXTableVisualCheck extends JXTableUnitTest { private static final Logger LOG = Logger.getLogger(JXTableVisualCheck.class .getName()); public static void main(String args[]) { JXTableVisualCheck test = new JXTableVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*FloatingPoint.*"); test.runInteractiveTests("interactive.*Disable.*"); // test.runInteractiveTests("interactive.*Remove.*"); // test.runInteractiveTests("interactive.*ColumnProp.*"); // test.runInteractiveTests("interactive.*Multiple.*"); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Scrollable.*"); // test.runInteractiveTests("interactive.*isable.*"); // test.runInteractiveTests("interactive.*Policy.*"); // test.runInteractiveTests("interactive.*Rollover.*"); // test.runInteractiveTests("interactive.*Revalidate.*"); // test.runInteractiveTests("interactive.*UpdateUI.*"); // test.runInteractiveTests("interactiveColumnHighlighting"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { super.setUp(); // super has LF specific tests... setSystemLF(true); // setLookAndFeel("Nimbus"); } /** * Issue #1195-swingx: keep selection on remove * Basically, this is a core issue - fixed in DefaultSortController during * last cleanup round. * */ public void interactiveRemoveAndSelected() { final JXTable table = new JXTable(10, 5); JXFrame frame = wrapWithScrollingInFrame(table, "Issue #1195-swingx - keep selection on remove"); Action action = new AbstractAction("remove row before selected") { @Override public void actionPerformed(ActionEvent e) { int selected = table.getSelectedRow(); if (selected < 1) return; ((DefaultTableModel) table.getModel()).removeRow(selected - 1); } }; addAction(frame, action); show(frame); } /** * Issue #35-swingx: visual indicators of secondary sort columns * * Trick by David Hall: use unicode char * http://forums.java.net/jive/thread.jspa?threadID=71090 * * As he already noted: it's not necessarily pretty looking ;-) */ public void interactiveHeaderSecondarySortIndicator() { DefaultTableModel model = new DefaultTableModel(0, 3) { /** * @inherited <p> */ @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex < getColumnCount() - 1) { return Integer.class; } return super.getColumnClass(columnIndex); } }; int min = hexToInt("25A0"); int max = hexToInt("25FF"); for (int i = min; i <= max; i++) { Object[] row = new Object[3]; row[0] = i; row[1] = i; row[2] = (char) i + ""; model.addRow(row); } final JXTable table = new JXTable(); ColumnFactory factory = new ColumnFactory() { /** * @inherited <p> */ @Override public TableColumnExt createTableColumn(int modelIndex) { // TODO Auto-generated method stub TableColumnExt tableColumn = new SortAwareTableColumnExt(); tableColumn.setModelIndex(modelIndex); return tableColumn; } }; table.setColumnControlVisible(true); table.setColumnFactory(factory); table.setModel(model); RowSorterListener l = new RowSorterListener() { @SuppressWarnings("unchecked") @Override public void sorterChanged(RowSorterEvent e) { if (e.getType() == Type.SORT_ORDER_CHANGED) { List<TableColumn> list = table.getColumns(true); List<? extends SortKey> sortKeys = new ArrayList<SortKey>(e.getSource().getSortKeys()); // remove primary List<? extends SortKey> secondary = sortKeys.subList(1, sortKeys.size()); for (TableColumn tableColumn : list) { if (tableColumn instanceof TableColumnExt) { SortKey key = SortUtils.getFirstSortKeyForColumn(secondary, tableColumn.getModelIndex()); Object property = null; if (key != null && SortUtils.isSorted(key.getSortOrder())) { property = key.getSortOrder(); } ((TableColumnExt) tableColumn).putClientProperty(SortAwareTableColumnExt.SORT_ORDER_KEY, property); } } } } }; table.getRowSorter().addRowSorterListener(l); StringValue sv = new StringValue() { @Override public String getString(Object value) { return Integer.toHexString(((Integer) value).intValue()); } }; table.getColumn(1).setCellRenderer(new DefaultTableRenderer(sv, JLabel.RIGHT)); JXFrame frame = showWithScrollingInFrame(table, "Geometric shapes"); addComponentOrientationToggle(frame); } public static class SortAwareTableColumnExt extends TableColumnExt { public final static String DESCENDING_CHAR = " \u25bf"; public final static String ASCENDING_CHAR = " \u25b5"; public final static String SORT_ORDER_KEY = "columnExt.SortOrder"; /** * @inherited <p> */ @Override public Object getHeaderValue() { Object header = super.getHeaderValue(); Object sortOrder = getClientProperty(SORT_ORDER_KEY); if (SortOrder.ASCENDING == sortOrder) { header = header + ASCENDING_CHAR; } else if (SortOrder.DESCENDING == sortOrder){ header = header + DESCENDING_CHAR; } return header; } } private int hexToInt(String s) { return Integer.parseInt(s, 16); } /** * Issue #1254-swingx: JXTable not revalidated on update if filter. * * Core JTable issue * Problem is that the update might change the visible row count. */ public void interactiveRevalidateOnUpdateWithFilter() { String data[][] = { { "satuAA", "Satu", "SATU", "1" }, { "duaAAB", "Dua", "DUA", "2" }, { "tigaBAA", "Tiga", "TIGA", "3" }, { "empatBBA", "Empat", "EMPAT", "4" } }; String cols[] = { "col1", "col2", "col3", "col4" }; final JXTable table = new JXTable(data, cols); RowFilter<TableModel, Integer> tm = RowFilter.regexFilter( ".*AA.*", 0); table.setRowFilter(tm); JXFrame frame = wrapWithScrollingInFrame(table, "Update with RowFilter"); Action action = new AbstractAction("filter first row") { boolean hasAA = true; @Override public void actionPerformed(ActionEvent e) { String newValue = hasAA ? "BB" : "AA"; hasAA = !hasAA; table.getModel().setValueAt(newValue, 0, 0); } }; addAction(frame, action); show(frame); } /** * Trying to make null biggest value. * * Can't do - nulls don't reach the comparator. */ public void interactiveSortWithNull() { JXTable table = new JXTable(createAscendingModel(1, 20)); for (int i = 0; i < table.getRowCount(); i+=2) { table.setValueAt(null, i, 0); } Comparator<?> comparator = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { if (o1 == null) { if (o2 == null) return 0; return 1; } if (o2 == null) { return -1; } return ((Integer) o1).compareTo((Integer) o2); } }; table.getColumnExt(0).setComparator(comparator); showWithScrollingInFrame(table, "nulls"); } /** * Quick check of sort order cycle (including pathologicals) */ public void interactiveSortOrderCycle() { final JXTable table = new JXTable(new AncientSwingTeam()); JXFrame frame = wrapWithScrollingInFrame(table, new JTable(table.getModel()), "sort cycles"); Action three = new AbstractAction("three-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED); } }; addAction(frame, three); Action two = new AbstractAction("two-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING); } }; addAction(frame, two); Action one = new AbstractAction("one-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(SortOrder.DESCENDING); } }; addAction(frame, one); Action none = new AbstractAction("empty-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(); } }; addAction(frame, none); show(frame); } public void interactiveMultiColumnSort() { DefaultTableModel model = createMultiSortModel(); JXTable table = new JXTable(model); table.setVisibleRowCount(model.getRowCount()); JXFrame frame = wrapWithScrollingInFrame(table, "multi-column-sort"); final DefaultSortController<?> rowSorter = (DefaultSortController<?>) table.getRowSorter(); final List<SortKey> sortKeys = new ArrayList<SortKey>(); for (int i = 0; i < rowSorter.getMaxSortKeys(); i++) { sortKeys.add(new SortKey(i, SortOrder.ASCENDING)); } Action setSortKeys = new AbstractAction("sortKeys") { @Override public void actionPerformed(ActionEvent e) { rowSorter.setSortKeys(sortKeys); } }; addAction(frame, setSortKeys); Action reset = new AbstractAction("resetSort") { @Override public void actionPerformed(ActionEvent e) { rowSorter.setSortKeys(null); } }; rowSorter.setSortable(0, false); addAction(frame, reset); show(frame); } /** * @return */ private DefaultTableModel createMultiSortModel() { String[] first = { "animal", "plant" }; String[] second = {"insect", "mammal", "spider" }; String[] third = {"red", "green", "yellow", "blue" }; Integer[] age = { 1, 5, 12, 20, 100 }; Object[][] rows = new Object[][] { first, second, third, age }; DefaultTableModel model = new DefaultTableModel(20, 4) { @Override public Class<?> getColumnClass(int columnIndex) { return columnIndex == getColumnCount() - 1 ? Integer.class : super.getColumnClass(columnIndex); } }; for (int i = 0; i < rows.length; i++) { setValues(model, rows[i], i); } return model; } /** * @param model * @param first * @param i */ private void setValues(DefaultTableModel model, Object[] first, int column) { Random seed = new Random(); for (int row = 0; row < model.getRowCount(); row++) { int random = seed.nextInt(first.length); model.setValueAt(first[random], row, column); } } /** * Issue #908-swingx: move updateUI responsibility into column. * */ public void interactiveUpdateUIEditors() { DefaultTableModel model = new DefaultTableModel(5, 5) { @Override public Class<?> getColumnClass(int columnIndex) { if (getValueAt(0, columnIndex) == null) return super.getColumnClass(columnIndex); return getValueAt(0, columnIndex).getClass(); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Date(), i, 0); model.setValueAt(true, i, 1); } JXTable table = new JXTable(model); TableCellEditor editor = new DatePickerCellEditor(); table.getColumn(0).setCellEditor(editor); table.getColumn(4).setCellRenderer(new DefaultTableRenderer(new CheckBoxProvider())); showWithScrollingInFrame(table, "toggle ui - must update editors/renderers"); } /** * Issue #550-swingx: xtable must not reset columns' pref/size on * structureChanged if autocreate is false. * * */ public void interactiveColumnWidthOnStructureChanged() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setAutoCreateColumnsFromModel(false); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); table.setColumnControlVisible(true); // min/max is respected // mini.setMaxWidth(5); // mini.setMinWidth(5); Action structureChanged = new AbstractAction("fire structure changed") { public void actionPerformed(ActionEvent e) { table.tableChanged(null); } }; JXFrame frame = showWithScrollingInFrame(table, "structure change must not re-size columns"); addAction(frame, structureChanged); show(frame); } /** * Issue #675-swingx: esc doesn't reach rootpane. * * Verify that the escape is intercepted only if editing. * BUT: (core behaviour) starts editing in table processKeyBinding. So every * second is not passed on. */ public void interactiveDialogCancelOnEscape() { Action cancel = new AbstractActionExt("cancel") { public void actionPerformed(ActionEvent e) { LOG.info("performed: cancel action"); } }; final JButton field = new JButton(cancel); JXTable xTable = new JXTable(10, 3); JTable table = new JTable(xTable.getModel()); JXFrame frame = wrapWithScrollingInFrame(xTable, table, "escape passed to rootpane (if editing)"); frame.setCancelButton(field); frame.add(field, BorderLayout.SOUTH); frame.setVisible(true); } /** * Issue #508/547-swingx: clean up of pref scrollable. * Visual check: column init on model change. * */ public void interactivePrefScrollable() { final DefaultTableModel tableModel = new DefaultTableModel(30, 7); final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JXFrame frame = showWithScrollingInFrame(table, "initial sizing"); addMessage(frame, "initial size: " + table.getPreferredScrollableViewportSize()); Action action = new AbstractActionExt("toggle model") { public void actionPerformed(ActionEvent e) { table.setModel(table.getModel() == tableModel ? ancientSwingTeam : tableModel); frame.pack(); } }; addAction(frame, action); frame.pack(); } /** * Issue #508/547-swingx: clean up of pref scrollable. * Visual check: dynamic logical scroll sizes * Toggle visual row/column count. */ public void interactivePrefScrollableDynamic() { final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(ancientSwingTeam); table.setColumnControlVisible(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JXFrame frame = wrapWithScrollingInFrame(table, "Dynamic pref scrollable"); Action action = new AbstractActionExt("vis row") { public void actionPerformed(ActionEvent e) { int visRowCount = table.getVisibleRowCount() + 5; if (visRowCount > 30) { visRowCount = 10; } table.setVisibleRowCount(visRowCount); frame.pack(); } }; addAction(frame, action); Action columnAction = new AbstractActionExt("vis column") { public void actionPerformed(ActionEvent e) { int visColumnCount = table.getVisibleColumnCount(); if (visColumnCount > 8) { visColumnCount = -1; } else if (visColumnCount < 0 ) { visColumnCount = 2; } else { visColumnCount += 2; } table.setVisibleColumnCount(visColumnCount); frame.pack(); } }; addAction(frame, columnAction); frame.setVisible(true); frame.pack(); } /** * Issue #417-swingx: disable default find. * * Possible alternative to introducing disable api as suggested in the * issue report: disable the action? Move the action up the hierarchy to * the parent actionmap? Maybe JX specific parent? * */ public void interactiveDisableFind() { final JXTable table = new JXTable(sortableTableModel); Action findAction = new AbstractActionExt() { public void actionPerformed(ActionEvent e) { SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); } @Override public boolean isEnabled() { return false; } }; table.getActionMap().put("find", findAction); showWithScrollingInFrame(table, "disable finding"); } /** * visually check if we can bind the CCB's action to a keystroke. * * Working, but there's a visual glitch if opened by keystroke: * the popup is not trailing aligned to the CCB. And the * CCB must be visible, otherwise there's an IllegalStateException * because the popup tries to position itself relative to the CCB. * */ public void interactiveKeybindingColumnControl() { JXTable table = new JXTable(sortableTableModel); // JW: currently the CCB must be visible // table.setColumnControlVisible(true); Action openCCPopup = ((AbstractButton) table.getColumnControl()).getAction(); String actionKey = "popupColumnControl"; table.getActionMap().put(actionKey, openCCPopup); KeyStroke keyStroke = KeyStroke.getKeyStroke("F2"); table.getInputMap(JXTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, actionKey); showWithScrollingInFrame(table, "Press F2 to open column control"); } /** * calculate reasonable table rowHeight withouth "white pixel" in editor. * Compare table and xtable */ public void interactiveCompareRowHeight() { JXTable xtable = new JXTable(sortableTableModel); xtable.setShowGrid(false, false); JTable table = new JTable(sortableTableModel); table.setShowHorizontalLines(false); table.setShowVerticalLines(false); table.setRowMargin(0); table.getColumnModel().setColumnMargin(0); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "compare default rowheight of xtable vs. table"); frame.setVisible(true); } /** * visually check if terminateEditOnFocusLost, autoStartEdit * work as expected. * */ public void interactiveToggleEditProperties() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, new JButton("something to focus"), "JXTable: toggle terminate/autoStart on left (right is dummy) "); Action toggleTerminate = new AbstractAction("toggleTerminate") { public void actionPerformed(ActionEvent e) { table.setTerminateEditOnFocusLost(!table.isTerminateEditOnFocusLost()); } }; addAction(frame, toggleTerminate); Action toggleAutoStart = new AbstractAction("toggleAutoStart") { public void actionPerformed(ActionEvent e) { table.setAutoStartEditOnKeyStroke(!table.isAutoStartEditOnKeyStroke()); } }; addAction(frame, toggleAutoStart); frame.setVisible(true); } /** * Expose sorted column. * Example how to guarantee one column sorted at all times. */ public void interactiveAlwaysSorted() { final JXTable table = new JXTable(sortableTableModel) { @Override public void columnRemoved(TableColumnModelEvent e) { super.columnRemoved(e); if (!hasVisibleSortedColumn()) { toggleSortOrder(0); } } private boolean hasVisibleSortedColumn() { TableColumn column = getSortedColumn(); if (column instanceof TableColumnExt) { return ((TableColumnExt) column).isVisible(); } // JW: this path is not tested, don't really expect // non-ext column types, though JXTable must // cope with them return column != null; } }; table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "Always sorted"); frame.setVisible(true); } /** * Issue #282-swingx: compare disabled appearance of * collection views. * * Issue #1374-swingx: rollover effects on disabled collection views * */ public void interactiveDisabledCollectionViews() { final JXTable table = new JXTable(new AncientSwingTeam()); AbstractHyperlinkAction<Object> hyperlink = new AbstractHyperlinkAction<Object>() { @Override public void actionPerformed(ActionEvent e) { LOG.info("pressed link"); } }; table.getColumnExt(0).setCellRenderer(new DefaultTableRenderer(new HyperlinkProvider(hyperlink))); table.getColumnExt(0).setEditable(false); table.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.MAGENTA, null)); table.setEnabled(false); final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); list.setEnabled(false); list.setToolTipText("myText ... showing when disnabled?"); final JXTree tree = new JXTree(new FileSystemModel()); tree.setEnabled(false); JComponent box = Box.createHorizontalBox(); box.add(new JScrollPane(table)); box.add(new JScrollPane(list)); box.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(box, "disabled collection views"); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); list.setEnabled(!list.isEnabled()); tree.setEnabled(!tree.isEnabled()); } }; addAction(frame, action); JLabel label = new JLabel("disable label"); label.setEnabled(false); label.setToolTipText("tooltip of disabled label"); addStatusComponent(frame, label); show(frame); } /** * Issue #281-swingx: header should be auto-repainted on changes to * header title, value. * * */ public void interactiveUpdateHeader() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { int count; public void actionPerformed(ActionEvent e) { table.getColumn(0).setHeaderValue("A" + count++); } }; addAction(frame, action); action = new AbstractAction("update column title") { int count; public void actionPerformed(ActionEvent e) { table.getColumnExt(0).setTitle("A" + count++); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #281-swingx, Issue #334-swing: * header should be auto-repainted on changes to * header title, value. Must update size if appropriate. * * still open: core #4292511 - autowrap not really working * */ public void interactiveUpdateHeaderAndSizeRequirements() { final String[] alternate = { "simple", // "<html><b>This is a test of a large label to see if it wraps </font></b>", // "simple", "<html><center>Line 1<br>Line 2</center></html>" }; final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { boolean first; public void actionPerformed(ActionEvent e) { table.getColumn(1).setHeaderValue(first ? alternate[0] : alternate[1]); first = !first; } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #??-swingx: column auto-sizing support. * */ public void interactiveTestExpandsToViewportWidth() { final JXTable table = new JXTable(); ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); if (model.getColumnClass(columnExt.getModelIndex()) == Integer.class) { // to see the effect: excess width is distributed relative // to the difference between maxSize and prefSize columnExt.setMaxWidth(200); } else { columnExt.setMaxWidth(1024); } } }; table.setColumnFactory(factory); table.setColumnControlVisible(true); table.setModel(sortableTableModel); table.setHorizontalScrollEnabled(true); table.packAll(); JXFrame frame = wrapWithScrollingInFrame(table, "expand to width"); Action toggleModel = new AbstractAction("toggle model") { public void actionPerformed(ActionEvent e) { table.setModel(table.getModel() == sortableTableModel ? new DefaultTableModel(20, 4) : sortableTableModel); } }; addAction(frame, toggleModel); frame.setSize(table.getPreferredSize().width - 50, 300); frame.setVisible(true); LOG.info("table: " + table.getWidth()); LOG.info("Viewport: " + table.getParent().getWidth()); } /** * Issue ??: Anchor lost after receiving a structure changed. * Lead/anchor no longer automatically initialized - no visual clue * if table is focused. * */ public void interactiveTestToggleTableModelU6() { final DefaultTableModel tableModel = createAscendingModel(0, 20); final JTable table = new JTable(tableModel); // JW: need to explicitly set _both_ anchor and lead to >= 0 // need to set anchor first table.getSelectionModel().setAnchorSelectionIndex(0); table.getSelectionModel().setLeadSelectionIndex(0); table.getColumnModel().getSelectionModel().setAnchorSelectionIndex(0); table.getColumnModel().getSelectionModel().setLeadSelectionIndex(0); Action toggleAction = new AbstractAction("Toggle TableModel") { public void actionPerformed(ActionEvent e) { TableModel model = table.getModel(); table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel); } }; JXFrame frame = wrapWithScrollingInFrame(table, "JTable - anchor lost after structure changed"); addAction(frame, toggleAction); frame.setVisible(true); frame.pack(); SwingUtilities.invokeLater(new Runnable() { public void run() { // sanity - focus is on table LOG.info("isFocused? " + table.hasFocus()); LOG.info("who has focus? " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()); } }); } /** * Issue #186-swingxProblem with lead/selection and buttons as editors: * - move focus (using arrow keys) to first editable boolean * - press space to toggle boolean * - move focus to next row (same column) * - press space to toggle boolean * - move back to first row (same column) * - press space: boolean is toggled and (that's the problem) * lead selection is moved to next row. * No problem in JTable. * */ public void interactiveTestCompareTableBoolean() { JXTable xtable = new JXTable(createModelWithBooleans()); JTable table = new JTable(createModelWithBooleans()); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "Compare boolean renderer JXTable <--> JTable"); frame.setVisible(true); } private TableModel createModelWithBooleans() { String[] columnNames = { "text only", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { model.addRow(new Object[] {"text only " + i, Boolean.TRUE, Boolean.TRUE }); } return model; } /** * Issue #89-swingx: ColumnControl not updated with ComponentOrientation. * */ public void interactiveRToLTableWithColumnControl() { final JXTable table = new JXTable(createAscendingModel(0, 20)); JScrollPane pane = new JScrollPane(table); final JXFrame frame = wrapInFrame(pane, "RToLScrollPane"); addComponentOrientationToggle(frame); Action toggleColumnControl = new AbstractAction("toggle column control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; addAction(frame, toggleColumnControl); frame.setVisible(true); } /** * Issue #179: Sorter does not use collator if cell content is * a String. * */ public void interactiveTestLocaleSorter() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "aa" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); // { // public Class getColumnClass(int column) { // return column == 1 ? String.class : super.getColumnClass(column); // } // }; final JXTable table = new JXTable(model); table.toggleSortOrder(1); JFrame frame = wrapWithScrollingInFrame(table, "locale sorting"); frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicyAlways() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // initial state of column control visibility doesn't seem to matter // table.setColumnControlVisible(true); final JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); final JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy - always"); addAction(frame, toggleAction); Action packAction = new AbstractAction("Pack frame") { public void actionPerformed(ActionEvent e) { frame.remove(scrollPane1); frame.add(scrollPane1); } }; addAction(frame, packAction); frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicyNever() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // initial state of column control visibility doesn't seem to matter // table.setColumnControlVisible(true); final JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); final JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy - never"); addAction(frame, toggleAction); Action packAction = new AbstractAction("Pack frame") { public void actionPerformed(ActionEvent e) { frame.remove(scrollPane1); frame.add(scrollPane1); } }; addAction(frame, packAction); frame.setVisible(true); } /** * Issue #11: Column control not showing with few rows. * */ public void interactiveTestColumnControlFewRows() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl with few rows"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour outside scrollPane * */ public void interactiveTestColumnControlWithoutScrollPane() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; toggleAction.putValue(Action.SHORT_DESCRIPTION, "does nothing visible - no scrollpane"); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapInFrame(table, "JXTable: Toggle ColumnControl outside ScrollPane"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour of moving into/out of scrollpane. * */ public void interactiveTestToggleScrollPaneWithColumnControlOn() { final JXTable table = new JXTable(); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(table, "JXTable: Toggle ScrollPane with Columncontrol on"); Action toggleAction = new AbstractAction("Toggle ScrollPane") { public void actionPerformed(ActionEvent e) { Container parent = table.getParent(); boolean inScrollPane = parent instanceof JViewport; if (inScrollPane) { JScrollPane scrollPane = (JScrollPane) table.getParent().getParent(); frame.getContentPane().remove(scrollPane); frame.getContentPane().add(table); } else { parent.remove(table); parent.add(new JScrollPane(table)); } frame.pack(); } }; addAction(frame, toggleAction); frame.setVisible(true); } /** * TableColumnExt: user friendly resizable * */ public void interactiveTestColumnResizable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); final TableColumnExt priorityColumn = table.getColumnExt("First Name"); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable: Column with Min=Max not resizable"); Action action = new AbstractAction("Toggle MinMax of FirstName") { public void actionPerformed(ActionEvent e) { // user-friendly resizable flag if (priorityColumn.getMinWidth() == priorityColumn.getMaxWidth()) { priorityColumn.setMinWidth(50); priorityColumn.setMaxWidth(150); } else { priorityColumn.setMinWidth(100); priorityColumn.setMaxWidth(100); } } }; addAction(frame, action); frame.setVisible(true); } /** */ public void interactiveTestToggleSortable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); Action toggleSortableAction = new AbstractAction("Toggle Sortable") { public void actionPerformed(ActionEvent e) { table.setSortable(!table.isSortable()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ToggleSortingEnabled Test"); addAction(frame, toggleSortableAction); frame.setVisible(true); } public void interactiveTestTableSizing1() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); installLinkRenderer(table); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumnExt columns[] = new TableColumnExt[tableModel.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = new TableColumnExt(i); table.addColumn(columns[i]); } columns[0].setPrototypeValue(new Integer(0)); columns[1].setPrototypeValue("Simple String Value"); columns[2].setPrototypeValue(new Integer(1000)); columns[3].setPrototypeValue(Boolean.TRUE); columns[4].setPrototypeValue(new Date(100)); columns[5].setPrototypeValue(new Float(1.5)); columns[6].setPrototypeValue(new LinkModel("Sun Micro", "_blank", tableModel.linkURL)); columns[7].setPrototypeValue(new Integer(3023)); columns[8].setPrototypeValue("John Doh"); columns[9].setPrototypeValue("23434 Testcase St"); columns[10].setPrototypeValue(new Integer(33333)); columns[11].setPrototypeValue(Boolean.FALSE); table.setVisibleRowCount(12); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing1 Test"); frame.setVisible(true); } private void installLinkRenderer(JXTable table) { LinkModelAction<?> action = new LinkModelAction<LinkModel>() { @Override public void actionPerformed(ActionEvent e) { LOG.info("activated link: " + getTarget()); } }; TableCellRenderer linkRenderer = new DefaultTableRenderer( new HyperlinkProvider(action, LinkModel.class)); table.setDefaultRenderer(LinkModel.class, linkRenderer); } public void interactiveTestEmptyTableSizing() { JXTable table = new JXTable(0, 5); table.setColumnControlVisible(true); JFrame frame = wrapWithScrollingInFrame(table, "Empty Table (0 rows)"); frame.setVisible(true); } public void interactiveTestTableSizing2() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); installLinkRenderer(table); TableColumnExt columns[] = new TableColumnExt[6]; int viewIndex = 0; for (int i = columns.length - 1; i >= 0; i--) { columns[viewIndex] = new TableColumnExt(i); table.addColumn(columns[viewIndex++]); } columns[5].setHeaderValue("String Value"); columns[5].setPrototypeValue("9999"); columns[4].setHeaderValue("String Value"); columns[4].setPrototypeValue("Simple String Value"); columns[3].setHeaderValue("Int Value"); columns[3].setPrototypeValue(new Integer(1000)); columns[2].setHeaderValue("Bool"); columns[2].setPrototypeValue(Boolean.FALSE); //columns[2].setSortable(false); columns[1].setHeaderValue("Date"); columns[1].setPrototypeValue(new Date(0)); //columns[1].setSortable(false); columns[0].setHeaderValue("Float"); columns[0].setPrototypeValue(new Float(5.5)); table.setRowHeight(24); table.setRowMargin(2); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing2 Test"); frame.setVisible(true); } public void interactiveTestFocusedCellBackground() { TableModel model = new AncientSwingTeam() { @Override public boolean isCellEditable(int row, int column) { return column != 0; } }; JXTable xtable = new JXTable(model); xtable.setBackground(HighlighterFactory.NOTEPAD); JTable table = new JTable(model); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger JFrame frame = wrapWithScrollingInFrame(xtable, table, "Unselected focused background: JXTable/JTable"); frame.setVisible(true); } public void interactiveTestTableViewProperties() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setIntercellSpacing(new Dimension(15, 15)); table.setRowHeight(48); JFrame frame = wrapWithScrollingInFrame(table, "TableViewProperties Test"); frame.setVisible(true); } public void interactiveColumnHighlighting() { final JXTable table = new JXTable(new AncientSwingTeam()); table.getColumnExt("Favorite Color").setHighlighters(new AbstractHighlighter() { @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { Color color = (Color) adapter.getValue(); if (renderer instanceof JComponent) { ((JComponent) renderer).setBorder(BorderFactory.createLineBorder(color)); } return renderer; } }); JFrame frame = wrapWithScrollingInFrame(table, "Column Highlighter Test"); JToolBar bar = new JToolBar(); bar.add(new AbstractAction("Toggle") { boolean state = false; public void actionPerformed(ActionEvent e) { if (state) { table.getColumnExt("No.").setHighlighters(new Highlighter[0]); state = false; } else { table.getColumnExt("No.").addHighlighter( new AbstractHighlighter(new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return adapter.getValue().toString().contains("8"); } }) { @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { Font f = renderer.getFont().deriveFont(Font.ITALIC); renderer.setFont(f); return renderer; } } ); state = true; } } }); frame.add(bar, BorderLayout.NORTH); frame.setVisible(true); } /** * dummy */ @Test public void testDummy() { } }
swingx-core/src/test/java/org/jdesktop/swingx/JXTableVisualCheck.java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Random; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.RowFilter; import javax.swing.SortOrder; import javax.swing.SwingUtilities; import javax.swing.RowSorter.SortKey; import javax.swing.event.RowSorterEvent; import javax.swing.event.RowSorterListener; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.RowSorterEvent.Type; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.search.SearchFactory; import org.jdesktop.swingx.sort.DefaultSortController; import org.jdesktop.swingx.sort.SortUtils; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.DatePickerCellEditor; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; import org.junit.Test; /** * Split from old JXTableUnitTest - contains "interactive" * methods only. <p> * * PENDING: too many frames to fit all on screen - either split into different * tests or change positioning algo to start on top again if hidden. <p> * @author Jeanette Winzenburg */ public class JXTableVisualCheck extends JXTableUnitTest { private static final Logger LOG = Logger.getLogger(JXTableVisualCheck.class .getName()); public static void main(String args[]) { JXTableVisualCheck test = new JXTableVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*FloatingPoint.*"); // test.runInteractiveTests("interactive.*Disable.*"); test.runInteractiveTests("interactive.*Remove.*"); // test.runInteractiveTests("interactive.*ColumnProp.*"); // test.runInteractiveTests("interactive.*Multiple.*"); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Scrollable.*"); // test.runInteractiveTests("interactive.*isable.*"); // test.runInteractiveTests("interactive.*Policy.*"); // test.runInteractiveTests("interactive.*Rollover.*"); // test.runInteractiveTests("interactive.*Revalidate.*"); // test.runInteractiveTests("interactive.*UpdateUI.*"); // test.runInteractiveTests("interactiveColumnHighlighting"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { super.setUp(); // super has LF specific tests... setSystemLF(true); // setLookAndFeel("Nimbus"); } /** * Issue #1195-swingx: keep selection on remove * Basically, this is a core issue - fixed in DefaultSortController during * last cleanup round. * */ public void interactiveRemoveAndSelected() { final JXTable table = new JXTable(10, 5); JXFrame frame = wrapWithScrollingInFrame(table, "Issue #1195-swingx - keep selection on remove"); Action action = new AbstractAction("remove row before selected") { @Override public void actionPerformed(ActionEvent e) { int selected = table.getSelectedRow(); if (selected < 1) return; ((DefaultTableModel) table.getModel()).removeRow(selected - 1); } }; addAction(frame, action); show(frame); } /** * Issue #35-swingx: visual indicators of secondary sort columns * * Trick by David Hall: use unicode char * http://forums.java.net/jive/thread.jspa?threadID=71090 * * As he already noted: it's not necessarily pretty looking ;-) */ public void interactiveHeaderSecondarySortIndicator() { DefaultTableModel model = new DefaultTableModel(0, 3) { /** * @inherited <p> */ @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex < getColumnCount() - 1) { return Integer.class; } return super.getColumnClass(columnIndex); } }; int min = hexToInt("25A0"); int max = hexToInt("25FF"); for (int i = min; i <= max; i++) { Object[] row = new Object[3]; row[0] = i; row[1] = i; row[2] = (char) i + ""; model.addRow(row); } final JXTable table = new JXTable(); ColumnFactory factory = new ColumnFactory() { /** * @inherited <p> */ @Override public TableColumnExt createTableColumn(int modelIndex) { // TODO Auto-generated method stub TableColumnExt tableColumn = new SortAwareTableColumnExt(); tableColumn.setModelIndex(modelIndex); return tableColumn; } }; table.setColumnControlVisible(true); table.setColumnFactory(factory); table.setModel(model); RowSorterListener l = new RowSorterListener() { @SuppressWarnings("unchecked") @Override public void sorterChanged(RowSorterEvent e) { if (e.getType() == Type.SORT_ORDER_CHANGED) { List<TableColumn> list = table.getColumns(true); List<? extends SortKey> sortKeys = new ArrayList<SortKey>(e.getSource().getSortKeys()); // remove primary List<? extends SortKey> secondary = sortKeys.subList(1, sortKeys.size()); for (TableColumn tableColumn : list) { if (tableColumn instanceof TableColumnExt) { SortKey key = SortUtils.getFirstSortKeyForColumn(secondary, tableColumn.getModelIndex()); Object property = null; if (key != null && SortUtils.isSorted(key.getSortOrder())) { property = key.getSortOrder(); } ((TableColumnExt) tableColumn).putClientProperty(SortAwareTableColumnExt.SORT_ORDER_KEY, property); } } } } }; table.getRowSorter().addRowSorterListener(l); StringValue sv = new StringValue() { @Override public String getString(Object value) { return Integer.toHexString(((Integer) value).intValue()); } }; table.getColumn(1).setCellRenderer(new DefaultTableRenderer(sv, JLabel.RIGHT)); JXFrame frame = showWithScrollingInFrame(table, "Geometric shapes"); addComponentOrientationToggle(frame); } public static class SortAwareTableColumnExt extends TableColumnExt { public final static String DESCENDING_CHAR = " \u25bf"; public final static String ASCENDING_CHAR = " \u25b5"; public final static String SORT_ORDER_KEY = "columnExt.SortOrder"; /** * @inherited <p> */ @Override public Object getHeaderValue() { Object header = super.getHeaderValue(); Object sortOrder = getClientProperty(SORT_ORDER_KEY); if (SortOrder.ASCENDING == sortOrder) { header = header + ASCENDING_CHAR; } else if (SortOrder.DESCENDING == sortOrder){ header = header + DESCENDING_CHAR; } return header; } } private int hexToInt(String s) { return Integer.parseInt(s, 16); } /** * Issue #1254-swingx: JXTable not revalidated on update if filter. * * Core JTable issue * Problem is that the update might change the visible row count. */ public void interactiveRevalidateOnUpdateWithFilter() { String data[][] = { { "satuAA", "Satu", "SATU", "1" }, { "duaAAB", "Dua", "DUA", "2" }, { "tigaBAA", "Tiga", "TIGA", "3" }, { "empatBBA", "Empat", "EMPAT", "4" } }; String cols[] = { "col1", "col2", "col3", "col4" }; final JXTable table = new JXTable(data, cols); RowFilter<TableModel, Integer> tm = RowFilter.regexFilter( ".*AA.*", 0); table.setRowFilter(tm); JXFrame frame = wrapWithScrollingInFrame(table, "Update with RowFilter"); Action action = new AbstractAction("filter first row") { boolean hasAA = true; @Override public void actionPerformed(ActionEvent e) { String newValue = hasAA ? "BB" : "AA"; hasAA = !hasAA; table.getModel().setValueAt(newValue, 0, 0); } }; addAction(frame, action); show(frame); } /** * Trying to make null biggest value. * * Can't do - nulls don't reach the comparator. */ public void interactiveSortWithNull() { JXTable table = new JXTable(createAscendingModel(1, 20)); for (int i = 0; i < table.getRowCount(); i+=2) { table.setValueAt(null, i, 0); } Comparator<?> comparator = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { if (o1 == null) { if (o2 == null) return 0; return 1; } if (o2 == null) { return -1; } return ((Integer) o1).compareTo((Integer) o2); } }; table.getColumnExt(0).setComparator(comparator); showWithScrollingInFrame(table, "nulls"); } /** * Quick check of sort order cycle (including pathologicals) */ public void interactiveSortOrderCycle() { final JXTable table = new JXTable(new AncientSwingTeam()); JXFrame frame = wrapWithScrollingInFrame(table, new JTable(table.getModel()), "sort cycles"); Action three = new AbstractAction("three-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED); } }; addAction(frame, three); Action two = new AbstractAction("two-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING); } }; addAction(frame, two); Action one = new AbstractAction("one-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(SortOrder.DESCENDING); } }; addAction(frame, one); Action none = new AbstractAction("empty-cylce") { @Override public void actionPerformed(ActionEvent e) { table.setSortOrderCycle(); } }; addAction(frame, none); show(frame); } public void interactiveMultiColumnSort() { DefaultTableModel model = createMultiSortModel(); JXTable table = new JXTable(model); table.setVisibleRowCount(model.getRowCount()); JXFrame frame = wrapWithScrollingInFrame(table, "multi-column-sort"); final DefaultSortController<?> rowSorter = (DefaultSortController<?>) table.getRowSorter(); final List<SortKey> sortKeys = new ArrayList<SortKey>(); for (int i = 0; i < rowSorter.getMaxSortKeys(); i++) { sortKeys.add(new SortKey(i, SortOrder.ASCENDING)); } Action setSortKeys = new AbstractAction("sortKeys") { @Override public void actionPerformed(ActionEvent e) { rowSorter.setSortKeys(sortKeys); } }; addAction(frame, setSortKeys); Action reset = new AbstractAction("resetSort") { @Override public void actionPerformed(ActionEvent e) { rowSorter.setSortKeys(null); } }; rowSorter.setSortable(0, false); addAction(frame, reset); show(frame); } /** * @return */ private DefaultTableModel createMultiSortModel() { String[] first = { "animal", "plant" }; String[] second = {"insect", "mammal", "spider" }; String[] third = {"red", "green", "yellow", "blue" }; Integer[] age = { 1, 5, 12, 20, 100 }; Object[][] rows = new Object[][] { first, second, third, age }; DefaultTableModel model = new DefaultTableModel(20, 4) { @Override public Class<?> getColumnClass(int columnIndex) { return columnIndex == getColumnCount() - 1 ? Integer.class : super.getColumnClass(columnIndex); } }; for (int i = 0; i < rows.length; i++) { setValues(model, rows[i], i); } return model; } /** * @param model * @param first * @param i */ private void setValues(DefaultTableModel model, Object[] first, int column) { Random seed = new Random(); for (int row = 0; row < model.getRowCount(); row++) { int random = seed.nextInt(first.length); model.setValueAt(first[random], row, column); } } /** * Issue #908-swingx: move updateUI responsibility into column. * */ public void interactiveUpdateUIEditors() { DefaultTableModel model = new DefaultTableModel(5, 5) { @Override public Class<?> getColumnClass(int columnIndex) { if (getValueAt(0, columnIndex) == null) return super.getColumnClass(columnIndex); return getValueAt(0, columnIndex).getClass(); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Date(), i, 0); model.setValueAt(true, i, 1); } JXTable table = new JXTable(model); TableCellEditor editor = new DatePickerCellEditor(); table.getColumn(0).setCellEditor(editor); table.getColumn(4).setCellRenderer(new DefaultTableRenderer(new CheckBoxProvider())); showWithScrollingInFrame(table, "toggle ui - must update editors/renderers"); } /** * Issue #550-swingx: xtable must not reset columns' pref/size on * structureChanged if autocreate is false. * * */ public void interactiveColumnWidthOnStructureChanged() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setAutoCreateColumnsFromModel(false); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); table.setColumnControlVisible(true); // min/max is respected // mini.setMaxWidth(5); // mini.setMinWidth(5); Action structureChanged = new AbstractAction("fire structure changed") { public void actionPerformed(ActionEvent e) { table.tableChanged(null); } }; JXFrame frame = showWithScrollingInFrame(table, "structure change must not re-size columns"); addAction(frame, structureChanged); show(frame); } /** * Issue #675-swingx: esc doesn't reach rootpane. * * Verify that the escape is intercepted only if editing. * BUT: (core behaviour) starts editing in table processKeyBinding. So every * second is not passed on. */ public void interactiveDialogCancelOnEscape() { Action cancel = new AbstractActionExt("cancel") { public void actionPerformed(ActionEvent e) { LOG.info("performed: cancel action"); } }; final JButton field = new JButton(cancel); JXTable xTable = new JXTable(10, 3); JTable table = new JTable(xTable.getModel()); JXFrame frame = wrapWithScrollingInFrame(xTable, table, "escape passed to rootpane (if editing)"); frame.setCancelButton(field); frame.add(field, BorderLayout.SOUTH); frame.setVisible(true); } /** * Issue #508/547-swingx: clean up of pref scrollable. * Visual check: column init on model change. * */ public void interactivePrefScrollable() { final DefaultTableModel tableModel = new DefaultTableModel(30, 7); final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JXFrame frame = showWithScrollingInFrame(table, "initial sizing"); addMessage(frame, "initial size: " + table.getPreferredScrollableViewportSize()); Action action = new AbstractActionExt("toggle model") { public void actionPerformed(ActionEvent e) { table.setModel(table.getModel() == tableModel ? ancientSwingTeam : tableModel); frame.pack(); } }; addAction(frame, action); frame.pack(); } /** * Issue #508/547-swingx: clean up of pref scrollable. * Visual check: dynamic logical scroll sizes * Toggle visual row/column count. */ public void interactivePrefScrollableDynamic() { final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(ancientSwingTeam); table.setColumnControlVisible(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JXFrame frame = wrapWithScrollingInFrame(table, "Dynamic pref scrollable"); Action action = new AbstractActionExt("vis row") { public void actionPerformed(ActionEvent e) { int visRowCount = table.getVisibleRowCount() + 5; if (visRowCount > 30) { visRowCount = 10; } table.setVisibleRowCount(visRowCount); frame.pack(); } }; addAction(frame, action); Action columnAction = new AbstractActionExt("vis column") { public void actionPerformed(ActionEvent e) { int visColumnCount = table.getVisibleColumnCount(); if (visColumnCount > 8) { visColumnCount = -1; } else if (visColumnCount < 0 ) { visColumnCount = 2; } else { visColumnCount += 2; } table.setVisibleColumnCount(visColumnCount); frame.pack(); } }; addAction(frame, columnAction); frame.setVisible(true); frame.pack(); } /** * Issue #417-swingx: disable default find. * * Possible alternative to introducing disable api as suggested in the * issue report: disable the action? Move the action up the hierarchy to * the parent actionmap? Maybe JX specific parent? * */ public void interactiveDisableFind() { final JXTable table = new JXTable(sortableTableModel); Action findAction = new AbstractActionExt() { public void actionPerformed(ActionEvent e) { SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); } @Override public boolean isEnabled() { return false; } }; table.getActionMap().put("find", findAction); showWithScrollingInFrame(table, "disable finding"); } /** * visually check if we can bind the CCB's action to a keystroke. * * Working, but there's a visual glitch if opened by keystroke: * the popup is not trailing aligned to the CCB. And the * CCB must be visible, otherwise there's an IllegalStateException * because the popup tries to position itself relative to the CCB. * */ public void interactiveKeybindingColumnControl() { JXTable table = new JXTable(sortableTableModel); // JW: currently the CCB must be visible // table.setColumnControlVisible(true); Action openCCPopup = ((AbstractButton) table.getColumnControl()).getAction(); String actionKey = "popupColumnControl"; table.getActionMap().put(actionKey, openCCPopup); KeyStroke keyStroke = KeyStroke.getKeyStroke("F2"); table.getInputMap(JXTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, actionKey); showWithScrollingInFrame(table, "Press F2 to open column control"); } /** * calculate reasonable table rowHeight withouth "white pixel" in editor. * Compare table and xtable */ public void interactiveCompareRowHeight() { JXTable xtable = new JXTable(sortableTableModel); xtable.setShowGrid(false, false); JTable table = new JTable(sortableTableModel); table.setShowHorizontalLines(false); table.setShowVerticalLines(false); table.setRowMargin(0); table.getColumnModel().setColumnMargin(0); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "compare default rowheight of xtable vs. table"); frame.setVisible(true); } /** * visually check if terminateEditOnFocusLost, autoStartEdit * work as expected. * */ public void interactiveToggleEditProperties() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, new JButton("something to focus"), "JXTable: toggle terminate/autoStart on left (right is dummy) "); Action toggleTerminate = new AbstractAction("toggleTerminate") { public void actionPerformed(ActionEvent e) { table.setTerminateEditOnFocusLost(!table.isTerminateEditOnFocusLost()); } }; addAction(frame, toggleTerminate); Action toggleAutoStart = new AbstractAction("toggleAutoStart") { public void actionPerformed(ActionEvent e) { table.setAutoStartEditOnKeyStroke(!table.isAutoStartEditOnKeyStroke()); } }; addAction(frame, toggleAutoStart); frame.setVisible(true); } /** * Expose sorted column. * Example how to guarantee one column sorted at all times. */ public void interactiveAlwaysSorted() { final JXTable table = new JXTable(sortableTableModel) { @Override public void columnRemoved(TableColumnModelEvent e) { super.columnRemoved(e); if (!hasVisibleSortedColumn()) { toggleSortOrder(0); } } private boolean hasVisibleSortedColumn() { TableColumn column = getSortedColumn(); if (column instanceof TableColumnExt) { return ((TableColumnExt) column).isVisible(); } // JW: this path is not tested, don't really expect // non-ext column types, though JXTable must // cope with them return column != null; } }; table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "Always sorted"); frame.setVisible(true); } /** * Issue #282-swingx: compare disabled appearance of * collection views. * */ public void interactiveDisabledCollectionViews() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setEnabled(false); final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); list.setEnabled(false); final JXTree tree = new JXTree(new FileSystemModel()); tree.setEnabled(false); JComponent box = Box.createHorizontalBox(); box.add(new JScrollPane(table)); box.add(new JScrollPane(list)); box.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(box, "disabled collection views"); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); list.setEnabled(!list.isEnabled()); tree.setEnabled(!tree.isEnabled()); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #281-swingx: header should be auto-repainted on changes to * header title, value. * * */ public void interactiveUpdateHeader() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { int count; public void actionPerformed(ActionEvent e) { table.getColumn(0).setHeaderValue("A" + count++); } }; addAction(frame, action); action = new AbstractAction("update column title") { int count; public void actionPerformed(ActionEvent e) { table.getColumnExt(0).setTitle("A" + count++); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #281-swingx, Issue #334-swing: * header should be auto-repainted on changes to * header title, value. Must update size if appropriate. * * still open: core #4292511 - autowrap not really working * */ public void interactiveUpdateHeaderAndSizeRequirements() { final String[] alternate = { "simple", // "<html><b>This is a test of a large label to see if it wraps </font></b>", // "simple", "<html><center>Line 1<br>Line 2</center></html>" }; final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { boolean first; public void actionPerformed(ActionEvent e) { table.getColumn(1).setHeaderValue(first ? alternate[0] : alternate[1]); first = !first; } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #??-swingx: column auto-sizing support. * */ public void interactiveTestExpandsToViewportWidth() { final JXTable table = new JXTable(); ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); if (model.getColumnClass(columnExt.getModelIndex()) == Integer.class) { // to see the effect: excess width is distributed relative // to the difference between maxSize and prefSize columnExt.setMaxWidth(200); } else { columnExt.setMaxWidth(1024); } } }; table.setColumnFactory(factory); table.setColumnControlVisible(true); table.setModel(sortableTableModel); table.setHorizontalScrollEnabled(true); table.packAll(); JXFrame frame = wrapWithScrollingInFrame(table, "expand to width"); Action toggleModel = new AbstractAction("toggle model") { public void actionPerformed(ActionEvent e) { table.setModel(table.getModel() == sortableTableModel ? new DefaultTableModel(20, 4) : sortableTableModel); } }; addAction(frame, toggleModel); frame.setSize(table.getPreferredSize().width - 50, 300); frame.setVisible(true); LOG.info("table: " + table.getWidth()); LOG.info("Viewport: " + table.getParent().getWidth()); } /** * Issue ??: Anchor lost after receiving a structure changed. * Lead/anchor no longer automatically initialized - no visual clue * if table is focused. * */ public void interactiveTestToggleTableModelU6() { final DefaultTableModel tableModel = createAscendingModel(0, 20); final JTable table = new JTable(tableModel); // JW: need to explicitly set _both_ anchor and lead to >= 0 // need to set anchor first table.getSelectionModel().setAnchorSelectionIndex(0); table.getSelectionModel().setLeadSelectionIndex(0); table.getColumnModel().getSelectionModel().setAnchorSelectionIndex(0); table.getColumnModel().getSelectionModel().setLeadSelectionIndex(0); Action toggleAction = new AbstractAction("Toggle TableModel") { public void actionPerformed(ActionEvent e) { TableModel model = table.getModel(); table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel); } }; JXFrame frame = wrapWithScrollingInFrame(table, "JTable - anchor lost after structure changed"); addAction(frame, toggleAction); frame.setVisible(true); frame.pack(); SwingUtilities.invokeLater(new Runnable() { public void run() { // sanity - focus is on table LOG.info("isFocused? " + table.hasFocus()); LOG.info("who has focus? " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()); } }); } /** * Issue #186-swingxProblem with lead/selection and buttons as editors: * - move focus (using arrow keys) to first editable boolean * - press space to toggle boolean * - move focus to next row (same column) * - press space to toggle boolean * - move back to first row (same column) * - press space: boolean is toggled and (that's the problem) * lead selection is moved to next row. * No problem in JTable. * */ public void interactiveTestCompareTableBoolean() { JXTable xtable = new JXTable(createModelWithBooleans()); JTable table = new JTable(createModelWithBooleans()); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "Compare boolean renderer JXTable <--> JTable"); frame.setVisible(true); } private TableModel createModelWithBooleans() { String[] columnNames = { "text only", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { model.addRow(new Object[] {"text only " + i, Boolean.TRUE, Boolean.TRUE }); } return model; } /** * Issue #89-swingx: ColumnControl not updated with ComponentOrientation. * */ public void interactiveRToLTableWithColumnControl() { final JXTable table = new JXTable(createAscendingModel(0, 20)); JScrollPane pane = new JScrollPane(table); final JXFrame frame = wrapInFrame(pane, "RToLScrollPane"); addComponentOrientationToggle(frame); Action toggleColumnControl = new AbstractAction("toggle column control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; addAction(frame, toggleColumnControl); frame.setVisible(true); } /** * Issue #179: Sorter does not use collator if cell content is * a String. * */ public void interactiveTestLocaleSorter() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "aa" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); // { // public Class getColumnClass(int column) { // return column == 1 ? String.class : super.getColumnClass(column); // } // }; final JXTable table = new JXTable(model); table.toggleSortOrder(1); JFrame frame = wrapWithScrollingInFrame(table, "locale sorting"); frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicyAlways() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // initial state of column control visibility doesn't seem to matter // table.setColumnControlVisible(true); final JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); final JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy - always"); addAction(frame, toggleAction); Action packAction = new AbstractAction("Pack frame") { public void actionPerformed(ActionEvent e) { frame.remove(scrollPane1); frame.add(scrollPane1); } }; addAction(frame, packAction); frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicyNever() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // initial state of column control visibility doesn't seem to matter // table.setColumnControlVisible(true); final JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); final JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy - never"); addAction(frame, toggleAction); Action packAction = new AbstractAction("Pack frame") { public void actionPerformed(ActionEvent e) { frame.remove(scrollPane1); frame.add(scrollPane1); } }; addAction(frame, packAction); frame.setVisible(true); } /** * Issue #11: Column control not showing with few rows. * */ public void interactiveTestColumnControlFewRows() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl with few rows"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour outside scrollPane * */ public void interactiveTestColumnControlWithoutScrollPane() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; toggleAction.putValue(Action.SHORT_DESCRIPTION, "does nothing visible - no scrollpane"); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapInFrame(table, "JXTable: Toggle ColumnControl outside ScrollPane"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour of moving into/out of scrollpane. * */ public void interactiveTestToggleScrollPaneWithColumnControlOn() { final JXTable table = new JXTable(); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(table, "JXTable: Toggle ScrollPane with Columncontrol on"); Action toggleAction = new AbstractAction("Toggle ScrollPane") { public void actionPerformed(ActionEvent e) { Container parent = table.getParent(); boolean inScrollPane = parent instanceof JViewport; if (inScrollPane) { JScrollPane scrollPane = (JScrollPane) table.getParent().getParent(); frame.getContentPane().remove(scrollPane); frame.getContentPane().add(table); } else { parent.remove(table); parent.add(new JScrollPane(table)); } frame.pack(); } }; addAction(frame, toggleAction); frame.setVisible(true); } /** * TableColumnExt: user friendly resizable * */ public void interactiveTestColumnResizable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); final TableColumnExt priorityColumn = table.getColumnExt("First Name"); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable: Column with Min=Max not resizable"); Action action = new AbstractAction("Toggle MinMax of FirstName") { public void actionPerformed(ActionEvent e) { // user-friendly resizable flag if (priorityColumn.getMinWidth() == priorityColumn.getMaxWidth()) { priorityColumn.setMinWidth(50); priorityColumn.setMaxWidth(150); } else { priorityColumn.setMinWidth(100); priorityColumn.setMaxWidth(100); } } }; addAction(frame, action); frame.setVisible(true); } /** */ public void interactiveTestToggleSortable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); Action toggleSortableAction = new AbstractAction("Toggle Sortable") { public void actionPerformed(ActionEvent e) { table.setSortable(!table.isSortable()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ToggleSortingEnabled Test"); addAction(frame, toggleSortableAction); frame.setVisible(true); } public void interactiveTestTableSizing1() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); installLinkRenderer(table); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumnExt columns[] = new TableColumnExt[tableModel.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = new TableColumnExt(i); table.addColumn(columns[i]); } columns[0].setPrototypeValue(new Integer(0)); columns[1].setPrototypeValue("Simple String Value"); columns[2].setPrototypeValue(new Integer(1000)); columns[3].setPrototypeValue(Boolean.TRUE); columns[4].setPrototypeValue(new Date(100)); columns[5].setPrototypeValue(new Float(1.5)); columns[6].setPrototypeValue(new LinkModel("Sun Micro", "_blank", tableModel.linkURL)); columns[7].setPrototypeValue(new Integer(3023)); columns[8].setPrototypeValue("John Doh"); columns[9].setPrototypeValue("23434 Testcase St"); columns[10].setPrototypeValue(new Integer(33333)); columns[11].setPrototypeValue(Boolean.FALSE); table.setVisibleRowCount(12); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing1 Test"); frame.setVisible(true); } private void installLinkRenderer(JXTable table) { LinkModelAction<?> action = new LinkModelAction<LinkModel>() { @Override public void actionPerformed(ActionEvent e) { LOG.info("activated link: " + getTarget()); } }; TableCellRenderer linkRenderer = new DefaultTableRenderer( new HyperlinkProvider(action, LinkModel.class)); table.setDefaultRenderer(LinkModel.class, linkRenderer); } public void interactiveTestEmptyTableSizing() { JXTable table = new JXTable(0, 5); table.setColumnControlVisible(true); JFrame frame = wrapWithScrollingInFrame(table, "Empty Table (0 rows)"); frame.setVisible(true); } public void interactiveTestTableSizing2() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); installLinkRenderer(table); TableColumnExt columns[] = new TableColumnExt[6]; int viewIndex = 0; for (int i = columns.length - 1; i >= 0; i--) { columns[viewIndex] = new TableColumnExt(i); table.addColumn(columns[viewIndex++]); } columns[5].setHeaderValue("String Value"); columns[5].setPrototypeValue("9999"); columns[4].setHeaderValue("String Value"); columns[4].setPrototypeValue("Simple String Value"); columns[3].setHeaderValue("Int Value"); columns[3].setPrototypeValue(new Integer(1000)); columns[2].setHeaderValue("Bool"); columns[2].setPrototypeValue(Boolean.FALSE); //columns[2].setSortable(false); columns[1].setHeaderValue("Date"); columns[1].setPrototypeValue(new Date(0)); //columns[1].setSortable(false); columns[0].setHeaderValue("Float"); columns[0].setPrototypeValue(new Float(5.5)); table.setRowHeight(24); table.setRowMargin(2); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing2 Test"); frame.setVisible(true); } public void interactiveTestFocusedCellBackground() { TableModel model = new AncientSwingTeam() { @Override public boolean isCellEditable(int row, int column) { return column != 0; } }; JXTable xtable = new JXTable(model); xtable.setBackground(HighlighterFactory.NOTEPAD); JTable table = new JTable(model); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger JFrame frame = wrapWithScrollingInFrame(xtable, table, "Unselected focused background: JXTable/JTable"); frame.setVisible(true); } public void interactiveTestTableViewProperties() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setIntercellSpacing(new Dimension(15, 15)); table.setRowHeight(48); JFrame frame = wrapWithScrollingInFrame(table, "TableViewProperties Test"); frame.setVisible(true); } public void interactiveColumnHighlighting() { final JXTable table = new JXTable(new AncientSwingTeam()); table.getColumnExt("Favorite Color").setHighlighters(new AbstractHighlighter() { @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { Color color = (Color) adapter.getValue(); if (renderer instanceof JComponent) { ((JComponent) renderer).setBorder(BorderFactory.createLineBorder(color)); } return renderer; } }); JFrame frame = wrapWithScrollingInFrame(table, "Column Highlighter Test"); JToolBar bar = new JToolBar(); bar.add(new AbstractAction("Toggle") { boolean state = false; public void actionPerformed(ActionEvent e) { if (state) { table.getColumnExt("No.").setHighlighters(new Highlighter[0]); state = false; } else { table.getColumnExt("No.").addHighlighter( new AbstractHighlighter(new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return adapter.getValue().toString().contains("8"); } }) { @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { Font f = renderer.getFont().deriveFont(Font.ITALIC); renderer.setFont(f); return renderer; } } ); state = true; } } }); frame.add(bar, BorderLayout.NORTH); frame.setVisible(true); } /** * dummy */ @Test public void testDummy() { } }
Issue #1374: RolloverProducer fires when table is not enabled updated JXTableVisualCheck to see behaviour
swingx-core/src/test/java/org/jdesktop/swingx/JXTableVisualCheck.java
Issue #1374: RolloverProducer fires when table is not enabled updated JXTableVisualCheck to see behaviour
<ide><path>wingx-core/src/test/java/org/jdesktop/swingx/JXTableVisualCheck.java <ide> <ide> import org.jdesktop.swingx.action.AbstractActionExt; <ide> import org.jdesktop.swingx.decorator.AbstractHighlighter; <add>import org.jdesktop.swingx.decorator.ColorHighlighter; <ide> import org.jdesktop.swingx.decorator.ComponentAdapter; <ide> import org.jdesktop.swingx.decorator.HighlightPredicate; <ide> import org.jdesktop.swingx.decorator.Highlighter; <ide> import org.jdesktop.swingx.decorator.HighlighterFactory; <add>import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; <ide> import org.jdesktop.swingx.hyperlink.LinkModel; <ide> import org.jdesktop.swingx.hyperlink.LinkModelAction; <ide> import org.jdesktop.swingx.renderer.CheckBoxProvider; <ide> try { <ide> // test.runInteractiveTests(); <ide> // test.runInteractiveTests("interactive.*FloatingPoint.*"); <del>// test.runInteractiveTests("interactive.*Disable.*"); <del> test.runInteractiveTests("interactive.*Remove.*"); <add> test.runInteractiveTests("interactive.*Disable.*"); <add>// test.runInteractiveTests("interactive.*Remove.*"); <ide> // test.runInteractiveTests("interactive.*ColumnProp.*"); <ide> // test.runInteractiveTests("interactive.*Multiple.*"); <ide> // test.runInteractiveTests("interactive.*RToL.*"); <ide> /** <ide> * Issue #282-swingx: compare disabled appearance of <ide> * collection views. <add> * <add> * Issue #1374-swingx: rollover effects on disabled collection views <ide> * <ide> */ <ide> public void interactiveDisabledCollectionViews() { <ide> final JXTable table = new JXTable(new AncientSwingTeam()); <add> AbstractHyperlinkAction<Object> hyperlink = new AbstractHyperlinkAction<Object>() { <add> <add> @Override <add> public void actionPerformed(ActionEvent e) { <add> LOG.info("pressed link"); <add> } <add> }; <add> table.getColumnExt(0).setCellRenderer(new DefaultTableRenderer(new HyperlinkProvider(hyperlink))); <add> table.getColumnExt(0).setEditable(false); <add> table.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.MAGENTA, null)); <ide> table.setEnabled(false); <ide> final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); <ide> list.setEnabled(false); <add> list.setToolTipText("myText ... showing when disnabled?"); <ide> final JXTree tree = new JXTree(new FileSystemModel()); <ide> tree.setEnabled(false); <ide> JComponent box = Box.createHorizontalBox(); <ide> <ide> }; <ide> addAction(frame, action); <del> frame.setVisible(true); <del> <add> JLabel label = new JLabel("disable label"); <add> label.setEnabled(false); <add> label.setToolTipText("tooltip of disabled label"); <add> addStatusComponent(frame, label); <add> show(frame); <ide> } <ide> <ide> /**
Java
mit
58cc5584345c05a1efef3f64c0b4cc9a4347cffe
0
grobmeier/postmark4j
// The MIT License // // Copyright (c) 2010 Jared Holdcroft // // 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 de.grobmeier.postmark; import java.util.*; /** * Postmark for Java * <p/> * This library can be used to leverage the postmarkapp.com functionality from a Java client * <p/> * http://github.com/jaredholdcroft/postmark-java */ public class TestClient { public static void main(String[] args) { List<NameValuePair> headers = new ArrayList<NameValuePair>(); headers.add(new NameValuePair("HEADER", "test")); PostmarkMessage message = new PostmarkMessage(args[0], args[1], args[0], args[2], args[3], args[4], args[5], false, args[6], headers); String apiKey = "POSTMARK_API_TEST"; if(args[7] != null) apiKey = args[7]; PostmarkClient client = new PostmarkClient(apiKey); try { client.sendMessage(message); } catch (PostmarkException pe) { System.out.println("An error has occurred : " + pe.getMessage()); } } }
src/test/java/de/grobmeier/postmark/TestClient.java
// The MIT License // // Copyright (c) 2010 Jared Holdcroft // // 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 de.grobmeier.postmark; import de.grobmeier.postmark.NameValuePair; import de.grobmeier.postmark.PostmarkClient; import de.grobmeier.postmark.PostmarkException; import de.grobmeier.postmark.PostmarkMessage; import java.util.*; /** * Postmark for Java * <p/> * This library can be used to leverage the postmarkapp.com functionality from a Java client * <p/> * http://github.com/jaredholdcroft/postmark-java */ public class TestClient { public static void main(String[] args) { List<NameValuePair> headers = new ArrayList<NameValuePair>(); headers.add(new NameValuePair("HEADER", "test")); PostmarkMessage message = new PostmarkMessage(args[0], args[1], args[0], args[2], args[3], args[4], args[5], false, args[6], headers); String apiKey = "POSTMARK_API_TEST"; if(args[7] != null) apiKey = args[7]; PostmarkClient client = new PostmarkClient(apiKey); try { client.sendMessage(message); } catch (PostmarkException pe) { System.out.println("An error has occurred : " + pe.getMessage()); } } }
organized imports
src/test/java/de/grobmeier/postmark/TestClient.java
organized imports
<ide><path>rc/test/java/de/grobmeier/postmark/TestClient.java <ide> // THE SOFTWARE. <ide> <ide> package de.grobmeier.postmark; <del> <del>import de.grobmeier.postmark.NameValuePair; <del>import de.grobmeier.postmark.PostmarkClient; <del>import de.grobmeier.postmark.PostmarkException; <del>import de.grobmeier.postmark.PostmarkMessage; <ide> <ide> import java.util.*; <ide>
Java
lgpl-2.1
8fd2f1869f744e60131e3362d725677899267fb1
0
ggiudetti/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 org.opencms.jsp.search.config; import java.util.ArrayList; import java.util.List; /** Configuration for the query facet. */ public class CmsSearchConfigurationFacetQuery extends CmsSearchConfigurationFacet implements I_CmsSearchConfigurationFacetQuery { /** Representation of one query facet item. */ public static class CmsFacetQueryItem implements I_CmsFacetQueryItem { /** The query string for the item. */ String m_query; /** The label for the query item. */ String m_label; /** Constructor for a facet item. * @param query the query string for the item. * @param label the label for the item, defaults to the query string. */ public CmsFacetQueryItem(String query, String label) { m_query = query; m_label = label == null ? query : label; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object queryItem) { if (this.hashCode() != queryItem.hashCode()) { return false; } if (queryItem instanceof CmsFacetQueryItem) { CmsFacetQueryItem item = (CmsFacetQueryItem)queryItem; boolean equalQueries = ((null == m_query) && (null == item.getQuery())) || ((null != item.getQuery()) && m_query.equals(item.getQuery())); boolean equalLabels = false; if (equalQueries) { equalLabels = ((null == m_label) && (null == item.getLabel())) || ((null != item.getLabel()) && m_label.equals(item.getLabel())); } return equalQueries && equalLabels; } return false; } /** * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem#getLabel() */ @Override public String getLabel() { return m_label; } /** * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem#getQuery() */ @Override public String getQuery() { return m_query; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int hashCode = 0; if (null != m_label) { hashCode = m_label.hashCode(); } if (null != m_query) { hashCode += m_query.hashCode() / 2; } return hashCode; } } /** List of queries for the facet. */ List<I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem> m_queries; /** Constructor for the range facet configuration. * @param queries the queries that can be selected for the facet * @param label the label used to display the facet * @param isAndFacet true if checked facet entries should all be matched, otherwise only one checked entry must match * @param preselection list of entries that should be checked in advance * @param ignoreFiltersFromAllFacets A flag, indicating if filters from all facets should be ignored or not. */ public CmsSearchConfigurationFacetQuery( final List<I_CmsFacetQueryItem> queries, final String label, final Boolean isAndFacet, final List<String> preselection, final Boolean ignoreFiltersFromAllFacets) { super( null, label, I_CmsSearchConfigurationFacetQuery.NAME, isAndFacet, preselection, ignoreFiltersFromAllFacets); m_queries = queries != null ? queries : new ArrayList<I_CmsFacetQueryItem>(); } /** * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery#getQueryList() */ @Override public List<I_CmsFacetQueryItem> getQueryList() { return m_queries; } }
src/org/opencms/jsp/search/config/CmsSearchConfigurationFacetQuery.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 org.opencms.jsp.search.config; import java.util.ArrayList; import java.util.List; /** Configuration for the query facet. */ public class CmsSearchConfigurationFacetQuery extends CmsSearchConfigurationFacet implements I_CmsSearchConfigurationFacetQuery { /** Representation of one query facet item. */ public static class CmsFacetQueryItem implements I_CmsFacetQueryItem { /** The query string for the item. */ String m_query; /** The label for the query item. */ String m_label; /** Constructor for a facet item. * @param query the query string for the item. * @param label the label for the item, defaults to the query string. */ public CmsFacetQueryItem(String query, String label) { m_query = query; m_label = label == null ? query : label; } /** * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem#getLabel() */ @Override public String getLabel() { return m_label; } /** * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem#getQuery() */ @Override public String getQuery() { return m_query; } } /** List of queries for the facet. */ List<I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem> m_queries; /** Constructor for the range facet configuration. * @param queries the queries that can be selected for the facet * @param label the label used to display the facet * @param isAndFacet true if checked facet entries should all be matched, otherwise only one checked entry must match * @param preselection list of entries that should be checked in advance * @param ignoreFiltersFromAllFacets A flag, indicating if filters from all facets should be ignored or not. */ public CmsSearchConfigurationFacetQuery( final List<I_CmsFacetQueryItem> queries, final String label, final Boolean isAndFacet, final List<String> preselection, final Boolean ignoreFiltersFromAllFacets) { super( null, label, I_CmsSearchConfigurationFacetQuery.NAME, isAndFacet, preselection, ignoreFiltersFromAllFacets); m_queries = queries != null ? queries : new ArrayList<I_CmsFacetQueryItem>(); } /** * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery#getQueryList() */ @Override public List<I_CmsFacetQueryItem> getQueryList() { return m_queries; } }
Added equals(..) and hashCode() to CmsFacetQueryItem. This eases testing.
src/org/opencms/jsp/search/config/CmsSearchConfigurationFacetQuery.java
Added equals(..) and hashCode() to CmsFacetQueryItem.
<ide><path>rc/org/opencms/jsp/search/config/CmsSearchConfigurationFacetQuery.java <ide> } <ide> <ide> /** <add> * @see java.lang.Object#equals(java.lang.Object) <add> */ <add> @Override <add> public boolean equals(final Object queryItem) { <add> <add> if (this.hashCode() != queryItem.hashCode()) { <add> return false; <add> } <add> <add> if (queryItem instanceof CmsFacetQueryItem) { <add> CmsFacetQueryItem item = (CmsFacetQueryItem)queryItem; <add> boolean equalQueries = ((null == m_query) && (null == item.getQuery())) <add> || ((null != item.getQuery()) && m_query.equals(item.getQuery())); <add> boolean equalLabels = false; <add> if (equalQueries) { <add> equalLabels = ((null == m_label) && (null == item.getLabel())) <add> || ((null != item.getLabel()) && m_label.equals(item.getLabel())); <add> } <add> return equalQueries && equalLabels; <add> } <add> return false; <add> } <add> <add> /** <ide> * @see org.opencms.jsp.search.config.I_CmsSearchConfigurationFacetQuery.I_CmsFacetQueryItem#getLabel() <ide> */ <ide> @Override <ide> public String getQuery() { <ide> <ide> return m_query; <add> } <add> <add> /** <add> * @see java.lang.Object#hashCode() <add> */ <add> @Override <add> public int hashCode() { <add> <add> int hashCode = 0; <add> if (null != m_label) { <add> hashCode = m_label.hashCode(); <add> } <add> if (null != m_query) { <add> hashCode += m_query.hashCode() / 2; <add> } <add> return hashCode; <ide> } <ide> <ide> }
Java
apache-2.0
3f65ba1a31fbb7c04b77ff644e86fcd5112bf3a5
0
ibrahimshbat/JGroups,deepnarsay/JGroups,belaban/JGroups,belaban/JGroups,pferraro/JGroups,pruivo/JGroups,rhusar/JGroups,tristantarrant/JGroups,ibrahimshbat/JGroups,rvansa/JGroups,kedzie/JGroups,ibrahimshbat/JGroups,danberindei/JGroups,pferraro/JGroups,ligzy/JGroups,rhusar/JGroups,vjuranek/JGroups,TarantulaTechnology/JGroups,rhusar/JGroups,kedzie/JGroups,pruivo/JGroups,pferraro/JGroups,deepnarsay/JGroups,rvansa/JGroups,belaban/JGroups,ligzy/JGroups,rpelisse/JGroups,kedzie/JGroups,pruivo/JGroups,rpelisse/JGroups,slaskawi/JGroups,vjuranek/JGroups,danberindei/JGroups,danberindei/JGroups,slaskawi/JGroups,TarantulaTechnology/JGroups,TarantulaTechnology/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,Sanne/JGroups,dimbleby/JGroups,Sanne/JGroups,Sanne/JGroups,dimbleby/JGroups,dimbleby/JGroups,vjuranek/JGroups,deepnarsay/JGroups,slaskawi/JGroups,tristantarrant/JGroups,rpelisse/JGroups
// $Id: GossipData.java,v 1.3 2006/10/11 14:35:45 belaban Exp $ package org.jgroups.stack; import org.jgroups.Address; import org.jgroups.util.Streamable; import org.jgroups.util.Util; import java.io.*; import java.util.Vector; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; /** * Encapsulates data sent between GossipRouter and GossipClient * @author Bela Ban Oct 4 2001 */ public class GossipData implements Streamable { byte type=0; // One of GossipRouter type, e.g. CONNECT, REGISTER etc String group=null; // CONNECT, GET_REQ and GET_RSP Address addr=null; // CONNECT List mbrs=null; // GET_RSP public GossipData() { // for streamable } public GossipData(byte type) { this.type=type; } public GossipData(byte type, String group, Address addr, List mbrs) { this.type=type; this.group=group; this.addr=addr; this.mbrs=mbrs; } public byte getType() {return type;} public String getGroup() {return group;} public Address getAddress() {return addr;} public List getMembers() {return mbrs;} public void setMembers(List mbrs) { this.mbrs=mbrs; } public String toString() { StringBuffer sb=new StringBuffer(); sb.append(GossipRouter.type2String(type)).append( "(").append("group=").append(group).append(", addr=").append(addr); sb.append(", mbrs=").append(mbrs); return sb.toString(); } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); Util.writeString(group, out); Util.writeAddress(addr, out); Util.writeAddresses(mbrs, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); group=Util.readString(in); addr=Util.readAddress(in); mbrs=(List)Util.readAddresses(in, LinkedList.class); } }
src/org/jgroups/stack/GossipData.java
// $Id: GossipData.java,v 1.2 2004/03/30 06:47:27 belaban Exp $ package org.jgroups.stack; import org.jgroups.Address; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Vector; /** * Encapsulates data sent between GossipServer and GossipClient * @author Bela Ban Oct 4 2001 */ public class GossipData implements Externalizable { public static final int REGISTER_REQ = 1; public static final int GET_REQ = 2; public static final int GET_RSP = 3; int type=0; String group=null; // REGISTER, GET_REQ and GET_RSP Address mbr=null; // REGISTER Vector mbrs=null; // GET_RSP public GossipData() { ; // used for externalization } public GossipData(int type, String group, Address mbr, Vector mbrs) { this.type=type; this.group=group; this.mbr=mbr; this.mbrs=mbrs; } public int getType() {return type;} public String getGroup() {return group;} public Address getMbr() {return mbr;} public Vector getMbrs() {return mbrs;} public String toString() { StringBuffer sb=new StringBuffer(); sb.append(type2String(type)); switch(type) { case REGISTER_REQ: sb.append(" group=" + group + ", mbr=" + mbr); break; case GET_REQ: sb.append(" group=" + group); break; case GET_RSP: sb.append(" group=" + group + ", mbrs=" + mbrs); break; } return sb.toString(); } public static String type2String(int t) { switch(t) { case REGISTER_REQ: return "REGISTER_REQ"; case GET_REQ: return "GET_REQ"; case GET_RSP: return "GET_RSP"; default: return "<unknown>"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(type); out.writeUTF(group); out.writeObject(mbr); out.writeObject(mbrs); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readInt(); group=in.readUTF(); mbr=(Address)in.readObject(); mbrs=(Vector)in.readObject(); } }
changed to use Streamable
src/org/jgroups/stack/GossipData.java
changed to use Streamable
<ide><path>rc/org/jgroups/stack/GossipData.java <del>// $Id: GossipData.java,v 1.2 2004/03/30 06:47:27 belaban Exp $ <add>// $Id: GossipData.java,v 1.3 2006/10/11 14:35:45 belaban Exp $ <ide> <ide> package org.jgroups.stack; <ide> <ide> <ide> import org.jgroups.Address; <add>import org.jgroups.util.Streamable; <add>import org.jgroups.util.Util; <ide> <del>import java.io.Externalizable; <del>import java.io.IOException; <del>import java.io.ObjectInput; <del>import java.io.ObjectOutput; <add>import java.io.*; <ide> import java.util.Vector; <del> <add>import java.util.List; <add>import java.util.ArrayList; <add>import java.util.LinkedList; <ide> <ide> <ide> /** <del> * Encapsulates data sent between GossipServer and GossipClient <add> * Encapsulates data sent between GossipRouter and GossipClient <ide> * @author Bela Ban Oct 4 2001 <ide> */ <del>public class GossipData implements Externalizable { <del> public static final int REGISTER_REQ = 1; <del> public static final int GET_REQ = 2; <del> public static final int GET_RSP = 3; <add>public class GossipData implements Streamable { <add> byte type=0; // One of GossipRouter type, e.g. CONNECT, REGISTER etc <add> String group=null; // CONNECT, GET_REQ and GET_RSP <add> Address addr=null; // CONNECT <add> List mbrs=null; // GET_RSP <ide> <del> int type=0; <del> String group=null; // REGISTER, GET_REQ and GET_RSP <del> Address mbr=null; // REGISTER <del> Vector mbrs=null; // GET_RSP <del> <del> <del> public GossipData() { <del> ; // used for externalization <add> public GossipData() { // for streamable <ide> } <ide> <del> public GossipData(int type, String group, Address mbr, Vector mbrs) { <del> this.type=type; <del> this.group=group; <del> this.mbr=mbr; <del> this.mbrs=mbrs; <add> public GossipData(byte type) { <add> this.type=type; <add> } <add> <add> public GossipData(byte type, String group, Address addr, List mbrs) { <add> this.type=type; <add> this.group=group; <add> this.addr=addr; <add> this.mbrs=mbrs; <ide> } <ide> <ide> <del> public int getType() {return type;} <del> public String getGroup() {return group;} <del> public Address getMbr() {return mbr;} <del> public Vector getMbrs() {return mbrs;} <del> <add> public byte getType() {return type;} <add> public String getGroup() {return group;} <add> public Address getAddress() {return addr;} <add> public List getMembers() {return mbrs;} <add> <add> public void setMembers(List mbrs) { <add> this.mbrs=mbrs; <add> } <ide> <ide> <ide> public String toString() { <del> StringBuffer sb=new StringBuffer(); <del> sb.append(type2String(type)); <del> switch(type) { <del> case REGISTER_REQ: <del> sb.append(" group=" + group + ", mbr=" + mbr); <del> break; <del> <del> case GET_REQ: <del> sb.append(" group=" + group); <del> break; <del> <del> case GET_RSP: <del> sb.append(" group=" + group + ", mbrs=" + mbrs); <del> break; <del> } <del> return sb.toString(); <add> StringBuffer sb=new StringBuffer(); <add> sb.append(GossipRouter.type2String(type)).append( "(").append("group=").append(group).append(", addr=").append(addr); <add> sb.append(", mbrs=").append(mbrs); <add> return sb.toString(); <ide> } <ide> <ide> <del> public static String type2String(int t) { <del> switch(t) { <del> case REGISTER_REQ: return "REGISTER_REQ"; <del> case GET_REQ: return "GET_REQ"; <del> case GET_RSP: return "GET_RSP"; <del> default: return "<unknown>"; <del> } <add> public void writeTo(DataOutputStream out) throws IOException { <add> out.writeByte(type); <add> Util.writeString(group, out); <add> Util.writeAddress(addr, out); <add> Util.writeAddresses(mbrs, out); <add> } <add> <add> public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { <add> type=in.readByte(); <add> group=Util.readString(in); <add> addr=Util.readAddress(in); <add> mbrs=(List)Util.readAddresses(in, LinkedList.class); <ide> } <ide> <ide> <del> public void writeExternal(ObjectOutput out) throws IOException { <del> out.writeInt(type); <del> out.writeUTF(group); <del> out.writeObject(mbr); <del> out.writeObject(mbrs); <del> } <del> <del> <del> <del> public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { <del> type=in.readInt(); <del> group=in.readUTF(); <del> mbr=(Address)in.readObject(); <del> mbrs=(Vector)in.readObject(); <del> } <del> <ide> }
Java
apache-2.0
cad615e8e49c8acd65d55d1a609890244863aca8
0
GabrielBrascher/cloudstack,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,argv0/cloudstack,wido/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,cinderella/incubator-cloudstack,cinderella/incubator-cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,DaanHoogland/cloudstack,DaanHoogland/cloudstack,argv0/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,argv0/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,argv0/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,mufaddalq/cloudstack-datera-driver,argv0/cloudstack,wido/cloudstack,argv0/cloudstack
/** : * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. * * It 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. * */ package com.cloud.hypervisor.xen.resource; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import javax.ejb.Local; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.BackupSnapshotAnswer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteSnapshotBackupAnswer; import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotsDirCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; import com.cloud.agent.api.GetStorageStatsCommand; import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; import com.cloud.agent.api.HostStatsEntry; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; import com.cloud.agent.api.PingTestCommand; import com.cloud.agent.api.PoolEjectCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.Start2Answer; import com.cloud.agent.api.Start2Command; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartConsoleProxyAnswer; import com.cloud.agent.api.StartConsoleProxyCommand; import com.cloud.agent.api.StartRouterAnswer; import com.cloud.agent.api.StartRouterCommand; import com.cloud.agent.api.StartSecStorageVmAnswer; import com.cloud.agent.api.StartSecStorageVmCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.agent.api.ValidateSnapshotAnswer; import com.cloud.agent.api.ValidateSnapshotCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer; import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; import com.cloud.agent.api.routing.DhcpEntryCommand; import com.cloud.agent.api.routing.IPAssocCommand; import com.cloud.agent.api.routing.LoadBalancerCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRuleCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.CreatePrivateTemplateCommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.DownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.storage.ShareAnswer; import com.cloud.agent.api.storage.ShareCommand; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.StoragePoolTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor; import com.cloud.network.Network.BroadcastDomainType; import com.cloud.network.Network.TrafficType; import com.cloud.hypervisor.xen.resource.XenServerConnectionPool.XenServerConnection; import com.cloud.resource.ServerResource; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.VolumeVO; import com.cloud.storage.resource.StoragePoolResource; import com.cloud.storage.template.TemplateInfo; import com.cloud.template.VirtualMachineTemplate.BootloaderType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DiskCharacteristics; import com.cloud.vm.DomainRouter; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineName; import com.trilead.ssh2.SCPClient; import com.xensource.xenapi.APIVersion; import com.xensource.xenapi.Bond; import com.xensource.xenapi.Connection; import com.xensource.xenapi.Console; import com.xensource.xenapi.Host; import com.xensource.xenapi.HostCpu; import com.xensource.xenapi.HostMetrics; import com.xensource.xenapi.Network; import com.xensource.xenapi.PBD; import com.xensource.xenapi.PIF; import com.xensource.xenapi.Pool; import com.xensource.xenapi.SR; import com.xensource.xenapi.Session; import com.xensource.xenapi.Types; import com.xensource.xenapi.Types.BadServerResponse; import com.xensource.xenapi.Types.IpConfigurationMode; import com.xensource.xenapi.Types.VmPowerState; import com.xensource.xenapi.Types.XenAPIException; import com.xensource.xenapi.VBD; import com.xensource.xenapi.VDI; import com.xensource.xenapi.VIF; import com.xensource.xenapi.VLAN; import com.xensource.xenapi.VM; import com.xensource.xenapi.VMGuestMetrics; import com.xensource.xenapi.XenAPIObject; /** * Encapsulates the interface to the XenServer API. * */ @Local(value = ServerResource.class) public abstract class CitrixResourceBase implements StoragePoolResource, ServerResource { private static final Logger s_logger = Logger.getLogger(CitrixResourceBase.class); protected static final XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance(); protected static final int MB = 1024 * 1024; protected String _name; protected String _username; protected String _password; protected final int _retry = 24; protected final int _sleep = 10000; protected long _dcId; protected String _pod; protected String _cluster; protected HashMap<String, State> _vms = new HashMap<String, State>(71); protected String _patchPath; protected String _privateNetworkName; protected String _linkLocalPrivateNetworkName; protected String _publicNetworkName; protected String _storageNetworkName1; protected String _storageNetworkName2; protected String _guestNetworkName; protected int _wait; protected IAgentControl _agentControl; protected boolean _isRemoteAgent = false; protected final XenServerHost _host = new XenServerHost(); // Guest and Host Performance Statistics protected boolean _collectHostStats = false; protected String _consolidationFunction = "AVERAGE"; protected int _pollingIntervalInSeconds = 60; protected StorageLayer _storage; protected boolean _canBridgeFirewall = false; protected HashMap<StoragePoolType, StoragePoolResource> _pools = new HashMap<StoragePoolType, StoragePoolResource>(5); public enum SRType { NFS, LVM, ISCSI, ISO, LVMOISCSI; @Override public String toString() { return super.toString().toLowerCase(); } public boolean equals(String type) { return super.toString().equalsIgnoreCase(type); } } protected static HashMap<Types.VmPowerState, State> s_statesTable; protected String _localGateway; static { s_statesTable = new HashMap<Types.VmPowerState, State>(); s_statesTable.put(Types.VmPowerState.HALTED, State.Stopped); s_statesTable.put(Types.VmPowerState.PAUSED, State.Running); s_statesTable.put(Types.VmPowerState.RUNNING, State.Running); s_statesTable.put(Types.VmPowerState.SUSPENDED, State.Running); s_statesTable.put(Types.VmPowerState.UNKNOWN, State.Unknown); s_statesTable.put(Types.VmPowerState.UNRECOGNIZED, State.Unknown); } private static HashMap<String, String> _guestOsType = new HashMap<String, String>(50); static { _guestOsType.put("CentOS 4.5 (32-bit)", "CentOS 4.5"); _guestOsType.put("CentOS 4.6 (32-bit)", "CentOS 4.6"); _guestOsType.put("CentOS 4.7 (32-bit)", "CentOS 4.7"); _guestOsType.put("CentOS 4.8 (32-bit)", "CentOS 4.8"); _guestOsType.put("CentOS 5.0 (32-bit)", "CentOS 5.0"); _guestOsType.put("CentOS 5.0 (64-bit)", "CentOS 5.0 x64"); _guestOsType.put("CentOS 5.1 (32-bit)", "CentOS 5.1"); _guestOsType.put("CentOS 5.1 (64-bit)", "CentOS 5.1 x64"); _guestOsType.put("CentOS 5.2 (32-bit)", "CentOS 5.2"); _guestOsType.put("CentOS 5.2 (64-bit)", "CentOS 5.2 x64"); _guestOsType.put("CentOS 5.3 (32-bit)", "CentOS 5.3"); _guestOsType.put("CentOS 5.3 (64-bit)", "CentOS 5.3 x64"); _guestOsType.put("CentOS 5.4 (32-bit)", "CentOS 5.4"); _guestOsType.put("CentOS 5.4 (64-bit)", "CentOS 5.4 x64"); _guestOsType.put("Debian Lenny 5.0 (32-bit)", "Debian Lenny 5.0"); _guestOsType.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5.0"); _guestOsType.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5.0 x64"); _guestOsType.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5.1"); _guestOsType.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5.1 x64"); _guestOsType.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5.2"); _guestOsType.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5.2 x64"); _guestOsType.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5.3"); _guestOsType.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5.3 x64"); _guestOsType.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5.4"); _guestOsType.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5.4 x64"); _guestOsType.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5"); _guestOsType.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6"); _guestOsType.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7"); _guestOsType.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8"); _guestOsType.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5.0"); _guestOsType.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5.0 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5.1"); _guestOsType.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5.1 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5.2"); _guestOsType.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5.2 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5.3"); _guestOsType.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5.3 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5.4"); _guestOsType.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5.4 x64"); _guestOsType.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 x64"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 x64"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "Other install media"); _guestOsType.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11"); _guestOsType.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 x64"); _guestOsType.put("Windows 7 (32-bit)", "Windows 7"); _guestOsType.put("Windows 7 (64-bit)", "Windows 7 x64"); _guestOsType.put("Windows Server 2003 (32-bit)", "Windows Server 2003"); _guestOsType.put("Windows Server 2003 (64-bit)", "Windows Server 2003 x64"); _guestOsType.put("Windows Server 2008 (32-bit)", "Windows Server 2008"); _guestOsType.put("Windows Server 2008 (64-bit)", "Windows Server 2008 x64"); _guestOsType.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 x64"); _guestOsType.put("Windows 2000 SP4 (32-bit)", "Windows 2000 SP4"); _guestOsType.put("Windows Vista (32-bit)", "Windows Vista"); _guestOsType.put("Windows XP SP2 (32-bit)", "Windows XP SP2"); _guestOsType.put("Windows XP SP3 (32-bit)", "Windows XP SP3"); _guestOsType.put("Other install media", "Other install media"); } protected boolean isRefNull(XenAPIObject object) { return (object == null || object.toWireString().equals("OpaqueRef:NULL")); } @Override public void disconnected() { s_logger.debug("Logging out of " + _host.uuid); if (_host.pool != null) { _connPool.disconnect(_host.uuid, _host.pool); _host.pool = null; } } protected VDI cloudVDIcopy(VDI vdi, SR sr) throws BadServerResponse, XenAPIException, XmlRpcException{ Connection conn = getConnection(); return vdi.copy(conn, sr); } protected void destroyStoppedVm() { Map<VM, VM.Record> vmentries = null; Connection conn = getConnection(); for (int i = 0; i < 2; i++) { try { vmentries = VM.getAllRecords(conn); break; } catch (final Throwable e) { s_logger.warn("Unable to get vms", e); } try { Thread.sleep(1000); } catch (final InterruptedException ex) { } } if (vmentries == null) { return; } for (Map.Entry<VM, VM.Record> vmentry : vmentries.entrySet()) { VM.Record record = vmentry.getValue(); if (record.isControlDomain || record.isASnapshot || record.isATemplate) { continue; // Skip DOM0 } if (record.powerState != Types.VmPowerState.HALTED) { continue; } try { if (isRefNull(record.affinity) || !record.affinity.getUuid(conn).equals(_host.uuid)) { continue; } vmentry.getKey().destroy(conn); } catch (Exception e) { String msg = "VM destroy failed for " + record.nameLabel + " due to " + e.getMessage(); s_logger.warn(msg, e); } } } protected void cleanupDiskMounts() { Connection conn = getConnection(); Map<SR, SR.Record> srs; try { srs = SR.getAllRecords(conn); } catch (XenAPIException e) { s_logger.warn("Unable to get the SRs " + e.toString(), e); throw new CloudRuntimeException("Unable to get SRs " + e.toString(), e); } catch (XmlRpcException e) { throw new CloudRuntimeException("Unable to get SRs " + e.getMessage()); } for (Map.Entry<SR, SR.Record> sr : srs.entrySet()) { SR.Record rec = sr.getValue(); if (SRType.NFS.equals(rec.type) || (SRType.ISO.equals(rec.type) && rec.nameLabel.endsWith("iso"))) { if (rec.PBDs == null || rec.PBDs.size() == 0) { cleanSR(sr.getKey(), rec); continue; } for (PBD pbd : rec.PBDs) { if (isRefNull(pbd)) { continue; } PBD.Record pbdr = null; try { pbdr = pbd.getRecord(conn); } catch (XenAPIException e) { s_logger.warn("Unable to get pbd record " + e.toString()); } catch (XmlRpcException e) { s_logger.warn("Unable to get pbd record " + e.getMessage()); } if (pbdr == null) { continue; } try { if (pbdr.host.getUuid(conn).equals(_host.uuid)) { if (!currentlyAttached(sr.getKey(), rec, pbd, pbdr)) { pbd.unplug(conn); pbd.destroy(conn); cleanSR(sr.getKey(), rec); } else if (!pbdr.currentlyAttached) { pbd.plug(conn); } } } catch (XenAPIException e) { s_logger.warn("Catch XenAPIException due to" + e.toString(), e); } catch (XmlRpcException e) { s_logger.warn("Catch XmlRpcException due to" + e.getMessage(), e); } } } } } protected Pair<VM, VM.Record> getVmByNameLabel(Connection conn, Host host, String nameLabel, boolean getRecord) throws XmlRpcException, XenAPIException { Set<VM> vms = host.getResidentVMs(conn); for (VM vm : vms) { VM.Record rec = null; String name = null; if (getRecord) { rec = vm.getRecord(conn); name = rec.nameLabel; } else { name = vm.getNameLabel(conn); } if (name.equals(nameLabel)) { return new Pair<VM, VM.Record>(vm, rec); } } return null; } protected boolean currentlyAttached(SR sr, SR.Record rec, PBD pbd, PBD.Record pbdr) { String status = null; if (SRType.NFS.equals(rec.type)) { status = callHostPlugin("vmops", "checkMount", "mount", rec.uuid); } else if (SRType.LVMOISCSI.equals(rec.type) ) { String scsiid = pbdr.deviceConfig.get("SCSIid"); if (scsiid.isEmpty()) { return false; } status = callHostPlugin("vmops", "checkIscsi", "scsiid", scsiid); } else { return true; } if (status != null && status.equalsIgnoreCase("1")) { s_logger.debug("currently attached " + pbdr.uuid); return true; } else { s_logger.debug("currently not attached " + pbdr.uuid); return false; } } protected boolean pingdomr(String host, String port) { String status; status = callHostPlugin("vmops", "pingdomr", "host", host, "port", port); if (status == null || status.isEmpty()) { return false; } return true; } protected boolean pingxenserver() { String status; status = callHostPlugin("vmops", "pingxenserver"); if (status == null || status.isEmpty()) { return false; } return true; } protected String logX(XenAPIObject obj, String msg) { return new StringBuilder("Host ").append(_host.ip).append(" ").append(obj.toWireString()).append(": ").append(msg).toString(); } protected void cleanSR(SR sr, SR.Record rec) { Connection conn = getConnection(); if (rec.VDIs != null) { for (VDI vdi : rec.VDIs) { VDI.Record vdir; try { vdir = vdi.getRecord(conn); } catch (XenAPIException e) { s_logger.debug("Unable to get VDI: " + e.toString()); continue; } catch (XmlRpcException e) { s_logger.debug("Unable to get VDI: " + e.getMessage()); continue; } if (vdir.VBDs == null) continue; for (VBD vbd : vdir.VBDs) { try { VBD.Record vbdr = vbd.getRecord(conn); VM.Record vmr = vbdr.VM.getRecord(conn); if ((!isRefNull(vmr.residentOn) && vmr.residentOn.getUuid(conn).equals(_host.uuid)) || (isRefNull(vmr.residentOn) && !isRefNull(vmr.affinity) && vmr.affinity.getUuid(conn).equals(_host.uuid))) { if (vmr.powerState != VmPowerState.HALTED && vmr.powerState != VmPowerState.UNKNOWN && vmr.powerState != VmPowerState.UNRECOGNIZED) { try { vbdr.VM.hardShutdown(conn); } catch (XenAPIException e) { s_logger.debug("Shutdown hit error " + vmr.nameLabel + ": " + e.toString()); } } try { vbdr.VM.destroy(conn); } catch (XenAPIException e) { s_logger.debug("Destroy hit error " + vmr.nameLabel + ": " + e.toString()); } catch (XmlRpcException e) { s_logger.debug("Destroy hit error " + vmr.nameLabel + ": " + e.getMessage()); } vbd.destroy(conn); break; } } catch (XenAPIException e) { s_logger.debug("Unable to get VBD: " + e.toString()); continue; } catch (XmlRpcException e) { s_logger.debug("Uanbel to get VBD: " + e.getMessage()); continue; } } } } for (PBD pbd : rec.PBDs) { PBD.Record pbdr = null; try { pbdr = pbd.getRecord(conn); pbd.unplug(conn); pbd.destroy(conn); } catch (XenAPIException e) { s_logger.warn("PBD " + ((pbdr != null) ? "(uuid:" + pbdr.uuid + ")" : "") + "destroy failed due to " + e.toString()); } catch (XmlRpcException e) { s_logger.warn("PBD " + ((pbdr != null) ? "(uuid:" + pbdr.uuid + ")" : "") + "destroy failed due to " + e.getMessage()); } } try { rec = sr.getRecord(conn); if (rec.PBDs == null || rec.PBDs.size() == 0) { sr.forget(conn); return; } } catch (XenAPIException e) { s_logger.warn("Unable to retrieve sr again: " + e.toString(), e); } catch (XmlRpcException e) { s_logger.warn("Unable to retrieve sr again: " + e.getMessage(), e); } } @Override public Answer executeRequest(Command cmd) { if (cmd instanceof CreateCommand) { return execute((CreateCommand) cmd); } else if (cmd instanceof SetFirewallRuleCommand) { return execute((SetFirewallRuleCommand) cmd); } else if (cmd instanceof LoadBalancerCfgCommand) { return execute((LoadBalancerCfgCommand) cmd); } else if (cmd instanceof IPAssocCommand) { return execute((IPAssocCommand) cmd); } else if (cmd instanceof CheckConsoleProxyLoadCommand) { return execute((CheckConsoleProxyLoadCommand) cmd); } else if (cmd instanceof WatchConsoleProxyLoadCommand) { return execute((WatchConsoleProxyLoadCommand) cmd); } else if (cmd instanceof SavePasswordCommand) { return execute((SavePasswordCommand) cmd); } else if (cmd instanceof DhcpEntryCommand) { return execute((DhcpEntryCommand) cmd); } else if (cmd instanceof VmDataCommand) { return execute((VmDataCommand) cmd); } else if (cmd instanceof StartCommand) { return execute((StartCommand) cmd); } else if (cmd instanceof StartRouterCommand) { return execute((StartRouterCommand) cmd); } else if (cmd instanceof ReadyCommand) { return execute((ReadyCommand) cmd); } else if (cmd instanceof GetHostStatsCommand) { return execute((GetHostStatsCommand) cmd); } else if (cmd instanceof GetVmStatsCommand) { return execute((GetVmStatsCommand) cmd); } else if (cmd instanceof CheckHealthCommand) { return execute((CheckHealthCommand) cmd); } else if (cmd instanceof StopCommand) { return execute((StopCommand) cmd); } else if (cmd instanceof RebootRouterCommand) { return execute((RebootRouterCommand) cmd); } else if (cmd instanceof RebootCommand) { return execute((RebootCommand) cmd); } else if (cmd instanceof CheckVirtualMachineCommand) { return execute((CheckVirtualMachineCommand) cmd); } else if (cmd instanceof PrepareForMigrationCommand) { return execute((PrepareForMigrationCommand) cmd); } else if (cmd instanceof MigrateCommand) { return execute((MigrateCommand) cmd); } else if (cmd instanceof DestroyCommand) { return execute((DestroyCommand) cmd); } else if (cmd instanceof ShareCommand) { return execute((ShareCommand) cmd); } else if (cmd instanceof ModifyStoragePoolCommand) { return execute((ModifyStoragePoolCommand) cmd); } else if (cmd instanceof DeleteStoragePoolCommand) { return execute((DeleteStoragePoolCommand) cmd); } else if (cmd instanceof CopyVolumeCommand) { return execute((CopyVolumeCommand) cmd); } else if (cmd instanceof AttachVolumeCommand) { return execute((AttachVolumeCommand) cmd); } else if (cmd instanceof AttachIsoCommand) { return execute((AttachIsoCommand) cmd); } else if (cmd instanceof ValidateSnapshotCommand) { return execute((ValidateSnapshotCommand) cmd); } else if (cmd instanceof ManageSnapshotCommand) { return execute((ManageSnapshotCommand) cmd); } else if (cmd instanceof BackupSnapshotCommand) { return execute((BackupSnapshotCommand) cmd); } else if (cmd instanceof DeleteSnapshotBackupCommand) { return execute((DeleteSnapshotBackupCommand) cmd); } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { return execute((CreateVolumeFromSnapshotCommand) cmd); } else if (cmd instanceof DeleteSnapshotsDirCommand) { return execute((DeleteSnapshotsDirCommand) cmd); } else if (cmd instanceof CreatePrivateTemplateCommand) { return execute((CreatePrivateTemplateCommand) cmd); } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { return execute((CreatePrivateTemplateFromSnapshotCommand) cmd); } else if (cmd instanceof GetStorageStatsCommand) { return execute((GetStorageStatsCommand) cmd); } else if (cmd instanceof PrimaryStorageDownloadCommand) { return execute((PrimaryStorageDownloadCommand) cmd); } else if (cmd instanceof StartConsoleProxyCommand) { return execute((StartConsoleProxyCommand) cmd); } else if (cmd instanceof StartSecStorageVmCommand) { return execute((StartSecStorageVmCommand) cmd); } else if (cmd instanceof GetVncPortCommand) { return execute((GetVncPortCommand) cmd); } else if (cmd instanceof SetupCommand) { return execute((SetupCommand) cmd); } else if (cmd instanceof MaintainCommand) { return execute((MaintainCommand) cmd); } else if (cmd instanceof PingTestCommand) { return execute((PingTestCommand) cmd); } else if (cmd instanceof CheckOnHostCommand) { return execute((CheckOnHostCommand) cmd); } else if (cmd instanceof ModifySshKeysCommand) { return execute((ModifySshKeysCommand) cmd); } else if (cmd instanceof PoolEjectCommand) { return execute((PoolEjectCommand) cmd); } else if (cmd instanceof Start2Command) { return execute((Start2Command)cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } } Pair<Network, String> getNetworkForTraffic(Connection conn, TrafficType type) throws XenAPIException, XmlRpcException { if (type == TrafficType.Guest) { return new Pair<Network, String>(Network.getByUuid(conn, _host.guestNetwork), _host.guestPif); } else if (type == TrafficType.Control) { return new Pair<Network, String>(Network.getByUuid(conn, _host.linkLocalNetwork), null); } else if (type == TrafficType.Management) { return new Pair<Network, String>(Network.getByUuid(conn, _host.privateNetwork), _host.privatePif); } else if (type == TrafficType.Public) { return new Pair<Network, String>(Network.getByUuid(conn, _host.publicNetwork), _host.publicPif); } else if (type == TrafficType.Storage) { return new Pair<Network, String>(Network.getByUuid(conn, _host.storageNetwork1), _host.storagePif1); } else if (type == TrafficType.Vpn) { return new Pair<Network, String>(Network.getByUuid(conn, _host.publicNetwork), _host.publicPif); } throw new CloudRuntimeException("Unsupported network type: " + type); } protected VIF createVif(Connection conn, String vmName, VM vm, NicTO nic) throws XmlRpcException, XenAPIException { VIF.Record vifr = new VIF.Record(); vifr.VM = vm; vifr.device = Integer.toString(nic.getDeviceId()); vifr.MAC = nic.getMac(); Pair<Network, String> network = getNetworkForTraffic(conn, nic.getType()); if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { vifr.network = enableVlanNetwork(conn, nic.getVlan(), network.first(), network.second()); } else { vifr.network = network.first(); } if (nic.getNetworkRateMbps() != null) { vifr.qosAlgorithmType = "ratelimit"; vifr.qosAlgorithmParams = new HashMap<String, String>(); vifr.qosAlgorithmParams.put("kbps", Integer.toString(nic.getNetworkRateMbps() * 1000)); } VIF vif = VIF.create(conn, vifr); if (s_logger.isDebugEnabled()) { vifr = vif.getRecord(conn); s_logger.debug("Created a vif " + vifr.uuid + " on " + nic.getDeviceId()); } return vif; } protected VDI mount(Connection conn, String vmName, VolumeTO volume) throws XmlRpcException, XenAPIException { if (volume.getType() == VolumeType.ISO) { String isopath = volume.getPath(); int index = isopath.lastIndexOf("/"); String mountpoint = isopath.substring(0, index); URI uri; try { uri = new URI(mountpoint); } catch (URISyntaxException e) { throw new CloudRuntimeException("Incorrect uri " + mountpoint, e); } SR isoSr = createIsoSRbyURI(uri, vmName, false); String isoname = isopath.substring(index + 1); VDI isoVdi = getVDIbyLocationandSR(isoname, isoSr); if (isoVdi == null) { throw new CloudRuntimeException("Unable to find ISO " + volume.getPath()); } return isoVdi; } else { return VDI.getByUuid(conn, volume.getPath()); } } protected VBD createVbd(Connection conn, String vmName, VM vm, VolumeTO volume, boolean patch) throws XmlRpcException, XenAPIException { VolumeType type = volume.getType(); VDI vdi = mount(conn, vmName, volume); if (patch) { if (!patchSystemVm(vdi, vmName)) { throw new CloudRuntimeException("Unable to patch system vm"); } } VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; if (type == VolumeType.ROOT) { vbdr.bootable = true; } vbdr.userdevice = Long.toString(volume.getDeviceId()); if (volume.getType() == VolumeType.ISO) { vbdr.mode = Types.VbdMode.RO; vbdr.type = Types.VbdType.CD; } else { vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; } VBD vbd = VBD.create(conn, vbdr); if (s_logger.isDebugEnabled()) { s_logger.debug("VBD " + vbd.getUuid(conn) + " created for " + volume); } return vbd; } protected Pair<VM, String> createVmFromTemplate(Connection conn, VirtualMachineTO vmSpec, Host host) throws XenAPIException, XmlRpcException { String guestOsTypeName = getGuestOsType(vmSpec.getOs()); Set<VM> templates = VM.getByNameLabel(conn, guestOsTypeName); assert templates.size() == 1 : "Should only have 1 template but found " + templates.size(); VM template = templates.iterator().next(); VM vm = template.createClone(conn, vmSpec.getName()); vm.setAffinity(conn, host); VM.Record vmr = vm.getRecord(conn); if (s_logger.isDebugEnabled()) { s_logger.debug("Created VM " + vmr.uuid + " for " + vmSpec.getName()); } for (Console console : vmr.consoles) { console.destroy(conn); } vm.setIsATemplate(conn, false); vm.removeFromOtherConfig(conn, "disks"); vm.setNameLabel(conn, vmSpec.getName()); setMemory(conn, vm, vmSpec.getMinRam()); vm.setVCPUsAtStartup(conn, (long)vmSpec.getCpus()); vm.setVCPUsMax(conn, (long)vmSpec.getCpus()); vm.setVCPUsNumberLive(conn, (long)vmSpec.getCpus()); Map<String, String> vcpuParams = new HashMap<String, String>(); if (vmSpec.getWeight() != null) { vcpuParams.put("weight", Integer.toString(vmSpec.getWeight())); } if (vmSpec.getUtilization() != null) { vcpuParams.put("cap", Integer.toString(vmSpec.getUtilization())); } if (vcpuParams.size() > 0) { vm.setVCPUsParams(conn, vcpuParams); } vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY); vm.setActionsAfterShutdown(conn, Types.OnNormalExit.DESTROY); String bootArgs = vmSpec.getBootArgs(); if (bootArgs != null && bootArgs.length() > 0) { String pvargs = vm.getPVArgs(conn); pvargs = pvargs + vmSpec.getBootArgs(); if (s_logger.isDebugEnabled()) { s_logger.debug("PV args are " + pvargs); } vm.setPVArgs(conn, pvargs); } if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) { if (vmSpec.getBootloader() == BootloaderType.CD) { vm.setPVBootloader(conn, "eliloader"); vm.addToOtherConfig(conn, "install-repository", "cdrom"); } else if (vmSpec.getBootloader() == BootloaderType.PyGrub ){ vm.setPVBootloader(conn, "pygrub"); } else { vm.destroy(conn); throw new CloudRuntimeException("Unable to handle boot loader type: " + vmSpec.getBootloader()); } } return new Pair<VM, String>(vm, vmr.uuid); } protected String handleVmStartFailure(String vmName, VM vm, String message, Throwable th) { String msg = "Unable to start " + vmName + " due to " + message; s_logger.warn(msg, th); if (vm == null) { return msg; } Connection conn = getConnection(); try { VM.Record vmr = vm.getRecord(conn); if (vmr.powerState == VmPowerState.RUNNING) { try { vm.hardShutdown(conn); } catch (Exception e) { s_logger.warn("VM hardshutdown failed due to ", e); } } if (vm.getPowerState(conn) == VmPowerState.HALTED) { try { vm.destroy(conn); } catch (Exception e) { s_logger.warn("VM destroy failed due to ", e); } } for (VBD vbd : vmr.VBDs) { try { vbd.unplug(conn); vbd.destroy(conn); } catch (Exception e) { s_logger.warn("Unable to clean up VBD due to ", e); } } for (VIF vif : vmr.VIFs) { try { vif.unplug(conn); vif.destroy(conn); } catch (Exception e) { s_logger.warn("Unable to cleanup VIF", e); } } } catch (Exception e) { s_logger.warn("VM getRecord failed due to ", e); } return msg; } protected Start2Answer execute(Start2Command cmd) { VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); Connection conn = getConnection(); State state = State.Stopped; VM vm = null; try { Host host = Host.getByUuid(conn, _host.uuid); synchronized (_vms) { _vms.put(vmName, State.Starting); } Pair<VM, String> v = createVmFromTemplate(conn, vmSpec, host); vm = v.first(); String vmUuid = v.second(); for (VolumeTO disk : vmSpec.getDisks()) { createVbd(conn, vmName, vm, disk, disk.getType() == VolumeType.ROOT && vmSpec.getType() != VirtualMachine.Type.User); } NicTO controlNic = null; for (NicTO nic : vmSpec.getNetworks()) { if (nic.getControlPort() != null) { controlNic = nic; } createVif(conn, vmName, vm, nic); } /* * VBD.Record vbdr = new VBD.Record(); Ternary<SR, VDI, VolumeVO> mount = mounts.get(0); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = !bootFromISO; vbdr.userdevice = "0"; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; VBD.create(conn, vbdr); for (int i = 1; i < mounts.size(); i++) { mount = mounts.get(i); // vdi.setNameLabel(conn, cmd.getVmName() + "-DATA"); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = false; vbdr.userdevice = Long.toString(mount.third().getDeviceId()); vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; VBD.create(conn, vbdr); } VBD.Record cdromVBDR = new VBD.Record(); cdromVBDR.VM = vm; cdromVBDR.empty = true; cdromVBDR.bootable = bootFromISO; cdromVBDR.userdevice = "3"; cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; VBD cdromVBD = VBD.create(conn, cdromVBDR); String isopath = cmd.getISOPath(); if (isopath != null) { int index = isopath.lastIndexOf("/"); String mountpoint = isopath.substring(0, index); URI uri = new URI(mountpoint); isosr = createIsoSRbyURI(uri, cmd.getVmName(), false); String isoname = isopath.substring(index + 1); VDI isovdi = getVDIbyLocationandSR(isoname, isosr); if (isovdi == null) { String msg = " can not find ISO " + cmd.getISOPath(); s_logger.warn(msg); return new StartAnswer(cmd, msg); } else { cdromVBD.insert(conn, isovdi); } } */ vm.startOn(conn, host, false, true); if (_canBridgeFirewall) { String result = null; if (vmSpec.getType() != VirtualMachine.Type.User) { result = callHostPlugin("vmops", "default_network_rules_systemvm", "vmName", vmName); } else { } if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default network rules for " + vmName); } else { s_logger.info("Programmed default network rules for " + vmName); } } if (controlNic != null) { String privateIp = controlNic.getIp(); int cmdPort = controlNic.getControlPort(); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); } String result = connect(vmName, privateIp, cmdPort); if (result != null) { throw new CloudRuntimeException("Can not ping System vm " + vmName + "due to:" + result); } if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port succeeded for vm " + vmName); } } state = State.Running; return new Start2Answer(cmd); } catch (XmlRpcException e) { String msg = handleVmStartFailure(vmName, vm, "", e); return new Start2Answer(cmd, msg); } catch (XenAPIException e) { String msg = handleVmStartFailure(vmName, vm, "", e); return new Start2Answer(cmd, msg); } catch (Exception e) { String msg = handleVmStartFailure(vmName, vm, "", e); return new Start2Answer(cmd, msg); } finally { synchronized (_vms) { if (state != State.Stopped) { _vms.put(vmName, state); } else { _vms.remove(vmName); } } } } protected Answer execute(ModifySshKeysCommand cmd) { return new Answer(cmd); } private boolean doPingTest(final String computingHostIp) { String args = "-h " + computingHostIp; String result = callHostPlugin("vmops", "pingtest", "args", args); if (result == null || result.isEmpty()) return false; return true; } protected CheckOnHostAnswer execute(CheckOnHostCommand cmd) { return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); } private boolean doPingTest(final String domRIp, final String vmIp) { String args = "-i " + domRIp + " -p " + vmIp; String result = callHostPlugin("vmops", "pingtest", "args", args); if (result == null || result.isEmpty()) return false; return true; } private Answer execute(PingTestCommand cmd) { boolean result = false; final String computingHostIp = cmd.getComputingHostIp(); // TODO, split the command into 2 types if (computingHostIp != null) { result = doPingTest(computingHostIp); } else { result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp()); } if (!result) { return new Answer(cmd, false, "PingTestCommand failed"); } return new Answer(cmd); } protected MaintainAnswer execute(MaintainCommand cmd) { Connection conn = getConnection(); try { Pool pool = Pool.getByUuid(conn, _host.pool); Pool.Record poolr = pool.getRecord(conn); Host.Record hostr = poolr.master.getRecord(conn); if (!_host.uuid.equals(hostr.uuid)) { s_logger.debug("Not the master node so just return ok: " + _host.ip); return new MaintainAnswer(cmd); } Map<Host, Host.Record> hostMap = Host.getAllRecords(conn); if (hostMap.size() == 1) { s_logger.debug("There's no one to take over as master"); return new MaintainAnswer(cmd,false, "Only master in the pool"); } Host newMaster = null; Host.Record newMasterRecord = null; for (Map.Entry<Host, Host.Record> entry : hostMap.entrySet()) { if (!_host.uuid.equals(entry.getValue().uuid)) { newMaster = entry.getKey(); newMasterRecord = entry.getValue(); s_logger.debug("New master for the XenPool is " + newMasterRecord.uuid + " : " + newMasterRecord.address); try { _connPool.switchMaster(_host.ip, _host.pool, conn, newMaster, _username, _password, _wait); return new MaintainAnswer(cmd, "New Master is " + newMasterRecord.address); } catch (XenAPIException e) { s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " Trying again..."); } catch (XmlRpcException e) { s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " Trying again..."); } } } return new MaintainAnswer(cmd, false, "Unable to find an appropriate host to set as the new master"); } catch (XenAPIException e) { s_logger.warn("Unable to put server in maintainence mode", e); return new MaintainAnswer(cmd, false, e.getMessage()); } catch (XmlRpcException e) { s_logger.warn("Unable to put server in maintainence mode", e); return new MaintainAnswer(cmd, false, e.getMessage()); } } protected SetupAnswer execute(SetupCommand cmd) { return new SetupAnswer(cmd); } protected Answer execute(StartSecStorageVmCommand cmd) { final String vmName = cmd.getVmName(); SecondaryStorageVmVO storage = cmd.getSecondaryStorageVmVO(); try { Connection conn = getConnection(); Network network = Network.getByUuid(conn, _host.privateNetwork); String bootArgs = cmd.getBootArgs(); bootArgs += " zone=" + _dcId; bootArgs += " pod=" + _pod; bootArgs += " localgw=" + _localGateway; String result = startSystemVM(vmName, storage.getVlanId(), network, cmd.getVolumes(), bootArgs, storage.getGuestMacAddress(), storage.getGuestIpAddress(), storage .getPrivateMacAddress(), storage.getPublicMacAddress(), cmd.getProxyCmdPort(), storage.getRamSize()); if (result == null) { return new StartSecStorageVmAnswer(cmd); } return new StartSecStorageVmAnswer(cmd, result); } catch (Exception e) { String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); return new StartSecStorageVmAnswer(cmd, msg); } } protected Answer execute(final SetFirewallRuleCommand cmd) { String args; if (cmd.isEnable()) { args = "-A"; } else { args = "-D"; } args += " -P " + cmd.getProtocol().toLowerCase(); args += " -l " + cmd.getPublicIpAddress(); args += " -p " + cmd.getPublicPort(); args += " -n " + cmd.getRouterName(); args += " -i " + cmd.getRouterIpAddress(); args += " -r " + cmd.getPrivateIpAddress(); args += " -d " + cmd.getPrivatePort(); args += " -N " + cmd.getVlanNetmask(); String oldPrivateIP = cmd.getOldPrivateIP(); String oldPrivatePort = cmd.getOldPrivatePort(); if (oldPrivateIP != null) { args += " -w " + oldPrivateIP; } if (oldPrivatePort != null) { args += " -x " + oldPrivatePort; } String result = callHostPlugin("vmops", "setFirewallRule", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "SetFirewallRule failed"); } return new Answer(cmd); } protected Answer execute(final LoadBalancerCfgCommand cmd) { String routerIp = cmd.getRouterIp(); if (routerIp == null) { return new Answer(cmd); } String tmpCfgFilePath = "/tmp/" + cmd.getRouterIp().replace('.', '_') + ".cfg"; String tmpCfgFileContents = ""; for (int i = 0; i < cmd.getConfig().length; i++) { tmpCfgFileContents += cmd.getConfig()[i]; tmpCfgFileContents += "\n"; } String result = callHostPlugin("vmops", "createFile", "filepath", tmpCfgFilePath, "filecontents", tmpCfgFileContents); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "LoadBalancerCfgCommand failed to create HA proxy cfg file."); } String[] addRules = cmd.getAddFwRules(); String[] removeRules = cmd.getRemoveFwRules(); String args = ""; args += "-i " + routerIp; args += " -f " + tmpCfgFilePath; StringBuilder sb = new StringBuilder(); if (addRules.length > 0) { for (int i = 0; i < addRules.length; i++) { sb.append(addRules[i]).append(','); } args += " -a " + sb.toString(); } sb = new StringBuilder(); if (removeRules.length > 0) { for (int i = 0; i < removeRules.length; i++) { sb.append(removeRules[i]).append(','); } args += " -d " + sb.toString(); } result = callHostPlugin("vmops", "setLoadBalancerRule", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "LoadBalancerCfgCommand failed"); } callHostPlugin("vmops", "deleteFile", "filepath", tmpCfgFilePath); return new Answer(cmd); } protected synchronized Answer execute(final DhcpEntryCommand cmd) { String args = "-r " + cmd.getRouterPrivateIpAddress(); args += " -v " + cmd.getVmIpAddress(); args += " -m " + cmd.getVmMac(); args += " -n " + cmd.getVmName(); String result = callHostPlugin("vmops", "saveDhcpEntry", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "DhcpEntry failed"); } return new Answer(cmd); } protected Answer execute(final VmDataCommand cmd) { String routerPrivateIpAddress = cmd.getRouterPrivateIpAddress(); String vmIpAddress = cmd.getVmIpAddress(); List<String[]> vmData = cmd.getVmData(); String[] vmDataArgs = new String[vmData.size() * 2 + 4]; vmDataArgs[0] = "routerIP"; vmDataArgs[1] = routerPrivateIpAddress; vmDataArgs[2] = "vmIP"; vmDataArgs[3] = vmIpAddress; int i = 4; for (String[] vmDataEntry : vmData) { String folder = vmDataEntry[0]; String file = vmDataEntry[1]; String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; vmDataArgs[i] = folder + "," + file; vmDataArgs[i + 1] = contents; i += 2; } String result = callHostPlugin("vmops", "vm_data", vmDataArgs); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "vm_data failed"); } else { return new Answer(cmd); } } protected Answer execute(final SavePasswordCommand cmd) { final String password = cmd.getPassword(); final String routerPrivateIPAddress = cmd.getRouterPrivateIpAddress(); final String vmName = cmd.getVmName(); final String vmIpAddress = cmd.getVmIpAddress(); final String local = vmName; // Run save_password_to_domr.sh String args = "-r " + routerPrivateIPAddress; args += " -v " + vmIpAddress; args += " -p " + password; args += " " + local; String result = callHostPlugin("vmops", "savePassword", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "savePassword failed"); } return new Answer(cmd); } protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws InternalErrorException { try { Connection conn = getConnection(); VM router = getVM(conn, vmName); // Determine the correct VIF on DomR to associate/disassociate the // IP address with VIF correctVif = getCorrectVif(router, vlanId); // If we are associating an IP address and DomR doesn't have a VIF // for the specified vlan ID, we need to add a VIF // If we are disassociating the last IP address in the VLAN, we need // to remove a VIF boolean addVif = false; boolean removeVif = false; if (add && correctVif == null) { addVif = true; } else if (!add && firstIP) { removeVif = true; } if (addVif) { // Add a new VIF to DomR String vifDeviceNum = getLowestAvailableVIFDeviceNum(router); if (vifDeviceNum == null) { throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn)); } VIF.Record vifr = new VIF.Record(); vifr.VM = router; vifr.device = vifDeviceNum; vifr.MAC = vifMacAddress; if ("untagged".equalsIgnoreCase(vlanId)) { vifr.network = Network.getByUuid(conn, _host.publicNetwork); } else { Network vlanNetwork = enableVlanNetwork(Long.valueOf(vlanId), _host.publicNetwork, _host.publicPif); if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanId); } vifr.network = vlanNetwork; } correctVif = VIF.create(conn, vifr); correctVif.plug(conn); // Add iptables rule for network usage networkUsage(privateIpAddress, "addVif", "eth" + correctVif.getDevice(conn)); } if (correctVif == null) { throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); } String args; if (add) { args = "-A"; } else { args = "-D"; } if (sourceNat) { args += " -f"; } args += " -i "; args += privateIpAddress; args += " -l "; args += publicIpAddress; args += " -c "; args += "eth" + correctVif.getDevice(conn); args += " -g "; args += vlanGateway; String result = callHostPlugin("vmops", "ipassoc", "args", args); if (result == null || result.isEmpty()) { throw new InternalErrorException("Xen plugin \"ipassoc\" failed."); } if (removeVif) { Network network = correctVif.getNetwork(conn); // Mark this vif to be removed from network usage networkUsage(privateIpAddress, "deleteVif", "eth" + correctVif.getDevice(conn)); // Remove the VIF from DomR correctVif.unplug(conn); correctVif.destroy(conn); // Disable the VLAN network if necessary disableVlanNetwork(network); } } catch (XenAPIException e) { String msg = "Unable to assign public IP address due to " + e.toString(); s_logger.warn(msg, e); throw new InternalErrorException(msg); } catch (final XmlRpcException e) { String msg = "Unable to assign public IP address due to " + e.getMessage(); s_logger.warn(msg, e); throw new InternalErrorException(msg); } } protected String networkUsage(final String privateIpAddress, final String option, final String vif) { if (option.equals("get")) { return "0:0"; } return null; } protected Answer execute(final IPAssocCommand cmd) { try { assignPublicIpAddress(cmd.getRouterName(), cmd.getRouterIp(), cmd.getPublicIp(), cmd.isAdd(), cmd.isFirstIP(), cmd.isSourceNat(), cmd.getVlanId(), cmd.getVlanGateway(), cmd.getVlanNetmask(), cmd.getVifMacAddress()); } catch (InternalErrorException e) { return new Answer(cmd, false, e.getMessage()); } return new Answer(cmd); } protected GetVncPortAnswer execute(GetVncPortCommand cmd) { Connection conn = getConnection(); try { Set<VM> vms = VM.getByNameLabel(conn, cmd.getName()); return new GetVncPortAnswer(cmd, getVncPort(vms.iterator().next())); } catch (XenAPIException e) { s_logger.warn("Unable to get vnc port " + e.toString(), e); return new GetVncPortAnswer(cmd, e.toString()); } catch (Exception e) { s_logger.warn("Unable to get vnc port ", e); return new GetVncPortAnswer(cmd, e.getMessage()); } } protected Storage.StorageResourceType getStorageResourceType() { return Storage.StorageResourceType.STORAGE_POOL; } protected CheckHealthAnswer execute(CheckHealthCommand cmd) { boolean result = pingxenserver(); return new CheckHealthAnswer(cmd, result); } protected long[] getNetworkStats(String privateIP) { String result = networkUsage(privateIP, "get", null); long[] stats = new long[2]; if (result != null) { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } } return stats; } /** * This is the method called for getting the HOST stats * * @param cmd * @return */ protected GetHostStatsAnswer execute(GetHostStatsCommand cmd) { // Connection conn = getConnection(); try { HostStatsEntry hostStats = getHostStats(cmd, cmd.getHostGuid(), cmd.getHostId()); return new GetHostStatsAnswer(cmd, hostStats); } catch (Exception e) { String msg = "Unable to get Host stats" + e.toString(); s_logger.warn(msg, e); return new GetHostStatsAnswer(cmd, null); } } protected HostStatsEntry getHostStats(GetHostStatsCommand cmd, String hostGuid, long hostId) { HostStatsEntry hostStats = new HostStatsEntry(hostId, 0, 0, 0, 0, "host", 0, 0, 0, 0); Object[] rrdData = getRRDData(1); // call rrd method with 1 for host if (rrdData == null) { return null; } Integer numRows = (Integer) rrdData[0]; Integer numColumns = (Integer) rrdData[1]; Node legend = (Node) rrdData[2]; Node dataNode = (Node) rrdData[3]; NodeList legendChildren = legend.getChildNodes(); for (int col = 0; col < numColumns; col++) { if (legendChildren == null || legendChildren.item(col) == null) { continue; } String columnMetadata = getXMLNodeValue(legendChildren.item(col)); if (columnMetadata == null) { continue; } String[] columnMetadataList = columnMetadata.split(":"); if (columnMetadataList.length != 4) { continue; } String type = columnMetadataList[1]; String param = columnMetadataList[3]; if (type.equalsIgnoreCase("host")) { if (param.contains("pif_eth0_rx")) { hostStats.setNetworkReadKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("pif_eth0_tx")) { hostStats.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("memory_total_kib")) { hostStats.setTotalMemoryKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("memory_free_kib")) { hostStats.setFreeMemoryKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("cpu")) { hostStats.setNumCpus(hostStats.getNumCpus() + 1); hostStats.setCpuUtilization(hostStats.getCpuUtilization() + getDataAverage(dataNode, col, numRows)); } if (param.contains("loadavg")) { hostStats.setAverageLoad((hostStats.getAverageLoad() + getDataAverage(dataNode, col, numRows))); } } } // add the host cpu utilization if (hostStats.getNumCpus() != 0) { hostStats.setCpuUtilization(hostStats.getCpuUtilization() / hostStats.getNumCpus()); s_logger.debug("Host cpu utilization " + hostStats.getCpuUtilization()); } return hostStats; } protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { List<String> vmNames = cmd.getVmNames(); HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>(); if( vmNames.size() == 0 ) { return new GetVmStatsAnswer(cmd, vmStatsNameMap); } Connection conn = getConnection(); try { // Determine the UUIDs of the requested VMs List<String> vmUUIDs = new ArrayList<String>(); for (String vmName : vmNames) { VM vm = getVM(conn, vmName); vmUUIDs.add(vm.getUuid(conn)); } HashMap<String, VmStatsEntry> vmStatsUUIDMap = getVmStats(cmd, vmUUIDs, cmd.getHostGuid()); if( vmStatsUUIDMap == null ) return new GetVmStatsAnswer(cmd, vmStatsNameMap); for (String vmUUID : vmStatsUUIDMap.keySet()) { vmStatsNameMap.put(vmNames.get(vmUUIDs.indexOf(vmUUID)), vmStatsUUIDMap.get(vmUUID)); } return new GetVmStatsAnswer(cmd, vmStatsNameMap); } catch (XenAPIException e) { String msg = "Unable to get VM stats" + e.toString(); s_logger.warn(msg, e); return new GetVmStatsAnswer(cmd, vmStatsNameMap); } catch (XmlRpcException e) { String msg = "Unable to get VM stats" + e.getMessage(); s_logger.warn(msg, e); return new GetVmStatsAnswer(cmd, vmStatsNameMap); } } protected HashMap<String, VmStatsEntry> getVmStats(GetVmStatsCommand cmd, List<String> vmUUIDs, String hostGuid) { HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>(); for (String vmUUID : vmUUIDs) { vmResponseMap.put(vmUUID, new VmStatsEntry(0, 0, 0, 0, "vm")); } Object[] rrdData = getRRDData(2); // call rrddata with 2 for vm if (rrdData == null) { return null; } Integer numRows = (Integer) rrdData[0]; Integer numColumns = (Integer) rrdData[1]; Node legend = (Node) rrdData[2]; Node dataNode = (Node) rrdData[3]; NodeList legendChildren = legend.getChildNodes(); for (int col = 0; col < numColumns; col++) { if (legendChildren == null || legendChildren.item(col) == null) { continue; } String columnMetadata = getXMLNodeValue(legendChildren.item(col)); if (columnMetadata == null) { continue; } String[] columnMetadataList = columnMetadata.split(":"); if (columnMetadataList.length != 4) { continue; } String type = columnMetadataList[1]; String uuid = columnMetadataList[2]; String param = columnMetadataList[3]; if (type.equals("vm") && vmResponseMap.keySet().contains(uuid)) { VmStatsEntry vmStatsAnswer = vmResponseMap.get(uuid); vmStatsAnswer.setEntityType("vm"); if (param.contains("cpu")) { vmStatsAnswer.setNumCPUs(vmStatsAnswer.getNumCPUs() + 1); vmStatsAnswer.setCPUUtilization((vmStatsAnswer.getCPUUtilization() + getDataAverage(dataNode, col, numRows))*100); } else if (param.equals("vif_0_rx")) { vmStatsAnswer.setNetworkReadKBs(getDataAverage(dataNode, col, numRows)); } else if (param.equals("vif_0_tx")) { vmStatsAnswer.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows)); } } } for (String vmUUID : vmResponseMap.keySet()) { VmStatsEntry vmStatsAnswer = vmResponseMap.get(vmUUID); if (vmStatsAnswer.getNumCPUs() != 0) { vmStatsAnswer.setCPUUtilization(vmStatsAnswer.getCPUUtilization() / vmStatsAnswer.getNumCPUs()); s_logger.debug("Vm cpu utilization " + vmStatsAnswer.getCPUUtilization()); } } return vmResponseMap; } protected Object[] getRRDData(int flag) { /* * Note: 1 => called from host, hence host stats 2 => called from vm, hence vm stats */ String stats = ""; try { if (flag == 1) stats = getHostStatsRawXML(); if (flag == 2) stats = getVmStatsRawXML(); } catch (Exception e1) { s_logger.warn("Error whilst collecting raw stats from plugin:" + e1); return null; } // s_logger.debug("The raw xml stream is:"+stats); // s_logger.debug("Length of raw xml is:"+stats.length()); //stats are null when the host plugin call fails (host down state) if(stats == null) return null; StringReader statsReader = new StringReader(stats); InputSource statsSource = new InputSource(statsReader); Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(statsSource); } catch (Exception e) { } NodeList firstLevelChildren = doc.getChildNodes(); NodeList secondLevelChildren = (firstLevelChildren.item(0)).getChildNodes(); Node metaNode = secondLevelChildren.item(0); Node dataNode = secondLevelChildren.item(1); Integer numRows = 0; Integer numColumns = 0; Node legend = null; NodeList metaNodeChildren = metaNode.getChildNodes(); for (int i = 0; i < metaNodeChildren.getLength(); i++) { Node n = metaNodeChildren.item(i); if (n.getNodeName().equals("rows")) { numRows = Integer.valueOf(getXMLNodeValue(n)); } else if (n.getNodeName().equals("columns")) { numColumns = Integer.valueOf(getXMLNodeValue(n)); } else if (n.getNodeName().equals("legend")) { legend = n; } } return new Object[] { numRows, numColumns, legend, dataNode }; } protected String getXMLNodeValue(Node n) { return n.getChildNodes().item(0).getNodeValue(); } protected double getDataAverage(Node dataNode, int col, int numRows) { double value = 0; double dummy = 0; int numRowsUsed = 0; for (int row = 0; row < numRows; row++) { Node data = dataNode.getChildNodes().item(numRows - 1 - row).getChildNodes().item(col + 1); Double currentDataAsDouble = Double.valueOf(getXMLNodeValue(data)); if (!currentDataAsDouble.equals(Double.NaN)) { numRowsUsed += 1; value += currentDataAsDouble; } } if(numRowsUsed == 0) { if((!Double.isInfinite(value))&&(!Double.isInfinite(value))) { return value; } else { s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows=0"); return dummy; } } else { if((!Double.isInfinite(value/numRowsUsed))&&(!Double.isInfinite(value/numRowsUsed))) { return (value/numRowsUsed); } else { s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows>0"); return dummy; } } } protected String getHostStatsRawXML() { Date currentDate = new Date(); String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000); return callHostPlugin("vmops", "gethostvmstats", "collectHostStats", String.valueOf("true"), "consolidationFunction", _consolidationFunction, "interval", String .valueOf(_pollingIntervalInSeconds), "startTime", startTime); } protected String getVmStatsRawXML() { Date currentDate = new Date(); String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000); return callHostPlugin("vmops", "gethostvmstats", "collectHostStats", String.valueOf("false"), "consolidationFunction", _consolidationFunction, "interval", String .valueOf(_pollingIntervalInSeconds), "startTime", startTime); } protected void recordWarning(final VM vm, final String message, final Throwable e) { Connection conn = getConnection(); final StringBuilder msg = new StringBuilder(); try { final Long domId = vm.getDomid(conn); msg.append("[").append(domId != null ? domId : -1l).append("] "); } catch (final BadServerResponse e1) { } catch (final XmlRpcException e1) { } catch (XenAPIException e1) { } msg.append(message); } protected State convertToState(Types.VmPowerState ps) { final State state = s_statesTable.get(ps); return state == null ? State.Unknown : state; } protected HashMap<String, State> getAllVms() { final HashMap<String, State> vmStates = new HashMap<String, State>(); Connection conn = getConnection(); Set<VM> vms = null; for (int i = 0; i < 2; i++) { try { Host host = Host.getByUuid(conn, _host.uuid); vms = host.getResidentVMs(conn); break; } catch (final Throwable e) { s_logger.warn("Unable to get vms", e); } try { Thread.sleep(1000); } catch (final InterruptedException ex) { } } if (vms == null) { return null; } for (VM vm : vms) { VM.Record record = null; for (int i = 0; i < 2; i++) { try { record = vm.getRecord(conn); break; } catch (XenAPIException e1) { s_logger.debug("VM.getRecord failed on host:" + _host.uuid + " due to " + e1.toString()); } catch (XmlRpcException e1) { s_logger.debug("VM.getRecord failed on host:" + _host.uuid + " due to " + e1.getMessage()); } try { Thread.sleep(1000); } catch (final InterruptedException ex) { } } if (record == null) { continue; } if (record.isControlDomain || record.isASnapshot || record.isATemplate) { continue; // Skip DOM0 } VmPowerState ps = record.powerState; final State state = convertToState(ps); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + record.nameLabel + ": powerstate = " + ps + "; vm state=" + state.toString()); } vmStates.put(record.nameLabel, state); } return vmStates; } protected State getVmState(final String vmName) { Connection conn = getConnection(); int retry = 3; while (retry-- > 0) { try { Set<VM> vms = VM.getByNameLabel(conn, vmName); for (final VM vm : vms) { return convertToState(vm.getPowerState(conn)); } } catch (final BadServerResponse e) { // There is a race condition within xen such that if a vm is // deleted and we // happen to ask for it, it throws this stupid response. So // if this happens, // we take a nap and try again which then avoids the race // condition because // the vm's information is now cleaned up by xen. The error // is as follows // com.xensource.xenapi.Types$BadServerResponse // [HANDLE_INVALID, VM, // 3dde93f9-c1df-55a7-2cde-55e1dce431ab] s_logger.info("Unable to get a vm PowerState due to " + e.toString() + ". We are retrying. Count: " + retry); try { Thread.sleep(3000); } catch (final InterruptedException ex) { } } catch (XenAPIException e) { String msg = "Unable to get a vm PowerState due to " + e.toString(); s_logger.warn(msg, e); break; } catch (final XmlRpcException e) { String msg = "Unable to get a vm PowerState due to " + e.getMessage(); s_logger.warn(msg, e); break; } } return State.Stopped; } protected CheckVirtualMachineAnswer execute(final CheckVirtualMachineCommand cmd) { final String vmName = cmd.getVmName(); final State state = getVmState(vmName); Integer vncPort = null; if (state == State.Running) { synchronized (_vms) { _vms.put(vmName, State.Running); } } return new CheckVirtualMachineAnswer(cmd, state, vncPort); } protected PrepareForMigrationAnswer execute(final PrepareForMigrationCommand cmd) { /* * * String result = null; * * List<VolumeVO> vols = cmd.getVolumes(); result = mountwithoutvdi(vols, cmd.getMappings()); if (result != * null) { return new PrepareForMigrationAnswer(cmd, false, result); } */ final String vmName = cmd.getVmName(); try { Connection conn = getConnection(); Set<Host> hosts = Host.getAll(conn); // workaround before implementing xenserver pool // no migration if (hosts.size() <= 1) { return new PrepareForMigrationAnswer(cmd, false, "not in a same xenserver pool"); } // if the vm have CD // 1. make iosSR shared // 2. create pbd in target xenserver SR sr = getISOSRbyVmName(cmd.getVmName()); if (sr != null) { Set<PBD> pbds = sr.getPBDs(conn); boolean found = false; for (PBD pbd : pbds) { if (Host.getByUuid(conn, _host.uuid).equals(pbd.getHost(conn))) { found = true; break; } } if (!found) { sr.setShared(conn, true); PBD pbd = pbds.iterator().next(); PBD.Record pbdr = new PBD.Record(); pbdr.deviceConfig = pbd.getDeviceConfig(conn); pbdr.host = Host.getByUuid(conn, _host.uuid); pbdr.SR = sr; PBD newpbd = PBD.create(conn, pbdr); newpbd.plug(conn); } } Set<VM> vms = VM.getByNameLabel(conn, vmName); if (vms.size() != 1) { String msg = "There are " + vms.size() + " " + vmName; s_logger.warn(msg); return new PrepareForMigrationAnswer(cmd, false, msg); } VM vm = vms.iterator().next(); // check network Set<VIF> vifs = vm.getVIFs(conn); for (VIF vif : vifs) { Network network = vif.getNetwork(conn); Set<PIF> pifs = network.getPIFs(conn); Long vlan = null; PIF npif = null; for (PIF pif : pifs) { try { vlan = pif.getVLAN(conn); if (vlan != null) { VLAN vland = pif.getVLANMasterOf(conn); npif = vland.getTaggedPIF(conn); break; } }catch (Exception e) { vlan = null; continue; } } if (vlan == null) { continue; } network = npif.getNetwork(conn); String nwuuid = network.getUuid(conn); String pifuuid = null; if(nwuuid.equalsIgnoreCase(_host.privateNetwork)) { pifuuid = _host.privatePif; } else if(nwuuid.equalsIgnoreCase(_host.publicNetwork)) { pifuuid = _host.publicPif; } else { continue; } Network vlanNetwork = enableVlanNetwork(vlan, nwuuid, pifuuid); if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlan); } } synchronized (_vms) { _vms.put(cmd.getVmName(), State.Migrating); } return new PrepareForMigrationAnswer(cmd, true, null); } catch (Exception e) { String msg = "catch exception " + e.getMessage(); s_logger.warn(msg, e); return new PrepareForMigrationAnswer(cmd, false, msg); } } @Override public DownloadAnswer execute(final PrimaryStorageDownloadCommand cmd) { SR tmpltsr = null; String tmplturl = cmd.getUrl(); int index = tmplturl.lastIndexOf("/"); String mountpoint = tmplturl.substring(0, index); String tmpltname = null; if (index < tmplturl.length() - 1) tmpltname = tmplturl.substring(index + 1).replace(".vhd", ""); try { Connection conn = getConnection(); String pUuid = cmd.getPoolUuid(); SR poolsr = null; Set<SR> srs = SR.getByNameLabel(conn, pUuid); if (srs.size() != 1) { String msg = "There are " + srs.size() + " SRs with same name: " + pUuid; s_logger.warn(msg); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } else { poolsr = srs.iterator().next(); } /* Does the template exist in primary storage pool? If yes, no copy */ VDI vmtmpltvdi = null; Set<VDI> vdis = VDI.getByNameLabel(conn, "Template " + cmd.getName()); for (VDI vdi : vdis) { VDI.Record vdir = vdi.getRecord(conn); if (vdir.SR.equals(poolsr)) { vmtmpltvdi = vdi; break; } } String uuid; if (vmtmpltvdi == null) { tmpltsr = createNfsSRbyURI(new URI(mountpoint), false); tmpltsr.scan(conn); VDI tmpltvdi = null; if (tmpltname != null) { tmpltvdi = getVDIbyUuid(tmpltname); } if (tmpltvdi == null) { vdis = tmpltsr.getVDIs(conn); for (VDI vdi : vdis) { tmpltvdi = vdi; break; } } if (tmpltvdi == null) { String msg = "Unable to find template vdi on secondary storage" + "host:" + _host.uuid + "pool: " + tmplturl; s_logger.warn(msg); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } vmtmpltvdi = cloudVDIcopy(tmpltvdi, poolsr); vmtmpltvdi.setNameLabel(conn, "Template " + cmd.getName()); // vmtmpltvdi.setNameDescription(conn, cmd.getDescription()); uuid = vmtmpltvdi.getUuid(conn); } else uuid = vmtmpltvdi.getUuid(conn); // Determine the size of the template long createdSize = vmtmpltvdi.getVirtualSize(conn); DownloadAnswer answer = new DownloadAnswer(null, 100, cmd, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, uuid, uuid); answer.setTemplateSize(createdSize); return answer; } catch (XenAPIException e) { String msg = "XenAPIException:" + e.toString() + "host:" + _host.uuid + "pool: " + tmplturl; s_logger.warn(msg, e); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } catch (Exception e) { String msg = "XenAPIException:" + e.getMessage() + "host:" + _host.uuid + "pool: " + tmplturl; s_logger.warn(msg, e); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } finally { removeSR(tmpltsr); } } protected String removeSRSync(SR sr) { if (sr == null) { return null; } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Removing SR")); } Connection conn = getConnection(); long waittime = 0; try { Set<VDI> vdis = sr.getVDIs(conn); for (VDI vdi : vdis) { Map<java.lang.String, Types.VdiOperations> currentOperation = vdi.getCurrentOperations(conn); if (currentOperation == null || currentOperation.size() == 0) { continue; } if (waittime >= 1800000) { String msg = "This template is being used, try late time"; s_logger.warn(msg); return msg; } waittime += 30000; try { Thread.sleep(30000); } catch (final InterruptedException ex) { } } removeSR(sr); return null; } catch (XenAPIException e) { s_logger.warn(logX(sr, "Unable to get current opertions " + e.toString()), e); } catch (XmlRpcException e) { s_logger.warn(logX(sr, "Unable to get current opertions " + e.getMessage()), e); } String msg = "Remove SR failed"; s_logger.warn(msg); return msg; } protected void removeSR(SR sr) { if (sr == null) { return; } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Removing SR")); } for (int i = 0; i < 2; i++) { Connection conn = getConnection(); try { Set<VDI> vdis = sr.getVDIs(conn); for (VDI vdi : vdis) { vdi.forget(conn); } Set<PBD> pbds = sr.getPBDs(conn); for (PBD pbd : pbds) { if (s_logger.isDebugEnabled()) { s_logger.debug(logX(pbd, "Unplugging pbd")); } if (pbd.getCurrentlyAttached(conn)) { pbd.unplug(conn); } pbd.destroy(conn); } pbds = sr.getPBDs(conn); if (pbds.size() == 0) { if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Forgetting")); } sr.forget(conn); return; } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "There are still pbd attached")); if (s_logger.isTraceEnabled()) { for (PBD pbd : pbds) { s_logger.trace(logX(pbd, " Still attached")); } } } } catch (XenAPIException e) { s_logger.debug(logX(sr, "Catch XenAPIException: " + e.toString())); } catch (XmlRpcException e) { s_logger.debug(logX(sr, "Catch Exception: " + e.getMessage())); } } s_logger.warn(logX(sr, "Unable to remove SR")); } protected MigrateAnswer execute(final MigrateCommand cmd) { final String vmName = cmd.getVmName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { Connection conn = getConnection(); Set<VM> vms = VM.getByNameLabel(conn, vmName); String ipaddr = cmd.getDestinationIp(); Set<Host> hosts = Host.getAll(conn); Host dsthost = null; for (Host host : hosts) { if (host.getAddress(conn).equals(ipaddr)) { dsthost = host; break; } } // if it is windows, we will not fake it is migrateable, // windows requires PV driver to migrate for (VM vm : vms) { if (!cmd.isWindows()) { String uuid = vm.getUuid(conn); String result = callHostPlugin("vmops", "preparemigration", "uuid", uuid); if (result == null || result.isEmpty()) { return new MigrateAnswer(cmd, false, "migration failed", null); } // check if pv version is successfully set up int i = 0; for (; i < 20; i++) { try { Thread.sleep(1000); } catch (final InterruptedException ex) { } VMGuestMetrics vmmetric = vm.getGuestMetrics(conn); if (isRefNull(vmmetric)) continue; Map<String, String> PVversion = vmmetric.getPVDriversVersion(conn); if (PVversion != null && PVversion.containsKey("major")) { break; } } if (i >= 20) { String msg = "migration failed due to can not fake PV driver for " + vmName; s_logger.warn(msg); return new MigrateAnswer(cmd, false, msg, null); } } final Map<String, String> options = new HashMap<String, String>(); vm.poolMigrate(conn, dsthost, options); state = State.Stopping; } return new MigrateAnswer(cmd, true, "migration succeeded", null); } catch (XenAPIException e) { String msg = "migration failed due to " + e.toString(); s_logger.warn(msg, e); return new MigrateAnswer(cmd, false, msg, null); } catch (XmlRpcException e) { String msg = "migration failed due to " + e.getMessage(); s_logger.warn(msg, e); return new MigrateAnswer(cmd, false, msg, null); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } protected State getRealPowerState(String label) { Connection conn = getConnection(); int i = 0; s_logger.trace("Checking on the HALTED State"); for (; i < 20; i++) { try { Set<VM> vms = VM.getByNameLabel(conn, label); if (vms == null || vms.size() == 0) { continue; } VM vm = vms.iterator().next(); VmPowerState vps = vm.getPowerState(conn); if (vps != null && vps != VmPowerState.HALTED && vps != VmPowerState.UNKNOWN && vps != VmPowerState.UNRECOGNIZED) { return convertToState(vps); } } catch (XenAPIException e) { String msg = "Unable to get real power state due to " + e.toString(); s_logger.warn(msg, e); } catch (XmlRpcException e) { String msg = "Unable to get real power state due to " + e.getMessage(); s_logger.warn(msg, e); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } return State.Stopped; } protected Pair<VM, VM.Record> getControlDomain(Connection conn) throws XenAPIException, XmlRpcException { Host host = Host.getByUuid(conn, _host.uuid); Set<VM> vms = null; vms = host.getResidentVMs(conn); for (VM vm : vms) { if (vm.getIsControlDomain(conn)) { return new Pair<VM, VM.Record>(vm, vm.getRecord(conn)); } } throw new CloudRuntimeException("Com'on no control domain? What the crap?!#@!##$@"); } protected HashMap<String, State> sync() { HashMap<String, State> newStates; HashMap<String, State> oldStates = null; final HashMap<String, State> changes = new HashMap<String, State>(); synchronized (_vms) { newStates = getAllVms(); if (newStates == null) { s_logger.debug("Unable to get the vm states so no state sync at this point."); return null; } oldStates = new HashMap<String, State>(_vms.size()); oldStates.putAll(_vms); for (final Map.Entry<String, State> entry : newStates.entrySet()) { final String vm = entry.getKey(); State newState = entry.getValue(); final State oldState = oldStates.remove(vm); if (newState == State.Stopped && oldState != State.Stopping && oldState != null && oldState != State.Stopped) { newState = getRealPowerState(vm); } if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + ": xen has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); } if (vm.startsWith("migrating")) { s_logger.debug("Migrating from xen detected. Skipping"); continue; } if (oldState == null) { _vms.put(vm, newState); s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); changes.put(vm, newState); } else if (oldState == State.Starting) { if (newState == State.Running) { _vms.put(vm, newState); } else if (newState == State.Stopped) { s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); } } else if (oldState == State.Migrating) { if (newState == State.Running) { s_logger.debug("Detected that an migrating VM is now running: " + vm); _vms.put(vm, newState); } } else if (oldState == State.Stopping) { if (newState == State.Stopped) { _vms.put(vm, newState); } else if (newState == State.Running) { s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); } } else if (oldState != newState) { _vms.put(vm, newState); if (newState == State.Stopped) { /* * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); * newState = State.Error; } */ } changes.put(vm, newState); } } for (final Map.Entry<String, State> entry : oldStates.entrySet()) { final String vm = entry.getKey(); final State oldState = entry.getValue(); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + " is now missing from xen so reporting stopped"); } if (oldState == State.Stopping) { s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); _vms.remove(vm); } else if (oldState == State.Starting) { s_logger.debug("Ignoring VM " + vm + " in transition state starting."); } else if (oldState == State.Stopped) { _vms.remove(vm); } else if (oldState == State.Migrating) { s_logger.debug("Ignoring VM " + vm + " in migrating state."); } else { State state = State.Stopped; /* * if (_vmsKilled.remove(entry.getKey())) { s_logger.debug("VM " + vm + * " has been killed by storage monitor"); state = State.Error; } */ changes.put(entry.getKey(), state); } } } return changes; } protected ReadyAnswer execute(ReadyCommand cmd) { Long dcId = cmd.getDataCenterId(); // Ignore the result of the callHostPlugin. Even if unmounting the // snapshots dir fails, let Ready command // succeed. callHostPlugin("vmopsSnapshot", "unmountSnapshotsDir", "dcId", dcId.toString()); return new ReadyAnswer(cmd); } // // using synchronized on VM name in the caller does not prevent multiple // commands being sent against // the same VM, there will be a race condition here in finally clause and // the main block if // there are multiple requests going on // // Therefore, a lazy solution is to add a synchronized guard here protected int getVncPort(VM vm) { Connection conn = getConnection(); VM.Record record; try { record = vm.getRecord(conn); } catch (XenAPIException e) { String msg = "Unable to get vnc-port due to " + e.toString(); s_logger.warn(msg, e); return -1; } catch (XmlRpcException e) { String msg = "Unable to get vnc-port due to " + e.getMessage(); s_logger.warn(msg, e); return -1; } String hvm = "true"; if (record.HVMBootPolicy.isEmpty()) { hvm = "false"; } String vncport = callHostPlugin("vmops", "getvncport", "domID", record.domid.toString(), "hvm", hvm); if (vncport == null || vncport.isEmpty()) { return -1; } vncport = vncport.replace("\n", ""); return NumbersUtil.parseInt(vncport, -1); } protected Answer execute(final RebootCommand cmd) { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Starting); } try { Connection conn = getConnection(); Set<VM> vms = null; try { vms = VM.getByNameLabel(conn, cmd.getVmName()); } catch (XenAPIException e0) { s_logger.debug("getByNameLabel failed " + e0.toString()); return new RebootAnswer(cmd, "getByNameLabel failed " + e0.toString()); } catch (Exception e0) { s_logger.debug("getByNameLabel failed " + e0.getMessage()); return new RebootAnswer(cmd, "getByNameLabel failed"); } for (VM vm : vms) { try { vm.cleanReboot(conn); } catch (XenAPIException e) { s_logger.debug("Do Not support Clean Reboot, fall back to hard Reboot: " + e.toString()); try { vm.hardReboot(conn); } catch (XenAPIException e1) { s_logger.debug("Caught exception on hard Reboot " + e1.toString()); return new RebootAnswer(cmd, "reboot failed: " + e1.toString()); } catch (XmlRpcException e1) { s_logger.debug("Caught exception on hard Reboot " + e1.getMessage()); return new RebootAnswer(cmd, "reboot failed"); } } catch (XmlRpcException e) { String msg = "Clean Reboot failed due to " + e.getMessage(); s_logger.warn(msg, e); return new RebootAnswer(cmd, msg); } } return new RebootAnswer(cmd, "reboot succeeded", null, null); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Running); } } } protected Answer execute(RebootRouterCommand cmd) { Long bytesSent = 0L; Long bytesRcvd = 0L; if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); bytesSent = stats[0]; bytesRcvd = stats[1]; } RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); answer.setBytesSent(bytesSent); answer.setBytesReceived(bytesRcvd); if (answer.getResult()) { String cnct = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); networkUsage(cmd.getPrivateIpAddress(), "create", null); if (cnct == null) { return answer; } else { return new Answer(cmd, false, cnct); } } return answer; } protected VM createVmFromTemplate(Connection conn, StartCommand cmd) throws XenAPIException, XmlRpcException { Set<VM> templates; VM vm = null; String stdType = cmd.getGuestOSDescription(); String guestOsTypeName = getGuestOsType(stdType); templates = VM.getByNameLabel(conn, guestOsTypeName); assert templates.size() == 1 : "Should only have 1 template but found " + templates.size(); VM template = templates.iterator().next(); vm = template.createClone(conn, cmd.getVmName()); vm.removeFromOtherConfig(conn, "disks"); if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) { if (cmd.getBootFromISO()) vm.setPVBootloader(conn, "eliloader"); else vm.setPVBootloader(conn, "pygrub"); vm.addToOtherConfig(conn, "install-repository", "cdrom"); } return vm; } protected String getGuestOsType(String stdType) { return _guestOsType.get(stdType); } public boolean joinPool(String address, String username, String password) { Connection conn = getConnection(); Connection poolConn = null; try { // set the _host.poolUuid to the old pool uuid in case it's not set. _host.pool = getPoolUuid(); // Connect and find out about the new connection to the new pool. poolConn = _connPool.connect(address, username, password, _wait); Map<Pool, Pool.Record> pools = Pool.getAllRecords(poolConn); Pool.Record pr = pools.values().iterator().next(); // Now join it. String masterAddr = pr.master.getAddress(poolConn); Pool.join(conn, masterAddr, username, password); if (s_logger.isDebugEnabled()) { s_logger.debug("Joined the pool at " + masterAddr); } disconnected(); // Logout of our own session. try { // slave will restart xapi in 10 sec Thread.sleep(10000); } catch (InterruptedException e) { } // Set the pool uuid now to the newest pool. _host.pool = pr.uuid; URL url; try { url = new URL("http://" + _host.ip); } catch (MalformedURLException e1) { throw new CloudRuntimeException("Problem with url " + _host.ip); } Connection c = null; for (int i = 0; i < 15; i++) { c = new Connection(url, _wait); try { Session.loginWithPassword(c, _username, _password, APIVersion.latest().toString()); s_logger.debug("Still waiting for the conversion to the master"); Session.logout(c); c.dispose(); } catch (Types.HostIsSlave e) { try { Session.logout(c); c.dispose(); } catch (XmlRpcException e1) { s_logger.debug("Unable to logout of test connection due to " + e1.getMessage()); } catch (XenAPIException e1) { s_logger.debug("Unable to logout of test connection due to " + e1.getMessage()); } break; } catch (XmlRpcException e) { s_logger.debug("XmlRpcException: Still waiting for the conversion to the master"); } catch (Exception e) { s_logger.debug("Exception: Still waiting for the conversion to the master"); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } return true; } catch (XenAPIException e) { String msg = "Unable to allow host " + _host.uuid + " to join pool " + address + " due to " + e.toString(); s_logger.warn(msg, e); throw new RuntimeException(msg); } catch (XmlRpcException e) { String msg = "Unable to allow host " + _host.uuid + " to join pool " + address + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new RuntimeException(msg); } finally { if (poolConn != null) { XenServerConnectionPool.logout(poolConn); } } } protected void startvmfailhandle(VM vm, List<Ternary<SR, VDI, VolumeVO>> mounts) { Connection conn = getConnection(); if (vm != null) { try { if (vm.getPowerState(conn) == VmPowerState.RUNNING) { try { vm.hardShutdown(conn); } catch (Exception e) { String msg = "VM hardshutdown failed due to " + e.toString(); s_logger.warn(msg); } } if (vm.getPowerState(conn) == VmPowerState.HALTED) { try { vm.destroy(conn); } catch (Exception e) { String msg = "VM destroy failed due to " + e.toString(); s_logger.warn(msg); } } } catch (Exception e) { String msg = "VM getPowerState failed due to " + e.toString(); s_logger.warn(msg); } } if (mounts != null) { for (Ternary<SR, VDI, VolumeVO> mount : mounts) { VDI vdi = mount.second(); Set<VBD> vbds = null; try { vbds = vdi.getVBDs(conn); } catch (Exception e) { String msg = "VDI getVBDS failed due to " + e.toString(); s_logger.warn(msg); continue; } for (VBD vbd : vbds) { try { vbd.unplug(conn); vbd.destroy(conn); } catch (Exception e) { String msg = "VBD destroy failed due to " + e.toString(); s_logger.warn(msg); } } } } } protected void setMemory(Connection conn, VM vm, long memsize) throws XmlRpcException, XenAPIException { vm.setMemoryStaticMin(conn, memsize); vm.setMemoryDynamicMin(conn, memsize); vm.setMemoryDynamicMax(conn, memsize); vm.setMemoryStaticMax(conn, memsize); } protected StartAnswer execute(StartCommand cmd) { State state = State.Stopped; Connection conn = getConnection(); VM vm = null; SR isosr = null; List<Ternary<SR, VDI, VolumeVO>> mounts = null; for (int retry = 0; retry < 2; retry++) { try { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Starting); } List<VolumeVO> vols = cmd.getVolumes(); mounts = mount(vols); if (retry == 1) { // at the second time, try hvm cmd.setGuestOSDescription("Other install media"); } vm = createVmFromTemplate(conn, cmd); long memsize = cmd.getRamSize() * 1024L * 1024L; setMemory(conn, vm, memsize); vm.setIsATemplate(conn, false); vm.setVCPUsMax(conn, (long) cmd.getCpu()); vm.setVCPUsAtStartup(conn, (long) cmd.getCpu()); Host host = Host.getByUuid(conn, _host.uuid); vm.setAffinity(conn, host); Map<String, String> vcpuparam = new HashMap<String, String>(); vcpuparam.put("weight", Integer.toString(cmd.getCpuWeight())); vcpuparam.put("cap", Integer.toString(cmd.getUtilization())); vm.setVCPUsParams(conn, vcpuparam); boolean bootFromISO = cmd.getBootFromISO(); /* create root VBD */ VBD.Record vbdr = new VBD.Record(); Ternary<SR, VDI, VolumeVO> mount = mounts.get(0); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = !bootFromISO; vbdr.userdevice = "0"; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; VBD.create(conn, vbdr); /* create data VBDs */ for (int i = 1; i < mounts.size(); i++) { mount = mounts.get(i); // vdi.setNameLabel(conn, cmd.getVmName() + "-DATA"); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = false; vbdr.userdevice = Long.toString(mount.third().getDeviceId()); vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; VBD.create(conn, vbdr); } /* create CD-ROM VBD */ VBD.Record cdromVBDR = new VBD.Record(); cdromVBDR.VM = vm; cdromVBDR.empty = true; cdromVBDR.bootable = bootFromISO; cdromVBDR.userdevice = "3"; cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; VBD cdromVBD = VBD.create(conn, cdromVBDR); /* insert the ISO VDI if isoPath is not null */ String isopath = cmd.getISOPath(); if (isopath != null) { int index = isopath.lastIndexOf("/"); String mountpoint = isopath.substring(0, index); URI uri = new URI(mountpoint); isosr = createIsoSRbyURI(uri, cmd.getVmName(), false); String isoname = isopath.substring(index + 1); VDI isovdi = getVDIbyLocationandSR(isoname, isosr); if (isovdi == null) { String msg = " can not find ISO " + cmd.getISOPath(); s_logger.warn(msg); return new StartAnswer(cmd, msg); } else { cdromVBD.insert(conn, isovdi); } } createVIF(conn, vm, cmd.getGuestMacAddress(), cmd.getGuestNetworkId(), cmd.getNetworkRateMbps(), "0", false); if (cmd.getExternalMacAddress() != null && cmd.getExternalVlan() != null) { createVIF(conn, vm, cmd.getExternalMacAddress(), cmd.getExternalVlan(), 0, "1", true); } /* set action after crash as destroy */ vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY); vm.start(conn, false, true); if (_canBridgeFirewall) { String result = callHostPlugin("vmops", "default_network_rules", "vmName", cmd.getVmName(), "vmIP", cmd.getGuestIpAddress(), "vmMAC", cmd.getGuestMacAddress(), "vmID", Long.toString(cmd.getId())); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default network rules for vm " + cmd.getVmName()); } else { s_logger.info("Programmed default network rules for vm " + cmd.getVmName()); } } state = State.Running; return new StartAnswer(cmd); } catch (XenAPIException e) { String errormsg = e.toString(); String msg = "Exception caught while starting VM due to message:" + errormsg + " (" + e.getClass().getName() + ")"; if (!errormsg.contains("Unable to find partition containing kernel") && !errormsg.contains("Unable to access a required file in the specified repository")) { s_logger.warn(msg, e); startvmfailhandle(vm, mounts); removeSR(isosr); } else { startvmfailhandle(vm, mounts); removeSR(isosr); continue; } state = State.Stopped; return new StartAnswer(cmd, msg); } catch (Exception e) { String msg = "Exception caught while starting VM due to message:" + e.getMessage(); s_logger.warn(msg, e); startvmfailhandle(vm, mounts); removeSR(isosr); state = State.Stopped; return new StartAnswer(cmd, msg); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), state); } } } String msg = "Start VM failed"; return new StartAnswer(cmd, msg); } protected void createVIF(Connection conn, VM vm, String mac, String vlanTag, int rate, String devNum, boolean isPub) throws XenAPIException, XmlRpcException, InternalErrorException { VIF.Record vifr = new VIF.Record(); vifr.VM = vm; vifr.device = devNum; vifr.MAC = mac; String nwUuid = (isPub ? _host.publicNetwork : _host.guestNetwork); String pifUuid = (isPub ? _host.publicPif : _host.guestPif); Network vlanNetwork = null; if ("untagged".equalsIgnoreCase(vlanTag)) { vlanNetwork = Network.getByUuid(conn, nwUuid); } else { vlanNetwork = enableVlanNetwork(Long.valueOf(vlanTag), nwUuid, pifUuid); } if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanTag); } vifr.network = vlanNetwork; if (rate != 0) { vifr.qosAlgorithmType = "ratelimit"; vifr.qosAlgorithmParams = new HashMap<String, String>(); vifr.qosAlgorithmParams.put("kbps", Integer.toString(rate * 1000)); } VIF.create(conn, vifr); } protected StopAnswer execute(final StopCommand cmd) { String vmName = cmd.getVmName(); try { Connection conn = getConnection(); Set<VM> vms = VM.getByNameLabel(conn, vmName); // stop vm which is running on this host or is in halted state for (VM vm : vms) { VM.Record vmr = vm.getRecord(conn); if (vmr.powerState != VmPowerState.RUNNING) continue; if (isRefNull(vmr.residentOn)) continue; if (vmr.residentOn.getUuid(conn).equals(_host.uuid)) continue; vms.remove(vm); } if (vms.size() == 0) { s_logger.warn("VM does not exist on XenServer" + _host.uuid); synchronized (_vms) { _vms.remove(vmName); } return new StopAnswer(cmd, "VM does not exist", 0, 0L, 0L); } Long bytesSent = 0L; Long bytesRcvd = 0L; for (VM vm : vms) { VM.Record vmr = vm.getRecord(conn); if (vmr.isControlDomain) { String msg = "Tring to Shutdown control domain"; s_logger.warn(msg); return new StopAnswer(cmd, msg); } if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) { String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.uuid + " but host:" + vmr.residentOn.getUuid(conn); s_logger.warn(msg); return new StopAnswer(cmd, msg); } State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { if (vmr.powerState == VmPowerState.RUNNING) { /* when stop a vm, set affinity to current xenserver */ vm.setAffinity(conn, vm.getResidentOn(conn)); try { if (VirtualMachineName.isValidRouterName(vmName)) { if(cmd.getPrivateRouterIpAddress() != null){ long[] stats = getNetworkStats(cmd.getPrivateRouterIpAddress()); bytesSent = stats[0]; bytesRcvd = stats[1]; } } if (_canBridgeFirewall) { String result = callHostPlugin("vmops", "destroy_network_rules_for_vm", "vmName", cmd.getVmName()); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to remove network rules for vm " + cmd.getVmName()); } else { s_logger.info("Removed network rules for vm " + cmd.getVmName()); } } vm.cleanShutdown(conn); } catch (XenAPIException e) { s_logger.debug("Do Not support Clean Shutdown, fall back to hard Shutdown: " + e.toString()); try { vm.hardShutdown(conn); } catch (XenAPIException e1) { String msg = "Hard Shutdown failed due to " + e1.toString(); s_logger.warn(msg, e1); return new StopAnswer(cmd, msg); } catch (XmlRpcException e1) { String msg = "Hard Shutdown failed due to " + e1.getMessage(); s_logger.warn(msg, e1); return new StopAnswer(cmd, msg); } } catch (XmlRpcException e) { String msg = "Clean Shutdown failed due to " + e.getMessage(); s_logger.warn(msg, e); return new StopAnswer(cmd, msg); } } } catch (Exception e) { String msg = "Catch exception " + e.getClass().toString() + " when stop VM:" + cmd.getVmName(); s_logger.debug(msg); return new StopAnswer(cmd, msg); } finally { try { if (vm.getPowerState(conn) == VmPowerState.HALTED) { Set<VIF> vifs = vm.getVIFs(conn); List<Network> networks = new ArrayList<Network>(); for (VIF vif : vifs) { networks.add(vif.getNetwork(conn)); } List<VDI> vdis = getVdis(vm); vm.destroy(conn); for( VDI vdi : vdis ){ umount(vdi); } state = State.Stopped; SR sr = getISOSRbyVmName(cmd.getVmName()); removeSR(sr); // Disable any VLAN networks that aren't used // anymore for (Network network : networks) { if (network.getNameLabel(conn).startsWith("VLAN")) { disableVlanNetwork(network); } } } } catch (XenAPIException e) { String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage(); s_logger.warn(msg, e); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } } return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", 0, bytesSent, bytesRcvd); } catch (XenAPIException e) { String msg = "Stop Vm " + vmName + " fail due to " + e.toString(); s_logger.warn(msg, e); return new StopAnswer(cmd, msg); } catch (XmlRpcException e) { String msg = "Stop Vm " + vmName + " fail due to " + e.getMessage(); s_logger.warn(msg, e); return new StopAnswer(cmd, msg); } } private List<VDI> getVdis(VM vm) { List<VDI> vdis = new ArrayList<VDI>(); try { Connection conn = getConnection(); Set<VBD> vbds =vm.getVBDs(conn); for( VBD vbd : vbds ) { vdis.add(vbd.getVDI(conn)); } } catch (XenAPIException e) { String msg = "getVdis can not get VPD due to " + e.toString(); s_logger.warn(msg, e); } catch (XmlRpcException e) { String msg = "getVdis can not get VPD due to " + e.getMessage(); s_logger.warn(msg, e); } return vdis; } protected String connect(final String vmName, final String ipAddress, final int port) { for (int i = 0; i <= _retry; i++) { try { Connection conn = getConnection(); Set<VM> vms = VM.getByNameLabel(conn, vmName); if (vms.size() < 1) { String msg = "VM " + vmName + " is not running"; s_logger.warn(msg); return msg; } } catch (Exception e) { String msg = "VM.getByNameLabel " + vmName + " failed due to " + e.toString(); s_logger.warn(msg, e); return msg; } if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to connect to " + ipAddress); } if (pingdomr(ipAddress, Integer.toString(port))) return null; try { Thread.sleep(_sleep); } catch (final InterruptedException e) { } } String msg = "Timeout, Unable to logon to " + ipAddress; s_logger.debug(msg); return msg; } protected String connect(final String vmname, final String ipAddress) { return connect(vmname, ipAddress, 3922); } protected StartRouterAnswer execute(StartRouterCommand cmd) { final String vmName = cmd.getVmName(); final DomainRouter router = cmd.getRouter(); try { String tag = router.getVnet(); Network network = null; if ("untagged".equalsIgnoreCase(tag)) { Connection conn = getConnection(); network = Network.getByUuid(conn, _host.guestNetwork); } else { network = enableVlanNetwork(Long.parseLong(tag), _host.guestNetwork, _host.guestPif); } if (network == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + tag); } String bootArgs = cmd.getBootArgs(); String result = startSystemVM(vmName, router.getVlanId(), network, cmd.getVolumes(), bootArgs, router.getGuestMacAddress(), router.getPrivateIpAddress(), router .getPrivateMacAddress(), router.getPublicMacAddress(), 3922, router.getRamSize()); if (result == null) { networkUsage(router.getPrivateIpAddress(), "create", null); return new StartRouterAnswer(cmd); } return new StartRouterAnswer(cmd, result); } catch (Exception e) { String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); return new StartRouterAnswer(cmd, msg); } } protected String startSystemVM(String vmName, String vlanId, Network nw0, List<VolumeVO> vols, String bootArgs, String guestMacAddr, String privateIp, String privateMacAddr, String publicMacAddr, int cmdPort, long ramSize) { setupLinkLocalNetwork(); VM vm = null; List<Ternary<SR, VDI, VolumeVO>> mounts = null; Connection conn = getConnection(); State state = State.Stopped; try { synchronized (_vms) { _vms.put(vmName, State.Starting); } mounts = mount(vols); assert mounts.size() == 1 : "System VMs should have only 1 partition but we actually have " + mounts.size(); Ternary<SR, VDI, VolumeVO> mount = mounts.get(0); Set<VM> templates = VM.getByNameLabel(conn, "CentOS 5.3"); if (templates.size() == 0) { templates = VM.getByNameLabel(conn, "CentOS 5.3 (64-bit)"); if (templates.size() == 0) { String msg = " can not find template CentOS 5.3 "; s_logger.warn(msg); return msg; } } VM template = templates.iterator().next(); vm = template.createClone(conn, vmName); vm.removeFromOtherConfig(conn, "disks"); vm.setPVBootloader(conn, "pygrub"); long memsize = ramSize * 1024L * 1024L; setMemory(conn, vm, memsize); vm.setIsATemplate(conn, false); vm.setVCPUsAtStartup(conn, 1L); Host host = Host.getByUuid(conn, _host.uuid); vm.setAffinity(conn, host); /* create VBD */ VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = true; vbdr.userdevice = "0"; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; VBD.create(conn, vbdr); /* create CD-ROM VBD */ VBD.Record cdromVBDR = new VBD.Record(); cdromVBDR.VM = vm; cdromVBDR.empty = true; cdromVBDR.bootable = false; cdromVBDR.userdevice = "3"; cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; VBD cdromVBD = VBD.create(conn, cdromVBDR); cdromVBD.insert(conn, VDI.getByUuid(conn, _host.systemvmisouuid)); /* create VIF0 */ VIF.Record vifr = new VIF.Record(); vifr.VM = vm; vifr.device = "0"; vifr.MAC = guestMacAddr; if (VirtualMachineName.isValidConsoleProxyName(vmName) || VirtualMachineName.isValidSecStorageVmName(vmName, null)) { vifr.network = Network.getByUuid(conn, _host.linkLocalNetwork); } else vifr.network = nw0; VIF.create(conn, vifr); /* create VIF1 */ /* For routing vm, set its network as link local bridge */ vifr.VM = vm; vifr.device = "1"; vifr.MAC = privateMacAddr; if (VirtualMachineName.isValidRouterName(vmName) && privateIp.startsWith("169.254")) { vifr.network = Network.getByUuid(conn, _host.linkLocalNetwork); } else { vifr.network = Network.getByUuid(conn, _host.privateNetwork); } VIF.create(conn, vifr); if( !publicMacAddr.equalsIgnoreCase("FE:FF:FF:FF:FF:FF") ) { /* create VIF2 */ vifr.VM = vm; vifr.device = "2"; vifr.MAC = publicMacAddr; vifr.network = Network.getByUuid(conn, _host.publicNetwork); if ("untagged".equalsIgnoreCase(vlanId)) { vifr.network = Network.getByUuid(conn, _host.publicNetwork); } else { Network vlanNetwork = enableVlanNetwork(Long.valueOf(vlanId), _host.publicNetwork, _host.publicPif); if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanId); } vifr.network = vlanNetwork; } VIF.create(conn, vifr); } /* set up PV dom argument */ String pvargs = vm.getPVArgs(conn); pvargs = pvargs + bootArgs; if (s_logger.isInfoEnabled()) s_logger.info("PV args for system vm are " + pvargs); vm.setPVArgs(conn, pvargs); /* destroy console */ Set<Console> consoles = vm.getRecord(conn).consoles; for (Console console : consoles) { console.destroy(conn); } /* set action after crash as destroy */ vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY); vm.start(conn, false, true); if (_canBridgeFirewall) { String result = callHostPlugin("vmops", "default_network_rules_systemvm", "vmName", vmName); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default system vm network rules for " + vmName); } else { s_logger.info("Programmed default system vm network rules for " + vmName); } } if (s_logger.isInfoEnabled()) s_logger.info("Ping system vm command port, " + privateIp + ":" + cmdPort); state = State.Running; String result = connect(vmName, privateIp, cmdPort); if (result != null) { String msg = "Can not ping System vm " + vmName + "due to:" + result; s_logger.warn(msg); throw new CloudRuntimeException(msg); } else { if (s_logger.isInfoEnabled()) s_logger.info("Ping system vm command port succeeded for vm " + vmName); } return null; } catch (XenAPIException e) { String msg = "Exception caught while starting System vm " + vmName + " due to " + e.toString(); s_logger.warn(msg, e); startvmfailhandle(vm, mounts); state = State.Stopped; return msg; } catch (Exception e) { String msg = "Exception caught while starting System vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); startvmfailhandle(vm, mounts); state = State.Stopped; return msg; } finally { synchronized (_vms) { _vms.put(vmName, state); } } } // TODO : need to refactor it to reuse code with StartRouter protected Answer execute(final StartConsoleProxyCommand cmd) { final String vmName = cmd.getVmName(); final ConsoleProxyVO proxy = cmd.getProxy(); try { Connection conn = getConnection(); Network network = Network.getByUuid(conn, _host.privateNetwork); String bootArgs = cmd.getBootArgs(); bootArgs += " zone=" + _dcId; bootArgs += " pod=" + _pod; bootArgs += " guid=Proxy." + proxy.getId(); bootArgs += " proxy_vm=" + proxy.getId(); bootArgs += " localgw=" + _localGateway; String result = startSystemVM(vmName, proxy.getVlanId(), network, cmd.getVolumes(), bootArgs, proxy.getGuestMacAddress(), proxy.getGuestIpAddress(), proxy .getPrivateMacAddress(), proxy.getPublicMacAddress(), cmd.getProxyCmdPort(), proxy.getRamSize()); if (result == null) { return new StartConsoleProxyAnswer(cmd); } return new StartConsoleProxyAnswer(cmd, result); } catch (Exception e) { String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); return new StartConsoleProxyAnswer(cmd, msg); } } protected boolean patchSystemVm(VDI vdi, String vmName) { if (vmName.startsWith("r-")) { return patchSpecialVM(vdi, vmName, "router"); } else if (vmName.startsWith("v-")) { return patchSpecialVM(vdi, vmName, "consoleproxy"); } else if (vmName.startsWith("s-")) { return patchSpecialVM(vdi, vmName, "secstorage"); } else { throw new CloudRuntimeException("Tried to patch unknown type of system vm"); } } protected boolean isDeviceUsed(VM vm, Long deviceId) { // Figure out the disk number to attach the VM to String msg = null; try { Connection conn = getConnection(); Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn); if (allowedVBDDevices.contains(deviceId.toString())) { return false; } return true; } catch (XmlRpcException e) { msg = "Catch XmlRpcException due to: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { msg = "Catch XenAPIException due to: " + e.toString(); s_logger.warn(msg, e); } throw new CloudRuntimeException("When check deviceId " + msg); } protected String getUnusedDeviceNum(VM vm) { // Figure out the disk number to attach the VM to try { Connection conn = getConnection(); Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn); if (allowedVBDDevices.size() == 0) throw new CloudRuntimeException("Could not find an available slot in VM with name: " + vm.getNameLabel(conn) + " to attach a new disk."); return allowedVBDDevices.iterator().next(); } catch (XmlRpcException e) { String msg = "Catch XmlRpcException due to: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Catch XenAPIException due to: " + e.toString(); s_logger.warn(msg, e); } throw new CloudRuntimeException("Could not find an available slot in VM with name to attach a new disk."); } protected boolean patchSpecialVM(VDI vdi, String vmname, String vmtype) { // patch special vm here, domr, domp VBD vbd = null; Connection conn = getConnection(); try { Host host = Host.getByUuid(conn, _host.uuid); Set<VM> vms = host.getResidentVMs(conn); for (VM vm : vms) { VM.Record vmrec = null; try { vmrec = vm.getRecord(conn); } catch (Exception e) { String msg = "VM.getRecord failed due to " + e.toString() + " " + e.getMessage(); s_logger.warn(msg); continue; } if (vmrec.isControlDomain) { /* create VBD */ VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; vbdr.bootable = false; vbdr.userdevice = getUnusedDeviceNum(vm); vbdr.unpluggable = true; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbd = VBD.create(conn, vbdr); vbd.plug(conn); String device = vbd.getDevice(conn); return patchspecialvm(vmname, device, vmtype); } } } catch (XenAPIException e) { String msg = "patchSpecialVM faile on " + _host.uuid + " due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "patchSpecialVM faile on " + _host.uuid + " due to " + e.getMessage(); s_logger.warn(msg, e); } finally { if (vbd != null) { try { if (vbd.getCurrentlyAttached(conn)) { vbd.unplug(conn); } vbd.destroy(conn); } catch (XmlRpcException e) { String msg = "Catch XmlRpcException due to " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Catch XenAPIException due to " + e.toString(); s_logger.warn(msg, e); } } } return false; } protected boolean patchspecialvm(String vmname, String device, String vmtype) { String result = callHostPlugin("vmops", "patchdomr", "vmname", vmname, "vmtype", vmtype, "device", "/dev/" + device); if (result == null || result.isEmpty()) return false; return true; } protected String callHostPlugin(String plugin, String cmd, String... params) { Map<String, String> args = new HashMap<String, String>(); Session slaveSession = null; Connection slaveConn = null; try { URL slaveUrl = null; try { slaveUrl = new URL("http://" + _host.ip); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } slaveConn = new Connection(slaveUrl, 1800); slaveSession = Session.slaveLocalLoginWithPassword(slaveConn, _username, _password); if (s_logger.isDebugEnabled()) { s_logger.debug("Slave logon successful. session= " + slaveSession); } Host host = Host.getByUuid(slaveConn, _host.uuid); for (int i = 0; i < params.length; i += 2) { args.put(params[i], params[i + 1]); } if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args)); } String result = host.callPlugin(slaveConn, plugin, cmd, args); if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin Result: " + result); } return result.replace("\n", ""); } catch (XenAPIException e) { s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString()); } catch (XmlRpcException e) { s_logger.debug("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.getMessage()); } finally { if( slaveSession != null) { try { slaveSession.localLogout(slaveConn); } catch (Exception e) { } } } return null; } protected String getArgsString(Map<String, String> args) { StringBuilder argString = new StringBuilder(); for (Map.Entry<String, String> arg : args.entrySet()) { argString.append(arg.getKey() + ": " + arg.getValue() + ", "); } return argString.toString(); } protected boolean setIptables() { String result = callHostPlugin("vmops", "setIptables"); if (result == null || result.isEmpty()) return false; return true; } protected Nic getLocalNetwork(Connection conn, String name) throws XmlRpcException, XenAPIException { if( name == null) { return null; } Set<Network> networks = Network.getByNameLabel(conn, name); for (Network network : networks) { Network.Record nr = network.getRecord(conn); for (PIF pif : nr.PIFs) { PIF.Record pr = pif.getRecord(conn); if (_host.uuid.equals(pr.host.getUuid(conn))) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found a network called " + name + " on host=" + _host.ip + "; Network=" + nr.uuid + "; pif=" + pr.uuid); } if (pr.bondMasterOf != null && pr.bondMasterOf.size() > 0) { if (pr.bondMasterOf.size() > 1) { String msg = new StringBuilder("Unsupported configuration. Network " + name + " has more than one bond. Network=").append(nr.uuid) .append("; pif=").append(pr.uuid).toString(); s_logger.warn(msg); return null; } Bond bond = pr.bondMasterOf.iterator().next(); Set<PIF> slaves = bond.getSlaves(conn); for (PIF slave : slaves) { PIF.Record spr = slave.getRecord(conn); if (spr.management) { Host host = Host.getByUuid(conn, _host.uuid); if (!transferManagementNetwork(conn, host, slave, spr, pif)) { String msg = new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" + _host.uuid).toString(); s_logger.warn(msg); return null; } break; } } } return new Nic(network, nr, pif, pr); } } } return null; } protected VIF getCorrectVif(VM router, String vlanId) { try { Connection conn = getConnection(); Set<VIF> routerVIFs = router.getVIFs(conn); for (VIF vif : routerVIFs) { Network vifNetwork = vif.getNetwork(conn); if (vlanId.equals("untagged")) { if (vifNetwork.getUuid(conn).equals(_host.publicNetwork)) { return vif; } } else { if (vifNetwork.getNameLabel(conn).equals("VLAN" + vlanId)) { return vif; } } } } catch (XmlRpcException e) { String msg = "Caught XmlRpcException: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Caught XenAPIException: " + e.toString(); s_logger.warn(msg, e); } return null; } protected String getLowestAvailableVIFDeviceNum(VM vm) { try { Connection conn = getConnection(); Set<String> availableDeviceNums = vm.getAllowedVIFDevices(conn); Iterator<String> deviceNumsIterator = availableDeviceNums.iterator(); List<Integer> sortedDeviceNums = new ArrayList<Integer>(); while (deviceNumsIterator.hasNext()) { try { sortedDeviceNums.add(Integer.valueOf(deviceNumsIterator.next())); } catch (NumberFormatException e) { s_logger.debug("Obtained an invalid value for an available VIF device number for VM: " + vm.getNameLabel(conn)); return null; } } Collections.sort(sortedDeviceNums); return String.valueOf(sortedDeviceNums.get(0)); } catch (XmlRpcException e) { String msg = "Caught XmlRpcException: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Caught XenAPIException: " + e.toString(); s_logger.warn(msg, e); } return null; } protected VDI mount(StoragePoolType pooltype, String volumeFolder, String volumePath) { return getVDIbyUuid(volumePath); } protected List<Ternary<SR, VDI, VolumeVO>> mount(List<VolumeVO> vos) { ArrayList<Ternary<SR, VDI, VolumeVO>> mounts = new ArrayList<Ternary<SR, VDI, VolumeVO>>(vos.size()); for (VolumeVO vol : vos) { String vdiuuid = vol.getPath(); SR sr = null; VDI vdi = null; // Look up the VDI vdi = getVDIbyUuid(vdiuuid); Ternary<SR, VDI, VolumeVO> ter = new Ternary<SR, VDI, VolumeVO>(sr, vdi, vol); if( vol.getVolumeType() == VolumeType.ROOT ) { mounts.add(0, ter); } else { mounts.add(ter); } } return mounts; } protected Network getNetworkByName(String name) throws BadServerResponse, XenAPIException, XmlRpcException { Connection conn = getConnection(); Set<Network> networks = Network.getByNameLabel(conn, name); if (networks.size() > 0) { assert networks.size() == 1 : "How did we find more than one network with this name label" + name + "? Strange...."; return networks.iterator().next(); // Found it. } return null; } protected synchronized Network getNetworkByName(Connection conn, String name, boolean lookForPif) throws XenAPIException, XmlRpcException { Network found = null; Set<Network> networks = Network.getByNameLabel(conn, name); if (networks.size() == 1) { found = networks.iterator().next(); } else if (networks.size() > 1) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found more than one network with the name " + name); } for (Network network : networks) { if (!lookForPif) { found = network; break; } Network.Record netr = network.getRecord(conn); s_logger.debug("Checking network " + netr.uuid); if (netr.PIFs.size() == 0) { if (s_logger.isDebugEnabled()) { s_logger.debug("Network " + netr.uuid + " has no pifs so skipping that."); } } else { for (PIF pif : netr.PIFs) { PIF.Record pifr = pif.getRecord(conn); if (_host.uuid.equals(pifr.host.getUuid(conn))) { if (s_logger.isDebugEnabled()) { s_logger.debug("Network " + netr.uuid + " has a pif " + pifr.uuid + " for our host "); } found = network; break; } } } } } return found; } protected Network enableVlanNetwork(long tag, String networkUuid, String pifUuid) throws XenAPIException, XmlRpcException { // In XenServer, vlan is added by // 1. creating a network. // 2. creating a vlan associating network with the pif. // We always create // 1. a network with VLAN[vlan id in decimal] // 2. a vlan associating the network created with the pif to private // network. Connection conn = getConnection(); Network vlanNetwork = null; String name = "VLAN" + Long.toString(tag); synchronized (name.intern()) { vlanNetwork = getNetworkByName(name); if (vlanNetwork == null) { // Can't find it, then create it. if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN network for " + tag + " on host " + _host.ip); } Network.Record nwr = new Network.Record(); nwr.nameLabel = name; nwr.bridge = name; vlanNetwork = Network.create(conn, nwr); } PIF nPif = PIF.getByUuid(conn, pifUuid); PIF.Record nPifr = nPif.getRecord(conn); Network.Record vlanNetworkr = vlanNetwork.getRecord(conn); if (vlanNetworkr.PIFs != null) { for (PIF pif : vlanNetworkr.PIFs) { PIF.Record pifr = pif.getRecord(conn); if (pifr.device.equals(nPifr.device) && pifr.host.equals(nPifr.host)) { pif.plug(conn); return vlanNetwork; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN " + tag + " on host " + _host.ip + " on device " + nPifr.device); } VLAN vlan = VLAN.create(conn, nPif, tag, vlanNetwork); PIF untaggedPif = vlan.getUntaggedPIF(conn); if (!untaggedPif.getCurrentlyAttached(conn)) { untaggedPif.plug(conn); } } return vlanNetwork; } protected Network enableVlanNetwork(Connection conn, long tag, Network network, String pifUuid) throws XenAPIException, XmlRpcException { // In XenServer, vlan is added by // 1. creating a network. // 2. creating a vlan associating network with the pif. // We always create // 1. a network with VLAN[vlan id in decimal] // 2. a vlan associating the network created with the pif to private // network. Network vlanNetwork = null; String name = "VLAN" + Long.toString(tag); vlanNetwork = getNetworkByName(conn, name, true); if (vlanNetwork == null) { // Can't find it, then create it. if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN network for " + tag + " on host " + _host.ip); } Network.Record nwr = new Network.Record(); nwr.nameLabel = name; nwr.bridge = name; vlanNetwork = Network.create(conn, nwr); } PIF nPif = PIF.getByUuid(conn, pifUuid); PIF.Record nPifr = nPif.getRecord(conn); Network.Record vlanNetworkr = vlanNetwork.getRecord(conn); if (vlanNetworkr.PIFs != null) { for (PIF pif : vlanNetworkr.PIFs) { PIF.Record pifr = pif.getRecord(conn); if (pifr.device.equals(nPifr.device) && pifr.host.equals(nPifr.host)) { pif.plug(conn); return vlanNetwork; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN " + tag + " on host " + _host.ip + " on device " + nPifr.device); } VLAN vlan = VLAN.create(conn, nPif, tag, vlanNetwork); VLAN.Record vlanr = vlan.getRecord(conn); if (s_logger.isDebugEnabled()) { s_logger.debug("VLAN is created for " + tag + ". The uuid is " + vlanr.uuid); } PIF untaggedPif = vlanr.untaggedPIF; if (!untaggedPif.getCurrentlyAttached(conn)) { untaggedPif.plug(conn); } return vlanNetwork; } protected void disableVlanNetwork(Network network) throws InternalErrorException { try { Connection conn = getConnection(); if (network.getVIFs(conn).isEmpty()) { Iterator<PIF> pifs = network.getPIFs(conn).iterator(); while (pifs.hasNext()) { PIF pif = pifs.next(); pif.unplug(conn); } } } catch (XenAPIException e) { String msg = "Unable to disable VLAN network due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "Unable to disable VLAN network due to " + e.getMessage(); s_logger.warn(msg, e); } } protected SR getLocalLVMSR() { Connection conn = getConnection(); try { Map<SR, SR.Record> map = SR.getAllRecords(conn); for (Map.Entry<SR, SR.Record> entry : map.entrySet()) { SR.Record srRec = entry.getValue(); if (SRType.LVM.equals(srRec.type)) { Set<PBD> pbds = srRec.PBDs; if (pbds == null) { continue; } for (PBD pbd : pbds) { Host host = pbd.getHost(conn); if (!isRefNull(host) && host.getUuid(conn).equals(_host.uuid)) { if (!pbd.getCurrentlyAttached(conn)) { pbd.plug(conn); } SR sr = entry.getKey(); sr.scan(conn); return sr; } } } } } catch (XenAPIException e) { String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.toString(); s_logger.warn(msg); } catch (XmlRpcException e) { String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.getCause(); s_logger.warn(msg); } return null; } protected StartupStorageCommand initializeLocalSR() { SR lvmsr = getLocalLVMSR(); if (lvmsr == null) { return null; } try { Connection conn = getConnection(); String lvmuuid = lvmsr.getUuid(conn); long cap = lvmsr.getPhysicalSize(conn); if (cap < 0) return null; long avail = cap - lvmsr.getPhysicalUtilisation(conn); lvmsr.setNameLabel(conn, lvmuuid); String name = "VMOps local storage pool in host : " + _host.uuid; lvmsr.setNameDescription(conn, name); Host host = Host.getByUuid(conn, _host.uuid); String address = host.getAddress(conn); StoragePoolInfo pInfo = new StoragePoolInfo(name, lvmuuid, address, SRType.LVM.toString(), SRType.LVM.toString(), StoragePoolType.LVM, cap, avail); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setPoolInfo(pInfo); cmd.setGuid(_host.uuid); cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); return cmd; } catch (XenAPIException e) { String msg = "build startupstoragecommand err in host:" + _host.uuid + e.toString(); s_logger.warn(msg); } catch (XmlRpcException e) { String msg = "build startupstoragecommand err in host:" + _host.uuid + e.getMessage(); s_logger.warn(msg); } return null; } @Override public PingCommand getCurrentStatus(long id) { try { if (!pingxenserver()) { Thread.sleep(1000); if (!pingxenserver()) { s_logger.warn(" can not ping xenserver " + _host.uuid); return null; } } HashMap<String, State> newStates = sync(); if (newStates == null) { newStates = new HashMap<String, State>(); } if (!_canBridgeFirewall) { return new PingRoutingCommand(getType(), id, newStates); } else { HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id); return new PingRoutingWithNwGroupsCommand(getType(), id, newStates, nwGrpStates); } } catch (Exception e) { s_logger.warn("Unable to get current status", e); return null; } } private HashMap<String, Pair<Long,Long>> syncNetworkGroups(long id) { HashMap<String, Pair<Long,Long>> states = new HashMap<String, Pair<Long,Long>>(); String result = callHostPlugin("vmops", "get_rule_logs_for_vms", "host_uuid", _host.uuid); s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); String [] rulelogs = result != null ?result.split(";"): new String [0]; for (String rulesforvm: rulelogs){ String [] log = rulesforvm.split(","); if (log.length != 6) { continue; } //output = ','.join([vmName, vmID, vmIP, domID, signature, seqno]) try { states.put(log[0], new Pair<Long,Long>(Long.parseLong(log[1]), Long.parseLong(log[5]))); } catch (NumberFormatException nfe) { states.put(log[0], new Pair<Long,Long>(-1L, -1L)); } } return states; } @Override public Type getType() { return com.cloud.host.Host.Type.Routing; } protected void getPVISO(StartupStorageCommand sscmd) { Connection conn = getConnection(); try { Set<VDI> vids = VDI.getByNameLabel(conn, "xs-tools.iso"); if (vids.isEmpty()) return; VDI pvISO = vids.iterator().next(); String uuid = pvISO.getUuid(conn); Map<String, TemplateInfo> pvISOtmlt = new HashMap<String, TemplateInfo>(); TemplateInfo tmplt = new TemplateInfo("xs-tools.iso", uuid, pvISO.getVirtualSize(conn), true); pvISOtmlt.put("xs-tools", tmplt); sscmd.setTemplateInfo(pvISOtmlt); } catch (XenAPIException e) { s_logger.debug("Can't get xs-tools.iso: " + e.toString()); } catch (XmlRpcException e) { s_logger.debug("Can't get xs-tools.iso: " + e.toString()); } } protected boolean can_bridge_firewall() { return false; } protected boolean getHostInfo() throws IllegalArgumentException{ Connection conn = getConnection(); try { Host myself = Host.getByUuid(conn, _host.uuid); _host.pool = getPoolUuid(); boolean findsystemvmiso = false; Set<SR> srs = SR.getByNameLabel(conn, "XenServer Tools"); if( srs.size() != 1 ) { throw new CloudRuntimeException("There are " + srs.size() + " SRs with name XenServer Tools"); } SR sr = srs.iterator().next(); sr.scan(conn); SR.Record srr = sr.getRecord(conn); _host.systemvmisouuid = null; for( VDI vdi : srr.VDIs ) { VDI.Record vdir = vdi.getRecord(conn); if(vdir.nameLabel.contains("systemvm-premium")){ _host.systemvmisouuid = vdir.uuid; break; } } if( _host.systemvmisouuid == null ) { for( VDI vdi : srr.VDIs ) { VDI.Record vdir = vdi.getRecord(conn); if(vdir.nameLabel.contains("systemvm")){ _host.systemvmisouuid = vdir.uuid; break; } } } if( _host.systemvmisouuid == null ) { throw new CloudRuntimeException("can not find systemvmiso"); } String name = "cloud-private"; if (_privateNetworkName != null) { name = _privateNetworkName; } _localGateway = callHostPlugin("vmops", "getgateway", "mgmtIP", myself.getAddress(conn)); if (_localGateway == null || _localGateway.isEmpty()) { s_logger.warn("can not get gateway for host :" + _host.uuid); return false; } _canBridgeFirewall = can_bridge_firewall(); Nic privateNic = getLocalNetwork(conn, name); if (privateNic == null) { s_logger.debug("Unable to find any private network. Trying to determine that by route for host " + _host.ip); name = callHostPlugin("vmops", "getnetwork", "mgmtIP", myself.getAddress(conn)); if (name == null || name.isEmpty()) { s_logger.warn("Unable to determine the private network for host " + _host.ip); return false; } _privateNetworkName = name; privateNic = getLocalNetwork(conn, name); if (privateNic == null) { s_logger.warn("Unable to get private network " + name); return false; } } _host.privatePif = privateNic.pr.uuid; _host.privateNetwork = privateNic.nr.uuid; Nic guestNic = null; if (_guestNetworkName != null && !_guestNetworkName.equals(_privateNetworkName)) { guestNic = getLocalNetwork(conn, _guestNetworkName); if (guestNic == null) { s_logger.warn("Unable to find guest network " + _guestNetworkName); throw new IllegalArgumentException("Unable to find guest network " + _guestNetworkName + " for host " + _host.ip); } } else { guestNic = privateNic; _guestNetworkName = _privateNetworkName; } _host.guestNetwork = guestNic.nr.uuid; _host.guestPif = guestNic.pr.uuid; Nic publicNic = null; if (_publicNetworkName != null && !_publicNetworkName.equals(_guestNetworkName)) { publicNic = getLocalNetwork(conn, _publicNetworkName); if (publicNic == null) { s_logger.warn("Unable to find public network " + _publicNetworkName + " for host " + _host.ip); throw new IllegalArgumentException("Unable to find public network " + _publicNetworkName + " for host " + _host.ip); } } else { publicNic = guestNic; _publicNetworkName = _guestNetworkName; } _host.publicPif = publicNic.pr.uuid; _host.publicNetwork = publicNic.nr.uuid; Nic storageNic1 = getLocalNetwork(conn, _storageNetworkName1); if (storageNic1 == null) { storageNic1 = privateNic; _storageNetworkName1 = _privateNetworkName; } _host.storageNetwork1 = storageNic1.nr.uuid; _host.storagePif1 = storageNic1.pr.uuid; Nic storageNic2 = getLocalNetwork(conn, _storageNetworkName2); if (storageNic2 == null) { storageNic2 = privateNic; _storageNetworkName2 = _privateNetworkName; } _host.storageNetwork2 = storageNic2.nr.uuid; _host.storagePif2 = storageNic2.pr.uuid; s_logger.info("Private Network is " + _privateNetworkName + " for host " + _host.ip); s_logger.info("Guest Network is " + _guestNetworkName + " for host " + _host.ip); s_logger.info("Public Network is " + _publicNetworkName + " for host " + _host.ip); s_logger.info("Storage Network 1 is " + _storageNetworkName1 + " for host " + _host.ip); s_logger.info("Storage Network 2 is " + _storageNetworkName2 + " for host " + _host.ip); return true; } catch (XenAPIException e) { s_logger.warn("Unable to get host information for " + _host.ip, e); return false; } catch (XmlRpcException e) { s_logger.warn("Unable to get host information for " + _host.ip, e); return false; } } private void setupLinkLocalNetwork() { try { Network.Record rec = new Network.Record(); Connection conn = getConnection(); Set<Network> networks = Network.getByNameLabel(conn, _linkLocalPrivateNetworkName); Network linkLocal = null; if (networks.size() == 0) { rec.nameDescription = "link local network used by system vms"; rec.nameLabel = _linkLocalPrivateNetworkName; Map<String, String> configs = new HashMap<String, String>(); configs.put("ip_begin", NetUtils.getLinkLocalGateway()); configs.put("ip_end", NetUtils.getLinkLocalIpEnd()); configs.put("netmask", NetUtils.getLinkLocalNetMask()); rec.otherConfig = configs; linkLocal = Network.create(conn, rec); } else { linkLocal = networks.iterator().next(); } /* Make sure there is a physical bridge on this network */ VIF dom0vif = null; Pair<VM, VM.Record> vm = getControlDomain(conn); VM dom0 = vm.first(); Set<VIF> vifs = dom0.getVIFs(conn); if (vifs.size() != 0) { for (VIF vif : vifs) { Map<String, String> otherConfig = vif.getOtherConfig(conn); if (otherConfig != null) { String nameLabel = otherConfig.get("nameLabel"); if ((nameLabel != null) && nameLabel.equalsIgnoreCase("link_local_network_vif")) { dom0vif = vif; } } } } /* create temp VIF0 */ if (dom0vif == null) { s_logger.debug("Can't find a vif on dom0 for link local, creating a new one"); VIF.Record vifr = new VIF.Record(); vifr.VM = dom0; vifr.device = getLowestAvailableVIFDeviceNum(dom0); if (vifr.device == null) { s_logger.debug("Failed to create link local network, no vif available"); return; } Map<String, String> config = new HashMap<String, String>(); config.put("nameLabel", "link_local_network_vif"); vifr.otherConfig = config; vifr.MAC = "FE:FF:FF:FF:FF:FF"; vifr.network = linkLocal; dom0vif = VIF.create(conn, vifr); dom0vif.plug(conn); } else { s_logger.debug("already have a vif on dom0 for link local network"); if (!dom0vif.getCurrentlyAttached(conn)) { dom0vif.plug(conn); } } String brName = linkLocal.getBridge(conn); callHostPlugin("vmops", "setLinkLocalIP", "brName", brName); _host.linkLocalNetwork = linkLocal.getUuid(conn); } catch (XenAPIException e) { s_logger.warn("Unable to create local link network", e); } catch (XmlRpcException e) { // TODO Auto-generated catch block s_logger.warn("Unable to create local link network", e); } } protected boolean transferManagementNetwork(Connection conn, Host host, PIF src, PIF.Record spr, PIF dest) throws XmlRpcException, XenAPIException { dest.reconfigureIp(conn, spr.ipConfigurationMode, spr.IP, spr.netmask, spr.gateway, spr.DNS); Host.managementReconfigure(conn, dest); String hostUuid = null; int count = 0; while (count < 10) { try { Thread.sleep(10000); hostUuid = host.getUuid(conn); if (hostUuid != null) { break; } } catch (XmlRpcException e) { s_logger.debug("Waiting for host to come back: " + e.getMessage()); } catch (XenAPIException e) { s_logger.debug("Waiting for host to come back: " + e.getMessage()); } catch (InterruptedException e) { s_logger.debug("Gotta run"); return false; } } if (hostUuid == null) { s_logger.warn("Unable to transfer the management network from " + spr.uuid); return false; } src.reconfigureIp(conn, IpConfigurationMode.NONE, null, null, null, null); return true; } @Override public StartupCommand[] initialize() throws IllegalArgumentException{ disconnected(); setupServer(); if (!getHostInfo()) { s_logger.warn("Unable to get host information for " + _host.ip); return null; } destroyStoppedVm(); StartupRoutingCommand cmd = new StartupRoutingCommand(); fillHostInfo(cmd); cleanupDiskMounts(); Map<String, State> changes = null; synchronized (_vms) { _vms.clear(); changes = sync(); } cmd.setHypervisorType(Hypervisor.Type.XenServer); cmd.setChanges(changes); cmd.setCluster(_cluster); StartupStorageCommand sscmd = initializeLocalSR(); _host.pool = getPoolUuid(); if (sscmd != null) { /* report pv driver iso */ getPVISO(sscmd); return new StartupCommand[] { cmd, sscmd }; } return new StartupCommand[] { cmd }; } protected String getPoolUuid() { Connection conn = getConnection(); try { Map<Pool, Pool.Record> pools = Pool.getAllRecords(conn); assert (pools.size() == 1) : "Tell me how pool size can be " + pools.size(); Pool.Record rec = pools.values().iterator().next(); return rec.uuid; } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get pool ", e); } catch (XmlRpcException e) { throw new CloudRuntimeException("Unable to get pool ", e); } } protected void setupServer() { Connection conn = getConnection(); String version = CitrixResourceBase.class.getPackage().getImplementationVersion(); try { Host host = Host.getByUuid(conn, _host.uuid); /* enable host in case it is disabled somehow */ host.enable(conn); /* push patches to XenServer */ Host.Record hr = host.getRecord(conn); Iterator<String> it = hr.tags.iterator(); while (it.hasNext()) { String tag = it.next(); if (tag.startsWith("vmops-version-")) { if (tag.contains(version)) { s_logger.info(logX(host, "Host " + hr.address + " is already setup.")); return; } else { it.remove(); } } } com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22); try { sshConnection.connect(null, 60000, 60000); if (!sshConnection.authenticateWithPassword(_username, _password)) { throw new CloudRuntimeException("Unable to authenticate"); } SCPClient scp = new SCPClient(sshConnection); String path = _patchPath.substring(0, _patchPath.lastIndexOf(File.separator) + 1); List<File> files = getPatchFiles(); if( files == null || files.isEmpty() ) { throw new CloudRuntimeException("Can not find patch file"); } for( File file :files) { Properties props = new Properties(); props.load(new FileInputStream(file)); for (Map.Entry<Object, Object> entry : props.entrySet()) { String k = (String) entry.getKey(); String v = (String) entry.getValue(); assert (k != null && k.length() > 0 && v != null && v.length() > 0) : "Problems with " + k + "=" + v; String[] tokens = v.split(","); String f = null; if (tokens.length == 3 && tokens[0].length() > 0) { if (tokens[0].startsWith("/")) { f = tokens[0]; } else if (tokens[0].startsWith("~")) { String homedir = System.getenv("HOME"); f = homedir + tokens[0].substring(1) + k; } else { f = path + tokens[0] + '/' + k; } } else { f = path + k; } String d = tokens[tokens.length - 1]; f = f.replace('/', File.separatorChar); String p = "0755"; if (tokens.length == 3) { p = tokens[1]; } else if (tokens.length == 2) { p = tokens[0]; } if (!new File(f).exists()) { s_logger.warn("We cannot locate " + f); continue; } if (s_logger.isDebugEnabled()) { s_logger.debug("Copying " + f + " to " + d + " on " + hr.address + " with permission " + p); } scp.put(f, d, p); } } } catch (IOException e) { throw new CloudRuntimeException("Unable to setup the server correctly", e); } finally { sshConnection.close(); } if (!setIptables()) { s_logger.warn("set xenserver Iptable failed"); } hr.tags.add("vmops-version-" + version); host.setTags(conn, hr.tags); } catch (XenAPIException e) { String msg = "Xen setup failed due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException("Unable to get host information " + e.toString(), e); } catch (XmlRpcException e) { String msg = "Xen setup failed due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException("Unable to get host information ", e); } } protected List<File> getPatchFiles() { List<File> files = new ArrayList<File>(); File file = new File(_patchPath); files.add(file); return files; } protected SR getSRByNameLabelandHost(String name) throws BadServerResponse, XenAPIException, XmlRpcException { Connection conn = getConnection(); Set<SR> srs = SR.getByNameLabel(conn, name); SR ressr = null; for (SR sr : srs) { Set<PBD> pbds; pbds = sr.getPBDs(conn); for (PBD pbd : pbds) { PBD.Record pbdr = pbd.getRecord(conn); if (pbdr.host != null && pbdr.host.getUuid(conn).equals(_host.uuid)) { if (!pbdr.currentlyAttached) { pbd.plug(conn); } ressr = sr; break; } } } return ressr; } protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { try { Connection conn = getConnection(); Set<SR> srs = SR.getByNameLabel(conn, cmd.getStorageId()); if (srs.size() != 1) { String msg = "There are " + srs.size() + " storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } SR sr = srs.iterator().next(); sr.scan(conn); long capacity = sr.getPhysicalSize(conn); long used = sr.getPhysicalUtilisation(conn); return new GetStorageStatsAnswer(cmd, capacity, used); } catch (XenAPIException e) { String msg = "GetStorageStats Exception:" + e.toString() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } catch (XmlRpcException e) { String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } } protected boolean checkSR(SR sr) { try { Connection conn = getConnection(); SR.Record srr = sr.getRecord(conn); Set<PBD> pbds = sr.getPBDs(conn); if (pbds.size() == 0) { String msg = "There is no PBDs for this SR: " + _host.uuid; s_logger.warn(msg); removeSR(sr); return false; } Set<Host> hosts = null; if (srr.shared) { hosts = Host.getAll(conn); for (Host host : hosts) { boolean found = false; for (PBD pbd : pbds) { if (host.equals(pbd.getHost(conn))) { PBD.Record pbdr = pbd.getRecord(conn); if (currentlyAttached(sr, srr, pbd, pbdr)) { if (!pbdr.currentlyAttached) { pbd.plug(conn); } } else { if (pbdr.currentlyAttached) { pbd.unplug(conn); } pbd.plug(conn); } pbds.remove(pbd); found = true; break; } } if (!found) { PBD.Record pbdr = srr.PBDs.iterator().next().getRecord(conn); pbdr.host = host; pbdr.uuid = ""; PBD pbd = PBD.create(conn, pbdr); pbd.plug(conn); } } } else { for (PBD pbd : pbds) { PBD.Record pbdr = pbd.getRecord(conn); if (!pbdr.currentlyAttached) { pbd.plug(conn); } } } } catch (Exception e) { String msg = "checkSR failed host:" + _host.uuid; s_logger.warn(msg); return false; } return true; } protected Answer execute(ModifyStoragePoolCommand cmd) { StoragePoolVO pool = cmd.getPool(); try { Connection conn = getConnection(); SR sr = getStorageRepository(conn, pool); if (!checkSR(sr)) { String msg = "ModifyStoragePoolCommand checkSR failed! host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg); return new Answer(cmd, false, msg); } sr.setNameLabel(conn, pool.getUuid()); sr.setNameDescription(conn, pool.getName()); long capacity = sr.getPhysicalSize(conn); long available = capacity - sr.getPhysicalUtilisation(conn); if (capacity == -1) { String msg = "Pool capacity is -1! pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg); return new Answer(cmd, false, msg); } Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>(); ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); return answer; } catch (XenAPIException e) { String msg = "ModifyStoragePoolCommand XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { String msg = "ModifyStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } protected Answer execute(DeleteStoragePoolCommand cmd) { StoragePoolVO pool = cmd.getPool(); try { Connection conn = getConnection(); SR sr = getStorageRepository(conn, pool); if (!checkSR(sr)) { String msg = "DeleteStoragePoolCommand checkSR failed! host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg); return new Answer(cmd, false, msg); } sr.setNameLabel(conn, pool.getUuid()); sr.setNameDescription(conn, pool.getName()); Answer answer = new Answer(cmd, true, "success"); return answer; } catch (XenAPIException e) { String msg = "DeleteStoragePoolCommand XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } public Connection getConnection() { return _connPool.connect(_host.uuid, _host.ip, _username, _password, _wait); } protected void fillHostInfo(StartupRoutingCommand cmd) { long speed = 0; int cpus = 0; long ram = 0; Connection conn = getConnection(); long dom0Ram = 0; final StringBuilder caps = new StringBuilder(); try { Host host = Host.getByUuid(conn, _host.uuid); Host.Record hr = host.getRecord(conn); Map<String, String> details = cmd.getHostDetails(); if (details == null) { details = new HashMap<String, String>(); } if (_privateNetworkName != null) { details.put("private.network.device", _privateNetworkName); } if (_publicNetworkName != null) { details.put("public.network.device", _publicNetworkName); } if (_guestNetworkName != null) { details.put("guest.network.device", _guestNetworkName); } details.put("can_bridge_firewall", Boolean.toString(_canBridgeFirewall)); cmd.setHostDetails(details); cmd.setName(hr.nameLabel); cmd.setGuid(_host.uuid); cmd.setDataCenter(Long.toString(_dcId)); for (final String cap : hr.capabilities) { if (cap.length() > 0) { caps.append(cap).append(" , "); } } if (caps.length() > 0) { caps.delete(caps.length() - 3, caps.length()); } cmd.setCaps(caps.toString()); Set<HostCpu> hcs = host.getHostCPUs(conn); cpus = hcs.size(); for (final HostCpu hc : hcs) { speed = hc.getSpeed(conn); } cmd.setSpeed(speed); cmd.setCpus(cpus); long free = 0; HostMetrics hm = host.getMetrics(conn); ram = hm.getMemoryTotal(conn); free = hm.getMemoryFree(conn); Set<VM> vms = host.getResidentVMs(conn); for (VM vm : vms) { if (vm.getIsControlDomain(conn)) { dom0Ram = vm.getMemoryDynamicMax(conn); break; } } // assume the memory Virtualization overhead is 1/64 ram = (ram - dom0Ram) * 63/64; cmd.setMemory(ram); cmd.setDom0MinMemory(dom0Ram); if (s_logger.isDebugEnabled()) { s_logger.debug("Total Ram: " + ram + " Free Ram: " + free + " dom0 Ram: " + dom0Ram); } PIF pif = PIF.getByUuid(conn, _host.privatePif); PIF.Record pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setPrivateIpAddress(pifr.IP); cmd.setPrivateMacAddress(pifr.MAC); cmd.setPrivateNetmask(pifr.netmask); } pif = PIF.getByUuid(conn, _host.storagePif1); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setStorageIpAddress(pifr.IP); cmd.setStorageMacAddress(pifr.MAC); cmd.setStorageNetmask(pifr.netmask); } if (_host.storagePif2 != null) { pif = PIF.getByUuid(conn, _host.storagePif2); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setStorageIpAddressDeux(pifr.IP); cmd.setStorageMacAddressDeux(pifr.MAC); cmd.setStorageNetmaskDeux(pifr.netmask); } } Map<String, String> configs = hr.otherConfig; cmd.setIqn(configs.get("iscsi_iqn")); cmd.setPod(_pod); cmd.setVersion(CitrixResourceBase.class.getPackage().getImplementationVersion()); } catch (final XmlRpcException e) { throw new CloudRuntimeException("XML RPC Exception" + e.getMessage(), e); } catch (XenAPIException e) { throw new CloudRuntimeException("XenAPIException" + e.toString(), e); } } public CitrixResourceBase() { } protected String getPatchPath() { return "scripts/vm/hypervisor/xenserver/xcpserver"; } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; _host.uuid = (String) params.get("guid"); try { _dcId = Long.parseLong((String) params.get("zone")); } catch (NumberFormatException e) { throw new ConfigurationException("Unable to get the zone " + params.get("zone")); } _name = _host.uuid; _host.ip = (String) params.get("url"); _username = (String) params.get("username"); _password = (String) params.get("password"); _pod = (String) params.get("pod"); _cluster = (String)params.get("cluster"); _privateNetworkName = (String) params.get("private.network.device"); _publicNetworkName = (String) params.get("public.network.device"); _guestNetworkName = (String)params.get("guest.network.device"); _linkLocalPrivateNetworkName = (String) params.get("private.linkLocal.device"); if (_linkLocalPrivateNetworkName == null) _linkLocalPrivateNetworkName = "cloud_link_local_network"; _storageNetworkName1 = (String) params.get("storage.network.device1"); if (_storageNetworkName1 == null) { _storageNetworkName1 = "cloud-stor1"; } _storageNetworkName2 = (String) params.get("storage.network.device2"); if (_storageNetworkName2 == null) { _storageNetworkName2 = "cloud-stor2"; } String value = (String) params.get("wait"); _wait = NumbersUtil.parseInt(value, 1800); if (_pod == null) { throw new ConfigurationException("Unable to get the pod"); } if (_host.ip == null) { throw new ConfigurationException("Unable to get the host address"); } if (_username == null) { throw new ConfigurationException("Unable to get the username"); } if (_password == null) { throw new ConfigurationException("Unable to get the password"); } if (_host.uuid == null) { throw new ConfigurationException("Unable to get the uuid"); } params.put("domr.scripts.dir", "scripts/network/domr"); String patchPath = getPatchPath(); _patchPath = Script.findScript(patchPath, "patch"); if (_patchPath == null) { throw new ConfigurationException("Unable to find all of patch files for xenserver"); } _storage = (StorageLayer) params.get(StorageLayer.InstanceConfigKey); if (_storage == null) { value = (String) params.get(StorageLayer.ClassConfigKey); if (value == null) { value = "com.cloud.storage.JavaStorageLayer"; } try { Class<?> clazz = Class.forName(value); _storage = (StorageLayer) ComponentLocator.inject(clazz); _storage.configure("StorageLayer", params); } catch (ClassNotFoundException e) { throw new ConfigurationException("Unable to find class " + value); } } return true; } void destroyVDI(VDI vdi) { try { Connection conn = getConnection(); vdi.destroy(conn); } catch (Exception e) { String msg = "destroy VDI failed due to " + e.toString(); s_logger.warn(msg); } } @Override public CreateAnswer execute(CreateCommand cmd) { StoragePoolTO pool = cmd.getPool(); DiskCharacteristics dskch = cmd.getDiskCharacteristics(); VDI vdi = null; Connection conn = getConnection(); try { SR poolSr = getStorageRepository(conn, pool); if (cmd.getTemplateUrl() != null) { VDI tmpltvdi = null; tmpltvdi = getVDIbyUuid(cmd.getTemplateUrl()); vdi = tmpltvdi.createClone(conn, new HashMap<String, String>()); vdi.setNameLabel(conn, dskch.getName()); } else { VDI.Record vdir = new VDI.Record(); vdir.nameLabel = dskch.getName(); vdir.SR = poolSr; vdir.type = Types.VdiType.USER; if(cmd.getSize()!=0) vdir.virtualSize = cmd.getSize(); else vdir.virtualSize = dskch.getSize(); vdi = VDI.create(conn, vdir); } VDI.Record vdir; vdir = vdi.getRecord(conn); s_logger.debug("Succesfully created VDI for " + cmd + ". Uuid = " + vdir.uuid); VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), Storage.StorageResourceType.STORAGE_POOL, pool.getType(), vdir.nameLabel, pool.getPath(), vdir.uuid, vdir.virtualSize); return new CreateAnswer(cmd, vol); } catch (Exception e) { s_logger.warn("Unable to create volume; Pool=" + pool + "; Disk: " + dskch, e); return new CreateAnswer(cmd, e); } } protected SR getISOSRbyVmName(String vmName) { Connection conn = getConnection(); try { Set<SR> srs = SR.getByNameLabel(conn, vmName + "-ISO"); if (srs.size() == 0) { return null; } else if (srs.size() == 1) { return srs.iterator().next(); } else { String msg = "getIsoSRbyVmName failed due to there are more than 1 SR having same Label"; s_logger.warn(msg); } } catch (XenAPIException e) { String msg = "getIsoSRbyVmName failed due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "getIsoSRbyVmName failed due to " + e.getMessage(); s_logger.warn(msg, e); } return null; } protected SR createNfsSRbyURI(URI uri, boolean shared) { try { Connection conn = getConnection(); if (s_logger.isDebugEnabled()) { s_logger.debug("Creating a " + (shared ? "shared SR for " : "not shared SR for ") + uri); } Map<String, String> deviceConfig = new HashMap<String, String>(); String path = uri.getPath(); path = path.replace("//", "/"); deviceConfig.put("server", uri.getHost()); deviceConfig.put("serverpath", path); String name = UUID.nameUUIDFromBytes(new String(uri.getHost() + path).getBytes()).toString(); if (!shared) { Set<SR> srs = SR.getByNameLabel(conn, name); for (SR sr : srs) { SR.Record record = sr.getRecord(conn); if (SRType.NFS.equals(record.type) && record.contentType.equals("user") && !record.shared) { removeSRSync(sr); } } } Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), name, uri.getHost() + uri.getPath(), SRType.NFS.toString(), "user", shared, new HashMap<String, String>()); if( !checkSR(sr) ) { throw new Exception("no attached PBD"); } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Created a SR; UUID is " + sr.getUuid(conn))); } sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Can not create second storage SR mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Can not create second storage SR mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected SR createIsoSRbyURI(URI uri, String vmName, boolean shared) { try { Connection conn = getConnection(); Map<String, String> deviceConfig = new HashMap<String, String>(); String path = uri.getPath(); path = path.replace("//", "/"); deviceConfig.put("location", uri.getHost() + ":" + uri.getPath()); Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), uri.getHost() + uri.getPath(), "iso", "iso", "iso", shared, new HashMap<String, String>()); sr.setNameLabel(conn, vmName + "-ISO"); sr.setNameDescription(conn, deviceConfig.get("location")); sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected VDI getVDIbyLocationandSR(String loc, SR sr) { Connection conn = getConnection(); try { Set<VDI> vdis = sr.getVDIs(conn); for (VDI vdi : vdis) { if (vdi.getLocation(conn).startsWith(loc)) { return vdi; } } String msg = "can not getVDIbyLocationandSR " + loc; s_logger.warn(msg); return null; } catch (XenAPIException e) { String msg = "getVDIbyLocationandSR exception " + loc + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "getVDIbyLocationandSR exception " + loc + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected VDI getVDIbyUuid(String uuid) { try { Connection conn = getConnection(); return VDI.getByUuid(conn, uuid); } catch (XenAPIException e) { String msg = "VDI getByUuid for uuid: " + uuid + " failed due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "VDI getByUuid for uuid: " + uuid + " failed due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected SR getIscsiSR(Connection conn, StoragePoolVO pool) { synchronized (pool.getUuid().intern()) { Map<String, String> deviceConfig = new HashMap<String, String>(); try { String target = pool.getHostAddress().trim(); String path = pool.getPath().trim(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String tmp[] = path.split("/"); if (tmp.length != 3) { String msg = "Wrong iscsi path " + pool.getPath() + " it should be /targetIQN/LUN"; s_logger.warn(msg); throw new CloudRuntimeException(msg); } String targetiqn = tmp[1].trim(); String lunid = tmp[2].trim(); String scsiid = ""; Set<SR> srs = SR.getByNameLabel(conn, pool.getUuid()); for (SR sr : srs) { if (!SRType.LVMOISCSI.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("target") == null) continue; if (dc.get("targetIQN") == null) continue; if (dc.get("lunid") == null) continue; if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { return sr; } } deviceConfig.put("target", target); deviceConfig.put("targetIQN", targetiqn); Host host = Host.getByUuid(conn, _host.uuid); SR sr = null; try { sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), pool.getName(), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); } catch (XenAPIException e) { String errmsg = e.toString(); if (errmsg.contains("SR_BACKEND_FAILURE_107")) { String lun[] = errmsg.split("<LUN>"); boolean found = false; for (int i = 1; i < lun.length; i++) { int blunindex = lun[i].indexOf("<LUNid>") + 7; int elunindex = lun[i].indexOf("</LUNid>"); String ilun = lun[i].substring(blunindex, elunindex); ilun = ilun.trim(); if (ilun.equals(lunid)) { int bscsiindex = lun[i].indexOf("<SCSIid>") + 8; int escsiindex = lun[i].indexOf("</SCSIid>"); scsiid = lun[i].substring(bscsiindex, escsiindex); scsiid = scsiid.trim(); found = true; break; } } if (!found) { String msg = "can not find LUN " + lunid + " in " + errmsg; s_logger.warn(msg); throw new CloudRuntimeException(msg); } } else { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } deviceConfig.put("SCSIid", scsiid); sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), pool.getName(), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); if( !checkSR(sr) ) { throw new Exception("no attached PBD"); } sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } } protected SR getIscsiSR(Connection conn, StoragePoolTO pool) { synchronized (pool.getUuid().intern()) { Map<String, String> deviceConfig = new HashMap<String, String>(); try { String target = pool.getHost(); String path = pool.getPath(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String tmp[] = path.split("/"); if (tmp.length != 3) { String msg = "Wrong iscsi path " + pool.getPath() + " it should be /targetIQN/LUN"; s_logger.warn(msg); throw new CloudRuntimeException(msg); } String targetiqn = tmp[1].trim(); String lunid = tmp[2].trim(); String scsiid = ""; Set<SR> srs = SR.getByNameLabel(conn, pool.getUuid()); for (SR sr : srs) { if (!SRType.LVMOISCSI.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("target") == null) continue; if (dc.get("targetIQN") == null) continue; if (dc.get("lunid") == null) continue; if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { if (checkSR(sr)) { return sr; } } } deviceConfig.put("target", target); deviceConfig.put("targetIQN", targetiqn); Host host = Host.getByUuid(conn, _host.uuid); SR sr = null; try { sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); } catch (XenAPIException e) { String errmsg = e.toString(); if (errmsg.contains("SR_BACKEND_FAILURE_107")) { String lun[] = errmsg.split("<LUN>"); boolean found = false; for (int i = 1; i < lun.length; i++) { int blunindex = lun[i].indexOf("<LUNid>") + 7; int elunindex = lun[i].indexOf("</LUNid>"); String ilun = lun[i].substring(blunindex, elunindex); ilun = ilun.trim(); if (ilun.equals(lunid)) { int bscsiindex = lun[i].indexOf("<SCSIid>") + 8; int escsiindex = lun[i].indexOf("</SCSIid>"); scsiid = lun[i].substring(bscsiindex, escsiindex); scsiid = scsiid.trim(); found = true; break; } } if (!found) { String msg = "can not find LUN " + lunid + " in " + errmsg; s_logger.warn(msg); throw new CloudRuntimeException(msg); } } else { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } deviceConfig.put("SCSIid", scsiid); sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } } protected SR getNfsSR(StoragePoolVO pool) { Connection conn = getConnection(); Map<String, String> deviceConfig = new HashMap<String, String>(); try { String server = pool.getHostAddress(); String serverpath = pool.getPath(); serverpath = serverpath.replace("//", "/"); Set<SR> srs = SR.getAll(conn); for (SR sr : srs) { if (!SRType.NFS.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("server") == null) continue; if (dc.get("serverpath") == null) continue; if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { if (checkSR(sr)) { return sr; } } } deviceConfig.put("server", server); deviceConfig.put("serverpath", serverpath); Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), pool.getName(), SRType.NFS.toString(), "user", true, new HashMap<String, String>()); sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Unable to create NFS SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Unable to create NFS SR " + deviceConfig + " due to " + e.getMessage(); s_logger.warn(msg); throw new CloudRuntimeException(msg, e); } } protected SR getNfsSR(Connection conn, StoragePoolTO pool) { Map<String, String> deviceConfig = new HashMap<String, String>(); String server = pool.getHost(); String serverpath = pool.getPath(); serverpath = serverpath.replace("//", "/"); try { Set<SR> srs = SR.getAll(conn); for (SR sr : srs) { if (!SRType.NFS.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("server") == null) continue; if (dc.get("serverpath") == null) continue; if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { return sr; } } deviceConfig.put("server", server); deviceConfig.put("serverpath", serverpath); Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true, new HashMap<String, String>()); sr.scan(conn); return sr; } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e); } catch (XmlRpcException e) { throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e); } } @Override public Answer execute(DestroyCommand cmd) { VolumeTO vol = cmd.getVolume(); Connection conn = getConnection(); // Look up the VDI String volumeUUID = vol.getPath(); VDI vdi = null; try { vdi = getVDIbyUuid(volumeUUID); } catch (Exception e) { String msg = "getVDIbyUuid for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg); return new Answer(cmd, true, "Success"); } Set<VBD> vbds = null; try { vbds = vdi.getVBDs(conn); } catch (Exception e) { String msg = "VDI getVBDS for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } for (VBD vbd : vbds) { try { vbd.unplug(conn); vbd.destroy(conn); } catch (Exception e) { String msg = "VM destroy for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } try { vdi.destroy(conn); } catch (Exception e) { String msg = "VDI destroy for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd, true, "Success"); } @Override public ShareAnswer execute(final ShareCommand cmd) { if (!cmd.isShare()) { SR sr = getISOSRbyVmName(cmd.getVmName()); Connection conn = getConnection(); try { if (sr != null) { Set<VM> vms = VM.getByNameLabel(conn, cmd.getVmName()); if (vms.size() == 0) { removeSR(sr); } } } catch (Exception e) { String msg = "SR.getNameLabel failed due to " + e.getMessage() + e.toString(); s_logger.warn(msg); } } return new ShareAnswer(cmd, new HashMap<String, Integer>()); } @Override public CopyVolumeAnswer execute(final CopyVolumeCommand cmd) { String volumeUUID = cmd.getVolumePath(); StoragePoolVO pool = cmd.getPool(); String secondaryStorageURL = cmd.getSecondaryStorageURL(); URI uri = null; try { uri = new URI(secondaryStorageURL); } catch (URISyntaxException e) { return new CopyVolumeAnswer(cmd, false, "Invalid secondary storage URL specified.", null, null); } String remoteVolumesMountPath = uri.getHost() + ":" + uri.getPath() + "/volumes/"; String volumeFolder = String.valueOf(cmd.getVolumeId()) + "/"; boolean toSecondaryStorage = cmd.toSecondaryStorage(); String errorMsg = "Failed to copy volume"; SR primaryStoragePool = null; SR secondaryStorage = null; VDI srcVolume = null; VDI destVolume = null; Connection conn = getConnection(); try { if (toSecondaryStorage) { // Create the volume folder if (!createSecondaryStorageFolder(remoteVolumesMountPath, volumeFolder)) { throw new InternalErrorException("Failed to create the volume folder."); } // Create a SR for the volume UUID folder secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false); // Look up the volume on the source primary storage pool srcVolume = getVDIbyUuid(volumeUUID); // Copy the volume to secondary storage destVolume = cloudVDIcopy(srcVolume, secondaryStorage); } else { // Mount the volume folder secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false); // Look up the volume on secondary storage Set<VDI> vdis = secondaryStorage.getVDIs(conn); for (VDI vdi : vdis) { if (vdi.getUuid(conn).equals(volumeUUID)) { srcVolume = vdi; break; } } if (srcVolume == null) { throw new InternalErrorException("Failed to find volume on secondary storage."); } // Copy the volume to the primary storage pool primaryStoragePool = getStorageRepository(conn, pool); destVolume = cloudVDIcopy(srcVolume, primaryStoragePool); } String srUUID; if (primaryStoragePool == null) { srUUID = secondaryStorage.getUuid(conn); } else { srUUID = primaryStoragePool.getUuid(conn); } String destVolumeUUID = destVolume.getUuid(conn); return new CopyVolumeAnswer(cmd, true, null, srUUID, destVolumeUUID); } catch (XenAPIException e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new CopyVolumeAnswer(cmd, false, e.toString(), null, null); } catch (Exception e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null); } finally { if (!toSecondaryStorage && srcVolume != null) { // Delete the volume on secondary storage destroyVDI(srcVolume); } removeSR(secondaryStorage); if (!toSecondaryStorage) { // Delete the volume folder on secondary storage deleteSecondaryStorageFolder(remoteVolumesMountPath, volumeFolder); } } } protected AttachVolumeAnswer execute(final AttachVolumeCommand cmd) { boolean attach = cmd.getAttach(); String vmName = cmd.getVmName(); Long deviceId = cmd.getDeviceId(); String errorMsg; if (attach) { errorMsg = "Failed to attach volume"; } else { errorMsg = "Failed to detach volume"; } Connection conn = getConnection(); try { // Look up the VDI VDI vdi = mount(cmd.getPooltype(), cmd.getVolumeFolder(),cmd.getVolumePath()); // Look up the VM VM vm = getVM(conn, vmName); /* For HVM guest, if no pv driver installed, no attach/detach */ boolean isHVM; if (vm.getPVBootloader(conn).equalsIgnoreCase("")) isHVM = true; else isHVM = false; VMGuestMetrics vgm = vm.getGuestMetrics(conn); boolean pvDrvInstalled = false; if (!isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) { pvDrvInstalled = true; } if (isHVM && !pvDrvInstalled) { s_logger.warn(errorMsg + ": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected"); return new AttachVolumeAnswer(cmd, "You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); } if (attach) { // Figure out the disk number to attach the VM to String diskNumber = null; if( deviceId != null ) { if( deviceId.longValue() == 3 ) { String msg = "Device 3 is reserved for CD-ROM, choose other device"; return new AttachVolumeAnswer(cmd,msg); } if(isDeviceUsed(vm, deviceId)) { String msg = "Device " + deviceId + " is used in VM " + vmName; return new AttachVolumeAnswer(cmd,msg); } diskNumber = deviceId.toString(); } else { diskNumber = getUnusedDeviceNum(vm); } // Create a new VBD VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; vbdr.bootable = false; vbdr.userdevice = diskNumber; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; VBD vbd = VBD.create(conn, vbdr); // Attach the VBD to the VM vbd.plug(conn); // Update the VDI's label to include the VM name vdi.setNameLabel(conn, vmName + "-DATA"); return new AttachVolumeAnswer(cmd, Long.parseLong(diskNumber)); } else { // Look up all VBDs for this VDI Set<VBD> vbds = vdi.getVBDs(conn); // Detach each VBD from its VM, and then destroy it for (VBD vbd : vbds) { VBD.Record vbdr = vbd.getRecord(conn); if (vbdr.currentlyAttached) { vbd.unplug(conn); } vbd.destroy(conn); } // Update the VDI's label to be "detached" vdi.setNameLabel(conn, "detached"); umount(vdi); return new AttachVolumeAnswer(cmd); } } catch (XenAPIException e) { String msg = errorMsg + " for uuid: " + cmd.getVolumePath() + " due to " + e.toString(); s_logger.warn(msg, e); return new AttachVolumeAnswer(cmd, msg); } catch (Exception e) { String msg = errorMsg + " for uuid: " + cmd.getVolumePath() + " due to " + e.getMessage(); s_logger.warn(msg, e); return new AttachVolumeAnswer(cmd, msg); } } protected void umount(VDI vdi) { } protected Answer execute(final AttachIsoCommand cmd) { boolean attach = cmd.isAttach(); String vmName = cmd.getVmName(); String isoURL = cmd.getIsoPath(); String errorMsg; if (attach) { errorMsg = "Failed to attach ISO"; } else { errorMsg = "Failed to detach ISO"; } Connection conn = getConnection(); try { if (attach) { VBD isoVBD = null; // Find the VM VM vm = getVM(conn, vmName); // Find the ISO VDI VDI isoVDI = getIsoVDIByURL(conn, vmName, isoURL); // Find the VM's CD-ROM VBD Set<VBD> vbds = vm.getVBDs(conn); for (VBD vbd : vbds) { String userDevice = vbd.getUserdevice(conn); Types.VbdType type = vbd.getType(conn); if (userDevice.equals("3") && type == Types.VbdType.CD) { isoVBD = vbd; break; } } if (isoVBD == null) { throw new CloudRuntimeException("Unable to find CD-ROM VBD for VM: " + vmName); } else { // If an ISO is already inserted, eject it if (isoVBD.getEmpty(conn) == false) { isoVBD.eject(conn); } // Insert the new ISO isoVBD.insert(conn, isoVDI); } return new Answer(cmd); } else { // Find the VM VM vm = getVM(conn, vmName); String vmUUID = vm.getUuid(conn); // Find the ISO VDI VDI isoVDI = getIsoVDIByURL(conn, vmName, isoURL); SR sr = isoVDI.getSR(conn); // Look up all VBDs for this VDI Set<VBD> vbds = isoVDI.getVBDs(conn); // Iterate through VBDs, and if the VBD belongs the VM, eject // the ISO from it for (VBD vbd : vbds) { VM vbdVM = vbd.getVM(conn); String vbdVmUUID = vbdVM.getUuid(conn); if (vbdVmUUID.equals(vmUUID)) { // If an ISO is already inserted, eject it if (!vbd.getEmpty(conn)) { vbd.eject(conn); } break; } } if (!sr.getNameLabel(conn).startsWith("XenServer Tools")) { removeSR(sr); } return new Answer(cmd); } } catch (XenAPIException e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new Answer(cmd, false, e.toString()); } catch (Exception e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new Answer(cmd, false, e.getMessage()); } } protected ValidateSnapshotAnswer execute(final ValidateSnapshotCommand cmd) { String primaryStoragePoolNameLabel = cmd.getPrimaryStoragePoolNameLabel(); String volumeUuid = cmd.getVolumeUuid(); // Precondition: not null String firstBackupUuid = cmd.getFirstBackupUuid(); String previousSnapshotUuid = cmd.getPreviousSnapshotUuid(); String templateUuid = cmd.getTemplateUuid(); // By default assume failure String details = "Could not validate previous snapshot backup UUID " + "because the primary Storage SR could not be created from the name label: " + primaryStoragePoolNameLabel; boolean success = false; String expectedSnapshotBackupUuid = null; String actualSnapshotBackupUuid = null; String actualSnapshotUuid = null; Boolean isISCSI = false; String primaryStorageSRUuid = null; Connection conn = getConnection(); try { SR primaryStorageSR = getSRByNameLabelandHost(primaryStoragePoolNameLabel); if (primaryStorageSR != null) { primaryStorageSRUuid = primaryStorageSR.getUuid(conn); isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); } } catch (BadServerResponse e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } catch (XenAPIException e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } catch (XmlRpcException e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } if (primaryStorageSRUuid != null) { if (templateUuid == null) { templateUuid = ""; } if (firstBackupUuid == null) { firstBackupUuid = ""; } if (previousSnapshotUuid == null) { previousSnapshotUuid = ""; } String result = callHostPlugin("vmopsSnapshot", "validateSnapshot", "primaryStorageSRUuid", primaryStorageSRUuid, "volumeUuid", volumeUuid, "firstBackupUuid", firstBackupUuid, "previousSnapshotUuid", previousSnapshotUuid, "templateUuid", templateUuid, "isISCSI", isISCSI.toString()); if (result == null || result.isEmpty()) { details = "Validating snapshot backup for volume with UUID: " + volumeUuid + " failed because there was an exception in the plugin"; // callHostPlugin exception which has been logged already } else { String[] uuids = result.split("#", -1); if (uuids.length >= 3) { expectedSnapshotBackupUuid = uuids[1]; actualSnapshotBackupUuid = uuids[2]; } if (uuids.length >= 4) { actualSnapshotUuid = uuids[3]; } else { actualSnapshotUuid = ""; } if (uuids[0].equals("1")) { success = true; details = null; } else { details = "Previous snapshot backup on the primary storage is invalid. " + "Expected: " + expectedSnapshotBackupUuid + " Actual: " + actualSnapshotBackupUuid; // success is still false } s_logger.debug("ValidatePreviousSnapshotBackup returned " + " success: " + success + " details: " + details + " expectedSnapshotBackupUuid: " + expectedSnapshotBackupUuid + " actualSnapshotBackupUuid: " + actualSnapshotBackupUuid + " actualSnapshotUuid: " + actualSnapshotUuid); } } return new ValidateSnapshotAnswer(cmd, success, details, expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); } protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) { long snapshotId = cmd.getSnapshotId(); String snapshotName = cmd.getSnapshotName(); // By default assume failure boolean success = false; String cmdSwitch = cmd.getCommandSwitch(); String snapshotOp = "Unsupported snapshot command." + cmdSwitch; if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { snapshotOp = "create"; } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { snapshotOp = "destroy"; } String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; String snapshotUUID = null; Connection conn = getConnection(); try { if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { // Look up the volume String volumeUUID = cmd.getVolumePath(); VDI volume = getVDIbyUuid(volumeUUID); // Create a snapshot VDI snapshot = volume.snapshot(conn, new HashMap<String, String>()); if (snapshotName != null) { snapshot.setNameLabel(conn, snapshotName); } // Determine the UUID of the snapshot VDI.Record vdir = snapshot.getRecord(conn); snapshotUUID = vdir.uuid; success = true; details = null; } else if (cmd.getCommandSwitch().equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { // Look up the snapshot snapshotUUID = cmd.getSnapshotPath(); VDI snapshot = getVDIbyUuid(snapshotUUID); snapshot.destroy(conn); snapshotUUID = null; success = true; details = null; } } catch (XenAPIException e) { details += ", reason: " + e.toString(); s_logger.warn(details, e); } catch (Exception e) { details += ", reason: " + e.toString(); s_logger.warn(details, e); } return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); } protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateCommand cmd) { String secondaryStorageURL = cmd.getSecondaryStorageURL(); String snapshotUUID = cmd.getSnapshotPath(); String userSpecifiedName = cmd.getTemplateName(); SR secondaryStorage = null; VDI privateTemplate = null; Connection conn = getConnection(); try { URI uri = new URI(secondaryStorageURL); String remoteTemplateMountPath = uri.getHost() + ":" + uri.getPath() + "/template/"; String templateFolder = cmd.getAccountId() + "/" + cmd.getTemplateId() + "/"; String templateDownloadFolder = createTemplateDownloadFolder(remoteTemplateMountPath, templateFolder); String templateInstallFolder = "tmpl/" + templateFolder; // Create a SR for the secondary storage download folder secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/template/" + templateDownloadFolder), false); // Look up the snapshot and copy it to secondary storage VDI snapshot = getVDIbyUuid(snapshotUUID); privateTemplate = cloudVDIcopy(snapshot, secondaryStorage); if (userSpecifiedName != null) { privateTemplate.setNameLabel(conn, userSpecifiedName); } // Determine the template file name and install path VDI.Record vdir = privateTemplate.getRecord(conn); String templateName = vdir.uuid; String templateFilename = templateName + ".vhd"; String installPath = "template/" + templateInstallFolder + templateFilename; // Determine the template's virtual size and then forget the VDI long virtualSize = privateTemplate.getVirtualSize(conn); // Create the template.properties file in the download folder, move // the template and the template.properties file // to the install folder, and then delete the download folder if (!postCreatePrivateTemplate(remoteTemplateMountPath, templateDownloadFolder, templateInstallFolder, templateFilename, templateName, userSpecifiedName, null, virtualSize, cmd.getTemplateId())) { throw new InternalErrorException("Failed to create the template.properties file."); } return new CreatePrivateTemplateAnswer(cmd, true, null, installPath, virtualSize, templateName, ImageFormat.VHD); } catch (XenAPIException e) { if (privateTemplate != null) { destroyVDI(privateTemplate); } s_logger.warn("CreatePrivateTemplate Failed due to " + e.toString(), e); return new CreatePrivateTemplateAnswer(cmd, false, e.toString(), null, 0, null, null); } catch (Exception e) { s_logger.warn("CreatePrivateTemplate Failed due to " + e.getMessage(), e); return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage(), null, 0, null, null); } finally { // Remove the secondary storage SR removeSR(secondaryStorage); } } private String createTemplateDownloadFolder(String remoteTemplateMountPath, String templateFolder) throws InternalErrorException, URISyntaxException { String templateDownloadFolder = "download/" + _host.uuid + "/" + templateFolder; // Create the download folder if (!createSecondaryStorageFolder(remoteTemplateMountPath, templateDownloadFolder)) { throw new InternalErrorException("Failed to create the template download folder."); } return templateDownloadFolder; } protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) { String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String backedUpSnapshotUuid = cmd.getSnapshotUuid(); String origTemplateInstallPath = cmd.getOrigTemplateInstallPath(); Long newTemplateId = cmd.getNewTemplateId(); String userSpecifiedName = cmd.getTemplateName(); // By default, assume failure String details = "Failed to create private template " + newTemplateId + " from snapshot for volume: " + volumeId + " with backupUuid: " + backedUpSnapshotUuid; String newTemplatePath = null; String templateName = null; boolean result = false; long virtualSize = 0; try { URI uri = new URI(secondaryStoragePoolURL); String remoteTemplateMountPath = uri.getHost() + ":" + uri.getPath() + "/template/"; String templateFolder = cmd.getAccountId() + "/" + newTemplateId + "/"; String templateDownloadFolder = createTemplateDownloadFolder(remoteTemplateMountPath, templateFolder); String templateInstallFolder = "tmpl/" + templateFolder; // Yes, create a template vhd Pair<VHDInfo, String> vhdDetails = createVHDFromSnapshot(primaryStorageNameLabel, dcId, accountId, volumeId, secondaryStoragePoolURL, backedUpSnapshotUuid, origTemplateInstallPath, templateDownloadFolder); VHDInfo vhdInfo = vhdDetails.first(); String failureDetails = vhdDetails.second(); if (vhdInfo == null) { if (failureDetails != null) { details += failureDetails; } } else { templateName = vhdInfo.getUuid(); String templateFilename = templateName + ".vhd"; String templateInstallPath = templateInstallFolder + "/" + templateFilename; newTemplatePath = "template" + "/" + templateInstallPath; virtualSize = vhdInfo.getVirtualSize(); // create the template.properties file result = postCreatePrivateTemplate(remoteTemplateMountPath, templateDownloadFolder, templateInstallFolder, templateFilename, templateName, userSpecifiedName, null, virtualSize, newTemplateId); if (!result) { details += ", reason: Could not create the template.properties file on secondary storage dir: " + templateInstallFolder; } else { // Aaah, success. details = null; } } } catch (XenAPIException e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } catch (Exception e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } return new CreatePrivateTemplateAnswer(cmd, result, details, newTemplatePath, virtualSize, templateName, ImageFormat.VHD); } protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) { String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String snapshotUuid = cmd.getSnapshotUuid(); // not null: Precondition. String prevSnapshotUuid = cmd.getPrevSnapshotUuid(); String prevBackupUuid = cmd.getPrevBackupUuid(); boolean isFirstSnapshotOfRootVolume = cmd.isFirstSnapshotOfRootVolume(); // By default assume failure String details = null; boolean success = false; String snapshotBackupUuid = null; try { Connection conn = getConnection(); SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); URI uri = new URI(secondaryStoragePoolURL); String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details = "Couldn't backup snapshot because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { boolean gcHappened = true; if (gcHappened) { snapshotBackupUuid = backupSnapshot(primaryStorageSRUuid, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotUuid, prevSnapshotUuid, prevBackupUuid, isFirstSnapshotOfRootVolume, isISCSI); success = (snapshotBackupUuid != null); } else { s_logger.warn("GC hasn't happened yet for previousSnapshotUuid: " + prevSnapshotUuid + ". Will retry again after 1 min"); } } if (!success) { // Mark the snapshot as removed in the database. // When the next snapshot is taken, it will be // 1) deleted from the DB 2) The snapshotUuid will be deleted from the primary // 3) the snapshotBackupUuid will be copied to secondary // 4) if possible it will be coalesced with the next snapshot. } else if (prevSnapshotUuid != null && !isFirstSnapshotOfRootVolume) { // Destroy the previous snapshot, if it exists. // We destroy the previous snapshot only if the current snapshot // backup succeeds. // The aim is to keep the VDI of the last 'successful' snapshot // so that it doesn't get merged with the // new one // and muddle the vhd chain on the secondary storage. details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage."; destroySnapshotOnPrimaryStorage(prevSnapshotUuid); } } catch (XenAPIException e) { details = "BackupSnapshot Failed due to " + e.toString(); s_logger.warn(details, e); } catch (Exception e) { details = "BackupSnapshot Failed due to " + e.getMessage(); s_logger.warn(details, e); } return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid); } protected CreateVolumeFromSnapshotAnswer execute(final CreateVolumeFromSnapshotCommand cmd) { String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String backedUpSnapshotUuid = cmd.getSnapshotUuid(); String templatePath = cmd.getTemplatePath(); // By default, assume the command has failed and set the params to be // passed to CreateVolumeFromSnapshotAnswer appropriately boolean result = false; // Generic error message. String details = "Failed to create volume from snapshot for volume: " + volumeId + " with backupUuid: " + backedUpSnapshotUuid; String vhdUUID = null; SR temporarySROnSecondaryStorage = null; String mountPointOfTemporaryDirOnSecondaryStorage = null; try { VDI vdi = null; Connection conn = getConnection(); SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); // Get the absolute path of the template on the secondary storage. URI uri = new URI(secondaryStoragePoolURL); String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details += " because the URL passed: " + secondaryStoragePoolURL + " is invalid."; return new CreateVolumeFromSnapshotAnswer(cmd, result, details, vhdUUID); } // Create a volume and not a template String templateDownloadFolder = ""; VHDInfo vhdInfo = createVHDFromSnapshot(dcId, accountId, volumeId, secondaryStorageMountPath, backedUpSnapshotUuid, templatePath, templateDownloadFolder, isISCSI); if (vhdInfo == null) { details += " because the vmops plugin on XenServer failed at some point"; } else { vhdUUID = vhdInfo.getUuid(); String tempDirRelativePath = "snapshots" + File.separator + accountId + File.separator + volumeId + "_temp"; mountPointOfTemporaryDirOnSecondaryStorage = secondaryStorageMountPath + File.separator + tempDirRelativePath; uri = new URI("nfs://" + mountPointOfTemporaryDirOnSecondaryStorage); // No need to check if the SR already exists. It's a temporary // SR destroyed when this method exits. // And two createVolumeFromSnapshot operations cannot proceed at // the same time. temporarySROnSecondaryStorage = createNfsSRbyURI(uri, false); if (temporarySROnSecondaryStorage == null) { details += "because SR couldn't be created on " + mountPointOfTemporaryDirOnSecondaryStorage; } else { s_logger.debug("Successfully created temporary SR on secondary storage " + temporarySROnSecondaryStorage.getNameLabel(conn) + "with uuid " + temporarySROnSecondaryStorage.getUuid(conn) + " and scanned it"); // createNFSSRbyURI also scans the SR and introduces the VDI vdi = getVDIbyUuid(vhdUUID); if (vdi != null) { s_logger.debug("Successfully created VDI on secondary storage SR " + temporarySROnSecondaryStorage.getNameLabel(conn) + " with uuid " + vhdUUID); s_logger.debug("Copying VDI: " + vdi.getLocation(conn) + " from secondary to primary"); VDI vdiOnPrimaryStorage = cloudVDIcopy(vdi, primaryStorageSR); // vdi.copy introduces the vdi into the database. Don't // need to do a scan on the primary // storage. if (vdiOnPrimaryStorage != null) { vhdUUID = vdiOnPrimaryStorage.getUuid(conn); s_logger.debug("Successfully copied and introduced VDI on primary storage with path " + vdiOnPrimaryStorage.getLocation(conn) + " and uuid " + vhdUUID); result = true; details = null; } else { details += ". Could not copy the vdi " + vhdUUID + " to primary storage"; } // The VHD on temporary was scanned and introduced as a VDI // destroy it as we don't need it anymore. vdi.destroy(conn); } else { details += ". Could not scan and introduce vdi with uuid: " + vhdUUID; } } } } catch (XenAPIException e) { details += " due to " + e.toString(); s_logger.warn(details, e); } catch (Exception e) { details += " due to " + e.getMessage(); s_logger.warn(details, e); } finally { // In all cases, if the temporary SR was created, forget it. if (temporarySROnSecondaryStorage != null) { removeSR(temporarySROnSecondaryStorage); // Delete the temporary directory created. File folderPath = new File(mountPointOfTemporaryDirOnSecondaryStorage); String remoteMountPath = folderPath.getParent(); String folder = folderPath.getName(); deleteSecondaryStorageFolder(remoteMountPath, folder); } } if (!result) { // Is this logged at a higher level? s_logger.error(details); } // In all cases return something. return new CreateVolumeFromSnapshotAnswer(cmd, result, details, vhdUUID); } protected DeleteSnapshotBackupAnswer execute(final DeleteSnapshotBackupCommand cmd) { Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String backupUUID = cmd.getSnapshotUuid(); String childUUID = cmd.getChildUUID(); String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); String details = null; boolean success = false; SR primaryStorageSR = null; Boolean isISCSI = false; try { Connection conn = getConnection(); primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { details = "Primary Storage SR could not be created from the name label: " + primaryStorageNameLabel; throw new InternalErrorException(details); } isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); } catch (XenAPIException e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } catch (Exception e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } if (primaryStorageSR != null) { URI uri = null; try { uri = new URI(secondaryStoragePoolURL); } catch (URISyntaxException e) { details = "Error finding the secondary storage URL" + e.getMessage(); s_logger.error(details, e); } if (uri != null) { String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details = "Couldn't delete snapshot because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { details = deleteSnapshotBackup(dcId, accountId, volumeId, secondaryStorageMountPath, backupUUID, childUUID, isISCSI); success = (details != null && details.equals("1")); if (success) { s_logger.debug("Successfully deleted snapshot backup " + backupUUID); } } } } return new DeleteSnapshotBackupAnswer(cmd, success, details); } protected Answer execute(DeleteSnapshotsDirCommand cmd) { Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String snapshotUUID = cmd.getSnapshotUuid(); String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); String details = null; boolean success = false; SR primaryStorageSR = null; try { primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { details = "Primary Storage SR could not be created from the name label: " + primaryStorageNameLabel; } } catch (XenAPIException e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } catch (Exception e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } if (primaryStorageSR != null) { if (snapshotUUID != null) { VDI snapshotVDI = getVDIbyUuid(snapshotUUID); if (snapshotVDI != null) { destroyVDI(snapshotVDI); } } } URI uri = null; try { uri = new URI(secondaryStoragePoolURL); } catch (URISyntaxException e) { details = "Error finding the secondary storage URL" + e.getMessage(); s_logger.error(details, e); } if (uri != null) { String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details = "Couldn't delete snapshotsDir because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { details = deleteSnapshotsDir(dcId, accountId, volumeId, secondaryStorageMountPath); success = (details != null && details.equals("1")); if (success) { s_logger.debug("Successfully deleted snapshotsDir for volume: " + volumeId); } } } return new Answer(cmd, success, details); } protected VM getVM(Connection conn, String vmName) { // Look up VMs with the specified name Set<VM> vms; try { vms = VM.getByNameLabel(conn, vmName); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get " + vmName + ": " + e.toString(), e); } catch (Exception e) { throw new CloudRuntimeException("Unable to get " + vmName + ": " + e.getMessage(), e); } // If there are no VMs, throw an exception if (vms.size() == 0) throw new CloudRuntimeException("VM with name: " + vmName + " does not exist."); // If there is more than one VM, print a warning if (vms.size() > 1) s_logger.warn("Found " + vms.size() + " VMs with name: " + vmName); // Return the first VM in the set return vms.iterator().next(); } protected VDI getIsoVDIByURL(Connection conn, String vmName, String isoURL) { SR isoSR = null; String mountpoint = null; if (isoURL.startsWith("xs-tools")) { try { Set<VDI> vdis = VDI.getByNameLabel(conn, isoURL); if (vdis.isEmpty()) { throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL); } return vdis.iterator().next(); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get pv iso: " + isoURL + " due to " + e.toString()); } catch (Exception e) { throw new CloudRuntimeException("Unable to get pv iso: " + isoURL + " due to " + e.toString()); } } int index = isoURL.lastIndexOf("/"); mountpoint = isoURL.substring(0, index); URI uri; try { uri = new URI(mountpoint); } catch (URISyntaxException e) { // TODO Auto-generated catch block throw new CloudRuntimeException("isoURL is wrong: " + isoURL); } isoSR = getISOSRbyVmName(vmName); if (isoSR == null) { isoSR = createIsoSRbyURI(uri, vmName, false); } String isoName = isoURL.substring(index + 1); VDI isoVDI = getVDIbyLocationandSR(isoName, isoSR); if (isoVDI != null) { return isoVDI; } else { throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL); } } protected SR getStorageRepository(Connection conn, StoragePoolTO pool) { Set<SR> srs; try { srs = SR.getByNameLabel(conn, pool.getUuid()); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.toString(), e); } catch (Exception e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.getMessage(), e); } if (srs.size() > 1) { throw new CloudRuntimeException("More than one storage repository was found for pool with uuid: " + pool.getUuid()); } if (srs.size() == 1) { SR sr = srs.iterator().next(); if (s_logger.isDebugEnabled()) { s_logger.debug("SR retrieved for " + pool.getId() + " is mapped to " + sr.toString()); } if (checkSR(sr)) { return sr; } } if (pool.getType() == StoragePoolType.NetworkFilesystem) return getNfsSR(conn, pool); else if (pool.getType() == StoragePoolType.IscsiLUN) return getIscsiSR(conn, pool); else throw new CloudRuntimeException("The pool type: " + pool.getType().name() + " is not supported."); } protected SR getStorageRepository(Connection conn, StoragePoolVO pool) { Set<SR> srs; try { srs = SR.getByNameLabel(conn, pool.getUuid()); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.toString(), e); } catch (Exception e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.getMessage(), e); } if (srs.size() > 1) { throw new CloudRuntimeException("More than one storage repository was found for pool with uuid: " + pool.getUuid()); } else if (srs.size() == 1) { SR sr = srs.iterator().next(); if (s_logger.isDebugEnabled()) { s_logger.debug("SR retrieved for " + pool.getId() + " is mapped to " + sr.toString()); } if (checkSR(sr)) { return sr; } throw new CloudRuntimeException("Check this SR failed"); } else { if (pool.getPoolType() == StoragePoolType.NetworkFilesystem) return getNfsSR(pool); else if (pool.getPoolType() == StoragePoolType.IscsiLUN) return getIscsiSR(conn, pool); else throw new CloudRuntimeException("The pool type: " + pool.getPoolType().name() + " is not supported."); } } protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort()); } protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort()); } protected Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) { String result = null; final StringBuffer sb = new StringBuffer(); sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus"); boolean success = true; try { final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); // setting TIMEOUTs to avoid possible waiting until death situations conn.setConnectTimeout(5000); conn.setReadTimeout(5000); final InputStream is = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb2 = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) sb2.append(line + "\n"); result = sb2.toString(); } catch (final IOException e) { success = false; } finally { try { is.close(); } catch (final IOException e) { s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp); success = false; } } } catch (final IOException e) { s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); success = false; } return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result); } protected boolean createSecondaryStorageFolder(String remoteMountPath, String newFolder) { String result = callHostPlugin("vmopsSnapshot", "create_secondary_storage_folder", "remoteMountPath", remoteMountPath, "newFolder", newFolder); return (result != null); } protected boolean deleteSecondaryStorageFolder(String remoteMountPath, String folder) { String result = callHostPlugin("vmopsSnapshot", "delete_secondary_storage_folder", "remoteMountPath", remoteMountPath, "folder", folder); return (result != null); } protected boolean postCreatePrivateTemplate(String remoteTemplateMountPath, String templateDownloadFolder, String templateInstallFolder, String templateFilename, String templateName, String templateDescription, String checksum, long virtualSize, long templateId) { if (templateDescription == null) { templateDescription = ""; } if (checksum == null) { checksum = ""; } String result = callHostPlugin("vmopsSnapshot", "post_create_private_template", "remoteTemplateMountPath", remoteTemplateMountPath, "templateDownloadFolder", templateDownloadFolder, "templateInstallFolder", templateInstallFolder, "templateFilename", templateFilename, "templateName", templateName, "templateDescription", templateDescription, "checksum", checksum, "virtualSize", String.valueOf(virtualSize), "templateId", String.valueOf(templateId)); boolean success = false; if (result != null && !result.isEmpty()) { // Else, command threw an exception which has already been logged. String[] tmp = result.split("#"); String status = tmp[0]; if (status != null && status.equalsIgnoreCase("1")) { s_logger.debug("Successfully created template.properties file on secondary storage dir: " + templateInstallFolder); success = true; } else { s_logger.warn("Could not create template.properties file on secondary storage dir: " + templateInstallFolder + " for templateId: " + templateId + ". Failed with status " + status); } } return success; } // Each argument is put in a separate line for readability. // Using more lines does not harm the environment. protected String backupSnapshot(String primaryStorageSRUuid, Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String snapshotUuid, String prevSnapshotUuid, String prevBackupUuid, Boolean isFirstSnapshotOfRootVolume, Boolean isISCSI) { String backupSnapshotUuid = null; if (prevSnapshotUuid == null) { prevSnapshotUuid = ""; } if (prevBackupUuid == null) { prevBackupUuid = ""; } // Each argument is put in a separate line for readability. // Using more lines does not harm the environment. String results = callHostPlugin("vmopsSnapshot", "backupSnapshot", "primaryStorageSRUuid", primaryStorageSRUuid, "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "snapshotUuid", snapshotUuid, "prevSnapshotUuid", prevSnapshotUuid, "prevBackupUuid", prevBackupUuid, "isFirstSnapshotOfRootVolume", isFirstSnapshotOfRootVolume.toString(), "isISCSI", isISCSI.toString()); if (results == null || results.isEmpty()) { // errString is already logged. return null; } String[] tmp = results.split("#"); String status = tmp[0]; backupSnapshotUuid = tmp[1]; // status == "1" if and only if backupSnapshotUuid != null // So we don't rely on status value but return backupSnapshotUuid as an // indicator of success. String failureString = "Could not copy backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " from primary storage " + primaryStorageSRUuid + " to secondary storage " + secondaryStorageMountPath; if (status != null && status.equalsIgnoreCase("1") && backupSnapshotUuid != null) { s_logger.debug("Successfully copied backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " to secondary storage"); } else { s_logger.debug(failureString + ". Failed with status: " + status); } return backupSnapshotUuid; } protected boolean destroySnapshotOnPrimaryStorage(String snapshotUuid) { // Precondition snapshotUuid != null try { Connection conn = getConnection(); VDI snapshot = getVDIbyUuid(snapshotUuid); if (snapshot == null) { throw new InternalErrorException("Could not destroy snapshot " + snapshotUuid + " because the snapshot VDI was null"); } snapshot.destroy(conn); s_logger.debug("Successfully destroyed snapshotUuid: " + snapshotUuid + " on primary storage"); return true; } catch (XenAPIException e) { String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.toString(); s_logger.error(msg, e); } catch (Exception e) { String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.getMessage(); s_logger.warn(msg, e); } return false; } protected String deleteSnapshotBackup(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backupUUID, String childUUID, Boolean isISCSI) { // If anybody modifies the formatting below again, I'll skin them String result = callHostPlugin("vmopsSnapshot", "deleteSnapshotBackup", "backupUUID", backupUUID, "childUUID", childUUID, "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "isISCSI", isISCSI.toString()); return result; } protected String deleteSnapshotsDir(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath) { // If anybody modifies the formatting below again, I'll skin them String result = callHostPlugin("vmopsSnapshot", "deleteSnapshotsDir", "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath); return result; } // If anybody messes up with the formatting, I'll skin them protected Pair<VHDInfo, String> createVHDFromSnapshot(String primaryStorageNameLabel, Long dcId, Long accountId, Long volumeId, String secondaryStoragePoolURL, String backedUpSnapshotUuid, String templatePath, String templateDownloadFolder) throws XenAPIException, IOException, XmlRpcException, InternalErrorException, URISyntaxException { // Return values String details = null; Connection conn = getConnection(); SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot " + "because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); // Get the absolute path of the template on the secondary storage. URI uri = new URI(secondaryStoragePoolURL); String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); VHDInfo vhdInfo = null; if (secondaryStorageMountPath == null) { details = " because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { vhdInfo = createVHDFromSnapshot(dcId, accountId, volumeId, secondaryStorageMountPath, backedUpSnapshotUuid, templatePath, templateDownloadFolder, isISCSI); if (vhdInfo == null) { details = " because the vmops plugin on XenServer failed at some point"; } } return new Pair<VHDInfo, String>(vhdInfo, details); } protected VHDInfo createVHDFromSnapshot(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backedUpSnapshotUuid, String templatePath, String templateDownloadFolder, Boolean isISCSI) { String vdiUUID = null; String failureString = "Could not create volume from " + backedUpSnapshotUuid; templatePath = (templatePath == null) ? "" : templatePath; String results = callHostPlugin("vmopsSnapshot", "createVolumeFromSnapshot", "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "backedUpSnapshotUuid", backedUpSnapshotUuid, "templatePath", templatePath, "templateDownloadFolder", templateDownloadFolder, "isISCSI", isISCSI.toString()); if (results == null || results.isEmpty()) { // Command threw an exception which has already been logged. return null; } String[] tmp = results.split("#"); String status = tmp[0]; vdiUUID = tmp[1]; Long virtualSizeInMB = 0L; if (tmp.length == 3) { virtualSizeInMB = Long.valueOf(tmp[2]); } // status == "1" if and only if vdiUUID != null // So we don't rely on status value but return vdiUUID as an indicator // of success. if (status != null && status.equalsIgnoreCase("1") && vdiUUID != null) { s_logger.debug("Successfully created vhd file with all data on secondary storage : " + vdiUUID); } else { s_logger.debug(failureString + ". Failed with status " + status + " with vdiUuid " + vdiUUID); } return new VHDInfo(vdiUUID, virtualSizeInMB * MB); } @Override public boolean start() { return true; } @Override public boolean stop() { disconnected(); return true; } @Override public String getName() { return _name; } @Override public IAgentControl getAgentControl() { return _agentControl; } @Override public void setAgentControl(IAgentControl agentControl) { _agentControl = agentControl; } @Override public boolean IsRemoteAgent() { return _isRemoteAgent; } @Override public void setRemoteAgent(boolean remote) { _isRemoteAgent = remote; } protected Answer execute(PoolEjectCommand cmd) { Connection conn = getConnection(); String hostuuid = cmd.getHostuuid(); try { Host host = Host.getByUuid(conn, hostuuid); // remove all tags cloud stack add before eject Host.Record hr = host.getRecord(conn); Iterator<String> it = hr.tags.iterator(); while (it.hasNext()) { String tag = it.next(); if (tag.startsWith("vmops-version-")) { it.remove(); } } // eject from pool Pool.eject(conn, host); return new Answer(cmd); } catch (XenAPIException e) { String msg = "Unable to eject host " + _host.uuid + " due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { s_logger.warn("Unable to eject host " + _host.uuid, e); String msg = "Unable to eject host " + _host.uuid + " due to " + e.getMessage(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } protected class Nic { public Network n; public Network.Record nr; public PIF p; public PIF.Record pr; public Nic(Network n, Network.Record nr, PIF p, PIF.Record pr) { this.n = n; this.nr = nr; this.p = p; this.pr = pr; } } // A list of UUIDs that are gathered from the XenServer when // the resource first connects to XenServer. These UUIDs do // not change over time. protected class XenServerHost { public String systemvmisouuid; public String uuid; public String ip; public String publicNetwork; public String privateNetwork; public String linkLocalNetwork; public String storageNetwork1; public String storageNetwork2; public String guestNetwork; public String guestPif; public String publicPif; public String privatePif; public String storagePif1; public String storagePif2; public String pool; } private class VHDInfo { private final String uuid; private final Long virtualSize; public VHDInfo(String uuid, Long virtualSize) { this.uuid = uuid; this.virtualSize = virtualSize; } /** * @return the uuid */ public String getUuid() { return uuid; } /** * @return the virtualSize */ public Long getVirtualSize() { return virtualSize; } } }
core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
/** : * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. * * It 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. * */ package com.cloud.hypervisor.xen.resource; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import javax.ejb.Local; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.BackupSnapshotAnswer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteSnapshotBackupAnswer; import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotsDirCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; import com.cloud.agent.api.GetStorageStatsCommand; import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; import com.cloud.agent.api.HostStatsEntry; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; import com.cloud.agent.api.PingTestCommand; import com.cloud.agent.api.PoolEjectCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.Start2Answer; import com.cloud.agent.api.Start2Command; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartConsoleProxyAnswer; import com.cloud.agent.api.StartConsoleProxyCommand; import com.cloud.agent.api.StartRouterAnswer; import com.cloud.agent.api.StartRouterCommand; import com.cloud.agent.api.StartSecStorageVmAnswer; import com.cloud.agent.api.StartSecStorageVmCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.agent.api.ValidateSnapshotAnswer; import com.cloud.agent.api.ValidateSnapshotCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer; import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; import com.cloud.agent.api.routing.DhcpEntryCommand; import com.cloud.agent.api.routing.IPAssocCommand; import com.cloud.agent.api.routing.LoadBalancerCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRuleCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.CreatePrivateTemplateCommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.DownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.storage.ShareAnswer; import com.cloud.agent.api.storage.ShareCommand; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.StoragePoolTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor; import com.cloud.network.Network.BroadcastDomainType; import com.cloud.network.Network.TrafficType; import com.cloud.hypervisor.xen.resource.XenServerConnectionPool.XenServerConnection; import com.cloud.resource.ServerResource; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.VolumeVO; import com.cloud.storage.resource.StoragePoolResource; import com.cloud.storage.template.TemplateInfo; import com.cloud.template.VirtualMachineTemplate.BootloaderType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DiskCharacteristics; import com.cloud.vm.DomainRouter; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineName; import com.trilead.ssh2.SCPClient; import com.xensource.xenapi.APIVersion; import com.xensource.xenapi.Bond; import com.xensource.xenapi.Connection; import com.xensource.xenapi.Console; import com.xensource.xenapi.Host; import com.xensource.xenapi.HostCpu; import com.xensource.xenapi.HostMetrics; import com.xensource.xenapi.Network; import com.xensource.xenapi.PBD; import com.xensource.xenapi.PIF; import com.xensource.xenapi.Pool; import com.xensource.xenapi.SR; import com.xensource.xenapi.Session; import com.xensource.xenapi.Types; import com.xensource.xenapi.Types.BadServerResponse; import com.xensource.xenapi.Types.IpConfigurationMode; import com.xensource.xenapi.Types.VmPowerState; import com.xensource.xenapi.Types.XenAPIException; import com.xensource.xenapi.VBD; import com.xensource.xenapi.VDI; import com.xensource.xenapi.VIF; import com.xensource.xenapi.VLAN; import com.xensource.xenapi.VM; import com.xensource.xenapi.VMGuestMetrics; import com.xensource.xenapi.XenAPIObject; /** * Encapsulates the interface to the XenServer API. * */ @Local(value = ServerResource.class) public abstract class CitrixResourceBase implements StoragePoolResource, ServerResource { private static final Logger s_logger = Logger.getLogger(CitrixResourceBase.class); protected static final XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance(); protected static final int MB = 1024 * 1024; protected String _name; protected String _username; protected String _password; protected final int _retry = 24; protected final int _sleep = 10000; protected long _dcId; protected String _pod; protected String _cluster; protected HashMap<String, State> _vms = new HashMap<String, State>(71); protected String _patchPath; protected String _privateNetworkName; protected String _linkLocalPrivateNetworkName; protected String _publicNetworkName; protected String _storageNetworkName1; protected String _storageNetworkName2; protected String _guestNetworkName; protected int _wait; protected IAgentControl _agentControl; protected boolean _isRemoteAgent = false; protected final XenServerHost _host = new XenServerHost(); // Guest and Host Performance Statistics protected boolean _collectHostStats = false; protected String _consolidationFunction = "AVERAGE"; protected int _pollingIntervalInSeconds = 60; protected StorageLayer _storage; protected boolean _canBridgeFirewall = false; protected HashMap<StoragePoolType, StoragePoolResource> _pools = new HashMap<StoragePoolType, StoragePoolResource>(5); public enum SRType { NFS, LVM, ISCSI, ISO, LVMOISCSI; @Override public String toString() { return super.toString().toLowerCase(); } public boolean equals(String type) { return super.toString().equalsIgnoreCase(type); } } protected static HashMap<Types.VmPowerState, State> s_statesTable; protected String _localGateway; static { s_statesTable = new HashMap<Types.VmPowerState, State>(); s_statesTable.put(Types.VmPowerState.HALTED, State.Stopped); s_statesTable.put(Types.VmPowerState.PAUSED, State.Running); s_statesTable.put(Types.VmPowerState.RUNNING, State.Running); s_statesTable.put(Types.VmPowerState.SUSPENDED, State.Running); s_statesTable.put(Types.VmPowerState.UNKNOWN, State.Unknown); s_statesTable.put(Types.VmPowerState.UNRECOGNIZED, State.Unknown); } private static HashMap<String, String> _guestOsType = new HashMap<String, String>(50); static { _guestOsType.put("CentOS 4.5 (32-bit)", "CentOS 4.5"); _guestOsType.put("CentOS 4.6 (32-bit)", "CentOS 4.6"); _guestOsType.put("CentOS 4.7 (32-bit)", "CentOS 4.7"); _guestOsType.put("CentOS 4.8 (32-bit)", "CentOS 4.8"); _guestOsType.put("CentOS 5.0 (32-bit)", "CentOS 5.0"); _guestOsType.put("CentOS 5.0 (64-bit)", "CentOS 5.0 x64"); _guestOsType.put("CentOS 5.1 (32-bit)", "CentOS 5.1"); _guestOsType.put("CentOS 5.1 (64-bit)", "CentOS 5.1 x64"); _guestOsType.put("CentOS 5.2 (32-bit)", "CentOS 5.2"); _guestOsType.put("CentOS 5.2 (64-bit)", "CentOS 5.2 x64"); _guestOsType.put("CentOS 5.3 (32-bit)", "CentOS 5.3"); _guestOsType.put("CentOS 5.3 (64-bit)", "CentOS 5.3 x64"); _guestOsType.put("CentOS 5.4 (32-bit)", "CentOS 5.4"); _guestOsType.put("CentOS 5.4 (64-bit)", "CentOS 5.4 x64"); _guestOsType.put("Debian Lenny 5.0 (32-bit)", "Debian Lenny 5.0"); _guestOsType.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5.0"); _guestOsType.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5.0 x64"); _guestOsType.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5.1"); _guestOsType.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5.1 x64"); _guestOsType.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5.2"); _guestOsType.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5.2 x64"); _guestOsType.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5.3"); _guestOsType.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5.3 x64"); _guestOsType.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5.4"); _guestOsType.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5.4 x64"); _guestOsType.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5"); _guestOsType.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6"); _guestOsType.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7"); _guestOsType.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8"); _guestOsType.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5.0"); _guestOsType.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5.0 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5.1"); _guestOsType.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5.1 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5.2"); _guestOsType.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5.2 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5.3"); _guestOsType.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5.3 x64"); _guestOsType.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5.4"); _guestOsType.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5.4 x64"); _guestOsType.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 x64"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 x64"); _guestOsType.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "Other install media"); _guestOsType.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11"); _guestOsType.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 x64"); _guestOsType.put("Windows 7 (32-bit)", "Windows 7"); _guestOsType.put("Windows 7 (64-bit)", "Windows 7 x64"); _guestOsType.put("Windows Server 2003 (32-bit)", "Windows Server 2003"); _guestOsType.put("Windows Server 2003 (64-bit)", "Windows Server 2003 x64"); _guestOsType.put("Windows Server 2008 (32-bit)", "Windows Server 2008"); _guestOsType.put("Windows Server 2008 (64-bit)", "Windows Server 2008 x64"); _guestOsType.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 x64"); _guestOsType.put("Windows 2000 SP4 (32-bit)", "Windows 2000 SP4"); _guestOsType.put("Windows Vista (32-bit)", "Windows Vista"); _guestOsType.put("Windows XP SP2 (32-bit)", "Windows XP SP2"); _guestOsType.put("Windows XP SP3 (32-bit)", "Windows XP SP3"); _guestOsType.put("Other install media", "Other install media"); } protected boolean isRefNull(XenAPIObject object) { return (object == null || object.toWireString().equals("OpaqueRef:NULL")); } @Override public void disconnected() { s_logger.debug("Logging out of " + _host.uuid); if (_host.pool != null) { _connPool.disconnect(_host.uuid, _host.pool); _host.pool = null; } } protected VDI cloudVDIcopy(VDI vdi, SR sr) throws BadServerResponse, XenAPIException, XmlRpcException{ Connection conn = getConnection(); return vdi.copy(conn, sr); } protected void destroyStoppedVm() { Map<VM, VM.Record> vmentries = null; Connection conn = getConnection(); for (int i = 0; i < 2; i++) { try { vmentries = VM.getAllRecords(conn); break; } catch (final Throwable e) { s_logger.warn("Unable to get vms", e); } try { Thread.sleep(1000); } catch (final InterruptedException ex) { } } if (vmentries == null) { return; } for (Map.Entry<VM, VM.Record> vmentry : vmentries.entrySet()) { VM.Record record = vmentry.getValue(); if (record.isControlDomain || record.isASnapshot || record.isATemplate) { continue; // Skip DOM0 } if (record.powerState != Types.VmPowerState.HALTED) { continue; } try { if (isRefNull(record.affinity) || !record.affinity.getUuid(conn).equals(_host.uuid)) { continue; } vmentry.getKey().destroy(conn); } catch (Exception e) { String msg = "VM destroy failed for " + record.nameLabel + " due to " + e.getMessage(); s_logger.warn(msg, e); } } } protected void cleanupDiskMounts() { Connection conn = getConnection(); Map<SR, SR.Record> srs; try { srs = SR.getAllRecords(conn); } catch (XenAPIException e) { s_logger.warn("Unable to get the SRs " + e.toString(), e); throw new CloudRuntimeException("Unable to get SRs " + e.toString(), e); } catch (XmlRpcException e) { throw new CloudRuntimeException("Unable to get SRs " + e.getMessage()); } for (Map.Entry<SR, SR.Record> sr : srs.entrySet()) { SR.Record rec = sr.getValue(); if (SRType.NFS.equals(rec.type) || (SRType.ISO.equals(rec.type) && rec.nameLabel.endsWith("iso"))) { if (rec.PBDs == null || rec.PBDs.size() == 0) { cleanSR(sr.getKey(), rec); continue; } for (PBD pbd : rec.PBDs) { if (isRefNull(pbd)) { continue; } PBD.Record pbdr = null; try { pbdr = pbd.getRecord(conn); } catch (XenAPIException e) { s_logger.warn("Unable to get pbd record " + e.toString()); } catch (XmlRpcException e) { s_logger.warn("Unable to get pbd record " + e.getMessage()); } if (pbdr == null) { continue; } try { if (pbdr.host.getUuid(conn).equals(_host.uuid)) { if (!currentlyAttached(sr.getKey(), rec, pbd, pbdr)) { pbd.unplug(conn); pbd.destroy(conn); cleanSR(sr.getKey(), rec); } else if (!pbdr.currentlyAttached) { pbd.plug(conn); } } } catch (XenAPIException e) { s_logger.warn("Catch XenAPIException due to" + e.toString(), e); } catch (XmlRpcException e) { s_logger.warn("Catch XmlRpcException due to" + e.getMessage(), e); } } } } } protected Pair<VM, VM.Record> getVmByNameLabel(Connection conn, Host host, String nameLabel, boolean getRecord) throws XmlRpcException, XenAPIException { Set<VM> vms = host.getResidentVMs(conn); for (VM vm : vms) { VM.Record rec = null; String name = null; if (getRecord) { rec = vm.getRecord(conn); name = rec.nameLabel; } else { name = vm.getNameLabel(conn); } if (name.equals(nameLabel)) { return new Pair<VM, VM.Record>(vm, rec); } } return null; } protected boolean currentlyAttached(SR sr, SR.Record rec, PBD pbd, PBD.Record pbdr) { String status = null; if (SRType.NFS.equals(rec.type)) { status = callHostPlugin("vmops", "checkMount", "mount", rec.uuid); } else if (SRType.LVMOISCSI.equals(rec.type) ) { String scsiid = pbdr.deviceConfig.get("SCSIid"); if (scsiid.isEmpty()) { return false; } status = callHostPlugin("vmops", "checkIscsi", "scsiid", scsiid); } else { return true; } if (status != null && status.equalsIgnoreCase("1")) { s_logger.debug("currently attached " + pbdr.uuid); return true; } else { s_logger.debug("currently not attached " + pbdr.uuid); return false; } } protected boolean pingdomr(String host, String port) { String status; status = callHostPlugin("vmops", "pingdomr", "host", host, "port", port); if (status == null || status.isEmpty()) { return false; } return true; } protected boolean pingxenserver() { String status; status = callHostPlugin("vmops", "pingxenserver"); if (status == null || status.isEmpty()) { return false; } return true; } protected String logX(XenAPIObject obj, String msg) { return new StringBuilder("Host ").append(_host.ip).append(" ").append(obj.toWireString()).append(": ").append(msg).toString(); } protected void cleanSR(SR sr, SR.Record rec) { Connection conn = getConnection(); if (rec.VDIs != null) { for (VDI vdi : rec.VDIs) { VDI.Record vdir; try { vdir = vdi.getRecord(conn); } catch (XenAPIException e) { s_logger.debug("Unable to get VDI: " + e.toString()); continue; } catch (XmlRpcException e) { s_logger.debug("Unable to get VDI: " + e.getMessage()); continue; } if (vdir.VBDs == null) continue; for (VBD vbd : vdir.VBDs) { try { VBD.Record vbdr = vbd.getRecord(conn); VM.Record vmr = vbdr.VM.getRecord(conn); if ((!isRefNull(vmr.residentOn) && vmr.residentOn.getUuid(conn).equals(_host.uuid)) || (isRefNull(vmr.residentOn) && !isRefNull(vmr.affinity) && vmr.affinity.getUuid(conn).equals(_host.uuid))) { if (vmr.powerState != VmPowerState.HALTED && vmr.powerState != VmPowerState.UNKNOWN && vmr.powerState != VmPowerState.UNRECOGNIZED) { try { vbdr.VM.hardShutdown(conn); } catch (XenAPIException e) { s_logger.debug("Shutdown hit error " + vmr.nameLabel + ": " + e.toString()); } } try { vbdr.VM.destroy(conn); } catch (XenAPIException e) { s_logger.debug("Destroy hit error " + vmr.nameLabel + ": " + e.toString()); } catch (XmlRpcException e) { s_logger.debug("Destroy hit error " + vmr.nameLabel + ": " + e.getMessage()); } vbd.destroy(conn); break; } } catch (XenAPIException e) { s_logger.debug("Unable to get VBD: " + e.toString()); continue; } catch (XmlRpcException e) { s_logger.debug("Uanbel to get VBD: " + e.getMessage()); continue; } } } } for (PBD pbd : rec.PBDs) { PBD.Record pbdr = null; try { pbdr = pbd.getRecord(conn); pbd.unplug(conn); pbd.destroy(conn); } catch (XenAPIException e) { s_logger.warn("PBD " + ((pbdr != null) ? "(uuid:" + pbdr.uuid + ")" : "") + "destroy failed due to " + e.toString()); } catch (XmlRpcException e) { s_logger.warn("PBD " + ((pbdr != null) ? "(uuid:" + pbdr.uuid + ")" : "") + "destroy failed due to " + e.getMessage()); } } try { rec = sr.getRecord(conn); if (rec.PBDs == null || rec.PBDs.size() == 0) { sr.forget(conn); return; } } catch (XenAPIException e) { s_logger.warn("Unable to retrieve sr again: " + e.toString(), e); } catch (XmlRpcException e) { s_logger.warn("Unable to retrieve sr again: " + e.getMessage(), e); } } @Override public Answer executeRequest(Command cmd) { if (cmd instanceof CreateCommand) { return execute((CreateCommand) cmd); } else if (cmd instanceof SetFirewallRuleCommand) { return execute((SetFirewallRuleCommand) cmd); } else if (cmd instanceof LoadBalancerCfgCommand) { return execute((LoadBalancerCfgCommand) cmd); } else if (cmd instanceof IPAssocCommand) { return execute((IPAssocCommand) cmd); } else if (cmd instanceof CheckConsoleProxyLoadCommand) { return execute((CheckConsoleProxyLoadCommand) cmd); } else if (cmd instanceof WatchConsoleProxyLoadCommand) { return execute((WatchConsoleProxyLoadCommand) cmd); } else if (cmd instanceof SavePasswordCommand) { return execute((SavePasswordCommand) cmd); } else if (cmd instanceof DhcpEntryCommand) { return execute((DhcpEntryCommand) cmd); } else if (cmd instanceof VmDataCommand) { return execute((VmDataCommand) cmd); } else if (cmd instanceof StartCommand) { return execute((StartCommand) cmd); } else if (cmd instanceof StartRouterCommand) { return execute((StartRouterCommand) cmd); } else if (cmd instanceof ReadyCommand) { return execute((ReadyCommand) cmd); } else if (cmd instanceof GetHostStatsCommand) { return execute((GetHostStatsCommand) cmd); } else if (cmd instanceof GetVmStatsCommand) { return execute((GetVmStatsCommand) cmd); } else if (cmd instanceof CheckHealthCommand) { return execute((CheckHealthCommand) cmd); } else if (cmd instanceof StopCommand) { return execute((StopCommand) cmd); } else if (cmd instanceof RebootRouterCommand) { return execute((RebootRouterCommand) cmd); } else if (cmd instanceof RebootCommand) { return execute((RebootCommand) cmd); } else if (cmd instanceof CheckVirtualMachineCommand) { return execute((CheckVirtualMachineCommand) cmd); } else if (cmd instanceof PrepareForMigrationCommand) { return execute((PrepareForMigrationCommand) cmd); } else if (cmd instanceof MigrateCommand) { return execute((MigrateCommand) cmd); } else if (cmd instanceof DestroyCommand) { return execute((DestroyCommand) cmd); } else if (cmd instanceof ShareCommand) { return execute((ShareCommand) cmd); } else if (cmd instanceof ModifyStoragePoolCommand) { return execute((ModifyStoragePoolCommand) cmd); } else if (cmd instanceof DeleteStoragePoolCommand) { return execute((DeleteStoragePoolCommand) cmd); } else if (cmd instanceof CopyVolumeCommand) { return execute((CopyVolumeCommand) cmd); } else if (cmd instanceof AttachVolumeCommand) { return execute((AttachVolumeCommand) cmd); } else if (cmd instanceof AttachIsoCommand) { return execute((AttachIsoCommand) cmd); } else if (cmd instanceof ValidateSnapshotCommand) { return execute((ValidateSnapshotCommand) cmd); } else if (cmd instanceof ManageSnapshotCommand) { return execute((ManageSnapshotCommand) cmd); } else if (cmd instanceof BackupSnapshotCommand) { return execute((BackupSnapshotCommand) cmd); } else if (cmd instanceof DeleteSnapshotBackupCommand) { return execute((DeleteSnapshotBackupCommand) cmd); } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { return execute((CreateVolumeFromSnapshotCommand) cmd); } else if (cmd instanceof DeleteSnapshotsDirCommand) { return execute((DeleteSnapshotsDirCommand) cmd); } else if (cmd instanceof CreatePrivateTemplateCommand) { return execute((CreatePrivateTemplateCommand) cmd); } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { return execute((CreatePrivateTemplateFromSnapshotCommand) cmd); } else if (cmd instanceof GetStorageStatsCommand) { return execute((GetStorageStatsCommand) cmd); } else if (cmd instanceof PrimaryStorageDownloadCommand) { return execute((PrimaryStorageDownloadCommand) cmd); } else if (cmd instanceof StartConsoleProxyCommand) { return execute((StartConsoleProxyCommand) cmd); } else if (cmd instanceof StartSecStorageVmCommand) { return execute((StartSecStorageVmCommand) cmd); } else if (cmd instanceof GetVncPortCommand) { return execute((GetVncPortCommand) cmd); } else if (cmd instanceof SetupCommand) { return execute((SetupCommand) cmd); } else if (cmd instanceof MaintainCommand) { return execute((MaintainCommand) cmd); } else if (cmd instanceof PingTestCommand) { return execute((PingTestCommand) cmd); } else if (cmd instanceof CheckOnHostCommand) { return execute((CheckOnHostCommand) cmd); } else if (cmd instanceof ModifySshKeysCommand) { return execute((ModifySshKeysCommand) cmd); } else if (cmd instanceof PoolEjectCommand) { return execute((PoolEjectCommand) cmd); } else if (cmd instanceof Start2Command) { return execute((Start2Command)cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } } Pair<Network, String> getNetworkForTraffic(Connection conn, TrafficType type) throws XenAPIException, XmlRpcException { if (type == TrafficType.Guest) { return new Pair<Network, String>(Network.getByUuid(conn, _host.guestNetwork), _host.guestPif); } else if (type == TrafficType.Control) { return new Pair<Network, String>(Network.getByUuid(conn, _host.linkLocalNetwork), null); } else if (type == TrafficType.Management) { return new Pair<Network, String>(Network.getByUuid(conn, _host.privateNetwork), _host.privatePif); } else if (type == TrafficType.Public) { return new Pair<Network, String>(Network.getByUuid(conn, _host.publicNetwork), _host.publicPif); } else if (type == TrafficType.Storage) { return new Pair<Network, String>(Network.getByUuid(conn, _host.storageNetwork1), _host.storagePif1); } else if (type == TrafficType.Vpn) { return new Pair<Network, String>(Network.getByUuid(conn, _host.publicNetwork), _host.publicPif); } throw new CloudRuntimeException("Unsupported network type: " + type); } protected VIF createVif(Connection conn, String vmName, VM vm, NicTO nic) throws XmlRpcException, XenAPIException { VIF.Record vifr = new VIF.Record(); vifr.VM = vm; vifr.device = Integer.toString(nic.getDeviceId()); vifr.MAC = nic.getMac(); Pair<Network, String> network = getNetworkForTraffic(conn, nic.getType()); if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { vifr.network = enableVlanNetwork(conn, nic.getVlan(), network.first(), network.second()); } else { vifr.network = network.first(); } if (nic.getNetworkRateMbps() != null) { vifr.qosAlgorithmType = "ratelimit"; vifr.qosAlgorithmParams = new HashMap<String, String>(); vifr.qosAlgorithmParams.put("kbps", Integer.toString(nic.getNetworkRateMbps() * 1000)); } VIF vif = VIF.create(conn, vifr); if (s_logger.isDebugEnabled()) { vifr = vif.getRecord(conn); s_logger.debug("Created a vif " + vifr.uuid + " on " + nic.getDeviceId()); } return vif; } protected VDI mount(Connection conn, String vmName, VolumeTO volume) throws XmlRpcException, XenAPIException { if (volume.getType() == VolumeType.ISO) { String isopath = volume.getPath(); int index = isopath.lastIndexOf("/"); String mountpoint = isopath.substring(0, index); URI uri; try { uri = new URI(mountpoint); } catch (URISyntaxException e) { throw new CloudRuntimeException("Incorrect uri " + mountpoint, e); } SR isoSr = createIsoSRbyURI(uri, vmName, false); String isoname = isopath.substring(index + 1); VDI isoVdi = getVDIbyLocationandSR(isoname, isoSr); if (isoVdi == null) { throw new CloudRuntimeException("Unable to find ISO " + volume.getPath()); } return isoVdi; } else { return VDI.getByUuid(conn, volume.getPath()); } } protected VBD createVbd(Connection conn, String vmName, VM vm, VolumeTO volume, boolean patch) throws XmlRpcException, XenAPIException { VolumeType type = volume.getType(); VDI vdi = mount(conn, vmName, volume); if (patch) { if (!patchSystemVm(vdi, vmName)) { throw new CloudRuntimeException("Unable to patch system vm"); } } VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; if (type == VolumeType.ROOT) { vbdr.bootable = true; } vbdr.userdevice = Long.toString(volume.getDeviceId()); if (volume.getType() == VolumeType.ISO) { vbdr.mode = Types.VbdMode.RO; vbdr.type = Types.VbdType.CD; } else { vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; } VBD vbd = VBD.create(conn, vbdr); if (s_logger.isDebugEnabled()) { s_logger.debug("VBD " + vbd.getUuid(conn) + " created for " + volume); } return vbd; } protected Pair<VM, String> createVmFromTemplate(Connection conn, VirtualMachineTO vmSpec, Host host) throws XenAPIException, XmlRpcException { String guestOsTypeName = getGuestOsType(vmSpec.getOs()); Set<VM> templates = VM.getByNameLabel(conn, guestOsTypeName); assert templates.size() == 1 : "Should only have 1 template but found " + templates.size(); VM template = templates.iterator().next(); VM vm = template.createClone(conn, vmSpec.getName()); vm.setAffinity(conn, host); VM.Record vmr = vm.getRecord(conn); if (s_logger.isDebugEnabled()) { s_logger.debug("Created VM " + vmr.uuid + " for " + vmSpec.getName()); } for (Console console : vmr.consoles) { console.destroy(conn); } vm.setIsATemplate(conn, false); vm.removeFromOtherConfig(conn, "disks"); vm.setNameLabel(conn, vmSpec.getName()); setMemory(conn, vm, vmSpec.getMinRam()); vm.setVCPUsAtStartup(conn, (long)vmSpec.getCpus()); vm.setVCPUsMax(conn, (long)vmSpec.getCpus()); vm.setVCPUsNumberLive(conn, (long)vmSpec.getCpus()); Map<String, String> vcpuParams = new HashMap<String, String>(); if (vmSpec.getWeight() != null) { vcpuParams.put("weight", Integer.toString(vmSpec.getWeight())); } if (vmSpec.getUtilization() != null) { vcpuParams.put("cap", Integer.toString(vmSpec.getUtilization())); } if (vcpuParams.size() > 0) { vm.setVCPUsParams(conn, vcpuParams); } vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY); vm.setActionsAfterShutdown(conn, Types.OnNormalExit.DESTROY); String bootArgs = vmSpec.getBootArgs(); if (bootArgs != null && bootArgs.length() > 0) { String pvargs = vm.getPVArgs(conn); pvargs = pvargs + vmSpec.getBootArgs(); if (s_logger.isDebugEnabled()) { s_logger.debug("PV args are " + pvargs); } vm.setPVArgs(conn, pvargs); } if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) { if (vmSpec.getBootloader() == BootloaderType.CD) { vm.setPVBootloader(conn, "eliloader"); vm.addToOtherConfig(conn, "install-repository", "cdrom"); } else if (vmSpec.getBootloader() == BootloaderType.PyGrub ){ vm.setPVBootloader(conn, "pygrub"); } else { vm.destroy(conn); throw new CloudRuntimeException("Unable to handle boot loader type: " + vmSpec.getBootloader()); } } return new Pair<VM, String>(vm, vmr.uuid); } protected String handleVmStartFailure(String vmName, VM vm, String message, Throwable th) { String msg = "Unable to start " + vmName + " due to " + message; s_logger.warn(msg, th); if (vm == null) { return msg; } Connection conn = getConnection(); try { VM.Record vmr = vm.getRecord(conn); if (vmr.powerState == VmPowerState.RUNNING) { try { vm.hardShutdown(conn); } catch (Exception e) { s_logger.warn("VM hardshutdown failed due to ", e); } } if (vm.getPowerState(conn) == VmPowerState.HALTED) { try { vm.destroy(conn); } catch (Exception e) { s_logger.warn("VM destroy failed due to ", e); } } for (VBD vbd : vmr.VBDs) { try { vbd.unplug(conn); vbd.destroy(conn); } catch (Exception e) { s_logger.warn("Unable to clean up VBD due to ", e); } } for (VIF vif : vmr.VIFs) { try { vif.unplug(conn); vif.destroy(conn); } catch (Exception e) { s_logger.warn("Unable to cleanup VIF", e); } } } catch (Exception e) { s_logger.warn("VM getRecord failed due to ", e); } return msg; } protected Start2Answer execute(Start2Command cmd) { VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); Connection conn = getConnection(); State state = State.Stopped; VM vm = null; try { Host host = Host.getByUuid(conn, _host.uuid); synchronized (_vms) { _vms.put(vmName, State.Starting); } Pair<VM, String> v = createVmFromTemplate(conn, vmSpec, host); vm = v.first(); String vmUuid = v.second(); for (VolumeTO disk : vmSpec.getDisks()) { createVbd(conn, vmName, vm, disk, disk.getType() == VolumeType.ROOT && vmSpec.getType() != VirtualMachine.Type.User); } NicTO controlNic = null; for (NicTO nic : vmSpec.getNetworks()) { if (nic.getControlPort() != null) { controlNic = nic; } createVif(conn, vmName, vm, nic); } /* * VBD.Record vbdr = new VBD.Record(); Ternary<SR, VDI, VolumeVO> mount = mounts.get(0); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = !bootFromISO; vbdr.userdevice = "0"; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; VBD.create(conn, vbdr); for (int i = 1; i < mounts.size(); i++) { mount = mounts.get(i); // vdi.setNameLabel(conn, cmd.getVmName() + "-DATA"); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = false; vbdr.userdevice = Long.toString(mount.third().getDeviceId()); vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; VBD.create(conn, vbdr); } VBD.Record cdromVBDR = new VBD.Record(); cdromVBDR.VM = vm; cdromVBDR.empty = true; cdromVBDR.bootable = bootFromISO; cdromVBDR.userdevice = "3"; cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; VBD cdromVBD = VBD.create(conn, cdromVBDR); String isopath = cmd.getISOPath(); if (isopath != null) { int index = isopath.lastIndexOf("/"); String mountpoint = isopath.substring(0, index); URI uri = new URI(mountpoint); isosr = createIsoSRbyURI(uri, cmd.getVmName(), false); String isoname = isopath.substring(index + 1); VDI isovdi = getVDIbyLocationandSR(isoname, isosr); if (isovdi == null) { String msg = " can not find ISO " + cmd.getISOPath(); s_logger.warn(msg); return new StartAnswer(cmd, msg); } else { cdromVBD.insert(conn, isovdi); } } */ vm.startOn(conn, host, false, true); if (_canBridgeFirewall) { String result = null; if (vmSpec.getType() != VirtualMachine.Type.User) { result = callHostPlugin("vmops", "default_network_rules_systemvm", "vmName", vmName); } else { } if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default network rules for " + vmName); } else { s_logger.info("Programmed default network rules for " + vmName); } } if (controlNic != null) { String privateIp = controlNic.getIp(); int cmdPort = controlNic.getControlPort(); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); } String result = connect(vmName, privateIp, cmdPort); if (result != null) { throw new CloudRuntimeException("Can not ping System vm " + vmName + "due to:" + result); } if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port succeeded for vm " + vmName); } } state = State.Running; return new Start2Answer(cmd); } catch (XmlRpcException e) { String msg = handleVmStartFailure(vmName, vm, "", e); return new Start2Answer(cmd, msg); } catch (XenAPIException e) { String msg = handleVmStartFailure(vmName, vm, "", e); return new Start2Answer(cmd, msg); } catch (Exception e) { String msg = handleVmStartFailure(vmName, vm, "", e); return new Start2Answer(cmd, msg); } finally { synchronized (_vms) { if (state != State.Stopped) { _vms.put(vmName, state); } else { _vms.remove(vmName); } } } } protected Answer execute(ModifySshKeysCommand cmd) { return new Answer(cmd); } private boolean doPingTest(final String computingHostIp) { String args = "-h " + computingHostIp; String result = callHostPlugin("vmops", "pingtest", "args", args); if (result == null || result.isEmpty()) return false; return true; } protected CheckOnHostAnswer execute(CheckOnHostCommand cmd) { return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); } private boolean doPingTest(final String domRIp, final String vmIp) { String args = "-i " + domRIp + " -p " + vmIp; String result = callHostPlugin("vmops", "pingtest", "args", args); if (result == null || result.isEmpty()) return false; return true; } private Answer execute(PingTestCommand cmd) { boolean result = false; final String computingHostIp = cmd.getComputingHostIp(); // TODO, split the command into 2 types if (computingHostIp != null) { result = doPingTest(computingHostIp); } else { result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp()); } if (!result) { return new Answer(cmd, false, "PingTestCommand failed"); } return new Answer(cmd); } protected MaintainAnswer execute(MaintainCommand cmd) { Connection conn = getConnection(); try { Pool pool = Pool.getByUuid(conn, _host.pool); Pool.Record poolr = pool.getRecord(conn); Host.Record hostr = poolr.master.getRecord(conn); if (!_host.uuid.equals(hostr.uuid)) { s_logger.debug("Not the master node so just return ok: " + _host.ip); return new MaintainAnswer(cmd); } Map<Host, Host.Record> hostMap = Host.getAllRecords(conn); if (hostMap.size() == 1) { s_logger.debug("There's no one to take over as master"); return new MaintainAnswer(cmd,false, "Only master in the pool"); } Host newMaster = null; Host.Record newMasterRecord = null; for (Map.Entry<Host, Host.Record> entry : hostMap.entrySet()) { if (!_host.uuid.equals(entry.getValue().uuid)) { newMaster = entry.getKey(); newMasterRecord = entry.getValue(); s_logger.debug("New master for the XenPool is " + newMasterRecord.uuid + " : " + newMasterRecord.address); try { _connPool.switchMaster(_host.ip, _host.pool, conn, newMaster, _username, _password, _wait); return new MaintainAnswer(cmd, "New Master is " + newMasterRecord.address); } catch (XenAPIException e) { s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " Trying again..."); } catch (XmlRpcException e) { s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " Trying again..."); } } } return new MaintainAnswer(cmd, false, "Unable to find an appropriate host to set as the new master"); } catch (XenAPIException e) { s_logger.warn("Unable to put server in maintainence mode", e); return new MaintainAnswer(cmd, false, e.getMessage()); } catch (XmlRpcException e) { s_logger.warn("Unable to put server in maintainence mode", e); return new MaintainAnswer(cmd, false, e.getMessage()); } } protected SetupAnswer execute(SetupCommand cmd) { return new SetupAnswer(cmd); } protected Answer execute(StartSecStorageVmCommand cmd) { final String vmName = cmd.getVmName(); SecondaryStorageVmVO storage = cmd.getSecondaryStorageVmVO(); try { Connection conn = getConnection(); Network network = Network.getByUuid(conn, _host.privateNetwork); String bootArgs = cmd.getBootArgs(); bootArgs += " zone=" + _dcId; bootArgs += " pod=" + _pod; bootArgs += " localgw=" + _localGateway; String result = startSystemVM(vmName, storage.getVlanId(), network, cmd.getVolumes(), bootArgs, storage.getGuestMacAddress(), storage.getGuestIpAddress(), storage .getPrivateMacAddress(), storage.getPublicMacAddress(), cmd.getProxyCmdPort(), storage.getRamSize()); if (result == null) { return new StartSecStorageVmAnswer(cmd); } return new StartSecStorageVmAnswer(cmd, result); } catch (Exception e) { String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); return new StartSecStorageVmAnswer(cmd, msg); } } protected Answer execute(final SetFirewallRuleCommand cmd) { String args; if (cmd.isEnable()) { args = "-A"; } else { args = "-D"; } args += " -P " + cmd.getProtocol().toLowerCase(); args += " -l " + cmd.getPublicIpAddress(); args += " -p " + cmd.getPublicPort(); args += " -n " + cmd.getRouterName(); args += " -i " + cmd.getRouterIpAddress(); args += " -r " + cmd.getPrivateIpAddress(); args += " -d " + cmd.getPrivatePort(); args += " -N " + cmd.getVlanNetmask(); String oldPrivateIP = cmd.getOldPrivateIP(); String oldPrivatePort = cmd.getOldPrivatePort(); if (oldPrivateIP != null) { args += " -w " + oldPrivateIP; } if (oldPrivatePort != null) { args += " -x " + oldPrivatePort; } String result = callHostPlugin("vmops", "setFirewallRule", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "SetFirewallRule failed"); } return new Answer(cmd); } protected Answer execute(final LoadBalancerCfgCommand cmd) { String routerIp = cmd.getRouterIp(); if (routerIp == null) { return new Answer(cmd); } String tmpCfgFilePath = "/tmp/" + cmd.getRouterIp().replace('.', '_') + ".cfg"; String tmpCfgFileContents = ""; for (int i = 0; i < cmd.getConfig().length; i++) { tmpCfgFileContents += cmd.getConfig()[i]; tmpCfgFileContents += "\n"; } String result = callHostPlugin("vmops", "createFile", "filepath", tmpCfgFilePath, "filecontents", tmpCfgFileContents); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "LoadBalancerCfgCommand failed to create HA proxy cfg file."); } String[] addRules = cmd.getAddFwRules(); String[] removeRules = cmd.getRemoveFwRules(); String args = ""; args += "-i " + routerIp; args += " -f " + tmpCfgFilePath; StringBuilder sb = new StringBuilder(); if (addRules.length > 0) { for (int i = 0; i < addRules.length; i++) { sb.append(addRules[i]).append(','); } args += " -a " + sb.toString(); } sb = new StringBuilder(); if (removeRules.length > 0) { for (int i = 0; i < removeRules.length; i++) { sb.append(removeRules[i]).append(','); } args += " -d " + sb.toString(); } result = callHostPlugin("vmops", "setLoadBalancerRule", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "LoadBalancerCfgCommand failed"); } callHostPlugin("vmops", "deleteFile", "filepath", tmpCfgFilePath); return new Answer(cmd); } protected synchronized Answer execute(final DhcpEntryCommand cmd) { String args = "-r " + cmd.getRouterPrivateIpAddress(); args += " -v " + cmd.getVmIpAddress(); args += " -m " + cmd.getVmMac(); args += " -n " + cmd.getVmName(); String result = callHostPlugin("vmops", "saveDhcpEntry", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "DhcpEntry failed"); } return new Answer(cmd); } protected Answer execute(final VmDataCommand cmd) { String routerPrivateIpAddress = cmd.getRouterPrivateIpAddress(); String vmIpAddress = cmd.getVmIpAddress(); List<String[]> vmData = cmd.getVmData(); String[] vmDataArgs = new String[vmData.size() * 2 + 4]; vmDataArgs[0] = "routerIP"; vmDataArgs[1] = routerPrivateIpAddress; vmDataArgs[2] = "vmIP"; vmDataArgs[3] = vmIpAddress; int i = 4; for (String[] vmDataEntry : vmData) { String folder = vmDataEntry[0]; String file = vmDataEntry[1]; String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; vmDataArgs[i] = folder + "," + file; vmDataArgs[i + 1] = contents; i += 2; } String result = callHostPlugin("vmops", "vm_data", vmDataArgs); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "vm_data failed"); } else { return new Answer(cmd); } } protected Answer execute(final SavePasswordCommand cmd) { final String password = cmd.getPassword(); final String routerPrivateIPAddress = cmd.getRouterPrivateIpAddress(); final String vmName = cmd.getVmName(); final String vmIpAddress = cmd.getVmIpAddress(); final String local = vmName; // Run save_password_to_domr.sh String args = "-r " + routerPrivateIPAddress; args += " -v " + vmIpAddress; args += " -p " + password; args += " " + local; String result = callHostPlugin("vmops", "savePassword", "args", args); if (result == null || result.isEmpty()) { return new Answer(cmd, false, "savePassword failed"); } return new Answer(cmd); } protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws InternalErrorException { try { Connection conn = getConnection(); VM router = getVM(conn, vmName); // Determine the correct VIF on DomR to associate/disassociate the // IP address with VIF correctVif = getCorrectVif(router, vlanId); // If we are associating an IP address and DomR doesn't have a VIF // for the specified vlan ID, we need to add a VIF // If we are disassociating the last IP address in the VLAN, we need // to remove a VIF boolean addVif = false; boolean removeVif = false; if (add && correctVif == null) { addVif = true; } else if (!add && firstIP) { removeVif = true; } if (addVif) { // Add a new VIF to DomR String vifDeviceNum = getLowestAvailableVIFDeviceNum(router); if (vifDeviceNum == null) { throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn)); } VIF.Record vifr = new VIF.Record(); vifr.VM = router; vifr.device = vifDeviceNum; vifr.MAC = vifMacAddress; if ("untagged".equalsIgnoreCase(vlanId)) { vifr.network = Network.getByUuid(conn, _host.publicNetwork); } else { Network vlanNetwork = enableVlanNetwork(Long.valueOf(vlanId), _host.publicNetwork, _host.publicPif); if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanId); } vifr.network = vlanNetwork; } correctVif = VIF.create(conn, vifr); correctVif.plug(conn); // Add iptables rule for network usage networkUsage(privateIpAddress, "addVif", "eth" + correctVif.getDevice(conn)); } if (correctVif == null) { throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); } String args; if (add) { args = "-A"; } else { args = "-D"; } if (sourceNat) { args += " -f"; } args += " -i "; args += privateIpAddress; args += " -l "; args += publicIpAddress; args += " -c "; args += "eth" + correctVif.getDevice(conn); args += " -g "; args += vlanGateway; String result = callHostPlugin("vmops", "ipassoc", "args", args); if (result == null || result.isEmpty()) { throw new InternalErrorException("Xen plugin \"ipassoc\" failed."); } if (removeVif) { Network network = correctVif.getNetwork(conn); // Mark this vif to be removed from network usage networkUsage(privateIpAddress, "deleteVif", "eth" + correctVif.getDevice(conn)); // Remove the VIF from DomR correctVif.unplug(conn); correctVif.destroy(conn); // Disable the VLAN network if necessary disableVlanNetwork(network); } } catch (XenAPIException e) { String msg = "Unable to assign public IP address due to " + e.toString(); s_logger.warn(msg, e); throw new InternalErrorException(msg); } catch (final XmlRpcException e) { String msg = "Unable to assign public IP address due to " + e.getMessage(); s_logger.warn(msg, e); throw new InternalErrorException(msg); } } protected String networkUsage(final String privateIpAddress, final String option, final String vif) { if (option.equals("get")) { return "0:0"; } return null; } protected Answer execute(final IPAssocCommand cmd) { try { assignPublicIpAddress(cmd.getRouterName(), cmd.getRouterIp(), cmd.getPublicIp(), cmd.isAdd(), cmd.isFirstIP(), cmd.isSourceNat(), cmd.getVlanId(), cmd.getVlanGateway(), cmd.getVlanNetmask(), cmd.getVifMacAddress()); } catch (InternalErrorException e) { return new Answer(cmd, false, e.getMessage()); } return new Answer(cmd); } protected GetVncPortAnswer execute(GetVncPortCommand cmd) { Connection conn = getConnection(); try { Set<VM> vms = VM.getByNameLabel(conn, cmd.getName()); return new GetVncPortAnswer(cmd, getVncPort(vms.iterator().next())); } catch (XenAPIException e) { s_logger.warn("Unable to get vnc port " + e.toString(), e); return new GetVncPortAnswer(cmd, e.toString()); } catch (Exception e) { s_logger.warn("Unable to get vnc port ", e); return new GetVncPortAnswer(cmd, e.getMessage()); } } protected Storage.StorageResourceType getStorageResourceType() { return Storage.StorageResourceType.STORAGE_POOL; } protected CheckHealthAnswer execute(CheckHealthCommand cmd) { boolean result = pingxenserver(); return new CheckHealthAnswer(cmd, result); } protected long[] getNetworkStats(String privateIP) { String result = networkUsage(privateIP, "get", null); long[] stats = new long[2]; if (result != null) { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } } return stats; } /** * This is the method called for getting the HOST stats * * @param cmd * @return */ protected GetHostStatsAnswer execute(GetHostStatsCommand cmd) { // Connection conn = getConnection(); try { HostStatsEntry hostStats = getHostStats(cmd, cmd.getHostGuid(), cmd.getHostId()); return new GetHostStatsAnswer(cmd, hostStats); } catch (Exception e) { String msg = "Unable to get Host stats" + e.toString(); s_logger.warn(msg, e); return new GetHostStatsAnswer(cmd, null); } } protected HostStatsEntry getHostStats(GetHostStatsCommand cmd, String hostGuid, long hostId) { HostStatsEntry hostStats = new HostStatsEntry(hostId, 0, 0, 0, 0, "host", 0, 0, 0, 0); Object[] rrdData = getRRDData(1); // call rrd method with 1 for host if (rrdData == null) { return null; } Integer numRows = (Integer) rrdData[0]; Integer numColumns = (Integer) rrdData[1]; Node legend = (Node) rrdData[2]; Node dataNode = (Node) rrdData[3]; NodeList legendChildren = legend.getChildNodes(); for (int col = 0; col < numColumns; col++) { if (legendChildren == null || legendChildren.item(col) == null) { continue; } String columnMetadata = getXMLNodeValue(legendChildren.item(col)); if (columnMetadata == null) { continue; } String[] columnMetadataList = columnMetadata.split(":"); if (columnMetadataList.length != 4) { continue; } String type = columnMetadataList[1]; String param = columnMetadataList[3]; if (type.equalsIgnoreCase("host")) { if (param.contains("pif_eth0_rx")) { hostStats.setNetworkReadKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("pif_eth0_tx")) { hostStats.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("memory_total_kib")) { hostStats.setTotalMemoryKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("memory_free_kib")) { hostStats.setFreeMemoryKBs(getDataAverage(dataNode, col, numRows)); } if (param.contains("cpu")) { hostStats.setNumCpus(hostStats.getNumCpus() + 1); hostStats.setCpuUtilization(hostStats.getCpuUtilization() + getDataAverage(dataNode, col, numRows)); } if (param.contains("loadavg")) { hostStats.setAverageLoad((hostStats.getAverageLoad() + getDataAverage(dataNode, col, numRows))); } } } // add the host cpu utilization if (hostStats.getNumCpus() != 0) { hostStats.setCpuUtilization(hostStats.getCpuUtilization() / hostStats.getNumCpus()); s_logger.debug("Host cpu utilization " + hostStats.getCpuUtilization()); } return hostStats; } protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { List<String> vmNames = cmd.getVmNames(); HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>(); if( vmNames.size() == 0 ) { return new GetVmStatsAnswer(cmd, vmStatsNameMap); } Connection conn = getConnection(); try { // Determine the UUIDs of the requested VMs List<String> vmUUIDs = new ArrayList<String>(); for (String vmName : vmNames) { VM vm = getVM(conn, vmName); vmUUIDs.add(vm.getUuid(conn)); } HashMap<String, VmStatsEntry> vmStatsUUIDMap = getVmStats(cmd, vmUUIDs, cmd.getHostGuid()); if( vmStatsUUIDMap == null ) return new GetVmStatsAnswer(cmd, vmStatsNameMap); for (String vmUUID : vmStatsUUIDMap.keySet()) { vmStatsNameMap.put(vmNames.get(vmUUIDs.indexOf(vmUUID)), vmStatsUUIDMap.get(vmUUID)); } return new GetVmStatsAnswer(cmd, vmStatsNameMap); } catch (XenAPIException e) { String msg = "Unable to get VM stats" + e.toString(); s_logger.warn(msg, e); return new GetVmStatsAnswer(cmd, vmStatsNameMap); } catch (XmlRpcException e) { String msg = "Unable to get VM stats" + e.getMessage(); s_logger.warn(msg, e); return new GetVmStatsAnswer(cmd, vmStatsNameMap); } } protected HashMap<String, VmStatsEntry> getVmStats(GetVmStatsCommand cmd, List<String> vmUUIDs, String hostGuid) { HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>(); for (String vmUUID : vmUUIDs) { vmResponseMap.put(vmUUID, new VmStatsEntry(0, 0, 0, 0, "vm")); } Object[] rrdData = getRRDData(2); // call rrddata with 2 for vm if (rrdData == null) { return null; } Integer numRows = (Integer) rrdData[0]; Integer numColumns = (Integer) rrdData[1]; Node legend = (Node) rrdData[2]; Node dataNode = (Node) rrdData[3]; NodeList legendChildren = legend.getChildNodes(); for (int col = 0; col < numColumns; col++) { if (legendChildren == null || legendChildren.item(col) == null) { continue; } String columnMetadata = getXMLNodeValue(legendChildren.item(col)); if (columnMetadata == null) { continue; } String[] columnMetadataList = columnMetadata.split(":"); if (columnMetadataList.length != 4) { continue; } String type = columnMetadataList[1]; String uuid = columnMetadataList[2]; String param = columnMetadataList[3]; if (type.equals("vm") && vmResponseMap.keySet().contains(uuid)) { VmStatsEntry vmStatsAnswer = vmResponseMap.get(uuid); vmStatsAnswer.setEntityType("vm"); if (param.contains("cpu")) { vmStatsAnswer.setNumCPUs(vmStatsAnswer.getNumCPUs() + 1); vmStatsAnswer.setCPUUtilization((vmStatsAnswer.getCPUUtilization() + getDataAverage(dataNode, col, numRows))*100); } else if (param.equals("vif_0_rx")) { vmStatsAnswer.setNetworkReadKBs(getDataAverage(dataNode, col, numRows)); } else if (param.equals("vif_0_tx")) { vmStatsAnswer.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows)); } } } for (String vmUUID : vmResponseMap.keySet()) { VmStatsEntry vmStatsAnswer = vmResponseMap.get(vmUUID); if (vmStatsAnswer.getNumCPUs() != 0) { vmStatsAnswer.setCPUUtilization(vmStatsAnswer.getCPUUtilization() / vmStatsAnswer.getNumCPUs()); s_logger.debug("Vm cpu utilization " + vmStatsAnswer.getCPUUtilization()); } } return vmResponseMap; } protected Object[] getRRDData(int flag) { /* * Note: 1 => called from host, hence host stats 2 => called from vm, hence vm stats */ String stats = ""; try { if (flag == 1) stats = getHostStatsRawXML(); if (flag == 2) stats = getVmStatsRawXML(); } catch (Exception e1) { s_logger.warn("Error whilst collecting raw stats from plugin:" + e1); return null; } // s_logger.debug("The raw xml stream is:"+stats); // s_logger.debug("Length of raw xml is:"+stats.length()); //stats are null when the host plugin call fails (host down state) if(stats == null) return null; StringReader statsReader = new StringReader(stats); InputSource statsSource = new InputSource(statsReader); Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(statsSource); } catch (Exception e) { } NodeList firstLevelChildren = doc.getChildNodes(); NodeList secondLevelChildren = (firstLevelChildren.item(0)).getChildNodes(); Node metaNode = secondLevelChildren.item(0); Node dataNode = secondLevelChildren.item(1); Integer numRows = 0; Integer numColumns = 0; Node legend = null; NodeList metaNodeChildren = metaNode.getChildNodes(); for (int i = 0; i < metaNodeChildren.getLength(); i++) { Node n = metaNodeChildren.item(i); if (n.getNodeName().equals("rows")) { numRows = Integer.valueOf(getXMLNodeValue(n)); } else if (n.getNodeName().equals("columns")) { numColumns = Integer.valueOf(getXMLNodeValue(n)); } else if (n.getNodeName().equals("legend")) { legend = n; } } return new Object[] { numRows, numColumns, legend, dataNode }; } protected String getXMLNodeValue(Node n) { return n.getChildNodes().item(0).getNodeValue(); } protected double getDataAverage(Node dataNode, int col, int numRows) { double value = 0; double dummy = 0; int numRowsUsed = 0; for (int row = 0; row < numRows; row++) { Node data = dataNode.getChildNodes().item(numRows - 1 - row).getChildNodes().item(col + 1); Double currentDataAsDouble = Double.valueOf(getXMLNodeValue(data)); if (!currentDataAsDouble.equals(Double.NaN)) { numRowsUsed += 1; value += currentDataAsDouble; } } if(numRowsUsed == 0) { if((!Double.isInfinite(value))&&(!Double.isInfinite(value))) { return value; } else { s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows=0"); return dummy; } } else { if((!Double.isInfinite(value/numRowsUsed))&&(!Double.isInfinite(value/numRowsUsed))) { return (value/numRowsUsed); } else { s_logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows>0"); return dummy; } } } protected String getHostStatsRawXML() { Date currentDate = new Date(); String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000); return callHostPlugin("vmops", "gethostvmstats", "collectHostStats", String.valueOf("true"), "consolidationFunction", _consolidationFunction, "interval", String .valueOf(_pollingIntervalInSeconds), "startTime", startTime); } protected String getVmStatsRawXML() { Date currentDate = new Date(); String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000); return callHostPlugin("vmops", "gethostvmstats", "collectHostStats", String.valueOf("false"), "consolidationFunction", _consolidationFunction, "interval", String .valueOf(_pollingIntervalInSeconds), "startTime", startTime); } protected void recordWarning(final VM vm, final String message, final Throwable e) { Connection conn = getConnection(); final StringBuilder msg = new StringBuilder(); try { final Long domId = vm.getDomid(conn); msg.append("[").append(domId != null ? domId : -1l).append("] "); } catch (final BadServerResponse e1) { } catch (final XmlRpcException e1) { } catch (XenAPIException e1) { } msg.append(message); } protected State convertToState(Types.VmPowerState ps) { final State state = s_statesTable.get(ps); return state == null ? State.Unknown : state; } protected HashMap<String, State> getAllVms() { final HashMap<String, State> vmStates = new HashMap<String, State>(); Connection conn = getConnection(); Set<VM> vms = null; for (int i = 0; i < 2; i++) { try { Host host = Host.getByUuid(conn, _host.uuid); vms = host.getResidentVMs(conn); break; } catch (final Throwable e) { s_logger.warn("Unable to get vms", e); } try { Thread.sleep(1000); } catch (final InterruptedException ex) { } } if (vms == null) { return null; } for (VM vm : vms) { VM.Record record = null; for (int i = 0; i < 2; i++) { try { record = vm.getRecord(conn); break; } catch (XenAPIException e1) { s_logger.debug("VM.getRecord failed on host:" + _host.uuid + " due to " + e1.toString()); } catch (XmlRpcException e1) { s_logger.debug("VM.getRecord failed on host:" + _host.uuid + " due to " + e1.getMessage()); } try { Thread.sleep(1000); } catch (final InterruptedException ex) { } } if (record == null) { continue; } if (record.isControlDomain || record.isASnapshot || record.isATemplate) { continue; // Skip DOM0 } VmPowerState ps = record.powerState; final State state = convertToState(ps); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + record.nameLabel + ": powerstate = " + ps + "; vm state=" + state.toString()); } vmStates.put(record.nameLabel, state); } return vmStates; } protected State getVmState(final String vmName) { Connection conn = getConnection(); int retry = 3; while (retry-- > 0) { try { Set<VM> vms = VM.getByNameLabel(conn, vmName); for (final VM vm : vms) { return convertToState(vm.getPowerState(conn)); } } catch (final BadServerResponse e) { // There is a race condition within xen such that if a vm is // deleted and we // happen to ask for it, it throws this stupid response. So // if this happens, // we take a nap and try again which then avoids the race // condition because // the vm's information is now cleaned up by xen. The error // is as follows // com.xensource.xenapi.Types$BadServerResponse // [HANDLE_INVALID, VM, // 3dde93f9-c1df-55a7-2cde-55e1dce431ab] s_logger.info("Unable to get a vm PowerState due to " + e.toString() + ". We are retrying. Count: " + retry); try { Thread.sleep(3000); } catch (final InterruptedException ex) { } } catch (XenAPIException e) { String msg = "Unable to get a vm PowerState due to " + e.toString(); s_logger.warn(msg, e); break; } catch (final XmlRpcException e) { String msg = "Unable to get a vm PowerState due to " + e.getMessage(); s_logger.warn(msg, e); break; } } return State.Stopped; } protected CheckVirtualMachineAnswer execute(final CheckVirtualMachineCommand cmd) { final String vmName = cmd.getVmName(); final State state = getVmState(vmName); Integer vncPort = null; if (state == State.Running) { synchronized (_vms) { _vms.put(vmName, State.Running); } } return new CheckVirtualMachineAnswer(cmd, state, vncPort); } protected PrepareForMigrationAnswer execute(final PrepareForMigrationCommand cmd) { /* * * String result = null; * * List<VolumeVO> vols = cmd.getVolumes(); result = mountwithoutvdi(vols, cmd.getMappings()); if (result != * null) { return new PrepareForMigrationAnswer(cmd, false, result); } */ final String vmName = cmd.getVmName(); try { Connection conn = getConnection(); Set<Host> hosts = Host.getAll(conn); // workaround before implementing xenserver pool // no migration if (hosts.size() <= 1) { return new PrepareForMigrationAnswer(cmd, false, "not in a same xenserver pool"); } // if the vm have CD // 1. make iosSR shared // 2. create pbd in target xenserver SR sr = getISOSRbyVmName(cmd.getVmName()); if (sr != null) { Set<PBD> pbds = sr.getPBDs(conn); boolean found = false; for (PBD pbd : pbds) { if (Host.getByUuid(conn, _host.uuid).equals(pbd.getHost(conn))) { found = true; break; } } if (!found) { sr.setShared(conn, true); PBD pbd = pbds.iterator().next(); PBD.Record pbdr = new PBD.Record(); pbdr.deviceConfig = pbd.getDeviceConfig(conn); pbdr.host = Host.getByUuid(conn, _host.uuid); pbdr.SR = sr; PBD newpbd = PBD.create(conn, pbdr); newpbd.plug(conn); } } Set<VM> vms = VM.getByNameLabel(conn, vmName); if (vms.size() != 1) { String msg = "There are " + vms.size() + " " + vmName; s_logger.warn(msg); return new PrepareForMigrationAnswer(cmd, false, msg); } VM vm = vms.iterator().next(); // check network Set<VIF> vifs = vm.getVIFs(conn); for (VIF vif : vifs) { Network network = vif.getNetwork(conn); Set<PIF> pifs = network.getPIFs(conn); Long vlan = null; PIF npif = null; for (PIF pif : pifs) { try { vlan = pif.getVLAN(conn); if (vlan != null) { VLAN vland = pif.getVLANMasterOf(conn); npif = vland.getTaggedPIF(conn); break; } }catch (Exception e) { vlan = null; continue; } } if (vlan == null) { continue; } network = npif.getNetwork(conn); String nwuuid = network.getUuid(conn); String pifuuid = null; if(nwuuid.equalsIgnoreCase(_host.privateNetwork)) { pifuuid = _host.privatePif; } else if(nwuuid.equalsIgnoreCase(_host.publicNetwork)) { pifuuid = _host.publicPif; } else { continue; } Network vlanNetwork = enableVlanNetwork(vlan, nwuuid, pifuuid); if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlan); } } synchronized (_vms) { _vms.put(cmd.getVmName(), State.Migrating); } return new PrepareForMigrationAnswer(cmd, true, null); } catch (Exception e) { String msg = "catch exception " + e.getMessage(); s_logger.warn(msg, e); return new PrepareForMigrationAnswer(cmd, false, msg); } } @Override public DownloadAnswer execute(final PrimaryStorageDownloadCommand cmd) { SR tmpltsr = null; String tmplturl = cmd.getUrl(); int index = tmplturl.lastIndexOf("/"); String mountpoint = tmplturl.substring(0, index); String tmpltname = null; if (index < tmplturl.length() - 1) tmpltname = tmplturl.substring(index + 1).replace(".vhd", ""); try { Connection conn = getConnection(); String pUuid = cmd.getPoolUuid(); SR poolsr = null; Set<SR> srs = SR.getByNameLabel(conn, pUuid); if (srs.size() != 1) { String msg = "There are " + srs.size() + " SRs with same name: " + pUuid; s_logger.warn(msg); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } else { poolsr = srs.iterator().next(); } /* Does the template exist in primary storage pool? If yes, no copy */ VDI vmtmpltvdi = null; Set<VDI> vdis = VDI.getByNameLabel(conn, "Template " + cmd.getName()); for (VDI vdi : vdis) { VDI.Record vdir = vdi.getRecord(conn); if (vdir.SR.equals(poolsr)) { vmtmpltvdi = vdi; break; } } String uuid; if (vmtmpltvdi == null) { tmpltsr = createNfsSRbyURI(new URI(mountpoint), false); tmpltsr.scan(conn); VDI tmpltvdi = null; if (tmpltname != null) { tmpltvdi = getVDIbyUuid(tmpltname); } if (tmpltvdi == null) { vdis = tmpltsr.getVDIs(conn); for (VDI vdi : vdis) { tmpltvdi = vdi; break; } } if (tmpltvdi == null) { String msg = "Unable to find template vdi on secondary storage" + "host:" + _host.uuid + "pool: " + tmplturl; s_logger.warn(msg); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } vmtmpltvdi = cloudVDIcopy(tmpltvdi, poolsr); vmtmpltvdi.setNameLabel(conn, "Template " + cmd.getName()); // vmtmpltvdi.setNameDescription(conn, cmd.getDescription()); uuid = vmtmpltvdi.getUuid(conn); } else uuid = vmtmpltvdi.getUuid(conn); // Determine the size of the template long createdSize = vmtmpltvdi.getVirtualSize(conn); DownloadAnswer answer = new DownloadAnswer(null, 100, cmd, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED, uuid, uuid); answer.setTemplateSize(createdSize); return answer; } catch (XenAPIException e) { String msg = "XenAPIException:" + e.toString() + "host:" + _host.uuid + "pool: " + tmplturl; s_logger.warn(msg, e); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } catch (Exception e) { String msg = "XenAPIException:" + e.getMessage() + "host:" + _host.uuid + "pool: " + tmplturl; s_logger.warn(msg, e); return new DownloadAnswer(null, 0, msg, com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR, "", "", 0); } finally { removeSR(tmpltsr); } } protected String removeSRSync(SR sr) { if (sr == null) { return null; } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Removing SR")); } Connection conn = getConnection(); long waittime = 0; try { Set<VDI> vdis = sr.getVDIs(conn); for (VDI vdi : vdis) { Map<java.lang.String, Types.VdiOperations> currentOperation = vdi.getCurrentOperations(conn); if (currentOperation == null || currentOperation.size() == 0) { continue; } if (waittime >= 1800000) { String msg = "This template is being used, try late time"; s_logger.warn(msg); return msg; } waittime += 30000; try { Thread.sleep(30000); } catch (final InterruptedException ex) { } } removeSR(sr); return null; } catch (XenAPIException e) { s_logger.warn(logX(sr, "Unable to get current opertions " + e.toString()), e); } catch (XmlRpcException e) { s_logger.warn(logX(sr, "Unable to get current opertions " + e.getMessage()), e); } String msg = "Remove SR failed"; s_logger.warn(msg); return msg; } protected void removeSR(SR sr) { if (sr == null) { return; } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Removing SR")); } for (int i = 0; i < 2; i++) { Connection conn = getConnection(); try { Set<VDI> vdis = sr.getVDIs(conn); for (VDI vdi : vdis) { vdi.forget(conn); } Set<PBD> pbds = sr.getPBDs(conn); for (PBD pbd : pbds) { if (s_logger.isDebugEnabled()) { s_logger.debug(logX(pbd, "Unplugging pbd")); } if (pbd.getCurrentlyAttached(conn)) { pbd.unplug(conn); } pbd.destroy(conn); } pbds = sr.getPBDs(conn); if (pbds.size() == 0) { if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Forgetting")); } sr.forget(conn); return; } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "There are still pbd attached")); if (s_logger.isTraceEnabled()) { for (PBD pbd : pbds) { s_logger.trace(logX(pbd, " Still attached")); } } } } catch (XenAPIException e) { s_logger.debug(logX(sr, "Catch XenAPIException: " + e.toString())); } catch (XmlRpcException e) { s_logger.debug(logX(sr, "Catch Exception: " + e.getMessage())); } } s_logger.warn(logX(sr, "Unable to remove SR")); } protected MigrateAnswer execute(final MigrateCommand cmd) { final String vmName = cmd.getVmName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { Connection conn = getConnection(); Set<VM> vms = VM.getByNameLabel(conn, vmName); String ipaddr = cmd.getDestinationIp(); Set<Host> hosts = Host.getAll(conn); Host dsthost = null; for (Host host : hosts) { if (host.getAddress(conn).equals(ipaddr)) { dsthost = host; break; } } // if it is windows, we will not fake it is migrateable, // windows requires PV driver to migrate for (VM vm : vms) { if (!cmd.isWindows()) { String uuid = vm.getUuid(conn); String result = callHostPlugin("vmops", "preparemigration", "uuid", uuid); if (result == null || result.isEmpty()) { return new MigrateAnswer(cmd, false, "migration failed", null); } // check if pv version is successfully set up int i = 0; for (; i < 20; i++) { try { Thread.sleep(1000); } catch (final InterruptedException ex) { } VMGuestMetrics vmmetric = vm.getGuestMetrics(conn); if (isRefNull(vmmetric)) continue; Map<String, String> PVversion = vmmetric.getPVDriversVersion(conn); if (PVversion != null && PVversion.containsKey("major")) { break; } } if (i >= 20) { String msg = "migration failed due to can not fake PV driver for " + vmName; s_logger.warn(msg); return new MigrateAnswer(cmd, false, msg, null); } } final Map<String, String> options = new HashMap<String, String>(); vm.poolMigrate(conn, dsthost, options); state = State.Stopping; } return new MigrateAnswer(cmd, true, "migration succeeded", null); } catch (XenAPIException e) { String msg = "migration failed due to " + e.toString(); s_logger.warn(msg, e); return new MigrateAnswer(cmd, false, msg, null); } catch (XmlRpcException e) { String msg = "migration failed due to " + e.getMessage(); s_logger.warn(msg, e); return new MigrateAnswer(cmd, false, msg, null); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } protected State getRealPowerState(String label) { Connection conn = getConnection(); int i = 0; s_logger.trace("Checking on the HALTED State"); for (; i < 20; i++) { try { Set<VM> vms = VM.getByNameLabel(conn, label); if (vms == null || vms.size() == 0) { continue; } VM vm = vms.iterator().next(); VmPowerState vps = vm.getPowerState(conn); if (vps != null && vps != VmPowerState.HALTED && vps != VmPowerState.UNKNOWN && vps != VmPowerState.UNRECOGNIZED) { return convertToState(vps); } } catch (XenAPIException e) { String msg = "Unable to get real power state due to " + e.toString(); s_logger.warn(msg, e); } catch (XmlRpcException e) { String msg = "Unable to get real power state due to " + e.getMessage(); s_logger.warn(msg, e); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } return State.Stopped; } protected Pair<VM, VM.Record> getControlDomain(Connection conn) throws XenAPIException, XmlRpcException { Host host = Host.getByUuid(conn, _host.uuid); Set<VM> vms = null; vms = host.getResidentVMs(conn); for (VM vm : vms) { if (vm.getIsControlDomain(conn)) { return new Pair<VM, VM.Record>(vm, vm.getRecord(conn)); } } throw new CloudRuntimeException("Com'on no control domain? What the crap?!#@!##$@"); } protected HashMap<String, State> sync() { HashMap<String, State> newStates; HashMap<String, State> oldStates = null; final HashMap<String, State> changes = new HashMap<String, State>(); synchronized (_vms) { newStates = getAllVms(); if (newStates == null) { s_logger.debug("Unable to get the vm states so no state sync at this point."); return null; } oldStates = new HashMap<String, State>(_vms.size()); oldStates.putAll(_vms); for (final Map.Entry<String, State> entry : newStates.entrySet()) { final String vm = entry.getKey(); State newState = entry.getValue(); final State oldState = oldStates.remove(vm); if (newState == State.Stopped && oldState != State.Stopping && oldState != null && oldState != State.Stopped) { newState = getRealPowerState(vm); } if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + ": xen has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); } if (vm.startsWith("migrating")) { s_logger.debug("Migrating from xen detected. Skipping"); continue; } if (oldState == null) { _vms.put(vm, newState); s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); changes.put(vm, newState); } else if (oldState == State.Starting) { if (newState == State.Running) { _vms.put(vm, newState); } else if (newState == State.Stopped) { s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); } } else if (oldState == State.Migrating) { if (newState == State.Running) { s_logger.debug("Detected that an migrating VM is now running: " + vm); _vms.put(vm, newState); } } else if (oldState == State.Stopping) { if (newState == State.Stopped) { _vms.put(vm, newState); } else if (newState == State.Running) { s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); } } else if (oldState != newState) { _vms.put(vm, newState); if (newState == State.Stopped) { /* * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); * newState = State.Error; } */ } changes.put(vm, newState); } } for (final Map.Entry<String, State> entry : oldStates.entrySet()) { final String vm = entry.getKey(); final State oldState = entry.getValue(); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + " is now missing from xen so reporting stopped"); } if (oldState == State.Stopping) { s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); _vms.remove(vm); } else if (oldState == State.Starting) { s_logger.debug("Ignoring VM " + vm + " in transition state starting."); } else if (oldState == State.Stopped) { _vms.remove(vm); } else if (oldState == State.Migrating) { s_logger.debug("Ignoring VM " + vm + " in migrating state."); } else { State state = State.Stopped; /* * if (_vmsKilled.remove(entry.getKey())) { s_logger.debug("VM " + vm + * " has been killed by storage monitor"); state = State.Error; } */ changes.put(entry.getKey(), state); } } } return changes; } protected ReadyAnswer execute(ReadyCommand cmd) { Long dcId = cmd.getDataCenterId(); // Ignore the result of the callHostPlugin. Even if unmounting the // snapshots dir fails, let Ready command // succeed. callHostPlugin("vmopsSnapshot", "unmountSnapshotsDir", "dcId", dcId.toString()); return new ReadyAnswer(cmd); } // // using synchronized on VM name in the caller does not prevent multiple // commands being sent against // the same VM, there will be a race condition here in finally clause and // the main block if // there are multiple requests going on // // Therefore, a lazy solution is to add a synchronized guard here protected int getVncPort(VM vm) { Connection conn = getConnection(); VM.Record record; try { record = vm.getRecord(conn); } catch (XenAPIException e) { String msg = "Unable to get vnc-port due to " + e.toString(); s_logger.warn(msg, e); return -1; } catch (XmlRpcException e) { String msg = "Unable to get vnc-port due to " + e.getMessage(); s_logger.warn(msg, e); return -1; } String hvm = "true"; if (record.HVMBootPolicy.isEmpty()) { hvm = "false"; } String vncport = callHostPlugin("vmops", "getvncport", "domID", record.domid.toString(), "hvm", hvm); if (vncport == null || vncport.isEmpty()) { return -1; } vncport = vncport.replace("\n", ""); return NumbersUtil.parseInt(vncport, -1); } protected Answer execute(final RebootCommand cmd) { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Starting); } try { Connection conn = getConnection(); Set<VM> vms = null; try { vms = VM.getByNameLabel(conn, cmd.getVmName()); } catch (XenAPIException e0) { s_logger.debug("getByNameLabel failed " + e0.toString()); return new RebootAnswer(cmd, "getByNameLabel failed " + e0.toString()); } catch (Exception e0) { s_logger.debug("getByNameLabel failed " + e0.getMessage()); return new RebootAnswer(cmd, "getByNameLabel failed"); } for (VM vm : vms) { try { vm.cleanReboot(conn); } catch (XenAPIException e) { s_logger.debug("Do Not support Clean Reboot, fall back to hard Reboot: " + e.toString()); try { vm.hardReboot(conn); } catch (XenAPIException e1) { s_logger.debug("Caught exception on hard Reboot " + e1.toString()); return new RebootAnswer(cmd, "reboot failed: " + e1.toString()); } catch (XmlRpcException e1) { s_logger.debug("Caught exception on hard Reboot " + e1.getMessage()); return new RebootAnswer(cmd, "reboot failed"); } } catch (XmlRpcException e) { String msg = "Clean Reboot failed due to " + e.getMessage(); s_logger.warn(msg, e); return new RebootAnswer(cmd, msg); } } return new RebootAnswer(cmd, "reboot succeeded", null, null); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Running); } } } protected Answer execute(RebootRouterCommand cmd) { Long bytesSent = 0L; Long bytesRcvd = 0L; if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); bytesSent = stats[0]; bytesRcvd = stats[1]; } RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); answer.setBytesSent(bytesSent); answer.setBytesReceived(bytesRcvd); if (answer.getResult()) { String cnct = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); networkUsage(cmd.getPrivateIpAddress(), "create", null); if (cnct == null) { return answer; } else { return new Answer(cmd, false, cnct); } } return answer; } protected VM createVmFromTemplate(Connection conn, StartCommand cmd) throws XenAPIException, XmlRpcException { Set<VM> templates; VM vm = null; String stdType = cmd.getGuestOSDescription(); String guestOsTypeName = getGuestOsType(stdType); templates = VM.getByNameLabel(conn, guestOsTypeName); assert templates.size() == 1 : "Should only have 1 template but found " + templates.size(); VM template = templates.iterator().next(); vm = template.createClone(conn, cmd.getVmName()); vm.removeFromOtherConfig(conn, "disks"); if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) { if (cmd.getBootFromISO()) vm.setPVBootloader(conn, "eliloader"); else vm.setPVBootloader(conn, "pygrub"); vm.addToOtherConfig(conn, "install-repository", "cdrom"); } return vm; } protected String getGuestOsType(String stdType) { return _guestOsType.get(stdType); } public boolean joinPool(String address, String username, String password) { Connection conn = getConnection(); Connection poolConn = null; try { // set the _host.poolUuid to the old pool uuid in case it's not set. _host.pool = getPoolUuid(); // Connect and find out about the new connection to the new pool. poolConn = _connPool.connect(address, username, password, _wait); Map<Pool, Pool.Record> pools = Pool.getAllRecords(poolConn); Pool.Record pr = pools.values().iterator().next(); // Now join it. String masterAddr = pr.master.getAddress(poolConn); Pool.join(conn, masterAddr, username, password); if (s_logger.isDebugEnabled()) { s_logger.debug("Joined the pool at " + masterAddr); } disconnected(); // Logout of our own session. try { // slave will restart xapi in 10 sec Thread.sleep(10000); } catch (InterruptedException e) { } // Set the pool uuid now to the newest pool. _host.pool = pr.uuid; URL url; try { url = new URL("http://" + _host.ip); } catch (MalformedURLException e1) { throw new CloudRuntimeException("Problem with url " + _host.ip); } Connection c = null; for (int i = 0; i < 15; i++) { c = new Connection(url, _wait); try { Session.loginWithPassword(c, _username, _password, APIVersion.latest().toString()); s_logger.debug("Still waiting for the conversion to the master"); Session.logout(c); c.dispose(); } catch (Types.HostIsSlave e) { try { Session.logout(c); c.dispose(); } catch (XmlRpcException e1) { s_logger.debug("Unable to logout of test connection due to " + e1.getMessage()); } catch (XenAPIException e1) { s_logger.debug("Unable to logout of test connection due to " + e1.getMessage()); } break; } catch (XmlRpcException e) { s_logger.debug("XmlRpcException: Still waiting for the conversion to the master"); } catch (Exception e) { s_logger.debug("Exception: Still waiting for the conversion to the master"); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } return true; } catch (XenAPIException e) { String msg = "Unable to allow host " + _host.uuid + " to join pool " + address + " due to " + e.toString(); s_logger.warn(msg, e); throw new RuntimeException(msg); } catch (XmlRpcException e) { String msg = "Unable to allow host " + _host.uuid + " to join pool " + address + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new RuntimeException(msg); } finally { if (poolConn != null) { XenServerConnectionPool.logout(poolConn); } } } protected void startvmfailhandle(VM vm, List<Ternary<SR, VDI, VolumeVO>> mounts) { Connection conn = getConnection(); if (vm != null) { try { if (vm.getPowerState(conn) == VmPowerState.RUNNING) { try { vm.hardShutdown(conn); } catch (Exception e) { String msg = "VM hardshutdown failed due to " + e.toString(); s_logger.warn(msg); } } if (vm.getPowerState(conn) == VmPowerState.HALTED) { try { vm.destroy(conn); } catch (Exception e) { String msg = "VM destroy failed due to " + e.toString(); s_logger.warn(msg); } } } catch (Exception e) { String msg = "VM getPowerState failed due to " + e.toString(); s_logger.warn(msg); } } if (mounts != null) { for (Ternary<SR, VDI, VolumeVO> mount : mounts) { VDI vdi = mount.second(); Set<VBD> vbds = null; try { vbds = vdi.getVBDs(conn); } catch (Exception e) { String msg = "VDI getVBDS failed due to " + e.toString(); s_logger.warn(msg); continue; } for (VBD vbd : vbds) { try { vbd.unplug(conn); vbd.destroy(conn); } catch (Exception e) { String msg = "VBD destroy failed due to " + e.toString(); s_logger.warn(msg); } } } } } protected void setMemory(Connection conn, VM vm, long memsize) throws XmlRpcException, XenAPIException { vm.setMemoryStaticMin(conn, memsize); vm.setMemoryDynamicMin(conn, memsize); vm.setMemoryDynamicMax(conn, memsize); vm.setMemoryStaticMax(conn, memsize); } protected StartAnswer execute(StartCommand cmd) { State state = State.Stopped; Connection conn = getConnection(); VM vm = null; SR isosr = null; List<Ternary<SR, VDI, VolumeVO>> mounts = null; for (int retry = 0; retry < 2; retry++) { try { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Starting); } List<VolumeVO> vols = cmd.getVolumes(); mounts = mount(vols); if (retry == 1) { // at the second time, try hvm cmd.setGuestOSDescription("Other install media"); } vm = createVmFromTemplate(conn, cmd); long memsize = cmd.getRamSize() * 1024L * 1024L; setMemory(conn, vm, memsize); vm.setIsATemplate(conn, false); vm.setVCPUsMax(conn, (long) cmd.getCpu()); vm.setVCPUsAtStartup(conn, (long) cmd.getCpu()); Host host = Host.getByUuid(conn, _host.uuid); vm.setAffinity(conn, host); Map<String, String> vcpuparam = new HashMap<String, String>(); vcpuparam.put("weight", Integer.toString(cmd.getCpuWeight())); vcpuparam.put("cap", Integer.toString(cmd.getUtilization())); vm.setVCPUsParams(conn, vcpuparam); boolean bootFromISO = cmd.getBootFromISO(); /* create root VBD */ VBD.Record vbdr = new VBD.Record(); Ternary<SR, VDI, VolumeVO> mount = mounts.get(0); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = !bootFromISO; vbdr.userdevice = "0"; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; VBD.create(conn, vbdr); /* create data VBDs */ for (int i = 1; i < mounts.size(); i++) { mount = mounts.get(i); // vdi.setNameLabel(conn, cmd.getVmName() + "-DATA"); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = false; vbdr.userdevice = Long.toString(mount.third().getDeviceId()); vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; VBD.create(conn, vbdr); } /* create CD-ROM VBD */ VBD.Record cdromVBDR = new VBD.Record(); cdromVBDR.VM = vm; cdromVBDR.empty = true; cdromVBDR.bootable = bootFromISO; cdromVBDR.userdevice = "3"; cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; VBD cdromVBD = VBD.create(conn, cdromVBDR); /* insert the ISO VDI if isoPath is not null */ String isopath = cmd.getISOPath(); if (isopath != null) { int index = isopath.lastIndexOf("/"); String mountpoint = isopath.substring(0, index); URI uri = new URI(mountpoint); isosr = createIsoSRbyURI(uri, cmd.getVmName(), false); String isoname = isopath.substring(index + 1); VDI isovdi = getVDIbyLocationandSR(isoname, isosr); if (isovdi == null) { String msg = " can not find ISO " + cmd.getISOPath(); s_logger.warn(msg); return new StartAnswer(cmd, msg); } else { cdromVBD.insert(conn, isovdi); } } createVIF(conn, vm, cmd.getGuestMacAddress(), cmd.getGuestNetworkId(), cmd.getNetworkRateMbps(), "0", false); if (cmd.getExternalMacAddress() != null && cmd.getExternalVlan() != null) { createVIF(conn, vm, cmd.getExternalMacAddress(), cmd.getExternalVlan(), 0, "1", true); } /* set action after crash as destroy */ vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY); vm.start(conn, false, true); if (_canBridgeFirewall) { String result = callHostPlugin("vmops", "default_network_rules", "vmName", cmd.getVmName(), "vmIP", cmd.getGuestIpAddress(), "vmMAC", cmd.getGuestMacAddress(), "vmID", Long.toString(cmd.getId())); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default network rules for vm " + cmd.getVmName()); } else { s_logger.info("Programmed default network rules for vm " + cmd.getVmName()); } } state = State.Running; return new StartAnswer(cmd); } catch (XenAPIException e) { String errormsg = e.toString(); String msg = "Exception caught while starting VM due to message:" + errormsg + " (" + e.getClass().getName() + ")"; if (!errormsg.contains("Unable to find partition containing kernel") && !errormsg.contains("Unable to access a required file in the specified repository")) { s_logger.warn(msg, e); startvmfailhandle(vm, mounts); removeSR(isosr); } else { startvmfailhandle(vm, mounts); removeSR(isosr); continue; } state = State.Stopped; return new StartAnswer(cmd, msg); } catch (Exception e) { String msg = "Exception caught while starting VM due to message:" + e.getMessage(); s_logger.warn(msg, e); startvmfailhandle(vm, mounts); removeSR(isosr); state = State.Stopped; return new StartAnswer(cmd, msg); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), state); } } } String msg = "Start VM failed"; return new StartAnswer(cmd, msg); } protected void createVIF(Connection conn, VM vm, String mac, String vlanTag, int rate, String devNum, boolean isPub) throws XenAPIException, XmlRpcException, InternalErrorException { VIF.Record vifr = new VIF.Record(); vifr.VM = vm; vifr.device = devNum; vifr.MAC = mac; String nwUuid = (isPub ? _host.publicNetwork : _host.guestNetwork); String pifUuid = (isPub ? _host.publicPif : _host.guestPif); Network vlanNetwork = null; if ("untagged".equalsIgnoreCase(vlanTag)) { vlanNetwork = Network.getByUuid(conn, nwUuid); } else { vlanNetwork = enableVlanNetwork(Long.valueOf(vlanTag), nwUuid, pifUuid); } if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanTag); } vifr.network = vlanNetwork; if (rate != 0) { vifr.qosAlgorithmType = "ratelimit"; vifr.qosAlgorithmParams = new HashMap<String, String>(); vifr.qosAlgorithmParams.put("kbps", Integer.toString(rate * 1000)); } VIF.create(conn, vifr); } protected StopAnswer execute(final StopCommand cmd) { String vmName = cmd.getVmName(); try { Connection conn = getConnection(); Set<VM> vms = VM.getByNameLabel(conn, vmName); // stop vm which is running on this host or is in halted state for (VM vm : vms) { VM.Record vmr = vm.getRecord(conn); if (vmr.powerState != VmPowerState.RUNNING) continue; if (isRefNull(vmr.residentOn)) continue; if (vmr.residentOn.getUuid(conn).equals(_host.uuid)) continue; vms.remove(vm); } if (vms.size() == 0) { s_logger.warn("VM does not exist on XenServer" + _host.uuid); synchronized (_vms) { _vms.remove(vmName); } return new StopAnswer(cmd, "VM does not exist", 0, 0L, 0L); } Long bytesSent = 0L; Long bytesRcvd = 0L; for (VM vm : vms) { VM.Record vmr = vm.getRecord(conn); if (vmr.isControlDomain) { String msg = "Tring to Shutdown control domain"; s_logger.warn(msg); return new StopAnswer(cmd, msg); } if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) { String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.uuid + " but host:" + vmr.residentOn.getUuid(conn); s_logger.warn(msg); return new StopAnswer(cmd, msg); } State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { if (vmr.powerState == VmPowerState.RUNNING) { /* when stop a vm, set affinity to current xenserver */ vm.setAffinity(conn, vm.getResidentOn(conn)); try { if (VirtualMachineName.isValidRouterName(vmName)) { if(cmd.getPrivateRouterIpAddress() != null){ long[] stats = getNetworkStats(cmd.getPrivateRouterIpAddress()); bytesSent = stats[0]; bytesRcvd = stats[1]; } } if (_canBridgeFirewall) { String result = callHostPlugin("vmops", "destroy_network_rules_for_vm", "vmName", cmd.getVmName()); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to remove network rules for vm " + cmd.getVmName()); } else { s_logger.info("Removed network rules for vm " + cmd.getVmName()); } } vm.cleanShutdown(conn); } catch (XenAPIException e) { s_logger.debug("Do Not support Clean Shutdown, fall back to hard Shutdown: " + e.toString()); try { vm.hardShutdown(conn); } catch (XenAPIException e1) { String msg = "Hard Shutdown failed due to " + e1.toString(); s_logger.warn(msg, e1); return new StopAnswer(cmd, msg); } catch (XmlRpcException e1) { String msg = "Hard Shutdown failed due to " + e1.getMessage(); s_logger.warn(msg, e1); return new StopAnswer(cmd, msg); } } catch (XmlRpcException e) { String msg = "Clean Shutdown failed due to " + e.getMessage(); s_logger.warn(msg, e); return new StopAnswer(cmd, msg); } } } catch (Exception e) { String msg = "Catch exception " + e.getClass().toString() + " when stop VM:" + cmd.getVmName(); s_logger.debug(msg); return new StopAnswer(cmd, msg); } finally { try { if (vm.getPowerState(conn) == VmPowerState.HALTED) { Set<VIF> vifs = vm.getVIFs(conn); List<Network> networks = new ArrayList<Network>(); for (VIF vif : vifs) { networks.add(vif.getNetwork(conn)); } List<VDI> vdis = getVdis(vm); vm.destroy(conn); for( VDI vdi : vdis ){ umount(vdi); } state = State.Stopped; SR sr = getISOSRbyVmName(cmd.getVmName()); removeSR(sr); // Disable any VLAN networks that aren't used // anymore for (Network network : networks) { if (network.getNameLabel(conn).startsWith("VLAN")) { disableVlanNetwork(network); } } } } catch (XenAPIException e) { String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage(); s_logger.warn(msg, e); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } } return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", 0, bytesSent, bytesRcvd); } catch (XenAPIException e) { String msg = "Stop Vm " + vmName + " fail due to " + e.toString(); s_logger.warn(msg, e); return new StopAnswer(cmd, msg); } catch (XmlRpcException e) { String msg = "Stop Vm " + vmName + " fail due to " + e.getMessage(); s_logger.warn(msg, e); return new StopAnswer(cmd, msg); } } private List<VDI> getVdis(VM vm) { List<VDI> vdis = new ArrayList<VDI>(); try { Connection conn = getConnection(); Set<VBD> vbds =vm.getVBDs(conn); for( VBD vbd : vbds ) { vdis.add(vbd.getVDI(conn)); } } catch (XenAPIException e) { String msg = "getVdis can not get VPD due to " + e.toString(); s_logger.warn(msg, e); } catch (XmlRpcException e) { String msg = "getVdis can not get VPD due to " + e.getMessage(); s_logger.warn(msg, e); } return vdis; } protected String connect(final String vmName, final String ipAddress, final int port) { for (int i = 0; i <= _retry; i++) { try { Connection conn = getConnection(); Set<VM> vms = VM.getByNameLabel(conn, vmName); if (vms.size() < 1) { String msg = "VM " + vmName + " is not running"; s_logger.warn(msg); return msg; } } catch (Exception e) { String msg = "VM.getByNameLabel " + vmName + " failed due to " + e.toString(); s_logger.warn(msg, e); return msg; } if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to connect to " + ipAddress); } if (pingdomr(ipAddress, Integer.toString(port))) return null; try { Thread.sleep(_sleep); } catch (final InterruptedException e) { } } String msg = "Timeout, Unable to logon to " + ipAddress; s_logger.debug(msg); return msg; } protected String connect(final String vmname, final String ipAddress) { return connect(vmname, ipAddress, 3922); } protected StartRouterAnswer execute(StartRouterCommand cmd) { final String vmName = cmd.getVmName(); final DomainRouter router = cmd.getRouter(); try { String tag = router.getVnet(); Network network = null; if ("untagged".equalsIgnoreCase(tag)) { Connection conn = getConnection(); network = Network.getByUuid(conn, _host.guestNetwork); } else { network = enableVlanNetwork(Long.parseLong(tag), _host.guestNetwork, _host.guestPif); } if (network == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + tag); } String bootArgs = cmd.getBootArgs(); String result = startSystemVM(vmName, router.getVlanId(), network, cmd.getVolumes(), bootArgs, router.getGuestMacAddress(), router.getPrivateIpAddress(), router .getPrivateMacAddress(), router.getPublicMacAddress(), 3922, router.getRamSize()); if (result == null) { networkUsage(router.getPrivateIpAddress(), "create", null); return new StartRouterAnswer(cmd); } return new StartRouterAnswer(cmd, result); } catch (Exception e) { String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); return new StartRouterAnswer(cmd, msg); } } protected String startSystemVM(String vmName, String vlanId, Network nw0, List<VolumeVO> vols, String bootArgs, String guestMacAddr, String privateIp, String privateMacAddr, String publicMacAddr, int cmdPort, long ramSize) { setupLinkLocalNetwork(); VM vm = null; List<Ternary<SR, VDI, VolumeVO>> mounts = null; Connection conn = getConnection(); State state = State.Stopped; try { synchronized (_vms) { _vms.put(vmName, State.Starting); } mounts = mount(vols); assert mounts.size() == 1 : "System VMs should have only 1 partition but we actually have " + mounts.size(); Ternary<SR, VDI, VolumeVO> mount = mounts.get(0); Set<VM> templates = VM.getByNameLabel(conn, "CentOS 5.3"); if (templates.size() == 0) { templates = VM.getByNameLabel(conn, "CentOS 5.3 (64-bit)"); if (templates.size() == 0) { String msg = " can not find template CentOS 5.3 "; s_logger.warn(msg); return msg; } } VM template = templates.iterator().next(); vm = template.createClone(conn, vmName); vm.removeFromOtherConfig(conn, "disks"); vm.setPVBootloader(conn, "pygrub"); long memsize = ramSize * 1024L * 1024L; setMemory(conn, vm, memsize); vm.setIsATemplate(conn, false); vm.setVCPUsAtStartup(conn, 1L); Host host = Host.getByUuid(conn, _host.uuid); vm.setAffinity(conn, host); /* create VBD */ VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = mount.second(); vbdr.bootable = true; vbdr.userdevice = "0"; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; VBD.create(conn, vbdr); /* create CD-ROM VBD */ VBD.Record cdromVBDR = new VBD.Record(); cdromVBDR.VM = vm; cdromVBDR.empty = true; cdromVBDR.bootable = false; cdromVBDR.userdevice = "3"; cdromVBDR.mode = Types.VbdMode.RO; cdromVBDR.type = Types.VbdType.CD; VBD cdromVBD = VBD.create(conn, cdromVBDR); cdromVBD.insert(conn, VDI.getByUuid(conn, _host.systemvmisouuid)); /* create VIF0 */ VIF.Record vifr = new VIF.Record(); vifr.VM = vm; vifr.device = "0"; vifr.MAC = guestMacAddr; if (VirtualMachineName.isValidConsoleProxyName(vmName) || VirtualMachineName.isValidSecStorageVmName(vmName, null)) { vifr.network = Network.getByUuid(conn, _host.linkLocalNetwork); } else vifr.network = nw0; VIF.create(conn, vifr); /* create VIF1 */ /* For routing vm, set its network as link local bridge */ vifr.VM = vm; vifr.device = "1"; vifr.MAC = privateMacAddr; if (VirtualMachineName.isValidRouterName(vmName) && privateIp.startsWith("169.254")) { vifr.network = Network.getByUuid(conn, _host.linkLocalNetwork); } else { vifr.network = Network.getByUuid(conn, _host.privateNetwork); } VIF.create(conn, vifr); if( !publicMacAddr.equalsIgnoreCase("FE:FF:FF:FF:FF:FF") ) { /* create VIF2 */ vifr.VM = vm; vifr.device = "2"; vifr.MAC = publicMacAddr; vifr.network = Network.getByUuid(conn, _host.publicNetwork); if ("untagged".equalsIgnoreCase(vlanId)) { vifr.network = Network.getByUuid(conn, _host.publicNetwork); } else { Network vlanNetwork = enableVlanNetwork(Long.valueOf(vlanId), _host.publicNetwork, _host.publicPif); if (vlanNetwork == null) { throw new InternalErrorException("Failed to enable VLAN network with tag: " + vlanId); } vifr.network = vlanNetwork; } VIF.create(conn, vifr); } /* set up PV dom argument */ String pvargs = vm.getPVArgs(conn); pvargs = pvargs + bootArgs; if (s_logger.isInfoEnabled()) s_logger.info("PV args for system vm are " + pvargs); vm.setPVArgs(conn, pvargs); /* destroy console */ Set<Console> consoles = vm.getRecord(conn).consoles; for (Console console : consoles) { console.destroy(conn); } /* set action after crash as destroy */ vm.setActionsAfterCrash(conn, Types.OnCrashBehaviour.DESTROY); vm.start(conn, false, true); if (_canBridgeFirewall) { String result = callHostPlugin("vmops", "default_network_rules_systemvm", "vmName", vmName); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default system vm network rules for " + vmName); } else { s_logger.info("Programmed default system vm network rules for " + vmName); } } if (s_logger.isInfoEnabled()) s_logger.info("Ping system vm command port, " + privateIp + ":" + cmdPort); state = State.Running; String result = connect(vmName, privateIp, cmdPort); if (result != null) { String msg = "Can not ping System vm " + vmName + "due to:" + result; s_logger.warn(msg); throw new CloudRuntimeException(msg); } else { if (s_logger.isInfoEnabled()) s_logger.info("Ping system vm command port succeeded for vm " + vmName); } return null; } catch (XenAPIException e) { String msg = "Exception caught while starting System vm " + vmName + " due to " + e.toString(); s_logger.warn(msg, e); startvmfailhandle(vm, mounts); state = State.Stopped; return msg; } catch (Exception e) { String msg = "Exception caught while starting System vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); startvmfailhandle(vm, mounts); state = State.Stopped; return msg; } finally { synchronized (_vms) { _vms.put(vmName, state); } } } // TODO : need to refactor it to reuse code with StartRouter protected Answer execute(final StartConsoleProxyCommand cmd) { final String vmName = cmd.getVmName(); final ConsoleProxyVO proxy = cmd.getProxy(); try { Connection conn = getConnection(); Network network = Network.getByUuid(conn, _host.privateNetwork); String bootArgs = cmd.getBootArgs(); bootArgs += " zone=" + _dcId; bootArgs += " pod=" + _pod; bootArgs += " guid=Proxy." + proxy.getId(); bootArgs += " proxy_vm=" + proxy.getId(); bootArgs += " localgw=" + _localGateway; String result = startSystemVM(vmName, proxy.getVlanId(), network, cmd.getVolumes(), bootArgs, proxy.getGuestMacAddress(), proxy.getGuestIpAddress(), proxy .getPrivateMacAddress(), proxy.getPublicMacAddress(), cmd.getProxyCmdPort(), proxy.getRamSize()); if (result == null) { return new StartConsoleProxyAnswer(cmd); } return new StartConsoleProxyAnswer(cmd, result); } catch (Exception e) { String msg = "Exception caught while starting router vm " + vmName + " due to " + e.getMessage(); s_logger.warn(msg, e); return new StartConsoleProxyAnswer(cmd, msg); } } protected boolean patchSystemVm(VDI vdi, String vmName) { if (vmName.startsWith("r-")) { return patchSpecialVM(vdi, vmName, "router"); } else if (vmName.startsWith("v-")) { return patchSpecialVM(vdi, vmName, "consoleproxy"); } else if (vmName.startsWith("s-")) { return patchSpecialVM(vdi, vmName, "secstorage"); } else { throw new CloudRuntimeException("Tried to patch unknown type of system vm"); } } protected boolean isDeviceUsed(VM vm, Long deviceId) { // Figure out the disk number to attach the VM to String msg = null; try { Connection conn = getConnection(); Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn); if (allowedVBDDevices.contains(deviceId.toString())) { return false; } return true; } catch (XmlRpcException e) { msg = "Catch XmlRpcException due to: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { msg = "Catch XenAPIException due to: " + e.toString(); s_logger.warn(msg, e); } throw new CloudRuntimeException("When check deviceId " + msg); } protected String getUnusedDeviceNum(VM vm) { // Figure out the disk number to attach the VM to try { Connection conn = getConnection(); Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn); if (allowedVBDDevices.size() == 0) throw new CloudRuntimeException("Could not find an available slot in VM with name: " + vm.getNameLabel(conn) + " to attach a new disk."); return allowedVBDDevices.iterator().next(); } catch (XmlRpcException e) { String msg = "Catch XmlRpcException due to: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Catch XenAPIException due to: " + e.toString(); s_logger.warn(msg, e); } throw new CloudRuntimeException("Could not find an available slot in VM with name to attach a new disk."); } protected boolean patchSpecialVM(VDI vdi, String vmname, String vmtype) { // patch special vm here, domr, domp VBD vbd = null; Connection conn = getConnection(); try { Host host = Host.getByUuid(conn, _host.uuid); Set<VM> vms = host.getResidentVMs(conn); for (VM vm : vms) { VM.Record vmrec = null; try { vmrec = vm.getRecord(conn); } catch (Exception e) { String msg = "VM.getRecord failed due to " + e.toString() + " " + e.getMessage(); s_logger.warn(msg); continue; } if (vmrec.isControlDomain) { /* create VBD */ VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; vbdr.bootable = false; vbdr.userdevice = getUnusedDeviceNum(vm); vbdr.unpluggable = true; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbd = VBD.create(conn, vbdr); vbd.plug(conn); String device = vbd.getDevice(conn); return patchspecialvm(vmname, device, vmtype); } } } catch (XenAPIException e) { String msg = "patchSpecialVM faile on " + _host.uuid + " due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "patchSpecialVM faile on " + _host.uuid + " due to " + e.getMessage(); s_logger.warn(msg, e); } finally { if (vbd != null) { try { if (vbd.getCurrentlyAttached(conn)) { vbd.unplug(conn); } vbd.destroy(conn); } catch (XmlRpcException e) { String msg = "Catch XmlRpcException due to " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Catch XenAPIException due to " + e.toString(); s_logger.warn(msg, e); } } } return false; } protected boolean patchspecialvm(String vmname, String device, String vmtype) { String result = callHostPlugin("vmops", "patchdomr", "vmname", vmname, "vmtype", vmtype, "device", "/dev/" + device); if (result == null || result.isEmpty()) return false; return true; } protected String callHostPlugin(String plugin, String cmd, String... params) { Map<String, String> args = new HashMap<String, String>(); Session slaveSession = null; Connection slaveConn = null; try { URL slaveUrl = null; try { slaveUrl = new URL("http://" + _host.ip); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } slaveConn = new Connection(slaveUrl, 1800); slaveSession = Session.slaveLocalLoginWithPassword(slaveConn, _username, _password); if (s_logger.isDebugEnabled()) { s_logger.debug("Slave logon successful. session= " + slaveSession); } Host host = Host.getByUuid(slaveConn, _host.uuid); for (int i = 0; i < params.length; i += 2) { args.put(params[i], params[i + 1]); } if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin executing for command " + cmd + " with " + getArgsString(args)); } String result = host.callPlugin(slaveConn, plugin, cmd, args); if (s_logger.isTraceEnabled()) { s_logger.trace("callHostPlugin Result: " + result); } return result.replace("\n", ""); } catch (XenAPIException e) { s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString()); } catch (XmlRpcException e) { s_logger.debug("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.getMessage()); } finally { if( slaveSession != null) { try { slaveSession.localLogout(slaveConn); } catch (Exception e) { } } } return null; } protected String getArgsString(Map<String, String> args) { StringBuilder argString = new StringBuilder(); for (Map.Entry<String, String> arg : args.entrySet()) { argString.append(arg.getKey() + ": " + arg.getValue() + ", "); } return argString.toString(); } protected boolean setIptables() { String result = callHostPlugin("vmops", "setIptables"); if (result == null || result.isEmpty()) return false; return true; } protected Nic getLocalNetwork(Connection conn, String name) throws XmlRpcException, XenAPIException { if( name == null) { return null; } Set<Network> networks = Network.getByNameLabel(conn, name); for (Network network : networks) { Network.Record nr = network.getRecord(conn); for (PIF pif : nr.PIFs) { PIF.Record pr = pif.getRecord(conn); if (_host.uuid.equals(pr.host.getUuid(conn))) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found a network called " + name + " on host=" + _host.ip + "; Network=" + nr.uuid + "; pif=" + pr.uuid); } if (pr.bondMasterOf != null && pr.bondMasterOf.size() > 0) { if (pr.bondMasterOf.size() > 1) { String msg = new StringBuilder("Unsupported configuration. Network " + name + " has more than one bond. Network=").append(nr.uuid) .append("; pif=").append(pr.uuid).toString(); s_logger.warn(msg); return null; } Bond bond = pr.bondMasterOf.iterator().next(); Set<PIF> slaves = bond.getSlaves(conn); for (PIF slave : slaves) { PIF.Record spr = slave.getRecord(conn); if (spr.management) { Host host = Host.getByUuid(conn, _host.uuid); if (!transferManagementNetwork(conn, host, slave, spr, pif)) { String msg = new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" + _host.uuid).toString(); s_logger.warn(msg); return null; } break; } } } return new Nic(network, nr, pif, pr); } } } return null; } protected VIF getCorrectVif(VM router, String vlanId) { try { Connection conn = getConnection(); Set<VIF> routerVIFs = router.getVIFs(conn); for (VIF vif : routerVIFs) { Network vifNetwork = vif.getNetwork(conn); if (vlanId.equals("untagged")) { if (vifNetwork.getUuid(conn).equals(_host.publicNetwork)) { return vif; } } else { if (vifNetwork.getNameLabel(conn).equals("VLAN" + vlanId)) { return vif; } } } } catch (XmlRpcException e) { String msg = "Caught XmlRpcException: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Caught XenAPIException: " + e.toString(); s_logger.warn(msg, e); } return null; } protected String getLowestAvailableVIFDeviceNum(VM vm) { try { Connection conn = getConnection(); Set<String> availableDeviceNums = vm.getAllowedVIFDevices(conn); Iterator<String> deviceNumsIterator = availableDeviceNums.iterator(); List<Integer> sortedDeviceNums = new ArrayList<Integer>(); while (deviceNumsIterator.hasNext()) { try { sortedDeviceNums.add(Integer.valueOf(deviceNumsIterator.next())); } catch (NumberFormatException e) { s_logger.debug("Obtained an invalid value for an available VIF device number for VM: " + vm.getNameLabel(conn)); return null; } } Collections.sort(sortedDeviceNums); return String.valueOf(sortedDeviceNums.get(0)); } catch (XmlRpcException e) { String msg = "Caught XmlRpcException: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Caught XenAPIException: " + e.toString(); s_logger.warn(msg, e); } return null; } protected VDI mount(StoragePoolType pooltype, String volumeFolder, String volumePath) { return getVDIbyUuid(volumePath); } protected List<Ternary<SR, VDI, VolumeVO>> mount(List<VolumeVO> vos) { ArrayList<Ternary<SR, VDI, VolumeVO>> mounts = new ArrayList<Ternary<SR, VDI, VolumeVO>>(vos.size()); for (VolumeVO vol : vos) { String vdiuuid = vol.getPath(); SR sr = null; VDI vdi = null; // Look up the VDI vdi = getVDIbyUuid(vdiuuid); Ternary<SR, VDI, VolumeVO> ter = new Ternary<SR, VDI, VolumeVO>(sr, vdi, vol); if( vol.getVolumeType() == VolumeType.ROOT ) { mounts.add(0, ter); } else { mounts.add(ter); } } return mounts; } protected Network getNetworkByName(String name) throws BadServerResponse, XenAPIException, XmlRpcException { Connection conn = getConnection(); Set<Network> networks = Network.getByNameLabel(conn, name); if (networks.size() > 0) { assert networks.size() == 1 : "How did we find more than one network with this name label" + name + "? Strange...."; return networks.iterator().next(); // Found it. } return null; } protected synchronized Network getNetworkByName(Connection conn, String name, boolean lookForPif) throws XenAPIException, XmlRpcException { Network found = null; Set<Network> networks = Network.getByNameLabel(conn, name); if (networks.size() == 1) { found = networks.iterator().next(); } else if (networks.size() > 1) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found more than one network with the name " + name); } for (Network network : networks) { if (!lookForPif) { found = network; break; } Network.Record netr = network.getRecord(conn); s_logger.debug("Checking network " + netr.uuid); if (netr.PIFs.size() == 0) { if (s_logger.isDebugEnabled()) { s_logger.debug("Network " + netr.uuid + " has no pifs so skipping that."); } } else { for (PIF pif : netr.PIFs) { PIF.Record pifr = pif.getRecord(conn); if (_host.uuid.equals(pifr.host.getUuid(conn))) { if (s_logger.isDebugEnabled()) { s_logger.debug("Network " + netr.uuid + " has a pif " + pifr.uuid + " for our host "); } found = network; break; } } } } } return found; } protected Network enableVlanNetwork(long tag, String networkUuid, String pifUuid) throws XenAPIException, XmlRpcException { // In XenServer, vlan is added by // 1. creating a network. // 2. creating a vlan associating network with the pif. // We always create // 1. a network with VLAN[vlan id in decimal] // 2. a vlan associating the network created with the pif to private // network. Connection conn = getConnection(); Network vlanNetwork = null; String name = "VLAN" + Long.toString(tag); synchronized (name.intern()) { vlanNetwork = getNetworkByName(name); if (vlanNetwork == null) { // Can't find it, then create it. if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN network for " + tag + " on host " + _host.ip); } Network.Record nwr = new Network.Record(); nwr.nameLabel = name; nwr.bridge = name; vlanNetwork = Network.create(conn, nwr); } PIF nPif = PIF.getByUuid(conn, pifUuid); PIF.Record nPifr = nPif.getRecord(conn); Network.Record vlanNetworkr = vlanNetwork.getRecord(conn); if (vlanNetworkr.PIFs != null) { for (PIF pif : vlanNetworkr.PIFs) { PIF.Record pifr = pif.getRecord(conn); if (pifr.device.equals(nPifr.device) && pifr.host.equals(nPifr.host)) { pif.plug(conn); return vlanNetwork; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN " + tag + " on host " + _host.ip + " on device " + nPifr.device); } VLAN vlan = VLAN.create(conn, nPif, tag, vlanNetwork); PIF untaggedPif = vlan.getUntaggedPIF(conn); if (!untaggedPif.getCurrentlyAttached(conn)) { untaggedPif.plug(conn); } } return vlanNetwork; } protected Network enableVlanNetwork(Connection conn, long tag, Network network, String pifUuid) throws XenAPIException, XmlRpcException { // In XenServer, vlan is added by // 1. creating a network. // 2. creating a vlan associating network with the pif. // We always create // 1. a network with VLAN[vlan id in decimal] // 2. a vlan associating the network created with the pif to private // network. Network vlanNetwork = null; String name = "VLAN" + Long.toString(tag); vlanNetwork = getNetworkByName(conn, name, true); if (vlanNetwork == null) { // Can't find it, then create it. if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN network for " + tag + " on host " + _host.ip); } Network.Record nwr = new Network.Record(); nwr.nameLabel = name; nwr.bridge = name; vlanNetwork = Network.create(conn, nwr); } PIF nPif = PIF.getByUuid(conn, pifUuid); PIF.Record nPifr = nPif.getRecord(conn); Network.Record vlanNetworkr = vlanNetwork.getRecord(conn); if (vlanNetworkr.PIFs != null) { for (PIF pif : vlanNetworkr.PIFs) { PIF.Record pifr = pif.getRecord(conn); if (pifr.device.equals(nPifr.device) && pifr.host.equals(nPifr.host)) { pif.plug(conn); return vlanNetwork; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VLAN " + tag + " on host " + _host.ip + " on device " + nPifr.device); } VLAN vlan = VLAN.create(conn, nPif, tag, vlanNetwork); VLAN.Record vlanr = vlan.getRecord(conn); if (s_logger.isDebugEnabled()) { s_logger.debug("VLAN is created for " + tag + ". The uuid is " + vlanr.uuid); } PIF untaggedPif = vlanr.untaggedPIF; if (!untaggedPif.getCurrentlyAttached(conn)) { untaggedPif.plug(conn); } return vlanNetwork; } protected void disableVlanNetwork(Network network) throws InternalErrorException { try { Connection conn = getConnection(); if (network.getVIFs(conn).isEmpty()) { Iterator<PIF> pifs = network.getPIFs(conn).iterator(); while (pifs.hasNext()) { PIF pif = pifs.next(); pif.unplug(conn); } } } catch (XenAPIException e) { String msg = "Unable to disable VLAN network due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "Unable to disable VLAN network due to " + e.getMessage(); s_logger.warn(msg, e); } } protected SR getLocalLVMSR() { Connection conn = getConnection(); try { Map<SR, SR.Record> map = SR.getAllRecords(conn); for (Map.Entry<SR, SR.Record> entry : map.entrySet()) { SR.Record srRec = entry.getValue(); if (SRType.LVM.equals(srRec.type)) { Set<PBD> pbds = srRec.PBDs; if (pbds == null) { continue; } for (PBD pbd : pbds) { Host host = pbd.getHost(conn); if (!isRefNull(host) && host.getUuid(conn).equals(_host.uuid)) { if (!pbd.getCurrentlyAttached(conn)) { pbd.plug(conn); } SR sr = entry.getKey(); sr.scan(conn); return sr; } } } } } catch (XenAPIException e) { String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.toString(); s_logger.warn(msg); } catch (XmlRpcException e) { String msg = "Unable to get local LVMSR in host:" + _host.uuid + e.getCause(); s_logger.warn(msg); } return null; } protected StartupStorageCommand initializeLocalSR() { SR lvmsr = getLocalLVMSR(); if (lvmsr == null) { return null; } try { Connection conn = getConnection(); String lvmuuid = lvmsr.getUuid(conn); long cap = lvmsr.getPhysicalSize(conn); if (cap < 0) return null; long avail = cap - lvmsr.getPhysicalUtilisation(conn); lvmsr.setNameLabel(conn, lvmuuid); String name = "VMOps local storage pool in host : " + _host.uuid; lvmsr.setNameDescription(conn, name); Host host = Host.getByUuid(conn, _host.uuid); String address = host.getAddress(conn); StoragePoolInfo pInfo = new StoragePoolInfo(name, lvmuuid, address, SRType.LVM.toString(), SRType.LVM.toString(), StoragePoolType.LVM, cap, avail); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setPoolInfo(pInfo); cmd.setGuid(_host.uuid); cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); return cmd; } catch (XenAPIException e) { String msg = "build startupstoragecommand err in host:" + _host.uuid + e.toString(); s_logger.warn(msg); } catch (XmlRpcException e) { String msg = "build startupstoragecommand err in host:" + _host.uuid + e.getMessage(); s_logger.warn(msg); } return null; } @Override public PingCommand getCurrentStatus(long id) { try { if (!pingxenserver()) { Thread.sleep(1000); if (!pingxenserver()) { s_logger.warn(" can not ping xenserver " + _host.uuid); return null; } } HashMap<String, State> newStates = sync(); if (newStates == null) { newStates = new HashMap<String, State>(); } if (!_canBridgeFirewall) { return new PingRoutingCommand(getType(), id, newStates); } else { HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id); return new PingRoutingWithNwGroupsCommand(getType(), id, newStates, nwGrpStates); } } catch (Exception e) { s_logger.warn("Unable to get current status", e); return null; } } private HashMap<String, Pair<Long,Long>> syncNetworkGroups(long id) { HashMap<String, Pair<Long,Long>> states = new HashMap<String, Pair<Long,Long>>(); String result = callHostPlugin("vmops", "get_rule_logs_for_vms", "host_uuid", _host.uuid); s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); String [] rulelogs = result != null ?result.split(";"): new String [0]; for (String rulesforvm: rulelogs){ String [] log = rulesforvm.split(","); if (log.length != 6) { continue; } //output = ','.join([vmName, vmID, vmIP, domID, signature, seqno]) try { states.put(log[0], new Pair<Long,Long>(Long.parseLong(log[1]), Long.parseLong(log[5]))); } catch (NumberFormatException nfe) { states.put(log[0], new Pair<Long,Long>(-1L, -1L)); } } return states; } @Override public Type getType() { return com.cloud.host.Host.Type.Routing; } protected void getPVISO(StartupStorageCommand sscmd) { Connection conn = getConnection(); try { Set<VDI> vids = VDI.getByNameLabel(conn, "xs-tools.iso"); if (vids.isEmpty()) return; VDI pvISO = vids.iterator().next(); String uuid = pvISO.getUuid(conn); Map<String, TemplateInfo> pvISOtmlt = new HashMap<String, TemplateInfo>(); TemplateInfo tmplt = new TemplateInfo("xs-tools.iso", uuid, pvISO.getVirtualSize(conn), true); pvISOtmlt.put("xs-tools", tmplt); sscmd.setTemplateInfo(pvISOtmlt); } catch (XenAPIException e) { s_logger.debug("Can't get xs-tools.iso: " + e.toString()); } catch (XmlRpcException e) { s_logger.debug("Can't get xs-tools.iso: " + e.toString()); } } protected boolean can_bridge_firewall() { return false; } protected boolean getHostInfo() throws IllegalArgumentException{ Connection conn = getConnection(); try { Host myself = Host.getByUuid(conn, _host.uuid); _host.pool = getPoolUuid(); boolean findsystemvmiso = false; Set<SR> srs = SR.getByNameLabel(conn, "XenServer Tools"); if( srs.size() != 1 ) { throw new CloudRuntimeException("There are " + srs.size() + " SRs with name XenServer Tools"); } SR sr = srs.iterator().next(); sr.scan(conn); SR.Record srr = sr.getRecord(conn); _host.systemvmisouuid = null; for( VDI vdi : srr.VDIs ) { VDI.Record vdir = vdi.getRecord(conn); if(vdir.nameLabel.contains("systemvm-premium")){ _host.systemvmisouuid = vdir.uuid; break; } } if( _host.systemvmisouuid == null ) { for( VDI vdi : srr.VDIs ) { VDI.Record vdir = vdi.getRecord(conn); if(vdir.nameLabel.contains("systemvm")){ _host.systemvmisouuid = vdir.uuid; break; } } } if( _host.systemvmisouuid == null ) { throw new CloudRuntimeException("can not find systemvmiso"); } String name = "cloud-private"; if (_privateNetworkName != null) { name = _privateNetworkName; } _localGateway = callHostPlugin("vmops", "getgateway", "mgmtIP", myself.getAddress(conn)); if (_localGateway == null || _localGateway.isEmpty()) { s_logger.warn("can not get gateway for host :" + _host.uuid); return false; } _canBridgeFirewall = can_bridge_firewall(); Nic privateNic = getLocalNetwork(conn, name); if (privateNic == null) { s_logger.debug("Unable to find any private network. Trying to determine that by route for host " + _host.ip); name = callHostPlugin("vmops", "getnetwork", "mgmtIP", myself.getAddress(conn)); if (name == null || name.isEmpty()) { s_logger.warn("Unable to determine the private network for host " + _host.ip); return false; } _privateNetworkName = name; privateNic = getLocalNetwork(conn, name); if (privateNic == null) { s_logger.warn("Unable to get private network " + name); return false; } } _host.privatePif = privateNic.pr.uuid; _host.privateNetwork = privateNic.nr.uuid; Nic guestNic = null; if (_guestNetworkName != null && !_guestNetworkName.equals(_privateNetworkName)) { guestNic = getLocalNetwork(conn, _guestNetworkName); if (guestNic == null) { s_logger.warn("Unable to find guest network " + _guestNetworkName); throw new IllegalArgumentException("Unable to find guest network " + _guestNetworkName + " for host " + _host.ip); } } else { guestNic = privateNic; _guestNetworkName = _privateNetworkName; } _host.guestNetwork = guestNic.nr.uuid; _host.guestPif = guestNic.pr.uuid; Nic publicNic = null; if (_publicNetworkName != null && !_publicNetworkName.equals(_guestNetworkName)) { publicNic = getLocalNetwork(conn, _publicNetworkName); if (publicNic == null) { s_logger.warn("Unable to find public network " + _publicNetworkName + " for host " + _host.ip); throw new IllegalArgumentException("Unable to find public network " + _publicNetworkName + " for host " + _host.ip); } } else { publicNic = guestNic; _publicNetworkName = _guestNetworkName; } _host.publicPif = publicNic.pr.uuid; _host.publicNetwork = publicNic.nr.uuid; Nic storageNic1 = getLocalNetwork(conn, _storageNetworkName1); if (storageNic1 == null) { storageNic1 = privateNic; _storageNetworkName1 = _privateNetworkName; } _host.storageNetwork1 = storageNic1.nr.uuid; _host.storagePif1 = storageNic1.pr.uuid; Nic storageNic2 = getLocalNetwork(conn, _storageNetworkName2); if (storageNic2 == null) { storageNic2 = privateNic; _storageNetworkName2 = _privateNetworkName; } _host.storageNetwork2 = storageNic2.nr.uuid; _host.storagePif2 = storageNic2.pr.uuid; s_logger.info("Private Network is " + _privateNetworkName + " for host " + _host.ip); s_logger.info("Guest Network is " + _guestNetworkName + " for host " + _host.ip); s_logger.info("Public Network is " + _publicNetworkName + " for host " + _host.ip); s_logger.info("Storage Network 1 is " + _storageNetworkName1 + " for host " + _host.ip); s_logger.info("Storage Network 2 is " + _storageNetworkName2 + " for host " + _host.ip); return true; } catch (XenAPIException e) { s_logger.warn("Unable to get host information for " + _host.ip, e); return false; } catch (XmlRpcException e) { s_logger.warn("Unable to get host information for " + _host.ip, e); return false; } } private void setupLinkLocalNetwork() { try { Network.Record rec = new Network.Record(); Connection conn = getConnection(); Set<Network> networks = Network.getByNameLabel(conn, _linkLocalPrivateNetworkName); Network linkLocal = null; if (networks.size() == 0) { rec.nameDescription = "link local network used by system vms"; rec.nameLabel = _linkLocalPrivateNetworkName; Map<String, String> configs = new HashMap<String, String>(); configs.put("ip_begin", NetUtils.getLinkLocalGateway()); configs.put("ip_end", NetUtils.getLinkLocalIpEnd()); configs.put("netmask", NetUtils.getLinkLocalNetMask()); rec.otherConfig = configs; linkLocal = Network.create(conn, rec); } else { linkLocal = networks.iterator().next(); } /* Make sure there is a physical bridge on this network */ VIF dom0vif = null; Pair<VM, VM.Record> vm = getControlDomain(conn); VM dom0 = vm.first(); Set<VIF> vifs = dom0.getVIFs(conn); if (vifs.size() != 0) { for (VIF vif : vifs) { Map<String, String> otherConfig = vif.getOtherConfig(conn); if (otherConfig != null) { String nameLabel = otherConfig.get("nameLabel"); if ((nameLabel != null) && nameLabel.equalsIgnoreCase("link_local_network_vif")) { dom0vif = vif; } } } } /* create temp VIF0 */ if (dom0vif == null) { s_logger.debug("Can't find a vif on dom0 for link local, creating a new one"); VIF.Record vifr = new VIF.Record(); vifr.VM = dom0; vifr.device = getLowestAvailableVIFDeviceNum(dom0); if (vifr.device == null) { s_logger.debug("Failed to create link local network, no vif available"); return; } Map<String, String> config = new HashMap<String, String>(); config.put("nameLabel", "link_local_network_vif"); vifr.otherConfig = config; vifr.MAC = "FE:FF:FF:FF:FF:FF"; vifr.network = linkLocal; dom0vif = VIF.create(conn, vifr); dom0vif.plug(conn); } else { s_logger.debug("already have a vif on dom0 for link local network"); if (!dom0vif.getCurrentlyAttached(conn)) { dom0vif.plug(conn); } } String brName = linkLocal.getBridge(conn); callHostPlugin("vmops", "setLinkLocalIP", "brName", brName); _host.linkLocalNetwork = linkLocal.getUuid(conn); } catch (XenAPIException e) { s_logger.warn("Unable to create local link network", e); } catch (XmlRpcException e) { // TODO Auto-generated catch block s_logger.warn("Unable to create local link network", e); } } protected boolean transferManagementNetwork(Connection conn, Host host, PIF src, PIF.Record spr, PIF dest) throws XmlRpcException, XenAPIException { dest.reconfigureIp(conn, spr.ipConfigurationMode, spr.IP, spr.netmask, spr.gateway, spr.DNS); Host.managementReconfigure(conn, dest); String hostUuid = null; int count = 0; while (count < 10) { try { Thread.sleep(10000); hostUuid = host.getUuid(conn); if (hostUuid != null) { break; } } catch (XmlRpcException e) { s_logger.debug("Waiting for host to come back: " + e.getMessage()); } catch (XenAPIException e) { s_logger.debug("Waiting for host to come back: " + e.getMessage()); } catch (InterruptedException e) { s_logger.debug("Gotta run"); return false; } } if (hostUuid == null) { s_logger.warn("Unable to transfer the management network from " + spr.uuid); return false; } src.reconfigureIp(conn, IpConfigurationMode.NONE, null, null, null, null); return true; } @Override public StartupCommand[] initialize() throws IllegalArgumentException{ disconnected(); setupServer(); if (!getHostInfo()) { s_logger.warn("Unable to get host information for " + _host.ip); return null; } destroyStoppedVm(); StartupRoutingCommand cmd = new StartupRoutingCommand(); fillHostInfo(cmd); cleanupDiskMounts(); Map<String, State> changes = null; synchronized (_vms) { _vms.clear(); changes = sync(); } cmd.setHypervisorType(Hypervisor.Type.XenServer); cmd.setChanges(changes); cmd.setCluster(_cluster); StartupStorageCommand sscmd = initializeLocalSR(); _host.pool = getPoolUuid(); if (sscmd != null) { /* report pv driver iso */ getPVISO(sscmd); return new StartupCommand[] { cmd, sscmd }; } return new StartupCommand[] { cmd }; } protected String getPoolUuid() { Connection conn = getConnection(); try { Map<Pool, Pool.Record> pools = Pool.getAllRecords(conn); assert (pools.size() == 1) : "Tell me how pool size can be " + pools.size(); Pool.Record rec = pools.values().iterator().next(); return rec.uuid; } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get pool ", e); } catch (XmlRpcException e) { throw new CloudRuntimeException("Unable to get pool ", e); } } protected void setupServer() { Connection conn = getConnection(); String version = CitrixResourceBase.class.getPackage().getImplementationVersion(); try { Host host = Host.getByUuid(conn, _host.uuid); /* enable host in case it is disabled somehow */ host.enable(conn); /* push patches to XenServer */ Host.Record hr = host.getRecord(conn); Iterator<String> it = hr.tags.iterator(); while (it.hasNext()) { String tag = it.next(); if (tag.startsWith("vmops-version-")) { if (tag.contains(version)) { s_logger.info(logX(host, "Host " + hr.address + " is already setup.")); return; } else { it.remove(); } } } com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22); try { sshConnection.connect(null, 60000, 60000); if (!sshConnection.authenticateWithPassword(_username, _password)) { throw new CloudRuntimeException("Unable to authenticate"); } SCPClient scp = new SCPClient(sshConnection); File file = new File(_patchPath); Properties props = new Properties(); props.load(new FileInputStream(file)); String path = _patchPath.substring(0, _patchPath.lastIndexOf(File.separator) + 1); for (Map.Entry<Object, Object> entry : props.entrySet()) { String k = (String) entry.getKey(); String v = (String) entry.getValue(); assert (k != null && k.length() > 0 && v != null && v.length() > 0) : "Problems with " + k + "=" + v; String[] tokens = v.split(","); String f = null; if (tokens.length == 3 && tokens[0].length() > 0) { if (tokens[0].startsWith("/")) { f = tokens[0]; } else if (tokens[0].startsWith("~")) { String homedir = System.getenv("HOME"); f = homedir + tokens[0].substring(1) + k; } else { f = path + tokens[0] + '/' + k; } } else { f = path + k; } String d = tokens[tokens.length - 1]; f = f.replace('/', File.separatorChar); String p = "0755"; if (tokens.length == 3) { p = tokens[1]; } else if (tokens.length == 2) { p = tokens[0]; } if (!new File(f).exists()) { s_logger.warn("We cannot locate " + f); continue; } if (s_logger.isDebugEnabled()) { s_logger.debug("Copying " + f + " to " + d + " on " + hr.address + " with permission " + p); } scp.put(f, d, p); } } catch (IOException e) { throw new CloudRuntimeException("Unable to setup the server correctly", e); } finally { sshConnection.close(); } if (!setIptables()) { s_logger.warn("set xenserver Iptable failed"); } hr.tags.add("vmops-version-" + version); host.setTags(conn, hr.tags); } catch (XenAPIException e) { String msg = "Xen setup failed due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException("Unable to get host information " + e.toString(), e); } catch (XmlRpcException e) { String msg = "Xen setup failed due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException("Unable to get host information ", e); } } protected SR getSRByNameLabelandHost(String name) throws BadServerResponse, XenAPIException, XmlRpcException { Connection conn = getConnection(); Set<SR> srs = SR.getByNameLabel(conn, name); SR ressr = null; for (SR sr : srs) { Set<PBD> pbds; pbds = sr.getPBDs(conn); for (PBD pbd : pbds) { PBD.Record pbdr = pbd.getRecord(conn); if (pbdr.host != null && pbdr.host.getUuid(conn).equals(_host.uuid)) { if (!pbdr.currentlyAttached) { pbd.plug(conn); } ressr = sr; break; } } } return ressr; } protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { try { Connection conn = getConnection(); Set<SR> srs = SR.getByNameLabel(conn, cmd.getStorageId()); if (srs.size() != 1) { String msg = "There are " + srs.size() + " storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } SR sr = srs.iterator().next(); sr.scan(conn); long capacity = sr.getPhysicalSize(conn); long used = sr.getPhysicalUtilisation(conn); return new GetStorageStatsAnswer(cmd, capacity, used); } catch (XenAPIException e) { String msg = "GetStorageStats Exception:" + e.toString() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } catch (XmlRpcException e) { String msg = "GetStorageStats Exception:" + e.getMessage() + "host:" + _host.uuid + "storageid: " + cmd.getStorageId(); s_logger.warn(msg); return new GetStorageStatsAnswer(cmd, msg); } } protected boolean checkSR(SR sr) { try { Connection conn = getConnection(); SR.Record srr = sr.getRecord(conn); Set<PBD> pbds = sr.getPBDs(conn); if (pbds.size() == 0) { String msg = "There is no PBDs for this SR: " + _host.uuid; s_logger.warn(msg); removeSR(sr); return false; } Set<Host> hosts = null; if (srr.shared) { hosts = Host.getAll(conn); for (Host host : hosts) { boolean found = false; for (PBD pbd : pbds) { if (host.equals(pbd.getHost(conn))) { PBD.Record pbdr = pbd.getRecord(conn); if (currentlyAttached(sr, srr, pbd, pbdr)) { if (!pbdr.currentlyAttached) { pbd.plug(conn); } } else { if (pbdr.currentlyAttached) { pbd.unplug(conn); } pbd.plug(conn); } pbds.remove(pbd); found = true; break; } } if (!found) { PBD.Record pbdr = srr.PBDs.iterator().next().getRecord(conn); pbdr.host = host; pbdr.uuid = ""; PBD pbd = PBD.create(conn, pbdr); pbd.plug(conn); } } } else { for (PBD pbd : pbds) { PBD.Record pbdr = pbd.getRecord(conn); if (!pbdr.currentlyAttached) { pbd.plug(conn); } } } } catch (Exception e) { String msg = "checkSR failed host:" + _host.uuid; s_logger.warn(msg); return false; } return true; } protected Answer execute(ModifyStoragePoolCommand cmd) { StoragePoolVO pool = cmd.getPool(); try { Connection conn = getConnection(); SR sr = getStorageRepository(conn, pool); if (!checkSR(sr)) { String msg = "ModifyStoragePoolCommand checkSR failed! host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg); return new Answer(cmd, false, msg); } sr.setNameLabel(conn, pool.getUuid()); sr.setNameDescription(conn, pool.getName()); long capacity = sr.getPhysicalSize(conn); long available = capacity - sr.getPhysicalUtilisation(conn); if (capacity == -1) { String msg = "Pool capacity is -1! pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg); return new Answer(cmd, false, msg); } Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>(); ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); return answer; } catch (XenAPIException e) { String msg = "ModifyStoragePoolCommand XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { String msg = "ModifyStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } protected Answer execute(DeleteStoragePoolCommand cmd) { StoragePoolVO pool = cmd.getPool(); try { Connection conn = getConnection(); SR sr = getStorageRepository(conn, pool); if (!checkSR(sr)) { String msg = "DeleteStoragePoolCommand checkSR failed! host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg); return new Answer(cmd, false, msg); } sr.setNameLabel(conn, pool.getUuid()); sr.setNameDescription(conn, pool.getName()); Answer answer = new Answer(cmd, true, "success"); return answer; } catch (XenAPIException e) { String msg = "DeleteStoragePoolCommand XenAPIException:" + e.toString() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + _host.uuid + " pool: " + pool.getName() + pool.getHostAddress() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } public Connection getConnection() { return _connPool.connect(_host.uuid, _host.ip, _username, _password, _wait); } protected void fillHostInfo(StartupRoutingCommand cmd) { long speed = 0; int cpus = 0; long ram = 0; Connection conn = getConnection(); long dom0Ram = 0; final StringBuilder caps = new StringBuilder(); try { Host host = Host.getByUuid(conn, _host.uuid); Host.Record hr = host.getRecord(conn); Map<String, String> details = cmd.getHostDetails(); if (details == null) { details = new HashMap<String, String>(); } if (_privateNetworkName != null) { details.put("private.network.device", _privateNetworkName); } if (_publicNetworkName != null) { details.put("public.network.device", _publicNetworkName); } if (_guestNetworkName != null) { details.put("guest.network.device", _guestNetworkName); } details.put("can_bridge_firewall", Boolean.toString(_canBridgeFirewall)); cmd.setHostDetails(details); cmd.setName(hr.nameLabel); cmd.setGuid(_host.uuid); cmd.setDataCenter(Long.toString(_dcId)); for (final String cap : hr.capabilities) { if (cap.length() > 0) { caps.append(cap).append(" , "); } } if (caps.length() > 0) { caps.delete(caps.length() - 3, caps.length()); } cmd.setCaps(caps.toString()); Set<HostCpu> hcs = host.getHostCPUs(conn); cpus = hcs.size(); for (final HostCpu hc : hcs) { speed = hc.getSpeed(conn); } cmd.setSpeed(speed); cmd.setCpus(cpus); long free = 0; HostMetrics hm = host.getMetrics(conn); ram = hm.getMemoryTotal(conn); free = hm.getMemoryFree(conn); Set<VM> vms = host.getResidentVMs(conn); for (VM vm : vms) { if (vm.getIsControlDomain(conn)) { dom0Ram = vm.getMemoryDynamicMax(conn); break; } } // assume the memory Virtualization overhead is 1/64 ram = (ram - dom0Ram) * 63/64; cmd.setMemory(ram); cmd.setDom0MinMemory(dom0Ram); if (s_logger.isDebugEnabled()) { s_logger.debug("Total Ram: " + ram + " Free Ram: " + free + " dom0 Ram: " + dom0Ram); } PIF pif = PIF.getByUuid(conn, _host.privatePif); PIF.Record pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setPrivateIpAddress(pifr.IP); cmd.setPrivateMacAddress(pifr.MAC); cmd.setPrivateNetmask(pifr.netmask); } pif = PIF.getByUuid(conn, _host.storagePif1); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setStorageIpAddress(pifr.IP); cmd.setStorageMacAddress(pifr.MAC); cmd.setStorageNetmask(pifr.netmask); } if (_host.storagePif2 != null) { pif = PIF.getByUuid(conn, _host.storagePif2); pifr = pif.getRecord(conn); if (pifr.IP != null && pifr.IP.length() > 0) { cmd.setStorageIpAddressDeux(pifr.IP); cmd.setStorageMacAddressDeux(pifr.MAC); cmd.setStorageNetmaskDeux(pifr.netmask); } } Map<String, String> configs = hr.otherConfig; cmd.setIqn(configs.get("iscsi_iqn")); cmd.setPod(_pod); cmd.setVersion(CitrixResourceBase.class.getPackage().getImplementationVersion()); } catch (final XmlRpcException e) { throw new CloudRuntimeException("XML RPC Exception" + e.getMessage(), e); } catch (XenAPIException e) { throw new CloudRuntimeException("XenAPIException" + e.toString(), e); } } public CitrixResourceBase() { } protected String getPatchPath() { return "scripts/vm/hypervisor/xenserver/xcpserver"; } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; _host.uuid = (String) params.get("guid"); try { _dcId = Long.parseLong((String) params.get("zone")); } catch (NumberFormatException e) { throw new ConfigurationException("Unable to get the zone " + params.get("zone")); } _name = _host.uuid; _host.ip = (String) params.get("url"); _username = (String) params.get("username"); _password = (String) params.get("password"); _pod = (String) params.get("pod"); _cluster = (String)params.get("cluster"); _privateNetworkName = (String) params.get("private.network.device"); _publicNetworkName = (String) params.get("public.network.device"); _guestNetworkName = (String)params.get("guest.network.device"); _linkLocalPrivateNetworkName = (String) params.get("private.linkLocal.device"); if (_linkLocalPrivateNetworkName == null) _linkLocalPrivateNetworkName = "cloud_link_local_network"; _storageNetworkName1 = (String) params.get("storage.network.device1"); if (_storageNetworkName1 == null) { _storageNetworkName1 = "cloud-stor1"; } _storageNetworkName2 = (String) params.get("storage.network.device2"); if (_storageNetworkName2 == null) { _storageNetworkName2 = "cloud-stor2"; } String value = (String) params.get("wait"); _wait = NumbersUtil.parseInt(value, 1800); if (_pod == null) { throw new ConfigurationException("Unable to get the pod"); } if (_host.ip == null) { throw new ConfigurationException("Unable to get the host address"); } if (_username == null) { throw new ConfigurationException("Unable to get the username"); } if (_password == null) { throw new ConfigurationException("Unable to get the password"); } if (_host.uuid == null) { throw new ConfigurationException("Unable to get the uuid"); } params.put("domr.scripts.dir", "scripts/network/domr"); String patchPath = getPatchPath(); _patchPath = Script.findScript(patchPath, "patch"); if (_patchPath == null) { throw new ConfigurationException("Unable to find all of patch files for xenserver"); } _storage = (StorageLayer) params.get(StorageLayer.InstanceConfigKey); if (_storage == null) { value = (String) params.get(StorageLayer.ClassConfigKey); if (value == null) { value = "com.cloud.storage.JavaStorageLayer"; } try { Class<?> clazz = Class.forName(value); _storage = (StorageLayer) ComponentLocator.inject(clazz); _storage.configure("StorageLayer", params); } catch (ClassNotFoundException e) { throw new ConfigurationException("Unable to find class " + value); } } return true; } void destroyVDI(VDI vdi) { try { Connection conn = getConnection(); vdi.destroy(conn); } catch (Exception e) { String msg = "destroy VDI failed due to " + e.toString(); s_logger.warn(msg); } } @Override public CreateAnswer execute(CreateCommand cmd) { StoragePoolTO pool = cmd.getPool(); DiskCharacteristics dskch = cmd.getDiskCharacteristics(); VDI vdi = null; Connection conn = getConnection(); try { SR poolSr = getStorageRepository(conn, pool); if (cmd.getTemplateUrl() != null) { VDI tmpltvdi = null; tmpltvdi = getVDIbyUuid(cmd.getTemplateUrl()); vdi = tmpltvdi.createClone(conn, new HashMap<String, String>()); vdi.setNameLabel(conn, dskch.getName()); } else { VDI.Record vdir = new VDI.Record(); vdir.nameLabel = dskch.getName(); vdir.SR = poolSr; vdir.type = Types.VdiType.USER; if(cmd.getSize()!=0) vdir.virtualSize = cmd.getSize(); else vdir.virtualSize = dskch.getSize(); vdi = VDI.create(conn, vdir); } VDI.Record vdir; vdir = vdi.getRecord(conn); s_logger.debug("Succesfully created VDI for " + cmd + ". Uuid = " + vdir.uuid); VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), Storage.StorageResourceType.STORAGE_POOL, pool.getType(), vdir.nameLabel, pool.getPath(), vdir.uuid, vdir.virtualSize); return new CreateAnswer(cmd, vol); } catch (Exception e) { s_logger.warn("Unable to create volume; Pool=" + pool + "; Disk: " + dskch, e); return new CreateAnswer(cmd, e); } } protected SR getISOSRbyVmName(String vmName) { Connection conn = getConnection(); try { Set<SR> srs = SR.getByNameLabel(conn, vmName + "-ISO"); if (srs.size() == 0) { return null; } else if (srs.size() == 1) { return srs.iterator().next(); } else { String msg = "getIsoSRbyVmName failed due to there are more than 1 SR having same Label"; s_logger.warn(msg); } } catch (XenAPIException e) { String msg = "getIsoSRbyVmName failed due to " + e.toString(); s_logger.warn(msg, e); } catch (Exception e) { String msg = "getIsoSRbyVmName failed due to " + e.getMessage(); s_logger.warn(msg, e); } return null; } protected SR createNfsSRbyURI(URI uri, boolean shared) { try { Connection conn = getConnection(); if (s_logger.isDebugEnabled()) { s_logger.debug("Creating a " + (shared ? "shared SR for " : "not shared SR for ") + uri); } Map<String, String> deviceConfig = new HashMap<String, String>(); String path = uri.getPath(); path = path.replace("//", "/"); deviceConfig.put("server", uri.getHost()); deviceConfig.put("serverpath", path); String name = UUID.nameUUIDFromBytes(new String(uri.getHost() + path).getBytes()).toString(); if (!shared) { Set<SR> srs = SR.getByNameLabel(conn, name); for (SR sr : srs) { SR.Record record = sr.getRecord(conn); if (SRType.NFS.equals(record.type) && record.contentType.equals("user") && !record.shared) { removeSRSync(sr); } } } Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), name, uri.getHost() + uri.getPath(), SRType.NFS.toString(), "user", shared, new HashMap<String, String>()); if( !checkSR(sr) ) { throw new Exception("no attached PBD"); } if (s_logger.isDebugEnabled()) { s_logger.debug(logX(sr, "Created a SR; UUID is " + sr.getUuid(conn))); } sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Can not create second storage SR mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Can not create second storage SR mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected SR createIsoSRbyURI(URI uri, String vmName, boolean shared) { try { Connection conn = getConnection(); Map<String, String> deviceConfig = new HashMap<String, String>(); String path = uri.getPath(); path = path.replace("//", "/"); deviceConfig.put("location", uri.getHost() + ":" + uri.getPath()); Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), uri.getHost() + uri.getPath(), "iso", "iso", "iso", shared, new HashMap<String, String>()); sr.setNameLabel(conn, vmName + "-ISO"); sr.setNameDescription(conn, deviceConfig.get("location")); sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "createIsoSRbyURI failed! mountpoint: " + uri.getHost() + uri.getPath() + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected VDI getVDIbyLocationandSR(String loc, SR sr) { Connection conn = getConnection(); try { Set<VDI> vdis = sr.getVDIs(conn); for (VDI vdi : vdis) { if (vdi.getLocation(conn).startsWith(loc)) { return vdi; } } String msg = "can not getVDIbyLocationandSR " + loc; s_logger.warn(msg); return null; } catch (XenAPIException e) { String msg = "getVDIbyLocationandSR exception " + loc + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "getVDIbyLocationandSR exception " + loc + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected VDI getVDIbyUuid(String uuid) { try { Connection conn = getConnection(); return VDI.getByUuid(conn, uuid); } catch (XenAPIException e) { String msg = "VDI getByUuid for uuid: " + uuid + " failed due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "VDI getByUuid for uuid: " + uuid + " failed due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } protected SR getIscsiSR(Connection conn, StoragePoolVO pool) { synchronized (pool.getUuid().intern()) { Map<String, String> deviceConfig = new HashMap<String, String>(); try { String target = pool.getHostAddress().trim(); String path = pool.getPath().trim(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String tmp[] = path.split("/"); if (tmp.length != 3) { String msg = "Wrong iscsi path " + pool.getPath() + " it should be /targetIQN/LUN"; s_logger.warn(msg); throw new CloudRuntimeException(msg); } String targetiqn = tmp[1].trim(); String lunid = tmp[2].trim(); String scsiid = ""; Set<SR> srs = SR.getByNameLabel(conn, pool.getUuid()); for (SR sr : srs) { if (!SRType.LVMOISCSI.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("target") == null) continue; if (dc.get("targetIQN") == null) continue; if (dc.get("lunid") == null) continue; if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { return sr; } } deviceConfig.put("target", target); deviceConfig.put("targetIQN", targetiqn); Host host = Host.getByUuid(conn, _host.uuid); SR sr = null; try { sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), pool.getName(), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); } catch (XenAPIException e) { String errmsg = e.toString(); if (errmsg.contains("SR_BACKEND_FAILURE_107")) { String lun[] = errmsg.split("<LUN>"); boolean found = false; for (int i = 1; i < lun.length; i++) { int blunindex = lun[i].indexOf("<LUNid>") + 7; int elunindex = lun[i].indexOf("</LUNid>"); String ilun = lun[i].substring(blunindex, elunindex); ilun = ilun.trim(); if (ilun.equals(lunid)) { int bscsiindex = lun[i].indexOf("<SCSIid>") + 8; int escsiindex = lun[i].indexOf("</SCSIid>"); scsiid = lun[i].substring(bscsiindex, escsiindex); scsiid = scsiid.trim(); found = true; break; } } if (!found) { String msg = "can not find LUN " + lunid + " in " + errmsg; s_logger.warn(msg); throw new CloudRuntimeException(msg); } } else { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } deviceConfig.put("SCSIid", scsiid); sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), pool.getName(), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); if( !checkSR(sr) ) { throw new Exception("no attached PBD"); } sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } } protected SR getIscsiSR(Connection conn, StoragePoolTO pool) { synchronized (pool.getUuid().intern()) { Map<String, String> deviceConfig = new HashMap<String, String>(); try { String target = pool.getHost(); String path = pool.getPath(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String tmp[] = path.split("/"); if (tmp.length != 3) { String msg = "Wrong iscsi path " + pool.getPath() + " it should be /targetIQN/LUN"; s_logger.warn(msg); throw new CloudRuntimeException(msg); } String targetiqn = tmp[1].trim(); String lunid = tmp[2].trim(); String scsiid = ""; Set<SR> srs = SR.getByNameLabel(conn, pool.getUuid()); for (SR sr : srs) { if (!SRType.LVMOISCSI.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("target") == null) continue; if (dc.get("targetIQN") == null) continue; if (dc.get("lunid") == null) continue; if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { if (checkSR(sr)) { return sr; } } } deviceConfig.put("target", target); deviceConfig.put("targetIQN", targetiqn); Host host = Host.getByUuid(conn, _host.uuid); SR sr = null; try { sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); } catch (XenAPIException e) { String errmsg = e.toString(); if (errmsg.contains("SR_BACKEND_FAILURE_107")) { String lun[] = errmsg.split("<LUN>"); boolean found = false; for (int i = 1; i < lun.length; i++) { int blunindex = lun[i].indexOf("<LUNid>") + 7; int elunindex = lun[i].indexOf("</LUNid>"); String ilun = lun[i].substring(blunindex, elunindex); ilun = ilun.trim(); if (ilun.equals(lunid)) { int bscsiindex = lun[i].indexOf("<SCSIid>") + 8; int escsiindex = lun[i].indexOf("</SCSIid>"); scsiid = lun[i].substring(bscsiindex, escsiindex); scsiid = scsiid.trim(); found = true; break; } } if (!found) { String msg = "can not find LUN " + lunid + " in " + errmsg; s_logger.warn(msg); throw new CloudRuntimeException(msg); } } else { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } deviceConfig.put("SCSIid", scsiid); sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.LVMOISCSI.toString(), "user", true, new HashMap<String, String>()); sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Unable to create Iscsi SR " + deviceConfig + " due to " + e.getMessage(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } } } protected SR getNfsSR(StoragePoolVO pool) { Connection conn = getConnection(); Map<String, String> deviceConfig = new HashMap<String, String>(); try { String server = pool.getHostAddress(); String serverpath = pool.getPath(); serverpath = serverpath.replace("//", "/"); Set<SR> srs = SR.getAll(conn); for (SR sr : srs) { if (!SRType.NFS.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("server") == null) continue; if (dc.get("serverpath") == null) continue; if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { if (checkSR(sr)) { return sr; } } } deviceConfig.put("server", server); deviceConfig.put("serverpath", serverpath); Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), pool.getName(), SRType.NFS.toString(), "user", true, new HashMap<String, String>()); sr.scan(conn); return sr; } catch (XenAPIException e) { String msg = "Unable to create NFS SR " + deviceConfig + " due to " + e.toString(); s_logger.warn(msg, e); throw new CloudRuntimeException(msg, e); } catch (Exception e) { String msg = "Unable to create NFS SR " + deviceConfig + " due to " + e.getMessage(); s_logger.warn(msg); throw new CloudRuntimeException(msg, e); } } protected SR getNfsSR(Connection conn, StoragePoolTO pool) { Map<String, String> deviceConfig = new HashMap<String, String>(); String server = pool.getHost(); String serverpath = pool.getPath(); serverpath = serverpath.replace("//", "/"); try { Set<SR> srs = SR.getAll(conn); for (SR sr : srs) { if (!SRType.NFS.equals(sr.getType(conn))) continue; Set<PBD> pbds = sr.getPBDs(conn); if (pbds.isEmpty()) continue; PBD pbd = pbds.iterator().next(); Map<String, String> dc = pbd.getDeviceConfig(conn); if (dc == null) continue; if (dc.get("server") == null) continue; if (dc.get("serverpath") == null) continue; if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { return sr; } } deviceConfig.put("server", server); deviceConfig.put("serverpath", serverpath); Host host = Host.getByUuid(conn, _host.uuid); SR sr = SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true, new HashMap<String, String>()); sr.scan(conn); return sr; } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e); } catch (XmlRpcException e) { throw new CloudRuntimeException("Unable to create NFS SR " + pool.toString(), e); } } @Override public Answer execute(DestroyCommand cmd) { VolumeTO vol = cmd.getVolume(); Connection conn = getConnection(); // Look up the VDI String volumeUUID = vol.getPath(); VDI vdi = null; try { vdi = getVDIbyUuid(volumeUUID); } catch (Exception e) { String msg = "getVDIbyUuid for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg); return new Answer(cmd, true, "Success"); } Set<VBD> vbds = null; try { vbds = vdi.getVBDs(conn); } catch (Exception e) { String msg = "VDI getVBDS for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } for (VBD vbd : vbds) { try { vbd.unplug(conn); vbd.destroy(conn); } catch (Exception e) { String msg = "VM destroy for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } try { vdi.destroy(conn); } catch (Exception e) { String msg = "VDI destroy for " + volumeUUID + " failed due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd, true, "Success"); } @Override public ShareAnswer execute(final ShareCommand cmd) { if (!cmd.isShare()) { SR sr = getISOSRbyVmName(cmd.getVmName()); Connection conn = getConnection(); try { if (sr != null) { Set<VM> vms = VM.getByNameLabel(conn, cmd.getVmName()); if (vms.size() == 0) { removeSR(sr); } } } catch (Exception e) { String msg = "SR.getNameLabel failed due to " + e.getMessage() + e.toString(); s_logger.warn(msg); } } return new ShareAnswer(cmd, new HashMap<String, Integer>()); } @Override public CopyVolumeAnswer execute(final CopyVolumeCommand cmd) { String volumeUUID = cmd.getVolumePath(); StoragePoolVO pool = cmd.getPool(); String secondaryStorageURL = cmd.getSecondaryStorageURL(); URI uri = null; try { uri = new URI(secondaryStorageURL); } catch (URISyntaxException e) { return new CopyVolumeAnswer(cmd, false, "Invalid secondary storage URL specified.", null, null); } String remoteVolumesMountPath = uri.getHost() + ":" + uri.getPath() + "/volumes/"; String volumeFolder = String.valueOf(cmd.getVolumeId()) + "/"; boolean toSecondaryStorage = cmd.toSecondaryStorage(); String errorMsg = "Failed to copy volume"; SR primaryStoragePool = null; SR secondaryStorage = null; VDI srcVolume = null; VDI destVolume = null; Connection conn = getConnection(); try { if (toSecondaryStorage) { // Create the volume folder if (!createSecondaryStorageFolder(remoteVolumesMountPath, volumeFolder)) { throw new InternalErrorException("Failed to create the volume folder."); } // Create a SR for the volume UUID folder secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false); // Look up the volume on the source primary storage pool srcVolume = getVDIbyUuid(volumeUUID); // Copy the volume to secondary storage destVolume = cloudVDIcopy(srcVolume, secondaryStorage); } else { // Mount the volume folder secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false); // Look up the volume on secondary storage Set<VDI> vdis = secondaryStorage.getVDIs(conn); for (VDI vdi : vdis) { if (vdi.getUuid(conn).equals(volumeUUID)) { srcVolume = vdi; break; } } if (srcVolume == null) { throw new InternalErrorException("Failed to find volume on secondary storage."); } // Copy the volume to the primary storage pool primaryStoragePool = getStorageRepository(conn, pool); destVolume = cloudVDIcopy(srcVolume, primaryStoragePool); } String srUUID; if (primaryStoragePool == null) { srUUID = secondaryStorage.getUuid(conn); } else { srUUID = primaryStoragePool.getUuid(conn); } String destVolumeUUID = destVolume.getUuid(conn); return new CopyVolumeAnswer(cmd, true, null, srUUID, destVolumeUUID); } catch (XenAPIException e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new CopyVolumeAnswer(cmd, false, e.toString(), null, null); } catch (Exception e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null); } finally { if (!toSecondaryStorage && srcVolume != null) { // Delete the volume on secondary storage destroyVDI(srcVolume); } removeSR(secondaryStorage); if (!toSecondaryStorage) { // Delete the volume folder on secondary storage deleteSecondaryStorageFolder(remoteVolumesMountPath, volumeFolder); } } } protected AttachVolumeAnswer execute(final AttachVolumeCommand cmd) { boolean attach = cmd.getAttach(); String vmName = cmd.getVmName(); Long deviceId = cmd.getDeviceId(); String errorMsg; if (attach) { errorMsg = "Failed to attach volume"; } else { errorMsg = "Failed to detach volume"; } Connection conn = getConnection(); try { // Look up the VDI VDI vdi = mount(cmd.getPooltype(), cmd.getVolumeFolder(),cmd.getVolumePath()); // Look up the VM VM vm = getVM(conn, vmName); /* For HVM guest, if no pv driver installed, no attach/detach */ boolean isHVM; if (vm.getPVBootloader(conn).equalsIgnoreCase("")) isHVM = true; else isHVM = false; VMGuestMetrics vgm = vm.getGuestMetrics(conn); boolean pvDrvInstalled = false; if (!isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) { pvDrvInstalled = true; } if (isHVM && !pvDrvInstalled) { s_logger.warn(errorMsg + ": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected"); return new AttachVolumeAnswer(cmd, "You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); } if (attach) { // Figure out the disk number to attach the VM to String diskNumber = null; if( deviceId != null ) { if( deviceId.longValue() == 3 ) { String msg = "Device 3 is reserved for CD-ROM, choose other device"; return new AttachVolumeAnswer(cmd,msg); } if(isDeviceUsed(vm, deviceId)) { String msg = "Device " + deviceId + " is used in VM " + vmName; return new AttachVolumeAnswer(cmd,msg); } diskNumber = deviceId.toString(); } else { diskNumber = getUnusedDeviceNum(vm); } // Create a new VBD VBD.Record vbdr = new VBD.Record(); vbdr.VM = vm; vbdr.VDI = vdi; vbdr.bootable = false; vbdr.userdevice = diskNumber; vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; VBD vbd = VBD.create(conn, vbdr); // Attach the VBD to the VM vbd.plug(conn); // Update the VDI's label to include the VM name vdi.setNameLabel(conn, vmName + "-DATA"); return new AttachVolumeAnswer(cmd, Long.parseLong(diskNumber)); } else { // Look up all VBDs for this VDI Set<VBD> vbds = vdi.getVBDs(conn); // Detach each VBD from its VM, and then destroy it for (VBD vbd : vbds) { VBD.Record vbdr = vbd.getRecord(conn); if (vbdr.currentlyAttached) { vbd.unplug(conn); } vbd.destroy(conn); } // Update the VDI's label to be "detached" vdi.setNameLabel(conn, "detached"); umount(vdi); return new AttachVolumeAnswer(cmd); } } catch (XenAPIException e) { String msg = errorMsg + " for uuid: " + cmd.getVolumePath() + " due to " + e.toString(); s_logger.warn(msg, e); return new AttachVolumeAnswer(cmd, msg); } catch (Exception e) { String msg = errorMsg + " for uuid: " + cmd.getVolumePath() + " due to " + e.getMessage(); s_logger.warn(msg, e); return new AttachVolumeAnswer(cmd, msg); } } protected void umount(VDI vdi) { } protected Answer execute(final AttachIsoCommand cmd) { boolean attach = cmd.isAttach(); String vmName = cmd.getVmName(); String isoURL = cmd.getIsoPath(); String errorMsg; if (attach) { errorMsg = "Failed to attach ISO"; } else { errorMsg = "Failed to detach ISO"; } Connection conn = getConnection(); try { if (attach) { VBD isoVBD = null; // Find the VM VM vm = getVM(conn, vmName); // Find the ISO VDI VDI isoVDI = getIsoVDIByURL(conn, vmName, isoURL); // Find the VM's CD-ROM VBD Set<VBD> vbds = vm.getVBDs(conn); for (VBD vbd : vbds) { String userDevice = vbd.getUserdevice(conn); Types.VbdType type = vbd.getType(conn); if (userDevice.equals("3") && type == Types.VbdType.CD) { isoVBD = vbd; break; } } if (isoVBD == null) { throw new CloudRuntimeException("Unable to find CD-ROM VBD for VM: " + vmName); } else { // If an ISO is already inserted, eject it if (isoVBD.getEmpty(conn) == false) { isoVBD.eject(conn); } // Insert the new ISO isoVBD.insert(conn, isoVDI); } return new Answer(cmd); } else { // Find the VM VM vm = getVM(conn, vmName); String vmUUID = vm.getUuid(conn); // Find the ISO VDI VDI isoVDI = getIsoVDIByURL(conn, vmName, isoURL); SR sr = isoVDI.getSR(conn); // Look up all VBDs for this VDI Set<VBD> vbds = isoVDI.getVBDs(conn); // Iterate through VBDs, and if the VBD belongs the VM, eject // the ISO from it for (VBD vbd : vbds) { VM vbdVM = vbd.getVM(conn); String vbdVmUUID = vbdVM.getUuid(conn); if (vbdVmUUID.equals(vmUUID)) { // If an ISO is already inserted, eject it if (!vbd.getEmpty(conn)) { vbd.eject(conn); } break; } } if (!sr.getNameLabel(conn).startsWith("XenServer Tools")) { removeSR(sr); } return new Answer(cmd); } } catch (XenAPIException e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new Answer(cmd, false, e.toString()); } catch (Exception e) { s_logger.warn(errorMsg + ": " + e.toString(), e); return new Answer(cmd, false, e.getMessage()); } } protected ValidateSnapshotAnswer execute(final ValidateSnapshotCommand cmd) { String primaryStoragePoolNameLabel = cmd.getPrimaryStoragePoolNameLabel(); String volumeUuid = cmd.getVolumeUuid(); // Precondition: not null String firstBackupUuid = cmd.getFirstBackupUuid(); String previousSnapshotUuid = cmd.getPreviousSnapshotUuid(); String templateUuid = cmd.getTemplateUuid(); // By default assume failure String details = "Could not validate previous snapshot backup UUID " + "because the primary Storage SR could not be created from the name label: " + primaryStoragePoolNameLabel; boolean success = false; String expectedSnapshotBackupUuid = null; String actualSnapshotBackupUuid = null; String actualSnapshotUuid = null; Boolean isISCSI = false; String primaryStorageSRUuid = null; Connection conn = getConnection(); try { SR primaryStorageSR = getSRByNameLabelandHost(primaryStoragePoolNameLabel); if (primaryStorageSR != null) { primaryStorageSRUuid = primaryStorageSR.getUuid(conn); isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); } } catch (BadServerResponse e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } catch (XenAPIException e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } catch (XmlRpcException e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } if (primaryStorageSRUuid != null) { if (templateUuid == null) { templateUuid = ""; } if (firstBackupUuid == null) { firstBackupUuid = ""; } if (previousSnapshotUuid == null) { previousSnapshotUuid = ""; } String result = callHostPlugin("vmopsSnapshot", "validateSnapshot", "primaryStorageSRUuid", primaryStorageSRUuid, "volumeUuid", volumeUuid, "firstBackupUuid", firstBackupUuid, "previousSnapshotUuid", previousSnapshotUuid, "templateUuid", templateUuid, "isISCSI", isISCSI.toString()); if (result == null || result.isEmpty()) { details = "Validating snapshot backup for volume with UUID: " + volumeUuid + " failed because there was an exception in the plugin"; // callHostPlugin exception which has been logged already } else { String[] uuids = result.split("#", -1); if (uuids.length >= 3) { expectedSnapshotBackupUuid = uuids[1]; actualSnapshotBackupUuid = uuids[2]; } if (uuids.length >= 4) { actualSnapshotUuid = uuids[3]; } else { actualSnapshotUuid = ""; } if (uuids[0].equals("1")) { success = true; details = null; } else { details = "Previous snapshot backup on the primary storage is invalid. " + "Expected: " + expectedSnapshotBackupUuid + " Actual: " + actualSnapshotBackupUuid; // success is still false } s_logger.debug("ValidatePreviousSnapshotBackup returned " + " success: " + success + " details: " + details + " expectedSnapshotBackupUuid: " + expectedSnapshotBackupUuid + " actualSnapshotBackupUuid: " + actualSnapshotBackupUuid + " actualSnapshotUuid: " + actualSnapshotUuid); } } return new ValidateSnapshotAnswer(cmd, success, details, expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); } protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) { long snapshotId = cmd.getSnapshotId(); String snapshotName = cmd.getSnapshotName(); // By default assume failure boolean success = false; String cmdSwitch = cmd.getCommandSwitch(); String snapshotOp = "Unsupported snapshot command." + cmdSwitch; if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { snapshotOp = "create"; } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { snapshotOp = "destroy"; } String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; String snapshotUUID = null; Connection conn = getConnection(); try { if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { // Look up the volume String volumeUUID = cmd.getVolumePath(); VDI volume = getVDIbyUuid(volumeUUID); // Create a snapshot VDI snapshot = volume.snapshot(conn, new HashMap<String, String>()); if (snapshotName != null) { snapshot.setNameLabel(conn, snapshotName); } // Determine the UUID of the snapshot VDI.Record vdir = snapshot.getRecord(conn); snapshotUUID = vdir.uuid; success = true; details = null; } else if (cmd.getCommandSwitch().equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { // Look up the snapshot snapshotUUID = cmd.getSnapshotPath(); VDI snapshot = getVDIbyUuid(snapshotUUID); snapshot.destroy(conn); snapshotUUID = null; success = true; details = null; } } catch (XenAPIException e) { details += ", reason: " + e.toString(); s_logger.warn(details, e); } catch (Exception e) { details += ", reason: " + e.toString(); s_logger.warn(details, e); } return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); } protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateCommand cmd) { String secondaryStorageURL = cmd.getSecondaryStorageURL(); String snapshotUUID = cmd.getSnapshotPath(); String userSpecifiedName = cmd.getTemplateName(); SR secondaryStorage = null; VDI privateTemplate = null; Connection conn = getConnection(); try { URI uri = new URI(secondaryStorageURL); String remoteTemplateMountPath = uri.getHost() + ":" + uri.getPath() + "/template/"; String templateFolder = cmd.getAccountId() + "/" + cmd.getTemplateId() + "/"; String templateDownloadFolder = createTemplateDownloadFolder(remoteTemplateMountPath, templateFolder); String templateInstallFolder = "tmpl/" + templateFolder; // Create a SR for the secondary storage download folder secondaryStorage = createNfsSRbyURI(new URI(secondaryStorageURL + "/template/" + templateDownloadFolder), false); // Look up the snapshot and copy it to secondary storage VDI snapshot = getVDIbyUuid(snapshotUUID); privateTemplate = cloudVDIcopy(snapshot, secondaryStorage); if (userSpecifiedName != null) { privateTemplate.setNameLabel(conn, userSpecifiedName); } // Determine the template file name and install path VDI.Record vdir = privateTemplate.getRecord(conn); String templateName = vdir.uuid; String templateFilename = templateName + ".vhd"; String installPath = "template/" + templateInstallFolder + templateFilename; // Determine the template's virtual size and then forget the VDI long virtualSize = privateTemplate.getVirtualSize(conn); // Create the template.properties file in the download folder, move // the template and the template.properties file // to the install folder, and then delete the download folder if (!postCreatePrivateTemplate(remoteTemplateMountPath, templateDownloadFolder, templateInstallFolder, templateFilename, templateName, userSpecifiedName, null, virtualSize, cmd.getTemplateId())) { throw new InternalErrorException("Failed to create the template.properties file."); } return new CreatePrivateTemplateAnswer(cmd, true, null, installPath, virtualSize, templateName, ImageFormat.VHD); } catch (XenAPIException e) { if (privateTemplate != null) { destroyVDI(privateTemplate); } s_logger.warn("CreatePrivateTemplate Failed due to " + e.toString(), e); return new CreatePrivateTemplateAnswer(cmd, false, e.toString(), null, 0, null, null); } catch (Exception e) { s_logger.warn("CreatePrivateTemplate Failed due to " + e.getMessage(), e); return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage(), null, 0, null, null); } finally { // Remove the secondary storage SR removeSR(secondaryStorage); } } private String createTemplateDownloadFolder(String remoteTemplateMountPath, String templateFolder) throws InternalErrorException, URISyntaxException { String templateDownloadFolder = "download/" + _host.uuid + "/" + templateFolder; // Create the download folder if (!createSecondaryStorageFolder(remoteTemplateMountPath, templateDownloadFolder)) { throw new InternalErrorException("Failed to create the template download folder."); } return templateDownloadFolder; } protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) { String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String backedUpSnapshotUuid = cmd.getSnapshotUuid(); String origTemplateInstallPath = cmd.getOrigTemplateInstallPath(); Long newTemplateId = cmd.getNewTemplateId(); String userSpecifiedName = cmd.getTemplateName(); // By default, assume failure String details = "Failed to create private template " + newTemplateId + " from snapshot for volume: " + volumeId + " with backupUuid: " + backedUpSnapshotUuid; String newTemplatePath = null; String templateName = null; boolean result = false; long virtualSize = 0; try { URI uri = new URI(secondaryStoragePoolURL); String remoteTemplateMountPath = uri.getHost() + ":" + uri.getPath() + "/template/"; String templateFolder = cmd.getAccountId() + "/" + newTemplateId + "/"; String templateDownloadFolder = createTemplateDownloadFolder(remoteTemplateMountPath, templateFolder); String templateInstallFolder = "tmpl/" + templateFolder; // Yes, create a template vhd Pair<VHDInfo, String> vhdDetails = createVHDFromSnapshot(primaryStorageNameLabel, dcId, accountId, volumeId, secondaryStoragePoolURL, backedUpSnapshotUuid, origTemplateInstallPath, templateDownloadFolder); VHDInfo vhdInfo = vhdDetails.first(); String failureDetails = vhdDetails.second(); if (vhdInfo == null) { if (failureDetails != null) { details += failureDetails; } } else { templateName = vhdInfo.getUuid(); String templateFilename = templateName + ".vhd"; String templateInstallPath = templateInstallFolder + "/" + templateFilename; newTemplatePath = "template" + "/" + templateInstallPath; virtualSize = vhdInfo.getVirtualSize(); // create the template.properties file result = postCreatePrivateTemplate(remoteTemplateMountPath, templateDownloadFolder, templateInstallFolder, templateFilename, templateName, userSpecifiedName, null, virtualSize, newTemplateId); if (!result) { details += ", reason: Could not create the template.properties file on secondary storage dir: " + templateInstallFolder; } else { // Aaah, success. details = null; } } } catch (XenAPIException e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } catch (Exception e) { details += ", reason: " + e.getMessage(); s_logger.error(details, e); } return new CreatePrivateTemplateAnswer(cmd, result, details, newTemplatePath, virtualSize, templateName, ImageFormat.VHD); } protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) { String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String snapshotUuid = cmd.getSnapshotUuid(); // not null: Precondition. String prevSnapshotUuid = cmd.getPrevSnapshotUuid(); String prevBackupUuid = cmd.getPrevBackupUuid(); boolean isFirstSnapshotOfRootVolume = cmd.isFirstSnapshotOfRootVolume(); // By default assume failure String details = null; boolean success = false; String snapshotBackupUuid = null; try { Connection conn = getConnection(); SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); URI uri = new URI(secondaryStoragePoolURL); String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details = "Couldn't backup snapshot because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { boolean gcHappened = true; if (gcHappened) { snapshotBackupUuid = backupSnapshot(primaryStorageSRUuid, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotUuid, prevSnapshotUuid, prevBackupUuid, isFirstSnapshotOfRootVolume, isISCSI); success = (snapshotBackupUuid != null); } else { s_logger.warn("GC hasn't happened yet for previousSnapshotUuid: " + prevSnapshotUuid + ". Will retry again after 1 min"); } } if (!success) { // Mark the snapshot as removed in the database. // When the next snapshot is taken, it will be // 1) deleted from the DB 2) The snapshotUuid will be deleted from the primary // 3) the snapshotBackupUuid will be copied to secondary // 4) if possible it will be coalesced with the next snapshot. } else if (prevSnapshotUuid != null && !isFirstSnapshotOfRootVolume) { // Destroy the previous snapshot, if it exists. // We destroy the previous snapshot only if the current snapshot // backup succeeds. // The aim is to keep the VDI of the last 'successful' snapshot // so that it doesn't get merged with the // new one // and muddle the vhd chain on the secondary storage. details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage."; destroySnapshotOnPrimaryStorage(prevSnapshotUuid); } } catch (XenAPIException e) { details = "BackupSnapshot Failed due to " + e.toString(); s_logger.warn(details, e); } catch (Exception e) { details = "BackupSnapshot Failed due to " + e.getMessage(); s_logger.warn(details, e); } return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid); } protected CreateVolumeFromSnapshotAnswer execute(final CreateVolumeFromSnapshotCommand cmd) { String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String backedUpSnapshotUuid = cmd.getSnapshotUuid(); String templatePath = cmd.getTemplatePath(); // By default, assume the command has failed and set the params to be // passed to CreateVolumeFromSnapshotAnswer appropriately boolean result = false; // Generic error message. String details = "Failed to create volume from snapshot for volume: " + volumeId + " with backupUuid: " + backedUpSnapshotUuid; String vhdUUID = null; SR temporarySROnSecondaryStorage = null; String mountPointOfTemporaryDirOnSecondaryStorage = null; try { VDI vdi = null; Connection conn = getConnection(); SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); // Get the absolute path of the template on the secondary storage. URI uri = new URI(secondaryStoragePoolURL); String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details += " because the URL passed: " + secondaryStoragePoolURL + " is invalid."; return new CreateVolumeFromSnapshotAnswer(cmd, result, details, vhdUUID); } // Create a volume and not a template String templateDownloadFolder = ""; VHDInfo vhdInfo = createVHDFromSnapshot(dcId, accountId, volumeId, secondaryStorageMountPath, backedUpSnapshotUuid, templatePath, templateDownloadFolder, isISCSI); if (vhdInfo == null) { details += " because the vmops plugin on XenServer failed at some point"; } else { vhdUUID = vhdInfo.getUuid(); String tempDirRelativePath = "snapshots" + File.separator + accountId + File.separator + volumeId + "_temp"; mountPointOfTemporaryDirOnSecondaryStorage = secondaryStorageMountPath + File.separator + tempDirRelativePath; uri = new URI("nfs://" + mountPointOfTemporaryDirOnSecondaryStorage); // No need to check if the SR already exists. It's a temporary // SR destroyed when this method exits. // And two createVolumeFromSnapshot operations cannot proceed at // the same time. temporarySROnSecondaryStorage = createNfsSRbyURI(uri, false); if (temporarySROnSecondaryStorage == null) { details += "because SR couldn't be created on " + mountPointOfTemporaryDirOnSecondaryStorage; } else { s_logger.debug("Successfully created temporary SR on secondary storage " + temporarySROnSecondaryStorage.getNameLabel(conn) + "with uuid " + temporarySROnSecondaryStorage.getUuid(conn) + " and scanned it"); // createNFSSRbyURI also scans the SR and introduces the VDI vdi = getVDIbyUuid(vhdUUID); if (vdi != null) { s_logger.debug("Successfully created VDI on secondary storage SR " + temporarySROnSecondaryStorage.getNameLabel(conn) + " with uuid " + vhdUUID); s_logger.debug("Copying VDI: " + vdi.getLocation(conn) + " from secondary to primary"); VDI vdiOnPrimaryStorage = cloudVDIcopy(vdi, primaryStorageSR); // vdi.copy introduces the vdi into the database. Don't // need to do a scan on the primary // storage. if (vdiOnPrimaryStorage != null) { vhdUUID = vdiOnPrimaryStorage.getUuid(conn); s_logger.debug("Successfully copied and introduced VDI on primary storage with path " + vdiOnPrimaryStorage.getLocation(conn) + " and uuid " + vhdUUID); result = true; details = null; } else { details += ". Could not copy the vdi " + vhdUUID + " to primary storage"; } // The VHD on temporary was scanned and introduced as a VDI // destroy it as we don't need it anymore. vdi.destroy(conn); } else { details += ". Could not scan and introduce vdi with uuid: " + vhdUUID; } } } } catch (XenAPIException e) { details += " due to " + e.toString(); s_logger.warn(details, e); } catch (Exception e) { details += " due to " + e.getMessage(); s_logger.warn(details, e); } finally { // In all cases, if the temporary SR was created, forget it. if (temporarySROnSecondaryStorage != null) { removeSR(temporarySROnSecondaryStorage); // Delete the temporary directory created. File folderPath = new File(mountPointOfTemporaryDirOnSecondaryStorage); String remoteMountPath = folderPath.getParent(); String folder = folderPath.getName(); deleteSecondaryStorageFolder(remoteMountPath, folder); } } if (!result) { // Is this logged at a higher level? s_logger.error(details); } // In all cases return something. return new CreateVolumeFromSnapshotAnswer(cmd, result, details, vhdUUID); } protected DeleteSnapshotBackupAnswer execute(final DeleteSnapshotBackupCommand cmd) { Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String backupUUID = cmd.getSnapshotUuid(); String childUUID = cmd.getChildUUID(); String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); String details = null; boolean success = false; SR primaryStorageSR = null; Boolean isISCSI = false; try { Connection conn = getConnection(); primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { details = "Primary Storage SR could not be created from the name label: " + primaryStorageNameLabel; throw new InternalErrorException(details); } isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); } catch (XenAPIException e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } catch (Exception e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } if (primaryStorageSR != null) { URI uri = null; try { uri = new URI(secondaryStoragePoolURL); } catch (URISyntaxException e) { details = "Error finding the secondary storage URL" + e.getMessage(); s_logger.error(details, e); } if (uri != null) { String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details = "Couldn't delete snapshot because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { details = deleteSnapshotBackup(dcId, accountId, volumeId, secondaryStorageMountPath, backupUUID, childUUID, isISCSI); success = (details != null && details.equals("1")); if (success) { s_logger.debug("Successfully deleted snapshot backup " + backupUUID); } } } } return new DeleteSnapshotBackupAnswer(cmd, success, details); } protected Answer execute(DeleteSnapshotsDirCommand cmd) { Long dcId = cmd.getDataCenterId(); Long accountId = cmd.getAccountId(); Long volumeId = cmd.getVolumeId(); String secondaryStoragePoolURL = cmd.getSecondaryStoragePoolURL(); String snapshotUUID = cmd.getSnapshotUuid(); String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); String details = null; boolean success = false; SR primaryStorageSR = null; try { primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { details = "Primary Storage SR could not be created from the name label: " + primaryStorageNameLabel; } } catch (XenAPIException e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } catch (Exception e) { details = "Couldn't determine primary SR type " + e.getMessage(); s_logger.error(details, e); } if (primaryStorageSR != null) { if (snapshotUUID != null) { VDI snapshotVDI = getVDIbyUuid(snapshotUUID); if (snapshotVDI != null) { destroyVDI(snapshotVDI); } } } URI uri = null; try { uri = new URI(secondaryStoragePoolURL); } catch (URISyntaxException e) { details = "Error finding the secondary storage URL" + e.getMessage(); s_logger.error(details, e); } if (uri != null) { String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); if (secondaryStorageMountPath == null) { details = "Couldn't delete snapshotsDir because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { details = deleteSnapshotsDir(dcId, accountId, volumeId, secondaryStorageMountPath); success = (details != null && details.equals("1")); if (success) { s_logger.debug("Successfully deleted snapshotsDir for volume: " + volumeId); } } } return new Answer(cmd, success, details); } protected VM getVM(Connection conn, String vmName) { // Look up VMs with the specified name Set<VM> vms; try { vms = VM.getByNameLabel(conn, vmName); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get " + vmName + ": " + e.toString(), e); } catch (Exception e) { throw new CloudRuntimeException("Unable to get " + vmName + ": " + e.getMessage(), e); } // If there are no VMs, throw an exception if (vms.size() == 0) throw new CloudRuntimeException("VM with name: " + vmName + " does not exist."); // If there is more than one VM, print a warning if (vms.size() > 1) s_logger.warn("Found " + vms.size() + " VMs with name: " + vmName); // Return the first VM in the set return vms.iterator().next(); } protected VDI getIsoVDIByURL(Connection conn, String vmName, String isoURL) { SR isoSR = null; String mountpoint = null; if (isoURL.startsWith("xs-tools")) { try { Set<VDI> vdis = VDI.getByNameLabel(conn, isoURL); if (vdis.isEmpty()) { throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL); } return vdis.iterator().next(); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get pv iso: " + isoURL + " due to " + e.toString()); } catch (Exception e) { throw new CloudRuntimeException("Unable to get pv iso: " + isoURL + " due to " + e.toString()); } } int index = isoURL.lastIndexOf("/"); mountpoint = isoURL.substring(0, index); URI uri; try { uri = new URI(mountpoint); } catch (URISyntaxException e) { // TODO Auto-generated catch block throw new CloudRuntimeException("isoURL is wrong: " + isoURL); } isoSR = getISOSRbyVmName(vmName); if (isoSR == null) { isoSR = createIsoSRbyURI(uri, vmName, false); } String isoName = isoURL.substring(index + 1); VDI isoVDI = getVDIbyLocationandSR(isoName, isoSR); if (isoVDI != null) { return isoVDI; } else { throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL); } } protected SR getStorageRepository(Connection conn, StoragePoolTO pool) { Set<SR> srs; try { srs = SR.getByNameLabel(conn, pool.getUuid()); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.toString(), e); } catch (Exception e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.getMessage(), e); } if (srs.size() > 1) { throw new CloudRuntimeException("More than one storage repository was found for pool with uuid: " + pool.getUuid()); } if (srs.size() == 1) { SR sr = srs.iterator().next(); if (s_logger.isDebugEnabled()) { s_logger.debug("SR retrieved for " + pool.getId() + " is mapped to " + sr.toString()); } if (checkSR(sr)) { return sr; } } if (pool.getType() == StoragePoolType.NetworkFilesystem) return getNfsSR(conn, pool); else if (pool.getType() == StoragePoolType.IscsiLUN) return getIscsiSR(conn, pool); else throw new CloudRuntimeException("The pool type: " + pool.getType().name() + " is not supported."); } protected SR getStorageRepository(Connection conn, StoragePoolVO pool) { Set<SR> srs; try { srs = SR.getByNameLabel(conn, pool.getUuid()); } catch (XenAPIException e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.toString(), e); } catch (Exception e) { throw new CloudRuntimeException("Unable to get SR " + pool.getUuid() + " due to " + e.getMessage(), e); } if (srs.size() > 1) { throw new CloudRuntimeException("More than one storage repository was found for pool with uuid: " + pool.getUuid()); } else if (srs.size() == 1) { SR sr = srs.iterator().next(); if (s_logger.isDebugEnabled()) { s_logger.debug("SR retrieved for " + pool.getId() + " is mapped to " + sr.toString()); } if (checkSR(sr)) { return sr; } throw new CloudRuntimeException("Check this SR failed"); } else { if (pool.getPoolType() == StoragePoolType.NetworkFilesystem) return getNfsSR(pool); else if (pool.getPoolType() == StoragePoolType.IscsiLUN) return getIscsiSR(conn, pool); else throw new CloudRuntimeException("The pool type: " + pool.getPoolType().name() + " is not supported."); } } protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort()); } protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort()); } protected Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) { String result = null; final StringBuffer sb = new StringBuffer(); sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus"); boolean success = true; try { final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); // setting TIMEOUTs to avoid possible waiting until death situations conn.setConnectTimeout(5000); conn.setReadTimeout(5000); final InputStream is = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb2 = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) sb2.append(line + "\n"); result = sb2.toString(); } catch (final IOException e) { success = false; } finally { try { is.close(); } catch (final IOException e) { s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp); success = false; } } } catch (final IOException e) { s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); success = false; } return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result); } protected boolean createSecondaryStorageFolder(String remoteMountPath, String newFolder) { String result = callHostPlugin("vmopsSnapshot", "create_secondary_storage_folder", "remoteMountPath", remoteMountPath, "newFolder", newFolder); return (result != null); } protected boolean deleteSecondaryStorageFolder(String remoteMountPath, String folder) { String result = callHostPlugin("vmopsSnapshot", "delete_secondary_storage_folder", "remoteMountPath", remoteMountPath, "folder", folder); return (result != null); } protected boolean postCreatePrivateTemplate(String remoteTemplateMountPath, String templateDownloadFolder, String templateInstallFolder, String templateFilename, String templateName, String templateDescription, String checksum, long virtualSize, long templateId) { if (templateDescription == null) { templateDescription = ""; } if (checksum == null) { checksum = ""; } String result = callHostPlugin("vmopsSnapshot", "post_create_private_template", "remoteTemplateMountPath", remoteTemplateMountPath, "templateDownloadFolder", templateDownloadFolder, "templateInstallFolder", templateInstallFolder, "templateFilename", templateFilename, "templateName", templateName, "templateDescription", templateDescription, "checksum", checksum, "virtualSize", String.valueOf(virtualSize), "templateId", String.valueOf(templateId)); boolean success = false; if (result != null && !result.isEmpty()) { // Else, command threw an exception which has already been logged. String[] tmp = result.split("#"); String status = tmp[0]; if (status != null && status.equalsIgnoreCase("1")) { s_logger.debug("Successfully created template.properties file on secondary storage dir: " + templateInstallFolder); success = true; } else { s_logger.warn("Could not create template.properties file on secondary storage dir: " + templateInstallFolder + " for templateId: " + templateId + ". Failed with status " + status); } } return success; } // Each argument is put in a separate line for readability. // Using more lines does not harm the environment. protected String backupSnapshot(String primaryStorageSRUuid, Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String snapshotUuid, String prevSnapshotUuid, String prevBackupUuid, Boolean isFirstSnapshotOfRootVolume, Boolean isISCSI) { String backupSnapshotUuid = null; if (prevSnapshotUuid == null) { prevSnapshotUuid = ""; } if (prevBackupUuid == null) { prevBackupUuid = ""; } // Each argument is put in a separate line for readability. // Using more lines does not harm the environment. String results = callHostPlugin("vmopsSnapshot", "backupSnapshot", "primaryStorageSRUuid", primaryStorageSRUuid, "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "snapshotUuid", snapshotUuid, "prevSnapshotUuid", prevSnapshotUuid, "prevBackupUuid", prevBackupUuid, "isFirstSnapshotOfRootVolume", isFirstSnapshotOfRootVolume.toString(), "isISCSI", isISCSI.toString()); if (results == null || results.isEmpty()) { // errString is already logged. return null; } String[] tmp = results.split("#"); String status = tmp[0]; backupSnapshotUuid = tmp[1]; // status == "1" if and only if backupSnapshotUuid != null // So we don't rely on status value but return backupSnapshotUuid as an // indicator of success. String failureString = "Could not copy backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " from primary storage " + primaryStorageSRUuid + " to secondary storage " + secondaryStorageMountPath; if (status != null && status.equalsIgnoreCase("1") && backupSnapshotUuid != null) { s_logger.debug("Successfully copied backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " to secondary storage"); } else { s_logger.debug(failureString + ". Failed with status: " + status); } return backupSnapshotUuid; } protected boolean destroySnapshotOnPrimaryStorage(String snapshotUuid) { // Precondition snapshotUuid != null try { Connection conn = getConnection(); VDI snapshot = getVDIbyUuid(snapshotUuid); if (snapshot == null) { throw new InternalErrorException("Could not destroy snapshot " + snapshotUuid + " because the snapshot VDI was null"); } snapshot.destroy(conn); s_logger.debug("Successfully destroyed snapshotUuid: " + snapshotUuid + " on primary storage"); return true; } catch (XenAPIException e) { String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.toString(); s_logger.error(msg, e); } catch (Exception e) { String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.getMessage(); s_logger.warn(msg, e); } return false; } protected String deleteSnapshotBackup(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backupUUID, String childUUID, Boolean isISCSI) { // If anybody modifies the formatting below again, I'll skin them String result = callHostPlugin("vmopsSnapshot", "deleteSnapshotBackup", "backupUUID", backupUUID, "childUUID", childUUID, "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "isISCSI", isISCSI.toString()); return result; } protected String deleteSnapshotsDir(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath) { // If anybody modifies the formatting below again, I'll skin them String result = callHostPlugin("vmopsSnapshot", "deleteSnapshotsDir", "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath); return result; } // If anybody messes up with the formatting, I'll skin them protected Pair<VHDInfo, String> createVHDFromSnapshot(String primaryStorageNameLabel, Long dcId, Long accountId, Long volumeId, String secondaryStoragePoolURL, String backedUpSnapshotUuid, String templatePath, String templateDownloadFolder) throws XenAPIException, IOException, XmlRpcException, InternalErrorException, URISyntaxException { // Return values String details = null; Connection conn = getConnection(); SR primaryStorageSR = getSRByNameLabelandHost(primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot " + "because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } Boolean isISCSI = SRType.LVMOISCSI.equals(primaryStorageSR.getType(conn)); // Get the absolute path of the template on the secondary storage. URI uri = new URI(secondaryStoragePoolURL); String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); VHDInfo vhdInfo = null; if (secondaryStorageMountPath == null) { details = " because the URL passed: " + secondaryStoragePoolURL + " is invalid."; } else { vhdInfo = createVHDFromSnapshot(dcId, accountId, volumeId, secondaryStorageMountPath, backedUpSnapshotUuid, templatePath, templateDownloadFolder, isISCSI); if (vhdInfo == null) { details = " because the vmops plugin on XenServer failed at some point"; } } return new Pair<VHDInfo, String>(vhdInfo, details); } protected VHDInfo createVHDFromSnapshot(Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backedUpSnapshotUuid, String templatePath, String templateDownloadFolder, Boolean isISCSI) { String vdiUUID = null; String failureString = "Could not create volume from " + backedUpSnapshotUuid; templatePath = (templatePath == null) ? "" : templatePath; String results = callHostPlugin("vmopsSnapshot", "createVolumeFromSnapshot", "dcId", dcId.toString(), "accountId", accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "backedUpSnapshotUuid", backedUpSnapshotUuid, "templatePath", templatePath, "templateDownloadFolder", templateDownloadFolder, "isISCSI", isISCSI.toString()); if (results == null || results.isEmpty()) { // Command threw an exception which has already been logged. return null; } String[] tmp = results.split("#"); String status = tmp[0]; vdiUUID = tmp[1]; Long virtualSizeInMB = 0L; if (tmp.length == 3) { virtualSizeInMB = Long.valueOf(tmp[2]); } // status == "1" if and only if vdiUUID != null // So we don't rely on status value but return vdiUUID as an indicator // of success. if (status != null && status.equalsIgnoreCase("1") && vdiUUID != null) { s_logger.debug("Successfully created vhd file with all data on secondary storage : " + vdiUUID); } else { s_logger.debug(failureString + ". Failed with status " + status + " with vdiUuid " + vdiUUID); } return new VHDInfo(vdiUUID, virtualSizeInMB * MB); } @Override public boolean start() { return true; } @Override public boolean stop() { disconnected(); return true; } @Override public String getName() { return _name; } @Override public IAgentControl getAgentControl() { return _agentControl; } @Override public void setAgentControl(IAgentControl agentControl) { _agentControl = agentControl; } @Override public boolean IsRemoteAgent() { return _isRemoteAgent; } @Override public void setRemoteAgent(boolean remote) { _isRemoteAgent = remote; } protected Answer execute(PoolEjectCommand cmd) { Connection conn = getConnection(); String hostuuid = cmd.getHostuuid(); try { Host host = Host.getByUuid(conn, hostuuid); // remove all tags cloud stack add before eject Host.Record hr = host.getRecord(conn); Iterator<String> it = hr.tags.iterator(); while (it.hasNext()) { String tag = it.next(); if (tag.startsWith("vmops-version-")) { it.remove(); } } // eject from pool Pool.eject(conn, host); return new Answer(cmd); } catch (XenAPIException e) { String msg = "Unable to eject host " + _host.uuid + " due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { s_logger.warn("Unable to eject host " + _host.uuid, e); String msg = "Unable to eject host " + _host.uuid + " due to " + e.getMessage(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } protected class Nic { public Network n; public Network.Record nr; public PIF p; public PIF.Record pr; public Nic(Network n, Network.Record nr, PIF p, PIF.Record pr) { this.n = n; this.nr = nr; this.p = p; this.pr = pr; } } // A list of UUIDs that are gathered from the XenServer when // the resource first connects to XenServer. These UUIDs do // not change over time. protected class XenServerHost { public String systemvmisouuid; public String uuid; public String ip; public String publicNetwork; public String privateNetwork; public String linkLocalNetwork; public String storageNetwork1; public String storageNetwork2; public String guestNetwork; public String guestPif; public String publicPif; public String privatePif; public String storagePif1; public String storagePif2; public String pool; } private class VHDInfo { private final String uuid; private final Long virtualSize; public VHDInfo(String uuid, Long virtualSize) { this.uuid = uuid; this.virtualSize = virtualSize; } /** * @return the uuid */ public String getUuid() { return uuid; } /** * @return the virtualSize */ public Long getVirtualSize() { return virtualSize; } } }
support multiple patch files
core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
support multiple patch files
<ide><path>ore/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java <ide> } <ide> <ide> SCPClient scp = new SCPClient(sshConnection); <del> File file = new File(_patchPath); <del> <del> Properties props = new Properties(); <del> props.load(new FileInputStream(file)); <ide> <ide> String path = _patchPath.substring(0, _patchPath.lastIndexOf(File.separator) + 1); <del> for (Map.Entry<Object, Object> entry : props.entrySet()) { <del> String k = (String) entry.getKey(); <del> String v = (String) entry.getValue(); <del> <del> assert (k != null && k.length() > 0 && v != null && v.length() > 0) : "Problems with " + k + "=" + v; <del> <del> String[] tokens = v.split(","); <del> String f = null; <del> if (tokens.length == 3 && tokens[0].length() > 0) { <del> if (tokens[0].startsWith("/")) { <del> f = tokens[0]; <del> } else if (tokens[0].startsWith("~")) { <del> String homedir = System.getenv("HOME"); <del> f = homedir + tokens[0].substring(1) + k; <del> } else { <del> f = path + tokens[0] + '/' + k; <del> } <del> } else { <del> f = path + k; <del> } <del> String d = tokens[tokens.length - 1]; <del> f = f.replace('/', File.separatorChar); <del> <del> String p = "0755"; <del> if (tokens.length == 3) { <del> p = tokens[1]; <del> } else if (tokens.length == 2) { <del> p = tokens[0]; <del> } <del> <del> if (!new File(f).exists()) { <del> s_logger.warn("We cannot locate " + f); <del> continue; <del> } <del> if (s_logger.isDebugEnabled()) { <del> s_logger.debug("Copying " + f + " to " + d + " on " + hr.address + " with permission " + p); <del> } <del> scp.put(f, d, p); <del> <add> List<File> files = getPatchFiles(); <add> if( files == null || files.isEmpty() ) { <add> throw new CloudRuntimeException("Can not find patch file"); <add> } <add> for( File file :files) { <add> Properties props = new Properties(); <add> props.load(new FileInputStream(file)); <add> <add> for (Map.Entry<Object, Object> entry : props.entrySet()) { <add> String k = (String) entry.getKey(); <add> String v = (String) entry.getValue(); <add> <add> assert (k != null && k.length() > 0 && v != null && v.length() > 0) : "Problems with " + k + "=" + v; <add> <add> String[] tokens = v.split(","); <add> String f = null; <add> if (tokens.length == 3 && tokens[0].length() > 0) { <add> if (tokens[0].startsWith("/")) { <add> f = tokens[0]; <add> } else if (tokens[0].startsWith("~")) { <add> String homedir = System.getenv("HOME"); <add> f = homedir + tokens[0].substring(1) + k; <add> } else { <add> f = path + tokens[0] + '/' + k; <add> } <add> } else { <add> f = path + k; <add> } <add> String d = tokens[tokens.length - 1]; <add> f = f.replace('/', File.separatorChar); <add> <add> String p = "0755"; <add> if (tokens.length == 3) { <add> p = tokens[1]; <add> } else if (tokens.length == 2) { <add> p = tokens[0]; <add> } <add> <add> if (!new File(f).exists()) { <add> s_logger.warn("We cannot locate " + f); <add> continue; <add> } <add> if (s_logger.isDebugEnabled()) { <add> s_logger.debug("Copying " + f + " to " + d + " on " + hr.address + " with permission " + p); <add> } <add> scp.put(f, d, p); <add> <add> } <ide> } <ide> <ide> } catch (IOException e) { <ide> s_logger.warn(msg, e); <ide> throw new CloudRuntimeException("Unable to get host information ", e); <ide> } <add> } <add> <add> protected List<File> getPatchFiles() { <add> List<File> files = new ArrayList<File>(); <add> File file = new File(_patchPath); <add> files.add(file); <add> return files; <ide> } <ide> <ide> protected SR getSRByNameLabelandHost(String name) throws BadServerResponse, XenAPIException, XmlRpcException {
Java
apache-2.0
45a7457e3a9ae4e2db529fcb9ed852bfc389bde1
0
getlantern/lantern-common
package org.lantern; import java.net.InetSocketAddress; import java.nio.charset.Charset; /** * Constants for Lantern. */ public class LanternConstants { public static final int DASHCACHE_MAXAGE = 60 * 5; public static final String API_VERSION = "0.0.1"; public static final String BUILD_TIME = "build_time_tok"; public static final String UNCENSORED_ID = "-lan-"; /** * We make range requests of the form "bytes=x-y" where * y <= x + CHUNK_SIZE * in order to chunk and parallelize downloads of large entities. This * is especially important for requests to laeproxy since it is subject * to GAE's response size limits. * Because "bytes=x-y" requests bytes x through y _inclusive_, * this actually requests y - x + 1 bytes, * i.e. CHUNK_SIZE + 1 bytes * when x = 0 and y = CHUNK_SIZE. * This currently corresponds to laeproxy's RANGE_REQ_SIZE of 2000000. */ public static final long CHUNK_SIZE = 2000000 - 1; public static final String VERSION_KEY = "v"; public static final String OS_KEY = "os"; public static final String ARCH_KEY = "ar"; public static final int LANTERN_LOCALHOST_HTTP_PORT = 8787; public static final InetSocketAddress LANTERN_LOCALHOST_ADDR = new InetSocketAddress("127.0.0.1", LANTERN_LOCALHOST_HTTP_PORT); public static final String statshubBaseAddress = "https://pure-journey-3547.herokuapp.com/stats/"; public static final String USER_NAME = "un"; public static final String PASSWORD = "pwd"; public static final String DIRECT_BYTES = "db"; public static final String BYTES_PROXIED = "bp"; public static final String REQUESTS_PROXIED = "rp"; public static final String DIRECT_REQUESTS = "dr"; public static final String MACHINE_ID = "m"; public static final String COUNTRY_CODE = "cc"; public static final String WHITELIST_ADDITIONS = "wa"; public static final String WHITELIST_REMOVALS = "wr"; public static final String SERVERS = "s"; public static final String UPDATE_TIME = "ut"; public static final String ROSTER = "roster"; public static final String USER_GUID = "guid"; /** * The following are keys in the properties files. */ public static final String FORCE_CENSORED = "forceCensored"; /** * maps to a version id (e.g. "1.0.0-rc1") * Should really be called VERSION_KEY; when client sends to server * it maps to its version, when server sends to client it maps to the * latest version. */ public static final String UPDATE_KEY = "update"; public static final String INVITES_KEY = "invites"; public static final String INVITED_EMAIL = "invem"; public static final String INVITEE_NAME = "inv_name"; public static final String INVITER_NAME = "invr_name"; // Transitioning out; newer clients will use REFRESH_TOKEN... public static final String INVITER_REFRESH_TOKEN = "invr_refrtok"; public static final String INVITED = "invd"; public static final String INVITED_KEY = "invited"; public static final String FAILED_INVITES_KEY = "failed_invites"; public static final String INVITE_FAILED_REASON = "reason"; public static final String NEED_REFRESH_TOKEN = "need_refrtok"; // Old value kept around for compatibility with old clients. public static final String REFRESH_TOKEN = INVITER_REFRESH_TOKEN; public static final String HOST_AND_PORT = "host_and_port"; public static final String FALLBACK_HOST_AND_PORT = "fallback_host_and_port"; public static final String IS_FALLBACK_PROXY = "is_fallback_proxy"; /** * The length of keys in translation property files. */ public static final int I18N_KEY_LENGTH = 40; public static final String CONNECT_ON_LAUNCH = "connectOnLaunch"; public static final String START_AT_LOGIN = "startAtLogin"; public static final String FRIENDS = "friends"; public static final String FRIEND = "friend"; public static final String FRIENDED_BY_LAST_UPDATED = "fblu"; public static final String FRIENDED_BY = "fb"; public static final String UNFRIENDED_BY = "ufb"; /** * Note that we don't include the "X-" for experimental headers here. See: * the draft that appears likely to become an RFC at: * * http://tools.ietf.org/html/draft-ietf-appsawg-xdash */ public static final String LANTERN_VERSION_HTTP_HEADER_NAME = "Lantern-Version"; public static final boolean ON_APP_ENGINE; public static final int KSCOPE_ADVERTISEMENT = 0x2111; public static final String KSCOPE_ADVERTISEMENT_KEY = "ksak"; public static final String AWS_REGION = "ap-southeast-1"; public static final Charset UTF8 = Charset.forName("UTF8"); static { boolean tempAppEngine; try { Class.forName("org.lantern.LanternControllerUtils"); tempAppEngine = true; } catch (final ClassNotFoundException e) { tempAppEngine = false; } ON_APP_ENGINE = tempAppEngine; } }
src/main/java/org/lantern/LanternConstants.java
package org.lantern; import java.net.InetSocketAddress; import java.nio.charset.Charset; /** * Constants for Lantern. */ public class LanternConstants { public static final int DASHCACHE_MAXAGE = 60 * 5; public static final String API_VERSION = "0.0.1"; public static final String BUILD_TIME = "build_time_tok"; public static final String UNCENSORED_ID = "-lan-"; /** * We make range requests of the form "bytes=x-y" where * y <= x + CHUNK_SIZE * in order to chunk and parallelize downloads of large entities. This * is especially important for requests to laeproxy since it is subject * to GAE's response size limits. * Because "bytes=x-y" requests bytes x through y _inclusive_, * this actually requests y - x + 1 bytes, * i.e. CHUNK_SIZE + 1 bytes * when x = 0 and y = CHUNK_SIZE. * This currently corresponds to laeproxy's RANGE_REQ_SIZE of 2000000. */ public static final long CHUNK_SIZE = 2000000 - 1; public static final String VERSION_KEY = "v"; public static final String OS_KEY = "os"; public static final String ARCH_KEY = "ar"; public static final int LANTERN_LOCALHOST_HTTP_PORT = 8787; public static final InetSocketAddress LANTERN_LOCALHOST_ADDR = new InetSocketAddress("127.0.0.1", LANTERN_LOCALHOST_HTTP_PORT); public static final String statshubBaseAddress = "https://pure-journey-3547.herokuapp.com/stats/"; public static final String USER_NAME = "un"; public static final String PASSWORD = "pwd"; public static final String DIRECT_BYTES = "db"; public static final String BYTES_PROXIED = "bp"; public static final String REQUESTS_PROXIED = "rp"; public static final String DIRECT_REQUESTS = "dr"; public static final String MACHINE_ID = "m"; public static final String COUNTRY_CODE = "cc"; public static final String WHITELIST_ADDITIONS = "wa"; public static final String WHITELIST_REMOVALS = "wr"; public static final String SERVERS = "s"; public static final String UPDATE_TIME = "ut"; public static final String ROSTER = "roster"; public static final String USER_GUID = "guid"; /** * The following are keys in the properties files. */ public static final String FORCE_CENSORED = "forceCensored"; /** * maps to a version id (e.g. "1.0.0-rc1") * Should really be called VERSION_KEY; when client sends to server * it maps to its version, when server sends to client it maps to the * latest version. */ public static final String UPDATE_KEY = "update"; public static final String INVITES_KEY = "invites"; public static final String INVITED_EMAIL = "invem"; public static final String INVITEE_NAME = "inv_name"; public static final String INVITER_NAME = "invr_name"; // Transitioning out; newer clients will use REFRESH_TOKEN... public static final String INVITER_REFRESH_TOKEN = "invr_refrtok"; public static final String INVITED = "invd"; public static final String INVITED_KEY = "invited"; public static final String FAILED_INVITES_KEY = "failed_invites"; public static final String INVITE_FAILED_REASON = "reason"; public static final String NEED_REFRESH_TOKEN = "need_refrtok"; // Old value kept around for compatibility with old clients. public static final String REFRESH_TOKEN = INVITER_REFRESH_TOKEN; public static final String HOST_AND_PORT = "host_and_port"; public static final String FALLBACK_HOST_AND_PORT = "fallback_host_and_port"; public static final String IS_FALLBACK_PROXY = "is_fallback_proxy"; /** * The length of keys in translation property files. */ public static final int I18N_KEY_LENGTH = 40; public static final String CONNECT_ON_LAUNCH = "connectOnLaunch"; public static final String START_AT_LOGIN = "startAtLogin"; public static final String FRIENDS = "friends"; public static final String FRIEND = "friend"; public static final String FRIENDED_BY_LAST_UPDATED = "fblu"; public static final String FRIENDED_BY = "fb"; public static final String UNFRIENDED_BY = "ufb"; /** * Note that we don't include the "X-" for experimental headers here. See: * the draft that appears likely to become an RFC at: * * http://tools.ietf.org/html/draft-ietf-appsawg-xdash */ public static final String LANTERN_VERSION_HTTP_HEADER_NAME = "Lantern-Version"; public static final boolean ON_APP_ENGINE; public static final int KSCOPE_ADVERTISEMENT = 0x2111; public static final String KSCOPE_ADVERTISEMENT_KEY = "ksak"; public static final Charset UTF8 = Charset.forName("UTF8"); static { boolean tempAppEngine; try { Class.forName("org.lantern.LanternControllerUtils"); tempAppEngine = true; } catch (final ClassNotFoundException e) { tempAppEngine = false; } ON_APP_ENGINE = tempAppEngine; } }
added back region since we need it for SQS
src/main/java/org/lantern/LanternConstants.java
added back region since we need it for SQS
<ide><path>rc/main/java/org/lantern/LanternConstants.java <ide> <ide> public static final int KSCOPE_ADVERTISEMENT = 0x2111; <ide> public static final String KSCOPE_ADVERTISEMENT_KEY = "ksak"; <add> <add> public static final String AWS_REGION = "ap-southeast-1"; <ide> <ide> public static final Charset UTF8 = Charset.forName("UTF8"); <ide>
Java
lgpl-2.1
2b0236465c9af838d02ab005a43eb841ef243a20
0
rhusar/wildfly,tadamski/wildfly,iweiss/wildfly,pferraro/wildfly,wildfly/wildfly,99sono/wildfly,iweiss/wildfly,pferraro/wildfly,golovnin/wildfly,xasx/wildfly,wildfly/wildfly,xasx/wildfly,iweiss/wildfly,xasx/wildfly,rhusar/wildfly,tadamski/wildfly,tomazzupan/wildfly,pferraro/wildfly,tadamski/wildfly,99sono/wildfly,golovnin/wildfly,jstourac/wildfly,pferraro/wildfly,jstourac/wildfly,jstourac/wildfly,iweiss/wildfly,tomazzupan/wildfly,rhusar/wildfly,rhusar/wildfly,tomazzupan/wildfly,golovnin/wildfly,wildfly/wildfly,99sono/wildfly,wildfly/wildfly,jstourac/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.websocket.ClientEndpoint; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerContainer; import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; import io.undertow.servlet.util.DefaultClassIntrospector; import io.undertow.websockets.jsr.JsrWebSocketFilter; import io.undertow.websockets.jsr.JsrWebSocketLogger; import io.undertow.websockets.jsr.ServerWebSocketContainer; import org.jboss.as.ee.component.EEModuleDescription; import org.wildfly.extension.io.IOServices; import org.jboss.as.naming.ManagedReferenceInjector; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.service.BinderService; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.server.deployment.reflect.DeploymentClassIndex; import org.wildfly.extension.undertow.UndertowLogger; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.WarMetaData; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FiltersMetaData; import org.jboss.modules.Module; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.xnio.Pool; import org.xnio.XnioWorker; /** * Deployment processor for native JSR-356 websockets * <p/> * * @author Stuart Douglas */ public class UndertowJSRWebSocketDeploymentProcessor implements DeploymentUnitProcessor { private static final DotName SERVER_ENDPOINT = DotName.createSimple(ServerEndpoint.class.getName()); private static final DotName CLIENT_ENDPOINT = DotName.createSimple(ClientEndpoint.class.getName()); private static final DotName SERVER_APPLICATION_CONFIG = DotName.createSimple(ServerApplicationConfig.class.getName()); private static final DotName ENDPOINT = DotName.createSimple(Endpoint.class.getName()); public static final String FILTER_NAME = "Undertow Web Socket Filter"; @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentClassIndex classIndex = deploymentUnit.getAttachment(Attachments.CLASS_INDEX); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if(module == null) { return; } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (metaData == null) { return; } final Set<Class<?>> annotatedEndpoints = new HashSet<>(); final Set<Class<? extends Endpoint>> endpoints = new HashSet<>(); final Set<Class<? extends ServerApplicationConfig>> config = new HashSet<>(); final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); final List<AnnotationInstance> serverEndpoints = index.getAnnotations(SERVER_ENDPOINT); if (serverEndpoints != null) { for (AnnotationInstance endpoint : serverEndpoints) { if (endpoint.target() instanceof ClassInfo) { ClassInfo clazz = (ClassInfo) endpoint.target(); try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { annotatedEndpoints.add(moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e); } } } } final List<AnnotationInstance> clientEndpoints = index.getAnnotations(CLIENT_ENDPOINT); if (clientEndpoints != null) { for (AnnotationInstance endpoint : clientEndpoints) { if (endpoint.target() instanceof ClassInfo) { ClassInfo clazz = (ClassInfo) endpoint.target(); try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { annotatedEndpoints.add(moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e); } } } } final Set<ClassInfo> subclasses = index.getAllKnownImplementors(SERVER_APPLICATION_CONFIG); if (subclasses != null) { for (final ClassInfo clazz : subclasses) { try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { config.add((Class) moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e); } } } final Set<ClassInfo> epClasses = index.getAllKnownSubclasses(ENDPOINT); if (epClasses != null) { for (final ClassInfo clazz : epClasses) { try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { endpoints.add((Class) moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e); } } } ServerWebSocketContainer container = new ServerWebSocketContainer(DefaultClassIntrospector.INSTANCE); //TODO: fix doDeployment(container, annotatedEndpoints, config, endpoints); installWebsockets(phaseContext, metaData, container); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } private void installWebsockets(final DeploymentPhaseContext phaseContext, final WarMetaData metaData, final ServerWebSocketContainer container) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); FiltersMetaData filters = metaData.getMergedJBossWebMetaData().getFilters(); if (filters == null) { metaData.getMergedJBossWebMetaData().setFilters(filters = new FiltersMetaData()); } FilterMetaData filterMetaData = new FilterMetaData(); filterMetaData.setAsyncSupported(true); filterMetaData.setFilterClass(JsrWebSocketFilter.class.getName()); filterMetaData.setName(FILTER_NAME); filters.add(filterMetaData); List<FilterMappingMetaData> mappings = metaData.getMergedJBossWebMetaData().getFilterMappings(); if (mappings == null) { metaData.getMergedJBossWebMetaData().setFilterMappings(mappings = new ArrayList<>()); } FilterMappingMetaData mapping = new FilterMappingMetaData(); mapping.setFilterName(FILTER_NAME); mapping.setDispatchers(Collections.singletonList(org.jboss.metadata.web.spec.DispatcherType.REQUEST)); mapping.setUrlPatterns(Collections.singletonList("/*")); mappings.add(mapping); deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(ServerContainer.class.getName(), container)); final ServiceName serviceName = deploymentUnit.getServiceName().append(WebSocketContainerService.SERVICE_NAME); WebSocketContainerService service = new WebSocketContainerService(container); phaseContext.getServiceTarget().addService(serviceName, service) .addDependency(IOServices.WORKER.append("default"), XnioWorker.class, service.getXnioWorker()) //TODO: make this configurable .addDependency(IOServices.BUFFER_POOL.append("default"), Pool.class, service.getInjectedBuffer()) .install(); //bind the container to JNDI to make it availble for resource injection //this is not request by the spec, but is an convenient extension final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(), moduleDescription.getModuleName()); bindJndiServices(deploymentUnit, phaseContext.getServiceTarget(), moduleContextServiceName, serviceName); deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, serviceName); } private void bindJndiServices(final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget, final ServiceName contextServiceName, final ServiceName serviceName) { final ServiceName bindingServiceName = contextServiceName.append("ServerContainer"); final BinderService binderService = new BinderService("ServerContainer"); serviceTarget.addService(bindingServiceName, binderService) .addDependency(serviceName, ServerWebSocketContainer.class, new ManagedReferenceInjector<ServerWebSocketContainer>(binderService.getManagedObjectInjector())) .addDependency(contextServiceName, ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()) .install(); deploymentUnit.addToAttachmentList(org.jboss.as.server.deployment.Attachments.JNDI_DEPENDENCIES, bindingServiceName); } private void doDeployment(final ServerWebSocketContainer container, final Set<Class<?>> annotatedEndpoints, final Set<Class<? extends ServerApplicationConfig>> serverApplicationConfigClasses, final Set<Class<? extends Endpoint>> endpoints) throws DeploymentUnitProcessingException { Set<Class<? extends Endpoint>> allScannedEndpointImplementations = new HashSet<>(endpoints); Set<Class<?>> allAnnotatedEndpoints = new HashSet<>(annotatedEndpoints); Set<ServerEndpointConfig> serverEndpointConfigurations = new HashSet<>(); final Set<ServerApplicationConfig> configInstances = new HashSet<>(); for (Class<? extends ServerApplicationConfig> clazz : serverApplicationConfigClasses) { try { configInstances.add(clazz.newInstance()); } catch (InstantiationException | IllegalAccessException e) { JsrWebSocketLogger.ROOT_LOGGER.couldNotInitializeConfiguration(clazz, e); } } for (ServerApplicationConfig config : configInstances) { allAnnotatedEndpoints = config.getAnnotatedEndpointClasses(allAnnotatedEndpoints); Set<ServerEndpointConfig> endpointConfigs = config.getEndpointConfigs(allScannedEndpointImplementations); if(endpointConfigs != null) { serverEndpointConfigurations.addAll(endpointConfigs); } } //ok, now we have our endpoints, lets deploy them try { //annotated endpoints first for (Class<?> endpoint : allAnnotatedEndpoints) { container.addEndpoint(endpoint); } for (final ServerEndpointConfig endpoint : serverEndpointConfigurations) { container.addEndpoint(endpoint); } } catch (DeploymentException e) { throw new DeploymentUnitProcessingException(e); } } @Override public void undeploy(final DeploymentUnit context) { } }
undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowJSRWebSocketDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.websocket.ClientEndpoint; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerContainer; import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; import io.undertow.servlet.util.DefaultClassIntrospector; import io.undertow.websockets.jsr.JsrWebSocketFilter; import io.undertow.websockets.jsr.JsrWebSocketLogger; import io.undertow.websockets.jsr.ServerWebSocketContainer; import org.jboss.as.ee.component.EEModuleDescription; import org.wildfly.extension.io.IOServices; import org.jboss.as.naming.ManagedReferenceInjector; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.service.BinderService; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.as.server.deployment.reflect.DeploymentClassIndex; import org.wildfly.extension.undertow.UndertowLogger; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.WarMetaData; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FiltersMetaData; import org.jboss.modules.Module; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.xnio.Pool; import org.xnio.XnioWorker; /** * Deployment processor for native JSR-356 websockets * <p/> * * @author Stuart Douglas */ public class UndertowJSRWebSocketDeploymentProcessor implements DeploymentUnitProcessor { private static final DotName SERVER_ENDPOINT = DotName.createSimple(ServerEndpoint.class.getName()); private static final DotName CLIENT_ENDPOINT = DotName.createSimple(ClientEndpoint.class.getName()); private static final DotName SERVER_APPLICATION_CONFIG = DotName.createSimple(ServerApplicationConfig.class.getName()); private static final DotName ENDPOINT = DotName.createSimple(Endpoint.class.getName()); public static final String FILTER_NAME = "Undertow Web Socket Filter"; @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentClassIndex classIndex = deploymentUnit.getAttachment(Attachments.CLASS_INDEX); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if(module == null) { return; } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (metaData == null) { return; } final Set<Class<?>> annotatedEndpoints = new HashSet<>(); final Set<Class<? extends Endpoint>> endpoints = new HashSet<>(); final Set<Class<? extends ServerApplicationConfig>> config = new HashSet<>(); final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); final List<AnnotationInstance> serverEndpoints = index.getAnnotations(SERVER_ENDPOINT); if (serverEndpoints != null) { for (AnnotationInstance endpoint : serverEndpoints) { if (endpoint.target() instanceof ClassInfo) { ClassInfo clazz = (ClassInfo) endpoint.target(); try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { annotatedEndpoints.add(moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e); } } } } final List<AnnotationInstance> clientEndpoints = index.getAnnotations(CLIENT_ENDPOINT); if (clientEndpoints != null) { for (AnnotationInstance endpoint : clientEndpoints) { if (endpoint.target() instanceof ClassInfo) { ClassInfo clazz = (ClassInfo) endpoint.target(); try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { annotatedEndpoints.add(moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketEndpoint(clazz.name().toString(), e); } } } } final Set<ClassInfo> subclasses = index.getAllKnownImplementors(SERVER_APPLICATION_CONFIG); if (subclasses != null) { for (final ClassInfo clazz : subclasses) { try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { config.add((Class) moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e); } } } final Set<ClassInfo> epClasses = index.getAllKnownSubclasses(ENDPOINT); if (epClasses != null) { for (final ClassInfo clazz : epClasses) { try { Class<?> moduleClass = classIndex.classIndex(clazz.name().toString()).getModuleClass(); if (!Modifier.isAbstract(moduleClass.getModifiers())) { endpoints.add((Class) moduleClass); } } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotLoadWebSocketConfig(clazz.name().toString(), e); } } } ServerWebSocketContainer container = new ServerWebSocketContainer(DefaultClassIntrospector.INSTANCE); //TODO: fix doDeployment(container, annotatedEndpoints, config, endpoints); installWebsockets(phaseContext, metaData, container); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } private void installWebsockets(final DeploymentPhaseContext phaseContext, final WarMetaData metaData, final ServerWebSocketContainer container) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); FiltersMetaData filters = metaData.getMergedJBossWebMetaData().getFilters(); if (filters == null) { metaData.getMergedJBossWebMetaData().setFilters(filters = new FiltersMetaData()); } FilterMetaData filterMetaData = new FilterMetaData(); filterMetaData.setAsyncSupported(true); filterMetaData.setFilterClass(JsrWebSocketFilter.class.getName()); filterMetaData.setName(FILTER_NAME); filters.add(filterMetaData); List<FilterMappingMetaData> mappings = metaData.getMergedJBossWebMetaData().getFilterMappings(); if (mappings == null) { metaData.getMergedJBossWebMetaData().setFilterMappings(mappings = new ArrayList<>()); } FilterMappingMetaData mapping = new FilterMappingMetaData(); mapping.setFilterName(FILTER_NAME); mapping.setDispatchers(Collections.singletonList(org.jboss.metadata.web.spec.DispatcherType.REQUEST)); mapping.setUrlPatterns(Collections.singletonList("/*")); mappings.add(mapping); deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(ServerContainer.class.getName(), container)); final ServiceName serviceName = deploymentUnit.getServiceName().append(WebSocketContainerService.SERVICE_NAME); WebSocketContainerService service = new WebSocketContainerService(container); phaseContext.getServiceTarget().addService(serviceName, service) .addDependency(IOServices.WORKER.append("default"), XnioWorker.class, service.getXnioWorker()) //TODO: make this configurable .addDependency(IOServices.BUFFER_POOL.append("default"), Pool.class, service.getInjectedBuffer()) .install(); //bind the container to JNDI to make it availble for resource injection //this is not request by the spec, but is an convenient extension final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(), moduleDescription.getModuleName()); bindJndiServices(deploymentUnit, phaseContext.getServiceTarget(), moduleContextServiceName, serviceName); deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, serviceName); } private void bindJndiServices(final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget, final ServiceName contextServiceName, final ServiceName serviceName) { final ServiceName bindingServiceName = contextServiceName.append("ServerContainer"); final BinderService binderService = new BinderService("ServerContainer"); serviceTarget.addService(bindingServiceName, binderService) .addDependency(serviceName, ServerWebSocketContainer.class, new ManagedReferenceInjector<ServerWebSocketContainer>(binderService.getManagedObjectInjector())) .addDependency(contextServiceName, ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()) .install(); deploymentUnit.addToAttachmentList(org.jboss.as.server.deployment.Attachments.JNDI_DEPENDENCIES, bindingServiceName); } private void doDeployment(final ServerWebSocketContainer container, final Set<Class<?>> annotatedEndpoints, final Set<Class<? extends ServerApplicationConfig>> serverApplicationConfigClasses, final Set<Class<? extends Endpoint>> endpoints) throws DeploymentUnitProcessingException { Set<Class<? extends Endpoint>> allScannedEndpointImplementations = new HashSet<>(endpoints); Set<Class<?>> allAnnotatedEndpoints = new HashSet<>(annotatedEndpoints); Set<ServerEndpointConfig> serverEndpointConfigurations = new HashSet<>(); final Set<ServerApplicationConfig> configInstances = new HashSet<>(); for (Class<? extends ServerApplicationConfig> clazz : serverApplicationConfigClasses) { try { configInstances.add(clazz.newInstance()); } catch (InstantiationException | IllegalAccessException e) { JsrWebSocketLogger.ROOT_LOGGER.couldNotInitializeConfiguration(clazz, e); } } for (ServerApplicationConfig config : configInstances) { allAnnotatedEndpoints = config.getAnnotatedEndpointClasses(allAnnotatedEndpoints); serverEndpointConfigurations.addAll(config.getEndpointConfigs(allScannedEndpointImplementations)); } //ok, now we have our endpoints, lets deploy them try { //annotated endpoints first for (Class<?> endpoint : allAnnotatedEndpoints) { container.addEndpoint(endpoint); } for (final ServerEndpointConfig endpoint : serverEndpointConfigurations) { container.addEndpoint(endpoint); } } catch (DeploymentException e) { throw new DeploymentUnitProcessingException(e); } } @Override public void undeploy(final DeploymentUnit context) { } }
Fix NPE
undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowJSRWebSocketDeploymentProcessor.java
Fix NPE
<ide><path>ndertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowJSRWebSocketDeploymentProcessor.java <ide> <ide> for (ServerApplicationConfig config : configInstances) { <ide> allAnnotatedEndpoints = config.getAnnotatedEndpointClasses(allAnnotatedEndpoints); <del> serverEndpointConfigurations.addAll(config.getEndpointConfigs(allScannedEndpointImplementations)); <add> Set<ServerEndpointConfig> endpointConfigs = config.getEndpointConfigs(allScannedEndpointImplementations); <add> if(endpointConfigs != null) { <add> serverEndpointConfigurations.addAll(endpointConfigs); <add> } <ide> } <ide> <ide> //ok, now we have our endpoints, lets deploy them
JavaScript
mit
5e15dbf974bc6af778bc5651b008a00a46353798
0
Travelport-Ukraine/uapi-json
var proxy = require('proxyquire'); var sinon = require('sinon'); var assert = require('assert'); var fs = require('fs'); var _ = require('lodash'); const ParserUapi = require('../../src/uapi-parser'); const xmlFolder = __dirname + '/../FakeResponses/Air'; describe('#AirParser', function () { describe('AIR_LOW_FARE_SEARCH()', () => { it('should test parsing of low fare search request', () => { const uParser = new ParserUapi('air:LowFareSearchRsp', 'v_33_0', {}); const parseFunction = require('../../src/Air/AirParser').AIR_LOW_FARE_SEARCH_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/LowFaresSearch.2ADT1CNNIEVBKK.xml`).toString(); return uParser.parse(xml).then(json => { const result = parseFunction.call(uParser, json); assert(result.length === 27, 'Length is not 27'); assert(result[0].BasePrice, 'No base price.'); assert(result[0].Taxes, 'No taxes.'); assert(result[0].TotalPrice, 'No total price.'); assert(result[0].Directions, 'No Directions.'); assert(result[0].BookingComponents, 'No Booking components.'); assert(result[0].Directions.length, 'Directions length not 2.'); const directions = result[0].Directions; const first = directions[0][0]; const second = directions[1][0]; assert(directions[0].length == 1, 'From direction length shoudl be 1'); assert(first.Segments, 'No segments in dir[0][0]'); assert(second.Segments, 'No segments in dir[1][0]'); assert(first.from, 'No from in dir[0][0]'); assert(first.to, 'No to in dir[0][0]'); assert(first.platingCarrier, 'No PC in dir[0][0]'); const segment = first.Segments[0]; assert(segment.arrival, 'Segement should have arrival'); assert(segment.departure, 'Segement should have departure'); assert(segment.bookingClass, 'Segement should have bookingClass'); assert(segment.fareBasisCode, 'Segement should have fareBasisCode'); assert(segment.from, 'Segement should have from'); assert(segment.to, 'Segement should have to'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should compare xml with parsed json', () => { const uParser = new ParserUapi('air:LowFareSearchRsp', 'v_33_0', {}); const parseFunction = require('../../src/Air/AirParser').AIR_LOW_FARE_SEARCH_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/LowFaresSearch.2ADT1CNNIEVBKK.xml`).toString(); const jsonResult = require('../FakeResponses/Air/LowFaresSearch.2ADT1CNNIEVBKK.json'); return uParser.parse(xml).then(json => { const result = parseFunction.call(uParser, json); assert(JSON.stringify(result) === JSON.stringify(jsonResult), 'Results are not equal.'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should compare xml with parsed json', () => { const uParser = new ParserUapi('air:LowFareSearchRsp', 'v_33_0', {}); const parseFunction = require('../../src/Air/AirParser').AIR_LOW_FARE_SEARCH_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/LowFaresSearch.1ADTIEVPAR.xml`).toString(); const jsonResult = require('../FakeResponses/Air/LowFaresSearch.1ADTIEVPAR.json'); return uParser.parse(xml).then(json => { const result = parseFunction.call(uParser, json); assert(JSON.stringify(result) === JSON.stringify(jsonResult), 'Results are not equal.'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); }); describe('AIR_PRICE_REQ_XML()', () => { const test = (jsonResult) => { const airprice = jsonResult['air:AirPricingSolution']; const airpricexml = jsonResult['air:AirPricingSolution_XML']; assert(airprice, 'no air:AirPricingSolution'); assert(airpricexml, 'no xml object'); assert(airprice.TotalPrice, 'No total price'); assert(airprice.Key, 'No key'); assert(airprice.Taxes, 'No taxes'); assert(airpricexml['air:AirPricingInfo_XML'], 'no air:AirPricingInfo_XML'); assert(airpricexml['air:AirSegment_XML'], 'no air:AirSegment_XML'); assert(airpricexml['air:FareNote_XML'], 'no air:FareNote_XML'); } it('should test parser for correct work', () => { const passengers = [{ lastName: 'ENEKEN', firstName: 'SKYWALKER', passCountry: 'UA', passNumber: 'ES221731', birthDate: '25JUL68', gender: 'M', ageCategory: 'ADT', }]; const uParser = new ParserUapi(null, 'v_36_0', { passengers }); const parseFunction = require('../../src/Air/AirParser').AIR_PRICE_REQUEST_PRICING_SOLUTION_XML; const xml = fs.readFileSync(`${xmlFolder}/AirPricingSolution.IEVPAR.xml`).toString(); const jsonSaved = require('../FakeResponses/Air/AirPricingSolution.IEVPAR.json'); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); test(jsonResult); assert(JSON.stringify(jsonSaved) === JSON.stringify(jsonResult), 'Result is not equal to parsed'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test another request with 2 adults and 1 child', () => { const passengers = [{ lastName: 'ENEKEN', firstName: 'SKYWALKER', passCountry: 'UA', passNumber: 'ES221731', birthDate: '25JUL68', gender: 'M', ageCategory: 'ADT', }]; const uParser = new ParserUapi(null, 'v_36_0', { passengers }); const parseFunction = require('../../src/Air/AirParser').AIR_PRICE_REQUEST_PRICING_SOLUTION_XML; const xml = fs.readFileSync(`${xmlFolder}/AirPricingSolution.IEVPAR.2ADT1CNN.xml`).toString(); const jsonSaved = require('../FakeResponses/Air/AirPricingSolution.IEVPAR.2ADT1CNN.json'); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); test(jsonResult); assert(JSON.stringify(jsonSaved) === JSON.stringify(jsonResult), 'Result is not equal to parsed'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }) }); function testBooking(jsonResult, platingCarrier = true, tickets = false) { assert(_.isArray(jsonResult), 'result not array'); jsonResult.forEach(result => { assert(result.bookingPCC, 'no booking pcc'); assert(_.isArray(result.passengers), 'passengers is not array'); assert(result.passengers.length); assert(result.pnr, 'no pnr'); assert(_.isArray(result.pnrList), 'no pnrList'); assert(_.isArray(result.reservations), 'no reservations'); assert(result.reservations.length); assert(_.isArray(result.trips), 'no trips'); result.trips.forEach(trip => { assert(_.isArray(trip.baggage), 'No baggage in trips'); }); result.reservations.forEach(reservation => { let status = 'Reserved'; if (tickets) { status = 'Ticketed'; } assert(reservation.status === status); assert(!_.isEmpty(reservation.priceInfo), 'no price info'); assert(_.isEqual( Object.keys(reservation.priceInfo), ['TotalPrice', 'BasePrice', 'Taxes', 'passengersCount', 'TaxesInfo'] ), 'no required fields'); }); if (tickets) { assert(_.isArray(result.tickets), 'No tickets in result'); assert(result.tickets.length === result.passengers.length, 'tickets should be for each passenger'); result.tickets.forEach(ticket => { assert(!_.isEmpty(ticket.number), 'No ticket number'); assert(!_.isEmpty(ticket.uapi_passenger_ref), 'No passenger_ref in tickets'); }); } if (platingCarrier) { assert(!_.isEmpty(result.platingCarrier), 'no plating carrier'); } }); } describe('AIR_CREATE_RESERVATION()', () => { it('should test parsing of create reservation 2ADT1CNN', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.2ADT1CNN.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of create reservation 1ADT', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.1ADT.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of create reservation 1ADT (2)', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.1ADT.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of create reservation 1ADT (3)', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.1ADT.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of reservation with segment failure', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.SegmentFailure.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); assert(false, 'There should be error'); }).catch(err => { assert(err, 'No error returner'); }); }); }); describe('UNIVERSAL_RECORD_IMPORT_SIMPLE_REQUEST', () => { it('should test parsing of universal record import request', () => { const uParser = new ParserUapi('universal:UniversalRecordImportRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_IMPORT_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/UniversalRecordImport.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult, false); }); }); it('should test parsing of universal record import request with tickets', () => { const uParser = new ParserUapi('universal:UniversalRecordImportRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_IMPORT_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/UniversalRecordImport.Ticket.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json) testBooking(jsonResult, false, true); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of universal record import request with tickets (multiple passengers)', () => { const uParser = new ParserUapi('universal:UniversalRecordImportRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_IMPORT_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/UniversalRecordImport.MultiplePassengers.Ticket.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult, false, true); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); }); });
test/Air/AirParser.test.js
var proxy = require('proxyquire'); var sinon = require('sinon'); var assert = require('assert'); var fs = require('fs'); var _ = require('lodash'); const ParserUapi = require('../../src/uapi-parser'); const xmlFolder = __dirname + '/../FakeResponses/Air'; describe('#AirParser', function () { describe('AIR_LOW_FARE_SEARCH()', () => { it('should test parsing of low fare search request', () => { const uParser = new ParserUapi('air:LowFareSearchRsp', 'v_33_0', {}); const parseFunction = require('../../src/Air/AirParser').AIR_LOW_FARE_SEARCH_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/LowFaresSearch.2ADT1CNNIEVBKK.xml`).toString(); return uParser.parse(xml).then(json => { const result = parseFunction.call(uParser, json); assert(result.length === 27, 'Length is not 27'); assert(result[0].BasePrice, 'No base price.'); assert(result[0].Taxes, 'No taxes.'); assert(result[0].TotalPrice, 'No total price.'); assert(result[0].Directions, 'No Directions.'); assert(result[0].BookingComponents, 'No Booking components.'); assert(result[0].Directions.length, 'Directions length not 2.'); const directions = result[0].Directions; const first = directions[0][0]; const second = directions[1][0]; assert(directions[0].length == 1, 'From direction length shoudl be 1'); assert(first.Segments, 'No segments in dir[0][0]'); assert(second.Segments, 'No segments in dir[1][0]'); assert(first.from, 'No from in dir[0][0]'); assert(first.to, 'No to in dir[0][0]'); assert(first.platingCarrier, 'No PC in dir[0][0]'); const segment = first.Segments[0]; assert(segment.arrival, 'Segement should have arrival'); assert(segment.departure, 'Segement should have departure'); assert(segment.bookingClass, 'Segement should have bookingClass'); assert(segment.fareBasisCode, 'Segement should have fareBasisCode'); assert(segment.from, 'Segement should have from'); assert(segment.to, 'Segement should have to'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should compare xml with parsed json', () => { const uParser = new ParserUapi('air:LowFareSearchRsp', 'v_33_0', {}); const parseFunction = require('../../src/Air/AirParser').AIR_LOW_FARE_SEARCH_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/LowFaresSearch.2ADT1CNNIEVBKK.xml`).toString(); const jsonResult = require('../FakeResponses/Air/LowFaresSearch.2ADT1CNNIEVBKK.json'); return uParser.parse(xml).then(json => { const result = parseFunction.call(uParser, json); assert(JSON.stringify(result) === JSON.stringify(jsonResult), 'Results are not equal.'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should compare xml with parsed json', () => { const uParser = new ParserUapi('air:LowFareSearchRsp', 'v_33_0', {}); const parseFunction = require('../../src/Air/AirParser').AIR_LOW_FARE_SEARCH_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/LowFaresSearch.1ADTIEVPAR.xml`).toString(); const jsonResult = require('../FakeResponses/Air/LowFaresSearch.1ADTIEVPAR.json'); return uParser.parse(xml).then(json => { const result = parseFunction.call(uParser, json); assert(JSON.stringify(result) === JSON.stringify(jsonResult), 'Results are not equal.'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); }); describe('AIR_PRICE_REQ_XML()', () => { const test = (jsonResult) => { const airprice = jsonResult['air:AirPricingSolution']; const airpricexml = jsonResult['air:AirPricingSolution_XML']; assert(airprice, 'no air:AirPricingSolution'); assert(airpricexml, 'no xml object'); assert(airprice.TotalPrice, 'No total price'); assert(airprice.Key, 'No key'); assert(airprice.Taxes, 'No taxes'); assert(airpricexml['air:AirPricingInfo_XML'], 'no air:AirPricingInfo_XML'); assert(airpricexml['air:AirSegment_XML'], 'no air:AirSegment_XML'); assert(airpricexml['air:FareNote_XML'], 'no air:FareNote_XML'); } it('should test parser for correct work', () => { const passengers = [{ lastName: 'ENEKEN', firstName: 'SKYWALKER', passCountry: 'UA', passNumber: 'ES221731', birthDate: '25JUL68', gender: 'M', ageCategory: 'ADT', }]; const uParser = new ParserUapi(null, 'v_36_0', { passengers }); const parseFunction = require('../../src/Air/AirParser').AIR_PRICE_REQUEST_PRICING_SOLUTION_XML; const xml = fs.readFileSync(`${xmlFolder}/AirPricingSolution.IEVPAR.xml`).toString(); const jsonSaved = require('../FakeResponses/Air/AirPricingSolution.IEVPAR.json'); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); test(jsonResult); assert(JSON.stringify(jsonSaved) === JSON.stringify(jsonResult), 'Result is not equal to parsed'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test another request with 2 adults and 1 child', () => { const passengers = [{ lastName: 'ENEKEN', firstName: 'SKYWALKER', passCountry: 'UA', passNumber: 'ES221731', birthDate: '25JUL68', gender: 'M', ageCategory: 'ADT', }]; const uParser = new ParserUapi(null, 'v_36_0', { passengers }); const parseFunction = require('../../src/Air/AirParser').AIR_PRICE_REQUEST_PRICING_SOLUTION_XML; const xml = fs.readFileSync(`${xmlFolder}/AirPricingSolution.IEVPAR.2ADT1CNN.xml`).toString(); const jsonSaved = require('../FakeResponses/Air/AirPricingSolution.IEVPAR.2ADT1CNN.json'); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); test(jsonResult); assert(JSON.stringify(jsonSaved) === JSON.stringify(jsonResult), 'Result is not equal to parsed'); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }) }); function testBooking(jsonResult, platingCarrier = true, tickets = false) { assert(_.isArray(jsonResult), 'result not array'); jsonResult.forEach(result => { assert(result.bookingPCC, 'no booking pcc'); assert(_.isArray(result.passengers), 'passengers is not array'); assert(result.passengers.length); assert(result.pnr, 'no pnr'); assert(_.isArray(result.pnrList), 'no pnrList'); assert(_.isArray(result.reservations), 'no reservations'); assert(result.reservations.length); assert(_.isArray(result.trips), 'no trips'); result.trips.forEach(trip => { assert(_.isArray(trip.baggage), 'No baggage in trips'); }); result.reservations.forEach(reservation => { let status = 'Reserved'; if (tickets) { status = 'Ticketed'; } assert(reservation.status === status); assert(!_.isEmpty(reservation.priceInfo), 'no price info'); assert(_.isEqual( Object.keys(reservation.priceInfo), ['TotalPrice', 'BasePrice', 'Taxes', 'passengersCount', 'TaxesInfo'] ), 'no required fields'); }); if (tickets) { assert(_.isArray(result.tickets), 'No tickets in result'); assert(result.tickets.length === result.passengers.length, 'tickets should be for each passenger'); result.tickets.forEach(ticket => { assert(!_.isEmpty(ticket.number), 'No ticket number'); assert(!_.isEmpty(ticket.uapi_passenger_ref), 'No passenger_ref in tickets'); }); } if (platingCarrier) { assert(!_.isEmpty(result.platingCarrier), 'no plating carrier'); } }); } describe('AIR_CREATE_RESERVATION()', () => { it('should test parsing of create reservation 2ADT1CNN', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.2ADT1CNN.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of create reservation 1ADT', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.1ADT.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of create reservation 1ADT (2)', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.1ADT.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of create reservation 1ADT (3)', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.1ADT.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); }); it('should test parsing of reservation with segment failure', () => { const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_CREATE_RESERVATION_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/AirCreateReservation.SegmentFailure.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); assert(false, 'There should be error'); }).catch(err => { assert(err, 'No error returner'); }); }); }); describe('UNIVERSAL_RECORD_IMPORT_SIMPLE_REQUEST', () => { it('should test parsing of universal record import request', () => { const uParser = new ParserUapi('universal:UniversalRecordImportRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_IMPORT_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/UniversalRecordImport.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult, false); }); }); it('should test parsing of universal record import request with tickets', () => { const uParser = new ParserUapi('universal:UniversalRecordImportRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_IMPORT_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/UniversalRecordImport.Ticket.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json) testBooking(jsonResult, false, true); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); it('should test parsing of universal record import request with tickets (multiple passengers)', () => { const uParser = new ParserUapi('universal:UniversalRecordImportRsp', 'v36_0', { }); const parseFunction = require('../../src/Air/AirParser').AIR_IMPORT_REQUEST; const xml = fs.readFileSync(`${xmlFolder}/UniversalRecordImport.MultiplePassengers.Ticket.xml`).toString(); return uParser.parse(xml).then(json => { const jsonResult = parseFunction.call(uParser, json); testBooking(jsonResult, false, true); }).catch(err => assert(false, 'Error during parsing' + err.stack)); }); }); });
Fix: missing line
test/Air/AirParser.test.js
Fix: missing line
<ide><path>est/Air/AirParser.test.js <ide> testBooking(jsonResult); <ide> }).catch(err => assert(false, 'Error during parsing' + err.stack)); <ide> }); <del> }); <ide> <ide> it('should test parsing of reservation with segment failure', () => { <ide> const uParser = new ParserUapi('universal:AirCreateReservationRsp', 'v36_0', { });
Java
apache-2.0
e454ccb2541bfc409a62fda6e8ea856325839f53
0
dlwhitehurst/blackboard,dlwhitehurst/blackboard
package org.dlw.ai.blackboard.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dlw.ai.blackboard.dao.hibernate.GenericDaoHibernate; import org.dlw.ai.blackboard.rule.RuleSet; import org.hibernate.SessionFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class GenericDaoTest extends BaseDaoTestCase { Log log = LogFactory.getLog(GenericDaoTest.class); GenericDao<RuleSet, Long> genericDao; @Autowired SessionFactory sessionFactory; @Before public void setUp() { genericDao = new GenericDaoHibernate<RuleSet, Long>(RuleSet.class, sessionFactory); } @Test public void getRuleSet() { RuleSet ruleSet = genericDao.get(-1L); assertNotNull(ruleSet); assertEquals("PatternMatching",ruleSet.getName()); } }
src/test/java/org/dlw/ai/blackboard/dao/GenericDaoTest.java
package org.dlw.ai.blackboard.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dlw.ai.blackboard.dao.hibernate.GenericDaoHibernate; import org.dlw.ai.blackboard.rule.RuleSet; import org.hibernate.SessionFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class GenericDaoTest extends BaseDaoTestCase { Log log = LogFactory.getLog(GenericDaoTest.class); GenericDao<RuleSet, Long> genericDao; @Autowired SessionFactory sessionFactory; @Before public void setUp() { genericDao = new GenericDaoHibernate<RuleSet, Long>(RuleSet.class, sessionFactory); } @Test public void getUser() { RuleSet ruleSet = genericDao.get(-1L); assertNotNull(ruleSet); assertEquals("PatternMatching",ruleSet.getName()); } }
Method name refactor
src/test/java/org/dlw/ai/blackboard/dao/GenericDaoTest.java
Method name refactor
<ide><path>rc/test/java/org/dlw/ai/blackboard/dao/GenericDaoTest.java <ide> } <ide> <ide> @Test <del> public void getUser() { <add> public void getRuleSet() { <ide> RuleSet ruleSet = genericDao.get(-1L); <ide> assertNotNull(ruleSet); <ide> assertEquals("PatternMatching",ruleSet.getName());
Java
mit
7d0792754e86a6c0cf8ae8a5086f53d7272937c7
0
DominikRidder/ImageExtractor
package tools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class ImageExtractorConfig { private HashMap<String, String> options = new HashMap<String, String>(); public ImageExtractorConfig() { File file = new File("ImageExtractor.config"); System.out.println(file.getAbsolutePath()); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { if (line.startsWith("#")) { continue; } if (line.length() > 0 && Character.isAlphabetic(line.charAt(0))) { String parts[] = line.split("=", 2); options.put(parts[0], parts[1]); } else if (line.replace("\n", "").replace(" ", "").length() == 0) { continue; } } } catch (IOException e) { System.out .println("Reading the ImageExtractor.config Textfile failed."); System.out.println("Guessed dest: " + file.getAbsolutePath()); System.exit(0); } } public String getOption(String optionname) { return options.get(optionname); } public void setOption(String optionname, String value){ options.put(optionname, value); } public void save() { File file = new File("ImageExtractor.config"); StringBuffer text = new StringBuffer(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { if (line.startsWith("#")) { text.append(line + "\n"); } if (line.length() > 0 && Character.isAlphabetic(line.charAt(0))) { String parts[] = line.split("=", 2); text.append(parts[0] + "=" + options.get(parts[0])+"\n"); } else if (line.replace("\n", "").replace(" ", "").length() == 0) { text.append("\n"); continue; } } } catch (IOException e) { System.out .println("Reading the ImageExtractor.config Textfile failed."); System.out.println("Guessed dest: " + file.getAbsolutePath()); System.exit(0); } try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(text.toString()); } catch (IOException e) { System.out .println("Writing the ImageExtractor.config Textfile failed."); System.out.println("Guessed dest: " + file.getAbsolutePath()); System.exit(0); } } }
src/tools/ImageExtractorConfig.java
package tools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Text; public class ImageExtractorConfig { private HashMap<String, String> options = new HashMap<String, String>(); public ImageExtractorConfig() { File file = new File("ImageExtractor.config"); System.out.println(file.getAbsolutePath()); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { if (line.startsWith("#")) { continue; } if (line.length() > 0 && Character.isAlphabetic(line.charAt(0))) { String parts[] = line.split("=", 2); options.put(parts[0], parts[1]); } else if (line.replace("\n", "").replace(" ", "").length() == 0) { continue; } } } catch (IOException e) { System.out .println("Reading the ImageExtractor.config Textfile failed."); System.out.println("Guessed dest: " + file.getAbsolutePath()); System.exit(0); } } public String getOption(String optionname) { return options.get(optionname); } public void setOption(String optionname, String value){ options.put(optionname, value); } public void save() { File file = new File("ImageExtractor.config"); StringBuffer text = new StringBuffer(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { if (line.startsWith("#")) { text.append(line + "\n"); } if (line.length() > 0 && Character.isAlphabetic(line.charAt(0))) { String parts[] = line.split("=", 2); text.append(parts[0] + "=" + options.get(parts[0])+"\n"); } else if (line.replace("\n", "").replace(" ", "").length() == 0) { text.append("\n"); continue; } } } catch (IOException e) { System.out .println("Reading the ImageExtractor.config Textfile failed."); System.out.println("Guessed dest: " + file.getAbsolutePath()); System.exit(0); } try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(text.toString()); } catch (IOException e) { System.out .println("Writing the ImageExtractor.config Textfile failed."); System.out.println("Guessed dest: " + file.getAbsolutePath()); System.exit(0); } } }
removed import, because of warnings by NetBeans
src/tools/ImageExtractorConfig.java
removed import, because of warnings by NetBeans
<ide><path>rc/tools/ImageExtractorConfig.java <ide> import java.io.FileWriter; <ide> import java.io.IOException; <ide> import java.util.HashMap; <del> <del>import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Text; <ide> <ide> public class ImageExtractorConfig { <ide>
JavaScript
mit
28d39bd819069051c5c4147ce55a00227d026f79
0
unclegigi/two-way-binding,unclegigi/two-way-binding
var express = require('express'); var app = express(); app.use(express.static(__dirname + '/')); var server = app.listen(3000, function() { var host = server.address().address var port = server.address().port console.log('Server listening at http://%s:%s', host, port) });
Server.js
var express = require('express').express(); var server = express.listen(3000, function89 { var host = server.address().address var port = server.address().port console.log('Server listening at http://%s:%s', host, port) });
Change Server.js
Server.js
Change Server.js
<ide><path>erver.js <del>var express = require('express').express(); <add>var express = require('express'); <add>var app = express(); <ide> <add>app.use(express.static(__dirname + '/')); <ide> <del>var server = express.listen(3000, function89 { <add>var server = app.listen(3000, function() { <ide> var host = server.address().address <ide> var port = server.address().port <ide> console.log('Server listening at http://%s:%s', host, port)
Java
apache-2.0
89b96b5bab2b5addc3b65c894cf4ff949cfd67ac
0
jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. 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. </license>*/ package org.ppwcode.vernacular.value_III.stubs; import org.ppwcode.vernacular.value_III.AbstractValueEditor; public class StubAbstractValueEditor extends AbstractValueEditor<StubAbstractValue> { private final static StubAbstractValue DUMMY = new StubAbstractValue(); @Override public void setAsText(String text) { if (text == null) { setValue(null); } else { setValue(DUMMY); } } @Override public String getAsText() { if (getValue() == null) { return null; } else { return "DUMMY"; } } }
java/vernacular/value/trunk/src/test/java/org/ppwcode/vernacular/value_III/stubs/StubAbstractValueEditor.java
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. 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. </license>*/ package org.ppwcode.vernacular.value_III.stubs; import org.ppwcode.vernacular.value_III.AbstractValueEditor; public class StubAbstractValueEditor extends AbstractValueEditor<StubValue> { private final static StubAbstractValue DUMMY = new StubAbstractValue(); @Override public void setAsText(String text) { if (text == null) { setValue(null); } else { setValue(DUMMY); } } @Override public String getAsText() { if (getValue() == null) { return null; } else { return "DUMMY"; } } }
StubValue replaced by StubAbstractValue
java/vernacular/value/trunk/src/test/java/org/ppwcode/vernacular/value_III/stubs/StubAbstractValueEditor.java
StubValue replaced by StubAbstractValue
<ide><path>ava/vernacular/value/trunk/src/test/java/org/ppwcode/vernacular/value_III/stubs/StubAbstractValueEditor.java <ide> import org.ppwcode.vernacular.value_III.AbstractValueEditor; <ide> <ide> <del>public class StubAbstractValueEditor extends AbstractValueEditor<StubValue> { <add>public class StubAbstractValueEditor extends AbstractValueEditor<StubAbstractValue> { <ide> <ide> private final static StubAbstractValue DUMMY = new StubAbstractValue(); <ide>
Java
agpl-3.0
73f2f6b106b4aedc4ae671a2fef1a4570195d324
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
2d1d3ce8-2e62-11e5-9284-b827eb9e62be
hello.java
2d17d352-2e62-11e5-9284-b827eb9e62be
2d1d3ce8-2e62-11e5-9284-b827eb9e62be
hello.java
2d1d3ce8-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>2d17d352-2e62-11e5-9284-b827eb9e62be <add>2d1d3ce8-2e62-11e5-9284-b827eb9e62be
JavaScript
mit
a487821461148c9fa175a4b6bba622c4a97b679a
0
ryogeisya/vue,ryogeisya/vue
var utils = require('../utils') /** * Binding for partials */ module.exports = { isLiteral: true, bind: function () { var id = this.expression if (!id) return var el = this.el, compiler = this.compiler, partial = compiler.getOption('partials', id) if (!partial) { if (id === 'yield') { utils.warn('{{>yield}} syntax has been deprecated. Use <content> tag instead.') } return } partial = partial.cloneNode(true) // comment ref node means inline partial if (el.nodeType === 8) { // keep a ref for the partial's content nodes var nodes = [].slice.call(partial.childNodes), parent = el.parentNode parent.insertBefore(partial, el) parent.removeChild(el) // compile partial after appending, because its children's parentNode // will change from the fragment to the correct parentNode. // This could affect directives that need access to its element's parentNode. nodes.forEach(compiler.compile, compiler) } else { // just set innerHTML... el.innerHTML = '' el.appendChild(partial) } } }
src/directives/partial.js
var utils = require('../utils') /** * Binding for partials */ module.exports = { isLiteral: true, bind: function () { var id = this.expression if (!id) return var el = this.el, compiler = this.compiler, partial = compiler.getOption('partials', id) if (!partial) { if (id === 'yield') { utils.warn('{{>yield}} syntax has been deprecated. Use <content> tag instead.') } return } partial = partial.cloneNode(true) // comment ref node means inline partial if (el.nodeType === 8) { // keep a ref for the partial's content nodes var nodes = [].slice.call(partial.childNodes), parent = el.parentNode parent.insertBefore(partial, el) parent.removeChild(el) // compile partial after appending, because its children's parentNode // will change from the fragment to the correct parentNode. // This could affect directives that need access to its element's parentNode. nodes.forEach(compiler.compile, compiler) } else { // just set innerHTML... el.innerHTML = '' el.appendChild(partial) } } }
strip newline at end
src/directives/partial.js
strip newline at end
JavaScript
isc
39433338901821f882380226e880ff2801d7b3ba
0
dbp/latinamerica,dbp/latinamerica,dbp/latinamerica,dbp/latinamerica
function init(set_year, initial_year, close_callback, load_entry, load_year) { var set_year_wrap = function(year) { execF(execF(set_year, year), null); }; $(document).ready(function() { $(".slider").slider({ min: 1491, max: 2020, step: 1, value: initial_year, }); var reqPending = false; $(".slider").bind("slide", function(event, ui) { if (!reqPending) { reqPending = true; setTimeout(function () { reqPending = false; set_year_wrap(ui.value); }, 200); } $(".yearIndicator").text(ui.value); }); $(".yearIndicator").text("" + initial_year); $(document).on("click", ".close", function () { set_fragment(get_fragment_year(), -1); execF(close_callback, null); }); $(document).on("click", "a[data-entry]", function() { var id = parseInt($(this).attr("data-entry")); var year = -1; if (typeof $(this).attr("data-year") !== "undefined") { year = parseInt($(this).attr("data-year")); $(".slider").slider("value", year); $(".yearIndicator").text(year); } execF(execF(execF(load_entry, year), id), null); return false; }); window.onpopstate = function(event) { if (event.laInfo === "manual") { return; } console.log("popping"); var year = get_fragment_year(); var id = get_fragment_id(); $(".slider").slider("value", year); $(".yearIndicator").text(year); if (id !== -1) { execF(execF(execF(load_entry, year), id), null); } else { execF(close_callback, null); execF(execF(load_year, year), null); } }; }); } function set_year_specific(year) { if (year >= 1900) { $(".inset").show(); } else { $(".inset").hide(); } } function set_fragment(year, id) { history.pushState({laInfo: "manual"}, '', "#year=" + year + ",id=" + id); } function paginate(id) { var d = $(".id" + id); var pageDividers = d.find(".page"); if (pageDividers.length != 0) { var pages = []; var collected = []; var cur = $("<div class='page'>"); var start = false; d.children().each(function(i,e) { console.log(e); if (!start) { if ($(e).hasClass("page")) { start = true; if (typeof $(e).attr("data-title") !== "undefined") { cur.attr("data-title", $(e).attr("data-title")); } $(e).remove(); } } else { if ($(e).hasClass("page")) { collected.map(function(elt) { cur.append(elt); }); collected = []; pages.push(cur); cur = $("<div class='page'>"); if (typeof $(e).attr("data-title") !== "undefined") { cur.attr("data-title", $(e).attr("data-title")); } } else { collected.push($(e).clone()); } $(e).remove(); } }); collected.map(function(elt) { cur.append(elt); }); pages.push(cur); console.log(pages); pages.map(function(e) { d.append(e); }); var pagesDS = pages.map(function (p) { var title; if (typeof $(p).attr("data-title") !== "undefined") { title = "" + $(p).attr("data-title"); } else { title = ""; } return {title: title, page: p}; }); set_page(d, pagesDS, 0); } d.find(".close").show(); } function set_page(d, pages, i) { d.find('.page').hide(); $(pages[i].page).show(); d.find(".nav").remove(); var nav = $("<div class='nav'>"); var titleText = "Page " + (i+1) + " of " + pages.length; if (pages[i].title !== "") { titleText = titleText + ": " + pages[i].title; } var title = $("<span class='title'>").text(titleText); var prev = $("<a href='#' class='prev'>Previous</span>"); var next = $("<a href='#' class='next'>Next</span>"); if (i !== 0) { nav.append(prev); } nav.append(title); if (i !== pages.length - 1) { nav.append(next); } prev.on('click', function () { if (i > 0) { set_page(d, pages, i-1); } return false; }); next.on('click', function () { if (i < pages.length - 1) { set_page(d, pages, i+1); } return false; }); d.append(nav); } function toggle_div(id) { $("#" + id).toggle(); } function get_fragment_year() { try { var v = parseInt(location.hash.split(",")[0].split("=")[1]); if (isNaN(v)) { return -1; } else { return v; } } catch (e) { return -1; } } function get_fragment_id() { try { return parseInt(location.hash.split(",")[1].split("=")[1]); } catch (e) { return -1; } }
site.js
function init(set_year, initial_year, close_callback, load_entry, load_year) { var set_year_wrap = function(year) { execF(execF(set_year, year), null); }; $(document).ready(function() { $(".slider").slider({ min: 1491, max: 2020, step: 1, value: initial_year, }); $(".slider").bind("slide", function(event, ui) { set_year_wrap(ui.value); $(".yearIndicator").text(ui.value); }); $(".yearIndicator").text("" + initial_year); $(document).on("click", ".close", function () { set_fragment(get_fragment_year(), -1); execF(close_callback, null); }); $(document).on("click", "a[data-entry]", function() { var id = parseInt($(this).attr("data-entry")); var year = -1; if (typeof $(this).attr("data-year") !== "undefined") { year = parseInt($(this).attr("data-year")); $(".slider").slider("value", year); $(".yearIndicator").text(year); } execF(execF(execF(load_entry, year), id), null); return false; }); window.onpopstate = function(event) { if (event.laInfo === "manual") { return; } console.log("popping"); var year = get_fragment_year(); var id = get_fragment_id(); $(".slider").slider("value", year); $(".yearIndicator").text(year); if (id !== -1) { execF(execF(execF(load_entry, year), id), null); } else { execF(close_callback, null); execF(execF(load_year, year), null); } }; }); } function set_year_specific(year) { if (year >= 1900) { $(".inset").show(); } else { $(".inset").hide(); } } function set_fragment(year, id) { history.pushState({laInfo: "manual"}, '', "#year=" + year + ",id=" + id); } function paginate(id) { var d = $(".id" + id); var pageDividers = d.find(".page"); if (pageDividers.length != 0) { var pages = []; var collected = []; var cur = $("<div class='page'>"); var start = false; d.children().each(function(i,e) { console.log(e); if (!start) { if ($(e).hasClass("page")) { start = true; if (typeof $(e).attr("data-title") !== "undefined") { cur.attr("data-title", $(e).attr("data-title")); } $(e).remove(); } } else { if ($(e).hasClass("page")) { collected.map(function(elt) { cur.append(elt); }); collected = []; pages.push(cur); cur = $("<div class='page'>"); if (typeof $(e).attr("data-title") !== "undefined") { cur.attr("data-title", $(e).attr("data-title")); } } else { collected.push($(e).clone()); } $(e).remove(); } }); collected.map(function(elt) { cur.append(elt); }); pages.push(cur); console.log(pages); pages.map(function(e) { d.append(e); }); var pagesDS = pages.map(function (p) { var title; if (typeof $(p).attr("data-title") !== "undefined") { title = "" + $(p).attr("data-title"); } else { title = ""; } return {title: title, page: p}; }); set_page(d, pagesDS, 0); } d.find(".close").show(); } function set_page(d, pages, i) { d.find('.page').hide(); $(pages[i].page).show(); d.find(".nav").remove(); var nav = $("<div class='nav'>"); var titleText = "Page " + (i+1) + " of " + pages.length; if (pages[i].title !== "") { titleText = titleText + ": " + pages[i].title; } var title = $("<span class='title'>").text(titleText); var prev = $("<a href='#' class='prev'>Previous</span>"); var next = $("<a href='#' class='next'>Next</span>"); if (i !== 0) { nav.append(prev); } nav.append(title); if (i !== pages.length - 1) { nav.append(next); } prev.on('click', function () { if (i > 0) { set_page(d, pages, i-1); } return false; }); next.on('click', function () { if (i < pages.length - 1) { set_page(d, pages, i+1); } return false; }); d.append(nav); } function toggle_div(id) { $("#" + id).toggle(); } function get_fragment_year() { try { var v = parseInt(location.hash.split(",")[0].split("=")[1]); if (isNaN(v)) { return -1; } else { return v; } } catch (e) { return -1; } } function get_fragment_id() { try { return parseInt(location.hash.split(",")[1].split("=")[1]); } catch (e) { return -1; } }
partial fix for faster load - load on sliding, with a minor delay Conflicts: site.js
site.js
partial fix for faster load - load on sliding, with a minor delay
<ide><path>ite.js <ide> value: initial_year, <ide> }); <ide> <add> var reqPending = false; <add> <ide> $(".slider").bind("slide", function(event, ui) { <del> set_year_wrap(ui.value); <add> if (!reqPending) { <add> reqPending = true; <add> setTimeout(function () { <add> reqPending = false; <add> set_year_wrap(ui.value); <add> }, 200); <add> } <ide> $(".yearIndicator").text(ui.value); <ide> }); <ide>
Java
mit
a2f60c61338a74e2b80932886d517d3b3c65e1b9
0
ictrobot/Cubes,ictrobot/Cubes,RedTroop/Cubes_2,RedTroop/Cubes_2
package ethanjones.modularworld.core.compatibility; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import ethanjones.modularworld.ModularWorld; import ethanjones.modularworld.core.logging.Log; import ethanjones.modularworld.graphics.AssetManager; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public abstract class Compatibility { public final Application.ApplicationType applicationType; protected Compatibility(Application.ApplicationType applicationType) { this.applicationType = applicationType; } public void init() { ModularWorld.instance.eventBus.register(this); } public boolean isHeadless() { return false; } public FileHandle getBaseFolder() { return Gdx.files.absolute(System.getProperty("user.dir")); } public FileHandle getWorkingFolder() { return Gdx.files.absolute(System.getProperty("user.dir")); } public void getAssets(AssetManager assetManager) { findAssets(Gdx.files.internal("assets"), assetManager.assets, ""); } protected void findAssets(FileHandle parent, AssetManager.AssetFolder parentFolder, String path) { for (FileHandle fileHandle : parent.list()) { if (fileHandle.isDirectory()) { AssetManager.AssetFolder folder = new AssetManager.AssetFolder(fileHandle.name(), parentFolder); parentFolder.addFolder(folder); findAssets(fileHandle, folder, path + fileHandle.name() + "/"); } else if (fileHandle.name().endsWith(".png")) { parentFolder.addFile(new AssetManager.Asset(fileHandle, path + fileHandle.name(), fileHandle.readBytes(), parentFolder)); } } } /** * Extracts from jar */ protected void extractAssets(AssetManager assetManager) { String assets = "assets"; try { CodeSource src = Compatibility.class.getProtectionDomain().getCodeSource(); List<String> list = new ArrayList<String>(); if (src != null) { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String name = ze.getName(); if (name.startsWith(assets)) { name = name.substring(ze.getName().lastIndexOf(assets) + assets.length() + 1); Log.info(name); } } } } catch (Exception e) { e.printStackTrace(); } } }
core/src/ethanjones/modularworld/core/compatibility/Compatibility.java
package ethanjones.modularworld.core.compatibility; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import ethanjones.modularworld.ModularWorld; import ethanjones.modularworld.core.logging.Log; import ethanjones.modularworld.graphics.AssetManager; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public abstract class Compatibility { public final Application.ApplicationType applicationType; protected Compatibility(Application.ApplicationType applicationType) { this.applicationType = applicationType; } public void init() { ModularWorld.instance.eventBus.register(this); } public boolean isHeadless() { return false; } public FileHandle getBaseFolder() { return Gdx.files.absolute(System.getProperty("user.dir")); } public FileHandle getWorkingFolder() { return Gdx.files.absolute(System.getProperty("user.dir")); } public void getAssets(AssetManager assetManager) { findAssets(Gdx.files.internal("assets"), assetManager.assets, ""); } protected void findAssets(FileHandle parent, AssetManager.AssetFolder parentFolder, String path) { for (FileHandle fileHandle : parent.list()) { if (fileHandle.isDirectory()) { AssetManager.AssetFolder folder = new AssetManager.AssetFolder(fileHandle.name(), parentFolder); parentFolder.addFolder(folder); findAssets(fileHandle, folder, path + fileHandle.name() + "/"); } else if (fileHandle.name().endsWith(".png")) { parentFolder.addFile(new AssetManager.Asset(fileHandle, path + fileHandle.name(), fileHandle.readBytes(), parentFolder)); } } } /** * Extracts from jar */ protected void extractAssets(AssetManager assetManager) { try { CodeSource src = Compatibility.class.getProtectionDomain().getCodeSource(); List<String> list = new ArrayList<String>(); if (src != null) { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { if (ze.getName().startsWith("assets")) { String name = ze.getName().substring(ze.getName().lastIndexOf("assets")); Log.info(name); } } } } catch (Exception e) { e.printStackTrace(); } } }
Fix assets on non exploded installs (try 2)
core/src/ethanjones/modularworld/core/compatibility/Compatibility.java
Fix assets on non exploded installs (try 2)
<ide><path>ore/src/ethanjones/modularworld/core/compatibility/Compatibility.java <ide> * Extracts from jar <ide> */ <ide> protected void extractAssets(AssetManager assetManager) { <add> String assets = "assets"; <ide> try { <ide> CodeSource src = Compatibility.class.getProtectionDomain().getCodeSource(); <ide> List<String> list = new ArrayList<String>(); <ide> ZipEntry ze = null; <ide> <ide> while ((ze = zip.getNextEntry()) != null) { <del> if (ze.getName().startsWith("assets")) { <del> String name = ze.getName().substring(ze.getName().lastIndexOf("assets")); <add> String name = ze.getName(); <add> if (name.startsWith(assets)) { <add> name = name.substring(ze.getName().lastIndexOf(assets) + assets.length() + 1); <ide> Log.info(name); <ide> } <ide> }
Java
apache-2.0
2f8a3be465fde0bc8e8278c8ec46f5a9d15ebcac
0
subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/base
package io.subutai.core.kurjun.manager.impl; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.ws.rs.core.Response; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.http.HttpStatus; import com.google.common.base.Strings; import io.subutai.common.dao.DaoManager; import io.subutai.common.security.crypto.pgp.PGPKeyUtil; import io.subutai.common.settings.SystemSettings; import io.subutai.common.util.RestUtil; import io.subutai.core.identity.api.IdentityManager; import io.subutai.core.kurjun.manager.api.KurjunManager; import io.subutai.core.kurjun.manager.api.model.Kurjun; import io.subutai.core.kurjun.manager.impl.dao.KurjunDataService; import io.subutai.core.kurjun.manager.impl.model.KurjunEntity; import io.subutai.core.kurjun.manager.impl.model.KurjunType; import io.subutai.core.security.api.SecurityManager; /** * */ public class KurjunManagerImpl implements KurjunManager { //********************************** private IdentityManager identityManager; private SecurityManager securityManager; private DaoManager daoManager; private KurjunDataService dataService; private static Properties properties; //********************************** //TODO getValues from SystemManager; private String localKurjunURL; private String globalKurjunURL; //**************************************** // public void KurjunManagerImpl( /*IdentityManager identityManager, SecurityManager securityManager,*/ // DaoManager daoManager ) // { // this.identityManager = identityManager; // this.securityManager = securityManager; // this.daoManager = daoManager; // // dataService = new KurjunDataService( daoManager ); // } //**************************************** public void init() { String fingerprint = securityManager.getKeyManager().getFingerprint( null ); properties = loadProperties(); dataService = new KurjunDataService( daoManager ); if ( Strings.isNullOrEmpty( getUser( KurjunType.Local.getId(), fingerprint ) ) ) { registerUser( KurjunType.Local.getId(), fingerprint ); } else { authorizeUser( KurjunType.Local.getId(), fingerprint ); } } //**************************************** private String getKurjunUrl( int kurjunType, String uri ) { try { if ( kurjunType == KurjunType.Local.getId() ) { for ( final String s : SystemSettings.getGlobalKurjunUrls() ) { return s + uri; } } else if ( kurjunType == KurjunType.Global.getId() ) { for ( final String s : SystemSettings.getLocalKurjunUrls() ) { return s + uri; } } else { for ( final String s : SystemSettings.getGlobalKurjunUrls() ) { return s + uri; } } } catch ( ConfigurationException e ) { e.printStackTrace(); } // if ( kurjunType == KurjunType.Local.getId() ) // { // return localKurjunURL + uri; // } // else if ( kurjunType == KurjunType.Global.getId() ) // { // return globalKurjunURL + uri; // } // else // { // return globalKurjunURL + uri; // } return null; } //**************************************** @Override public String registerUser( int kurjunType, String fingerprint ) { //***************************************** String authId = ""; if ( Strings.isNullOrEmpty( getUser( kurjunType, fingerprint ) ) ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.add" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); Response response = client.get(); //TODO get authID from client //authId = client Output; } if ( dataService.getKurjunData( fingerprint ) == null ) { //************* Sign ********************* String signedMessage = ""; //securityManager.getEncryptionTool(). //**************************************** Kurjun kurjun = new KurjunEntity(); kurjun.setType( kurjunType ); kurjun.setOwnerFingerprint( fingerprint ); kurjun.setAuthID( authId ); kurjun.setSignedMessage( signedMessage ); dataService.persistKurjunData( kurjun ); } return null; } //**************************************** @Override public String authorizeUser( int kurjunType, String fingerprint ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.get" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); return null; } //**************************************** @Override public boolean setSystemOwner( int kurjunType, String fingerprint ) { return true; } //**************************************** @Override public String getSystemOwner( int kurjunType ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.auth" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); return null; } //**************************************** @Override public String getUser( int kurjunType, String fingerprint ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.get" ) ); WebClient client = RestUtil.createTrustedWebClient( url + "/" + fingerprint ); // client.query( "fingerprint", fingerprint ); Response response = client.get(); if ( response.getStatus() != HttpStatus.SC_OK ) { return null; } return null; } public void setIdentityManager( final IdentityManager identityManager ) { this.identityManager = identityManager; } public void setSecurityManager( final SecurityManager securityManager ) { this.securityManager = securityManager; } private Properties loadProperties() { Properties configProp = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream( "rest.properties" ); System.out.println( "Read all properties from file" ); try { configProp.load( in ); return configProp; } catch ( IOException e ) { e.printStackTrace(); return null; } } public void setDaoManager( final DaoManager daoManager ) { this.daoManager = daoManager; } }
management/server/core/kurjun-manager/kurjun-manager-impl/src/main/java/io/subutai/core/kurjun/manager/impl/KurjunManagerImpl.java
package io.subutai.core.kurjun.manager.impl; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.ws.rs.core.Response; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.cxf.jaxrs.client.WebClient; import com.google.common.base.Strings; import io.subutai.common.dao.DaoManager; import io.subutai.common.security.crypto.pgp.PGPKeyUtil; import io.subutai.common.util.RestUtil; import io.subutai.core.identity.api.IdentityManager; import io.subutai.core.kurjun.manager.api.KurjunManager; import io.subutai.core.kurjun.manager.api.model.Kurjun; import io.subutai.core.kurjun.manager.impl.dao.KurjunDataService; import io.subutai.core.kurjun.manager.impl.model.KurjunEntity; import io.subutai.core.kurjun.manager.impl.model.KurjunType; import io.subutai.core.security.api.SecurityManager; /** * */ public class KurjunManagerImpl implements KurjunManager { //********************************** private IdentityManager identityManager; private SecurityManager securityManager; private DaoManager daoManager; private KurjunDataService dataService; private static Properties properties; //********************************** //TODO getValues from SystemManager; private String localKurjunURL; private String globalKurjunURL; //**************************************** // public void KurjunManagerImpl( /*IdentityManager identityManager, SecurityManager securityManager,*/ // DaoManager daoManager ) // { // this.identityManager = identityManager; // this.securityManager = securityManager; // this.daoManager = daoManager; // // dataService = new KurjunDataService( daoManager ); // } //**************************************** public void init() { String fingerprint = securityManager.getKeyManager().getFingerprint( null ); properties = loadProperties(); dataService = new KurjunDataService( daoManager ); if ( Strings.isNullOrEmpty( getUser( KurjunType.Local.getId(), fingerprint ) ) ) { registerUser( KurjunType.Local.getId(), fingerprint ); } else { authorizeUser( KurjunType.Local.getId(), fingerprint ); } } //**************************************** private String getKurjunUrl( int kurjunType, String uri ) { if ( kurjunType == KurjunType.Local.getId() ) { return localKurjunURL + uri; } else if ( kurjunType == KurjunType.Global.getId() ) { return globalKurjunURL + uri; } else { return globalKurjunURL + uri; } } //**************************************** @Override public String registerUser( int kurjunType, String fingerprint ) { //***************************************** String authId = ""; if ( Strings.isNullOrEmpty( getUser( kurjunType, fingerprint ) ) ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.add" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); Response response = client.get(); //TODO get authID from client //authId = client Output; } if ( dataService.getKurjunData( fingerprint ) == null ) { //************* Sign ********************* String signedMessage = ""; //securityManager.getEncryptionTool(). //**************************************** Kurjun kurjun = new KurjunEntity(); kurjun.setType( kurjunType ); kurjun.setOwnerFingerprint( fingerprint ); kurjun.setAuthID( authId ); kurjun.setSignedMessage( signedMessage ); dataService.persistKurjunData( kurjun ); } return null; } //**************************************** @Override public String authorizeUser( int kurjunType, String fingerprint ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.get" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); return null; } //**************************************** @Override public boolean setSystemOwner( int kurjunType, String fingerprint ) { return true; } //**************************************** @Override public String getSystemOwner( int kurjunType ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.auth" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); return null; } //**************************************** @Override public String getUser( int kurjunType, String fingerprint ) { String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.get" ) ); WebClient client = RestUtil.createTrustedWebClient( url ); return null; } public void setIdentityManager( final IdentityManager identityManager ) { this.identityManager = identityManager; } public void setSecurityManager( final SecurityManager securityManager ) { this.securityManager = securityManager; } private Properties loadProperties() { Properties configProp = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream( "rest.properties" ); System.out.println( "Read all properties from file" ); try { configProp.load( in ); return configProp; } catch ( IOException e ) { e.printStackTrace(); return null; } } public void setDaoManager( final DaoManager daoManager ) { this.daoManager = daoManager; } }
added global and local kurjun urls
management/server/core/kurjun-manager/kurjun-manager-impl/src/main/java/io/subutai/core/kurjun/manager/impl/KurjunManagerImpl.java
added global and local kurjun urls
<ide><path>anagement/server/core/kurjun-manager/kurjun-manager-impl/src/main/java/io/subutai/core/kurjun/manager/impl/KurjunManagerImpl.java <ide> import org.apache.commons.configuration.ConfigurationException; <ide> import org.apache.commons.configuration.PropertiesConfiguration; <ide> import org.apache.cxf.jaxrs.client.WebClient; <add>import org.apache.http.HttpStatus; <ide> <ide> import com.google.common.base.Strings; <ide> <ide> import io.subutai.common.dao.DaoManager; <ide> import io.subutai.common.security.crypto.pgp.PGPKeyUtil; <add>import io.subutai.common.settings.SystemSettings; <ide> import io.subutai.common.util.RestUtil; <ide> import io.subutai.core.identity.api.IdentityManager; <ide> import io.subutai.core.kurjun.manager.api.KurjunManager; <ide> //**************************************** <ide> private String getKurjunUrl( int kurjunType, String uri ) <ide> { <del> if ( kurjunType == KurjunType.Local.getId() ) <del> { <del> return localKurjunURL + uri; <del> } <del> else if ( kurjunType == KurjunType.Global.getId() ) <del> { <del> return globalKurjunURL + uri; <del> } <del> else <del> { <del> return globalKurjunURL + uri; <del> } <add> try <add> { <add> if ( kurjunType == KurjunType.Local.getId() ) <add> { <add> for ( final String s : SystemSettings.getGlobalKurjunUrls() ) <add> { <add> return s + uri; <add> } <add> } <add> else if ( kurjunType == KurjunType.Global.getId() ) <add> { <add> for ( final String s : SystemSettings.getLocalKurjunUrls() ) <add> { <add> return s + uri; <add> } <add> } <add> else <add> { <add> for ( final String s : SystemSettings.getGlobalKurjunUrls() ) <add> { <add> return s + uri; <add> } <add> } <add> } <add> catch ( ConfigurationException e ) <add> { <add> e.printStackTrace(); <add> } <add> <add> // if ( kurjunType == KurjunType.Local.getId() ) <add> // { <add> // return localKurjunURL + uri; <add> // } <add> // else if ( kurjunType == KurjunType.Global.getId() ) <add> // { <add> // return globalKurjunURL + uri; <add> // } <add> // else <add> // { <add> // return globalKurjunURL + uri; <add> // } <add> return null; <ide> } <ide> <ide> <ide> public String getUser( int kurjunType, String fingerprint ) <ide> { <ide> String url = getKurjunUrl( kurjunType, properties.getProperty( "url.identity.user.get" ) ); <del> WebClient client = RestUtil.createTrustedWebClient( url ); <del> <add> WebClient client = RestUtil.createTrustedWebClient( url + "/" + fingerprint ); <add> // client.query( "fingerprint", fingerprint ); <add> <add> Response response = client.get(); <add> <add> if ( response.getStatus() != HttpStatus.SC_OK ) <add> { <add> return null; <add> } <ide> <ide> return null; <ide> }
Java
apache-2.0
61196f1a951e0d8aeacd224e9c5878b19bcae57c
0
gkqzdxajh/dubbo,dangdangdotcom/dubbox,atreeyang/dubbo,delavior/dubbo,grayaaa/dubbo,remoting/dubbox,lovepoem/dubbo,gyk001/dubbox,youjava/dubbo,wtmilk/dubbo,BianWenlong/dubbo,finch0219/dubbo,11wuqingchao/dubbo,kyle-liu/dubbo2study,nichoding/dubbo,ykqabc/dubbo,damy/dubbo,wthuan/dubbox,gjhuai/dubbo,DR-YangLong/dubbox,Karanyxy/IRepository,TonyLeee/dubbo,ryankong/dubbo,npccsb/dubbox,gkqzdxajh/dubbo,flamezyg/dubbo,aglne/dubbo,13366348079/Dubbo,wuwen5/dubbo,alibaba/dubbo,sinsinpub/dubbo,luyulong/dubbox,lsw0742/dubbox,micmiu/dubbo,wuwenyu19860817/dubbo,zk279444107/dubbo,codingboys/dubbox,xiaozhou322/dubbo-master,wei121363/dubbo,ligzy/dubbo,dangdangdotcom/dubbox,wz12406/dubbo,kkllwww007/dubbox,Kevin2030/dubbo,xiaocat963/dubbo,mingbotang/dubbo,jerk1991/dubbo,yujiasun/dubbo,fzbook/dubboEvent,TonyLeee/dubbo,liyong7514/dubbo,yujiasun/dubbo,huangkunyhx/dubbox,kk17/dubbox,finch0219/dubbo,atreeyang/dubbo,lsjiguang/dangdangdotcom,remoting/dubbox,walkongrass/dubbo,shuvigoss/dubbox,liuxb945/dubbo,ys305751572/dubbo,ledotcom/le-dubbo,chengdedeng/dubbox,pipi668/dubbox,hutea/dubbo,tangqian/dubbo,magintursh/dubbo,gwisoft/dubbo,huangping40/dubbox,qtvbwfn/dubbo,mingbotang/dubbo,gigold/dubbo,JeffreyWei/dubbox,lovepoem/dubbo,sunxiang0918/dubbo,whubbt/dubbo,daniellitoc/dubbo-Research,lxq1008/dubbo,redbeans2015/dubbox,codingboys/dubbox,wuwenyu19860817/dubbo,winndows/dubbo,sinsinpub/dubbo,lsw0742/dubbox,hl198181/dubbo,dadarom/dubbo,bpzhang/dubbo,yuankui/dubbo,remoting/dubbox,zouyoujin/dubbo,tangqian/dubbo,huangping40/dubbox,forever342/dubbo,yihaijun/dubbox,npccsb/dubbox,qtvbwfn/dubbo,xiaoguiguixm/dubbo,wtmilk/dubbo,loafer/dubbox,HHzzhz/dubbo,lovepoem/dubbo,codingboys/dubbox,wei121363/dubbo,wusuoyongxin/dubbox,maczam/dubbox,lacrazyboy/dubbox,tangqian/dubbo,wuwen5/dubbo,gkqzdxajh/dubbo,nickeyfff/dubbox,yuyijq/dubbo,DR-YangLong/dubbox,lacrazyboy/dubbox,wangjingfei/dubbo,dadarom/dubbo,gwisoft/dubbo,BianWenlong/dubbo,allen-zkm/dubbo,nickeyfff/dubbox,gavinage/dubbox,yangaiche/dubbo,Jeromefromcn/dubbox,winndows/dubbo,zouyoujin/dubbo,luyulong/dubbox,springning/dubbo,lzwlzw/dubbo,hdp-piplus/dubbox,lsw0742/dubbox,taohaolong/dubbo,softliumin/dubbo,fzbook/dubboEvent,softliumin/dubbo,magintursh/dubbo,yinheli/dubbo,yinheli/dubbo,fengyie007/dubbo,lrysir/dubbo,open-source-explore/dubbo,walkongrass/dubbo,DR-YangLong/dubbox,kutala/dubbo,luyulong/dubbox,sunxiang0918/dubbo,xianjunkuang/dubbos,forever342/dubbo,yshaojie/dubbo,HHzzhz/dubbo,model919/dubbo,yiyezhangmu/dubbox,zzycjcg/dubbo,DavidAlphaFox/dubbo,cailin186/dubbox,archlevel/dubbo,followyourheart/dubbo,yshaojie/dubbo,JackyMoto/dubbo,hiboycomehere/dubbo,forever342/dubbo,fly3q/dubbo,kyle-liu/dubbo2study,xiaozhou322/dubbo-master,cf9lovely/cf_rp,yiyezhangmu/dubbox,RiverWeng/dubbo,Kevin2030/dubbo,Karanyxy/IRepository,HHzzhz/dubbo,huangping40/dubbox,grayaaa/dubbo,orika/dubbo,wtmilk/dubbo,quyixia/dubbox,wuwenyu19860817/dubbo,manlonglin/dubbo,dangdangdotcom/dubbox,delavior/dubbo,codingboyli/dubbo,mosoft521/dubbox,fengshao0907/dubbox,microIBM/dubbo,wangcan2014/dubbo,microIBM/dubbo,livvyguo/dubbo,13366348079/Dubbo,walkongrass/dubbo,ronaldo9grey/dubbo,fengshao0907/dubbox,majinkai/dubbox,wusuoyongxin/dubbox,RoyZeng/dubbo,aglne/dubbo,liuxinglanyue/dubbox,xianjunkuang/dubbos,hiboycomehere/dubbo,leesir/dubbo,asherhu/dubbox,guoxu0514/dubbo,JeffreyWei/dubbox,rabbitcount/dubbo,liuxb945/dubbo,xiaojunbeyond/dubbox,andydreaming/dubbo,andydreaming/dubbo,mosoft521/dubbox,followyourheart/dubbo,JeffreyWei/dubbox,MX2015/dubbo,grayaaa/dubbo,yunemr/dubbox,uubu/dubbox,lichenq/dubbo,leesir/dubbo,huangkunyhx/dubbox,kevintvh/dubbo,liyong7514/dubbo,leesir/dubbo,wthuan/dubbox,kevintvh/dubbo,Fushicho/dubbo,daodaoliang/dubbo,cailin186/dubbox,Jeromefromcn/dubbox,loafer/dubbox,izerui/dubbo,lxq1008/dubbo,delavior/dubbo,i54334/dubbo,ServerStarted/dubbo,rogerchina/dubbo,13366348079/Dubbo,gaoxianglong/dubbo,jerk1991/dubbo,clj198606061111/dubbox_spring4,guoxu0514/dubbo,xiaocat963/dubbo,JasonHZXie/dubbo,yshaojie/dubbo,wusuoyongxin/dubbox,JackyMoto/dubbo,gwisoft/dubbo,winndows/dubbo,majinkai/dubbox,cenqiongyu/dubbo,OopsOutOfMemory/dubbo,softliumin/dubbo,ryankong/dubbo,youjava/dubbo,archlevel/dubbo,coolworker/dubbo,youjava/dubbo,xiaoguiguixm/dubbo,orika/dubbo,cenqiongyu/dubbo,juqkai/dubbo,jieke-tao/dubbo,cf9lovely/cf_rp,kutala/dubbo,atreeyang/dubbo,wangsan/dubbo,wuwen5/dubbo,OopsOutOfMemory/dubbo,lichenq/dubbo,RoyZeng/dubbo,whubbt/dubbo,taohaolong/dubbo,RiverWeng/dubbo,gyk001/dubbox,lrysir/dubbo,liuxb945/dubbo,surlymo/dubbo,qtvbwfn/dubbo,nichoding/dubbo,yujiasun/dubbo,BianWenlong/dubbo,model919/dubbo,kk17/dubbox,springning/dubbo,wangsan/dubbo,ykqabc/dubbo,DavidAlphaFox/dubbo,orzroa/dubbo,gyk001/dubbox,yihaijun/dubbox,11wuqingchao/dubbo,jkchensc/dubbo,daniellitoc/dubbo-Research,suyimin/dubbox,juqkai/dubbo,clj198606061111/dubbox_spring4,i54334/dubbo,ys305751572/dubbo,DavidAlphaFox/dubbo,gdweijin/dubbo,nichoding/dubbo,fengyie007/dubbo,tisson/dubbox,livvyguo/dubbo,wz12406/dubbo,ronaldo9grey/dubbo,fultonlee1/dubbox,rabbitcount/dubbo,livvyguo/dubbo,11wuqingchao/dubbo,gjhuai/dubbo,surlymo/dubbo,orzroa/dubbo,xiaocat963/dubbo,npccsb/dubbox,lsjiguang/dangdangdotcom,sinsinpub/dubbo,rogerchina/dubbo,mosoft521/dubbox,lzwlzw/dubbo,karlchan-cn/dubbo,gavinage/dubbox,lzwlzw/dubbo,fultonlee1/dubbox,juqkai/dubbo,brother-eshop/dubbox,jerk1991/dubbo,micmiu/dubbo,Fushicho/dubbo,lrysir/dubbo,huangkunyhx/dubbox,welloncn/dubbo,tisson/dubbox,flamezyg/dubbo,springning/dubbo,Fushicho/dubbo,AllenRay/dubbo-ex,gigold/dubbo,daodaoliang/dubbo,chengdedeng/dubbox,quyixia/dubbox,lxq1008/dubbo,hdp-piplus/dubbox,zouyoujin/dubbo,hutea/dubbo,surlymo/dubbo,ligzy/dubbo,izerui/dubbo,ServerStarted/dubbo,MetSystem/dubbo,hyace/dubbo,hyace/dubbo,xiaozhou322/dubbo-master,chengdedeng/dubbox,orzroa/dubbo,kkllwww007/dubbox,manlonglin/dubbo,majinkai/dubbox,zk279444107/dubbo,xiaojunbeyond/dubbox,hl198181/dubbo,ykqabc/dubbo,hyace/dubbo,asherhu/dubbox,RoyZeng/dubbo,jkchensc/dubbo,maczam/dubbox,Jeromefromcn/dubbox,wangsan/dubbo,ledotcom/le-dubbo,open-source-explore/dubbo,yinheli/dubbo,ledotcom/le-dubbo,bpzhang/dubbo,Karanyxy/IRepository,clj198606061111/dubbox_spring4,maczam/dubbox,RandyChen1985/dubbo-ext,brother-eshop/dubbox,RandyChen1985/dubbo-ext,suyimin/dubbox,yiyezhangmu/dubbox,open-source-explore/dubbo,wangcan2014/dubbo,coolworker/dubbo,hdp-piplus/dubbox,alibaba/dubbo,liyong7514/dubbo,cf9lovely/cf_rp,cenqiongyu/dubbo,i54334/dubbo,fly3q/dubbo,jieke-tao/dubbo,allen-zkm/dubbo,ys305751572/dubbo,rabbitcount/dubbo,fzbook/dubboEvent,shuvigoss/dubbox,liuxinglanyue/dubbox,tisson/dubbox,micmiu/dubbo,shuvigoss/dubbox,hutea/dubbo,magintursh/dubbo,ronaldo9grey/dubbo,wei121363/dubbo,uubu/dubbox,taohaolong/dubbo,hermanzzp/dubbo,gigold/dubbo,microIBM/dubbo,OopsOutOfMemory/dubbo,zzycjcg/dubbo,yihaijun/dubbox,gdweijin/dubbo,daniellitoc/dubbo-Research,AllenRay/dubbo-ex,asherhu/dubbox,wz12406/dubbo,whubbt/dubbo,codingboyli/dubbo,yuyijq/dubbo,pipi668/dubbox,coolworker/dubbo,dadarom/dubbo,fengyie007/dubbo,welloncn/dubbo,kkllwww007/dubbox,archlevel/dubbo,xiaoguiguixm/dubbo,yangaiche/dubbo,manlonglin/dubbo,JackyMoto/dubbo,karlchan-cn/dubbo,allen-zkm/dubbo,jkchensc/dubbo,hermanzzp/dubbo,codingboyli/dubbo,kk17/dubbox,Kevin2030/dubbo,hiboycomehere/dubbo,loafer/dubbox,kutala/dubbo,yuankui/dubbo,daodaoliang/dubbo,gjhuai/dubbo,jieke-tao/dubbo,pipi668/dubbox,hl198181/dubbo,guoxu0514/dubbo,wangjingfei/dubbo,yunemr/dubbox,MX2015/dubbo,AllenRay/dubbo-ex,MX2015/dubbo,JasonHZXie/dubbo,hermanzzp/dubbo,followyourheart/dubbo,gaoxianglong/dubbo,wangjingfei/dubbo,cailin186/dubbox,ryankong/dubbo,fultonlee1/dubbox,qtvbwfn/dubbo,rogerchina/dubbo,zk279444107/dubbo,flamezyg/dubbo,damy/dubbo,finch0219/dubbo,andydreaming/dubbo,uubu/dubbox,welloncn/dubbo,sunxiang0918/dubbo,TonyLeee/dubbo,redbeans2015/dubbox,yunemr/dubbox,mingbotang/dubbo,lsjiguang/dangdangdotcom,gdweijin/dubbo,RiverWeng/dubbo,karlchan-cn/dubbo,MetSystem/dubbo,MetSystem/dubbo,quyixia/dubbox,liuxinglanyue/dubbox,lichenq/dubbo,izerui/dubbo,model919/dubbo,damy/dubbo,yuankui/dubbo,ligzy/dubbo,wthuan/dubbox,suyimin/dubbox,zzycjcg/dubbo,gaoxianglong/dubbo,gavinage/dubbox,nickeyfff/dubbox,xiaojunbeyond/dubbox,ServerStarted/dubbo,RandyChen1985/dubbo-ext,brother-eshop/dubbox,lacrazyboy/dubbox,yangaiche/dubbo,wangcan2014/dubbo,orika/dubbo,fly3q/dubbo,fengshao0907/dubbox,kevintvh/dubbo,kyle-liu/dubbo2study,redbeans2015/dubbox,aglne/dubbo,xianjunkuang/dubbos,bpzhang/dubbo
/* * Copyright 1999-2011 Alibaba Group. * * 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.alibaba.dubbo.config.spring.schema; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Date; import java.util.regex.Pattern; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.ExtensionLoader; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.config.ArgumentConfig; import com.alibaba.dubbo.config.MethodConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.ProtocolConfig; import com.alibaba.dubbo.config.RegistryConfig; import com.alibaba.dubbo.rpc.Protocol; /** * AbstractBeanDefinitionParser * * @author william.liangf */ public class DubboBeanDefinitionParser implements BeanDefinitionParser { private static final Logger logger = LoggerFactory.getLogger(DubboBeanDefinitionParser.class); private final Class<?> beanClass; private final boolean required; public DubboBeanDefinitionParser(Class<?> beanClass, boolean required) { this.beanClass = beanClass; this.required = required; } public BeanDefinition parse(Element element, ParserContext parserContext) { return parse(element, parserContext, beanClass, required); } private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClass(beanClass); beanDefinition.setLazyInit(false); String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { if (ProtocolConfig.class.equals(beanClass)) { generatedBeanName = "dubbo"; } else { generatedBeanName = element.getAttribute("interface"); } } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while(parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter ++); } } if (id != null && id.length() > 0) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } parserContext.getRegistry().registerBeanDefinition(id, beanDefinition); } if (ProtocolConfig.class.equals(beanClass)) { for (String name : parserContext.getRegistry().getBeanDefinitionNames()) { BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name); PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol"); if (property != null) { Object value = property.getValue(); if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) { definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id)); } } } } for (Method setter : beanClass.getMethods()) { String name = setter.getName(); if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) { Class<?> type = setter.getParameterTypes()[0]; String property = name.substring(3, 4).toLowerCase() + name.substring(4); Method getter = null; try { getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]); } catch (NoSuchMethodException e) { try { getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]); } catch (NoSuchMethodException e2) { } } if (getter == null || ! Modifier.isPublic(getter.getModifiers()) || ! type.equals(getter.getReturnType())) { continue; } if ("parameters".equals(property)) { parseParameters(element.getChildNodes(), beanDefinition); } else if ("methods".equals(property)) { parseMethods(id, element.getChildNodes(), beanDefinition, parserContext); } else if ("arguments".equals(property)) { parseArguments(id, element.getChildNodes(), beanDefinition, parserContext); } else { String value = element.getAttribute(property); if (value != null) { value = value.trim(); if (value.length() > 0) { if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig); } else if ("registry".equals(property) && value.indexOf(',') != -1) { parseMultiRef("registries", value, beanDefinition, parserContext); } else if ("provider".equals(property) && value.indexOf(',') != -1) { parseMultiRef("providers", value, beanDefinition, parserContext); } else if ("protocol".equals(property) && value.indexOf(',') != -1) { parseMultiRef("protocols", value, beanDefinition, parserContext); } else { Object reference; if (isPrimitive(type)) { if ("async".equals(property) && "false".equals(value) || "timeout".equals(property) && "0".equals(value) || "delay".equals(property) && "0".equals(value) || "version".equals(property) && "0.0.0".equals(value) || "stat".equals(property) && "-1".equals(value) || "reliable".equals(property) && "false".equals(value)) { // ๅ…ผๅฎนๆ—ง็‰ˆๆœฌxsdไธญ็š„defaultๅ€ผ value = null; } reference = value; if (! "id".equals(property) && ! "name".equals(property) && ! "interface".equals(property)) { String sysProperty = element.getPrefix() + "." + element.getLocalName() + "." + id + "." + property; String sysValue = System.getProperty(sysProperty); if (sysValue != null && sysValue.trim().length() > 0) { reference = sysValue.trim(); } else { sysProperty = element.getPrefix() + "." + element.getLocalName() + "." + property; sysValue = System.getProperty(sysProperty); if (sysValue != null && sysValue.trim().length() > 0) { reference = sysValue.trim(); } } } } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) && (! parserContext.getRegistry().containsBeanDefinition(value) || ! ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { if ("dubbo:provider".equals(element.getTagName())) { logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />"); } // ๅ…ผๅฎนๆ—ง็‰ˆๆœฌ้…็ฝฎ ProtocolConfig protocol = new ProtocolConfig(); protocol.setName(value); reference = protocol; } else if ("monitor".equals(property) && (! parserContext.getRegistry().containsBeanDefinition(value) || ! MonitorConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { // ๅ…ผๅฎนๆ—ง็‰ˆๆœฌ้…็ฝฎ reference = convertMonitor(value); } else if ("onreturn".equals(property)) { int index = value.lastIndexOf("."); String returnRef = value.substring(0, index); String returnMethod = value.substring(index + 1); reference = new RuntimeBeanReference(returnRef); beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod); } else if ("onthrow".equals(property)) { int index = value.lastIndexOf("."); String throwRef = value.substring(0, index); String throwMethod = value.substring(index + 1); reference = new RuntimeBeanReference(throwRef); beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod); } else { if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); if (! refBean.isSingleton()) { throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value+ "\" scope=\"singleton\" ...>"); } } reference = new RuntimeBeanReference(value); } beanDefinition.getPropertyValues().addPropertyValue(property, reference); } } } } } } return beanDefinition; } private static final Pattern GROUP_AND_VERION = Pattern.compile("^[\\-.0-9_a-zA-Z]+(\\:[\\-.0-9_a-zA-Z]+)?$"); protected static MonitorConfig convertMonitor(String monitor) { if (monitor == null || monitor.length() == 0) { return null; } if (GROUP_AND_VERION.matcher(monitor).matches()) { String group; String version; int i = monitor.indexOf(':'); if (i > 0) { group = monitor.substring(0, i); version = monitor.substring(i + 1); } else { group = monitor; version = null; } MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setGroup(group); monitorConfig.setVersion(version); return monitorConfig; } return null; } private static boolean isPrimitive(Class<?> cls) { return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class || cls == Character.class || cls == Short.class || cls == Integer.class || cls == Long.class || cls == Float.class || cls == Double.class || cls == String.class || cls == Date.class || cls == Class.class; } @SuppressWarnings("unchecked") private static void parseMultiRef(String property, String value, RootBeanDefinition beanDefinition, ParserContext parserContext) { String[] values = value.split("\\s*[,]+\\s*"); ManagedList list = null; for (int i = 0; i < values.length; i++) { String v = values[i]; if (v != null && v.length() > 0) { if (list == null) { list = new ManagedList(); } list.add(new RuntimeBeanReference(v)); } } beanDefinition.getPropertyValues().addPropertyValue(property, list); } @SuppressWarnings("unchecked") private static void parseParameters(NodeList nodeList, RootBeanDefinition beanDefinition) { if (nodeList != null && nodeList.getLength() > 0) { ManagedMap parameters = null; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { if ("parameter".equals(node.getNodeName()) || "parameter".equals(node.getLocalName())) { if (parameters == null) { parameters = new ManagedMap(); } String key = ((Element) node).getAttribute("key"); String value = ((Element) node).getAttribute("value"); boolean hide = "true".equals(((Element) node).getAttribute("hide")); if (hide) { key = Constants.HIDE_KEY_PREFIX + key; } parameters.put(key, new TypedStringValue(value, String.class)); } } } if (parameters != null) { beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters); } } } @SuppressWarnings("unchecked") private static void parseMethods(String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList != null && nodeList.getLength() > 0) { ManagedList methods = null; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; if ("method".equals(node.getNodeName()) || "method".equals(node.getLocalName())) { String methodName = element.getAttribute("name"); if (methodName == null || methodName.length() == 0) { throw new IllegalStateException("<dubbo:method> name attribute == null"); } if (methods == null) { methods = new ManagedList(); } BeanDefinition methodBeanDefinition = parse(((Element) node), parserContext, MethodConfig.class, false); String name = id + "." + methodName; BeanDefinitionHolder methodBeanDefinitionHolder = new BeanDefinitionHolder( methodBeanDefinition, name); methods.add(methodBeanDefinitionHolder); } } } if (methods != null) { beanDefinition.getPropertyValues().addPropertyValue("methods", methods); } } } @SuppressWarnings("unchecked") private static void parseArguments(String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList != null && nodeList.getLength() > 0) { ManagedList arguments = null; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; if ("argument".equals(node.getNodeName()) || "argument".equals(node.getLocalName())) { String argumentIndex = element.getAttribute("index"); if (arguments == null) { arguments = new ManagedList(); } BeanDefinition argumentBeanDefinition = parse(((Element) node), parserContext, ArgumentConfig.class, false); String name = id + "." + argumentIndex; BeanDefinitionHolder argumentBeanDefinitionHolder = new BeanDefinitionHolder( argumentBeanDefinition, name); arguments.add(argumentBeanDefinitionHolder); } } } if (arguments != null) { beanDefinition.getPropertyValues().addPropertyValue("arguments", arguments); } } } }
dubbo-config/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java
/* * Copyright 1999-2011 Alibaba Group. * * 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.alibaba.dubbo.config.spring.schema; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Date; import java.util.regex.Pattern; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.ExtensionLoader; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.config.ArgumentConfig; import com.alibaba.dubbo.config.MethodConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.ProtocolConfig; import com.alibaba.dubbo.config.RegistryConfig; import com.alibaba.dubbo.rpc.Protocol; /** * AbstractBeanDefinitionParser * * @author william.liangf */ public class DubboBeanDefinitionParser implements BeanDefinitionParser { private static final Logger logger = LoggerFactory.getLogger(DubboBeanDefinitionParser.class); private final Class<?> beanClass; private final boolean required; public DubboBeanDefinitionParser(Class<?> beanClass, boolean required) { this.beanClass = beanClass; this.required = required; } public BeanDefinition parse(Element element, ParserContext parserContext) { return parse(element, parserContext, beanClass, required); } private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClass(beanClass); beanDefinition.setLazyInit(false); String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = element.getAttribute("interface"); } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while(parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter ++); } } if (id != null && id.length() > 0) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } parserContext.getRegistry().registerBeanDefinition(id, beanDefinition); } if (ProtocolConfig.class.equals(beanClass)) { for (String name : parserContext.getRegistry().getBeanDefinitionNames()) { BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name); PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol"); if (property != null) { Object value = property.getValue(); if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) { definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id)); } } } } for (Method setter : beanClass.getMethods()) { String name = setter.getName(); if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) { Class<?> type = setter.getParameterTypes()[0]; String property = name.substring(3, 4).toLowerCase() + name.substring(4); Method getter = null; try { getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]); } catch (NoSuchMethodException e) { try { getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]); } catch (NoSuchMethodException e2) { } } if (getter == null || ! Modifier.isPublic(getter.getModifiers()) || ! type.equals(getter.getReturnType())) { continue; } if ("parameters".equals(property)) { parseParameters(element.getChildNodes(), beanDefinition); } else if ("methods".equals(property)) { parseMethods(id, element.getChildNodes(), beanDefinition, parserContext); } else if ("arguments".equals(property)) { parseArguments(id, element.getChildNodes(), beanDefinition, parserContext); } else { String value = element.getAttribute(property); if (value != null) { value = value.trim(); if (value.length() > 0) { if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig); } else if ("registry".equals(property) && value.indexOf(',') != -1) { parseMultiRef("registries", value, beanDefinition, parserContext); } else if ("provider".equals(property) && value.indexOf(',') != -1) { parseMultiRef("providers", value, beanDefinition, parserContext); } else if ("protocol".equals(property) && value.indexOf(',') != -1) { parseMultiRef("protocols", value, beanDefinition, parserContext); } else { Object reference; if (isPrimitive(type)) { if ("async".equals(property) && "false".equals(value) || "timeout".equals(property) && "0".equals(value) || "delay".equals(property) && "0".equals(value) || "version".equals(property) && "0.0.0".equals(value) || "stat".equals(property) && "-1".equals(value) || "reliable".equals(property) && "false".equals(value)) { // ๅ…ผๅฎนๆ—ง็‰ˆๆœฌxsdไธญ็š„defaultๅ€ผ value = null; } reference = value; if (! "id".equals(property) && ! "name".equals(property) && ! "interface".equals(property)) { String sysProperty = element.getPrefix() + "." + element.getLocalName() + "." + id + "." + property; String sysValue = System.getProperty(sysProperty); if (sysValue != null && sysValue.trim().length() > 0) { reference = sysValue.trim(); } else { sysProperty = element.getPrefix() + "." + element.getLocalName() + "." + property; sysValue = System.getProperty(sysProperty); if (sysValue != null && sysValue.trim().length() > 0) { reference = sysValue.trim(); } } } } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) && (! parserContext.getRegistry().containsBeanDefinition(value) || ! ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { if ("dubbo:provider".equals(element.getTagName())) { logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />"); } // ๅ…ผๅฎนๆ—ง็‰ˆๆœฌ้…็ฝฎ ProtocolConfig protocol = new ProtocolConfig(); protocol.setName(value); reference = protocol; } else if ("monitor".equals(property) && (! parserContext.getRegistry().containsBeanDefinition(value) || ! MonitorConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) { // ๅ…ผๅฎนๆ—ง็‰ˆๆœฌ้…็ฝฎ reference = convertMonitor(value); } else if ("onreturn".equals(property)) { int index = value.lastIndexOf("."); String returnRef = value.substring(0, index); String returnMethod = value.substring(index + 1); reference = new RuntimeBeanReference(returnRef); beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod); } else if ("onthrow".equals(property)) { int index = value.lastIndexOf("."); String throwRef = value.substring(0, index); String throwMethod = value.substring(index + 1); reference = new RuntimeBeanReference(throwRef); beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod); } else { if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); if (! refBean.isSingleton()) { throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value+ "\" scope=\"singleton\" ...>"); } } reference = new RuntimeBeanReference(value); } beanDefinition.getPropertyValues().addPropertyValue(property, reference); } } } } } } return beanDefinition; } private static final Pattern GROUP_AND_VERION = Pattern.compile("^[\\-.0-9_a-zA-Z]+(\\:[\\-.0-9_a-zA-Z]+)?$"); protected static MonitorConfig convertMonitor(String monitor) { if (monitor == null || monitor.length() == 0) { return null; } if (GROUP_AND_VERION.matcher(monitor).matches()) { String group; String version; int i = monitor.indexOf(':'); if (i > 0) { group = monitor.substring(0, i); version = monitor.substring(i + 1); } else { group = monitor; version = null; } MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setGroup(group); monitorConfig.setVersion(version); return monitorConfig; } return null; } private static boolean isPrimitive(Class<?> cls) { return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class || cls == Character.class || cls == Short.class || cls == Integer.class || cls == Long.class || cls == Float.class || cls == Double.class || cls == String.class || cls == Date.class || cls == Class.class; } @SuppressWarnings("unchecked") private static void parseMultiRef(String property, String value, RootBeanDefinition beanDefinition, ParserContext parserContext) { String[] values = value.split("\\s*[,]+\\s*"); ManagedList list = null; for (int i = 0; i < values.length; i++) { String v = values[i]; if (v != null && v.length() > 0) { if (list == null) { list = new ManagedList(); } list.add(new RuntimeBeanReference(v)); } } beanDefinition.getPropertyValues().addPropertyValue(property, list); } @SuppressWarnings("unchecked") private static void parseParameters(NodeList nodeList, RootBeanDefinition beanDefinition) { if (nodeList != null && nodeList.getLength() > 0) { ManagedMap parameters = null; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { if ("parameter".equals(node.getNodeName()) || "parameter".equals(node.getLocalName())) { if (parameters == null) { parameters = new ManagedMap(); } String key = ((Element) node).getAttribute("key"); String value = ((Element) node).getAttribute("value"); boolean hide = "true".equals(((Element) node).getAttribute("hide")); if (hide) { key = Constants.HIDE_KEY_PREFIX + key; } parameters.put(key, new TypedStringValue(value, String.class)); } } } if (parameters != null) { beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters); } } } @SuppressWarnings("unchecked") private static void parseMethods(String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList != null && nodeList.getLength() > 0) { ManagedList methods = null; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; if ("method".equals(node.getNodeName()) || "method".equals(node.getLocalName())) { String methodName = element.getAttribute("name"); if (methodName == null || methodName.length() == 0) { throw new IllegalStateException("<dubbo:method> name attribute == null"); } if (methods == null) { methods = new ManagedList(); } BeanDefinition methodBeanDefinition = parse(((Element) node), parserContext, MethodConfig.class, false); String name = id + "." + methodName; BeanDefinitionHolder methodBeanDefinitionHolder = new BeanDefinitionHolder( methodBeanDefinition, name); methods.add(methodBeanDefinitionHolder); } } } if (methods != null) { beanDefinition.getPropertyValues().addPropertyValue("methods", methods); } } } @SuppressWarnings("unchecked") private static void parseArguments(String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList != null && nodeList.getLength() > 0) { ManagedList arguments = null; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; if ("argument".equals(node.getNodeName()) || "argument".equals(node.getLocalName())) { String argumentIndex = element.getAttribute("index"); if (arguments == null) { arguments = new ManagedList(); } BeanDefinition argumentBeanDefinition = parse(((Element) node), parserContext, ArgumentConfig.class, false); String name = id + "." + argumentIndex; BeanDefinitionHolder argumentBeanDefinitionHolder = new BeanDefinitionHolder( argumentBeanDefinition, name); arguments.add(argumentBeanDefinitionHolder); } } } if (arguments != null) { beanDefinition.getPropertyValues().addPropertyValue("arguments", arguments); } } } }
DUBBO-149 <dubbo:protocolๆœช้…nameๆ—ถ๏ผŒ็”Ÿๆˆ็š„็ผบ็œidไนŸๅบ”ไธบdubbo๏ผŒไพฟไบŽ-Dๅ‚ๆ•ฐ่ฆ†็›– git-svn-id: 3d0e7b608a819e97e591a7b753bfd1a27aaeb5ee@697 1a56cb94-b969-4eaa-88fa-be21384802f2
dubbo-config/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java
DUBBO-149 <dubbo:protocolๆœช้…nameๆ—ถ๏ผŒ็”Ÿๆˆ็š„็ผบ็œidไนŸๅบ”ไธบdubbo๏ผŒไพฟไบŽ-Dๅ‚ๆ•ฐ่ฆ†็›–
<ide><path>ubbo-config/src/main/java/com/alibaba/dubbo/config/spring/schema/DubboBeanDefinitionParser.java <ide> if ((id == null || id.length() == 0) && required) { <ide> String generatedBeanName = element.getAttribute("name"); <ide> if (generatedBeanName == null || generatedBeanName.length() == 0) { <del> generatedBeanName = element.getAttribute("interface"); <add> if (ProtocolConfig.class.equals(beanClass)) { <add> generatedBeanName = "dubbo"; <add> } else { <add> generatedBeanName = element.getAttribute("interface"); <add> } <ide> } <ide> if (generatedBeanName == null || generatedBeanName.length() == 0) { <ide> generatedBeanName = beanClass.getName();
Java
bsd-3-clause
28496234fc873f273f1a719eb678609366c2994f
0
guywithnose/iCal4j,guywithnose/iCal4j,guywithnose/iCal4j
/* * $Id$ [05-Apr-2004] * * Copyright (c) 2004, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.model; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import net.fortuna.ical4j.model.property.Action; import net.fortuna.ical4j.model.property.Attach; import net.fortuna.ical4j.model.property.Attendee; import net.fortuna.ical4j.model.property.CalScale; import net.fortuna.ical4j.model.property.Categories; import net.fortuna.ical4j.model.property.Clazz; import net.fortuna.ical4j.model.property.Comment; import net.fortuna.ical4j.model.property.Completed; import net.fortuna.ical4j.model.property.Contact; import net.fortuna.ical4j.model.property.Country; import net.fortuna.ical4j.model.property.Created; import net.fortuna.ical4j.model.property.Description; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Due; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.ExRule; import net.fortuna.ical4j.model.property.ExtendedAddress; import net.fortuna.ical4j.model.property.FreeBusy; import net.fortuna.ical4j.model.property.Geo; import net.fortuna.ical4j.model.property.LastModified; import net.fortuna.ical4j.model.property.Locality; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.LocationType; import net.fortuna.ical4j.model.property.Method; import net.fortuna.ical4j.model.property.Name; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.PercentComplete; import net.fortuna.ical4j.model.property.Postalcode; import net.fortuna.ical4j.model.property.Priority; import net.fortuna.ical4j.model.property.ProdId; import net.fortuna.ical4j.model.property.RDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.RecurrenceId; import net.fortuna.ical4j.model.property.Region; import net.fortuna.ical4j.model.property.RelatedTo; import net.fortuna.ical4j.model.property.Repeat; import net.fortuna.ical4j.model.property.RequestStatus; import net.fortuna.ical4j.model.property.Resources; import net.fortuna.ical4j.model.property.Sequence; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.StreetAddress; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Tel; import net.fortuna.ical4j.model.property.Transp; import net.fortuna.ical4j.model.property.Trigger; import net.fortuna.ical4j.model.property.TzId; import net.fortuna.ical4j.model.property.TzName; import net.fortuna.ical4j.model.property.TzOffsetFrom; import net.fortuna.ical4j.model.property.TzOffsetTo; import net.fortuna.ical4j.model.property.TzUrl; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Url; import net.fortuna.ical4j.model.property.Version; import net.fortuna.ical4j.model.property.XProperty; /** * A factory for creating iCalendar properties. Note that if relaxed parsing is enabled (via specifying the system * property: icalj.parsing.relaxed=true) illegal property names are allowed. * @author Ben Fortuna */ public final class PropertyFactoryImpl extends AbstractContentFactory implements PropertyFactory { private static PropertyFactoryImpl instance = new PropertyFactoryImpl(); /** * Constructor made private to prevent instantiation. */ private PropertyFactoryImpl() { factories.put(Property.ACTION, createActionFactory()); factories.put(Property.ATTACH, createAttachFactory()); factories.put(Property.ATTENDEE, createAttendeeFactory()); factories.put(Property.CALSCALE, createCalScaleFactory()); factories.put(Property.CATEGORIES, createCategoriesFactory()); factories.put(Property.CLASS, createClazzFactory()); factories.put(Property.COMMENT, createCommentFactory()); factories.put(Property.COMPLETED, createCompletedFactory()); factories.put(Property.CONTACT, createContactFactory()); factories.put(Property.COUNTRY, createCountryFactory()); factories.put(Property.CREATED, createCreatedFactory()); factories.put(Property.DESCRIPTION, createDescriptionFactory()); factories.put(Property.DTEND, createDtEndFactory()); factories.put(Property.DTSTAMP, createDtStampFactory()); factories.put(Property.DTSTART, createDtStartFactory()); factories.put(Property.DUE, createDueFactory()); factories.put(Property.DURATION, createDurationFactory()); factories.put(Property.EXDATE, createExDateFactory()); factories.put(Property.EXRULE, createExRuleFactory()); factories.put(Property.EXTENDED_ADDRESS, createExtendedAddressFactory()); factories.put(Property.FREEBUSY, createFreeBusyFactory()); factories.put(Property.GEO, createGeoFactory()); factories.put(Property.LAST_MODIFIED, createLastModifiedFactory()); factories.put(Property.LOCALITY, createLocalityFactory()); factories.put(Property.LOCATION, createLocationFactory()); factories.put(Property.LOCATION_TYPE, createLocationTypeFactory()); factories.put(Property.METHOD, createMethodFactory()); factories.put(Property.NAME, createNameFactory()); factories.put(Property.ORGANIZER, createOrganizerFactory()); factories .put(Property.PERCENT_COMPLETE, createPercentCompleteFactory()); factories.put(Property.POSTALCODE, createPostalcodeFactory()); factories.put(Property.PRIORITY, createPriorityFactory()); factories.put(Property.PRODID, createProdIdFactory()); factories.put(Property.RDATE, createRDateFactory()); factories.put(Property.RECURRENCE_ID, createRecurrenceIdFactory()); factories.put(Property.REGION, createRegionFactory()); factories.put(Property.RELATED_TO, createRelatedToFactory()); factories.put(Property.REPEAT, createRepeatFactory()); factories.put(Property.REQUEST_STATUS, createRequestStatusFactory()); factories.put(Property.RESOURCES, createResourcesFactory()); factories.put(Property.RRULE, createRRuleFactory()); factories.put(Property.SEQUENCE, createSequenceFactory()); factories.put(Property.STATUS, createStatusFactory()); factories.put(Property.STREET_ADDRESS, createStreetAddressFactory()); factories.put(Property.SUMMARY, createSummaryFactory()); factories.put(Property.TEL, createTelFactory()); factories.put(Property.TRANSP, createTranspFactory()); factories.put(Property.TRIGGER, createTriggerFactory()); factories.put(Property.TZID, createTzIdFactory()); factories.put(Property.TZNAME, createTzNameFactory()); factories.put(Property.TZOFFSETFROM, createTzOffsetFromFactory()); factories.put(Property.TZOFFSETTO, createTzOffsetToFactory()); factories.put(Property.TZURL, createTzUrlFactory()); factories.put(Property.UID, createUidFactory()); factories.put(Property.URL, createUrlFactory()); factories.put(Property.VERSION, createVersionFactory()); } /** * @return */ private PropertyFactory createActionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Action(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Action(); } }; } /** * @return */ private PropertyFactory createAttachFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Attach(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Attach(); } }; } /** * @return */ private PropertyFactory createAttendeeFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Attendee(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Attendee(); } }; } /** * @return */ private PropertyFactory createCalScaleFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new CalScale(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new CalScale(); } }; } /** * @return */ private PropertyFactory createCategoriesFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Categories(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Categories(); } }; } /** * @return */ private PropertyFactory createClazzFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Clazz(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Clazz(); } }; } /** * @return */ private PropertyFactory createCommentFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Comment(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Comment(); } }; } /** * @return */ private PropertyFactory createCompletedFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Completed(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Completed(); } }; } /** * @return */ private PropertyFactory createContactFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Contact(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Contact(); } }; } /** * @return */ private PropertyFactory createCountryFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Country(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Country(); } }; } /** * @return */ private PropertyFactory createCreatedFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Created(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Created(); } }; } /** * @return */ private PropertyFactory createDescriptionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Description(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Description(); } }; } /** * @return */ private PropertyFactory createDtEndFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new DtEnd(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new DtEnd(); } }; } /** * @return */ private PropertyFactory createDtStampFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new DtStamp(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new DtStamp(); } }; } /** * @return */ private PropertyFactory createDtStartFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new DtStart(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new DtStart(); } }; } /** * @return */ private PropertyFactory createDueFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Due(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Due(); } }; } /** * @return */ private PropertyFactory createDurationFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Duration(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Duration(); } }; } /** * @return */ private PropertyFactory createExDateFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ExDate(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ExDate(); } }; } /** * @return */ private PropertyFactory createExRuleFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ExRule(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ExRule(); } }; } /** * @return */ private PropertyFactory createExtendedAddressFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ExtendedAddress(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ExtendedAddress(); } }; } /** * @return */ private PropertyFactory createFreeBusyFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new FreeBusy(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new FreeBusy(); } }; } /** * @return */ private PropertyFactory createGeoFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Geo(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Geo(); } }; } /** * @return */ private PropertyFactory createLastModifiedFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new LastModified(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new LastModified(); } }; } /** * @return */ private PropertyFactory createLocalityFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Locality(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Locality(); } }; } /** * @return */ private PropertyFactory createLocationFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Location(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Location(); } }; } /** * @return */ private PropertyFactory createLocationTypeFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new LocationType(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new LocationType(); } }; } /** * @return */ private PropertyFactory createMethodFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Method(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Method(); } }; } /** * @return */ private PropertyFactory createNameFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Name(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Name(); } }; } /** * @return */ private PropertyFactory createOrganizerFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Organizer(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Organizer(); } }; } /** * @return */ private PropertyFactory createPercentCompleteFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new PercentComplete(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new PercentComplete(); } }; } /** * @return */ private PropertyFactory createPostalcodeFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Postalcode(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Postalcode(); } }; } /** * @return */ private PropertyFactory createPriorityFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Priority(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Priority(); } }; } /** * @return */ private PropertyFactory createProdIdFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ProdId(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ProdId(); } }; } /** * @return */ private PropertyFactory createRDateFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RDate(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RDate(); } }; } /** * @return */ private PropertyFactory createRecurrenceIdFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RecurrenceId(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RecurrenceId(); } }; } /** * @return */ private PropertyFactory createRegionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Region(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Region(); } }; } /** * @return */ private PropertyFactory createRelatedToFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RelatedTo(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RelatedTo(); } }; } /** * @return */ private PropertyFactory createRepeatFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Repeat(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Repeat(); } }; } /** * @return */ private PropertyFactory createRequestStatusFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RequestStatus(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RequestStatus(); } }; } /** * @return */ private PropertyFactory createResourcesFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Resources(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Resources(); } }; } /** * @return */ private PropertyFactory createRRuleFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RRule(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RRule(); } }; } /** * @return */ private PropertyFactory createSequenceFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Sequence(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Sequence(); } }; } /** * @return */ private PropertyFactory createStatusFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Status(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Status(); } }; } /** * @return */ private PropertyFactory createStreetAddressFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new StreetAddress(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new StreetAddress(); } }; } /** * @return */ private PropertyFactory createSummaryFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Summary(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Summary(); } }; } /** * @return */ private PropertyFactory createTelFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Tel(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Tel(); } }; } /** * @return */ private PropertyFactory createTranspFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Transp(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Transp(); } }; } /** * @return */ private PropertyFactory createTriggerFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Trigger(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Trigger(); } }; } /** * @return */ private PropertyFactory createTzIdFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzId(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzId(); } }; } /** * @return */ private PropertyFactory createTzNameFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzName(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzName(); } }; } /** * @return */ private PropertyFactory createTzOffsetFromFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzOffsetFrom(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzOffsetFrom(); } }; } /** * @return */ private PropertyFactory createTzOffsetToFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzOffsetTo(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzOffsetTo(); } }; } /** * @return */ private PropertyFactory createTzUrlFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzUrl(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzUrl(); } }; } /** * @return */ private PropertyFactory createUidFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Uid(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Uid(); } }; } /** * @return */ private PropertyFactory createUrlFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Url(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Url(); } }; } /** * @return */ private PropertyFactory createVersionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Version(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Version(); } }; } /** * @return Returns the instance. */ public static PropertyFactoryImpl getInstance() { return instance; } /** * Creates an uninitialised property. * @param name name of the property * @return a property */ public Property createProperty(final String name) { PropertyFactory factory = (PropertyFactory) factories.get(name); if (factory != null) { return factory.createProperty(name); } else if (isExperimentalName(name)) { return new XProperty(name); } else if (allowIllegalNames()) { return new XProperty(name); } else { throw new IllegalArgumentException("Illegal property [" + name + "]"); } } /** * Creates a property. * @param name name of the property * @param parameters a list of property parameters * @param value a property value * @return a component */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { PropertyFactory factory = (PropertyFactory) factories.get(name); if (factory != null) { return factory.createProperty(name, parameters, value); } else if (isExperimentalName(name)) { return new XProperty(name, parameters, value); } else if (allowIllegalNames()) { return new XProperty(name, parameters, value); } else { throw new IllegalArgumentException("Illegal property [" + name + "]"); } } /** * @param name * @return */ private boolean isExperimentalName(final String name) { return name.startsWith(Property.EXPERIMENTAL_PREFIX) && name.length() > Property.EXPERIMENTAL_PREFIX.length(); } }
source/net/fortuna/ical4j/model/PropertyFactoryImpl.java
/* * $Id$ [05-Apr-2004] * * Copyright (c) 2004, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.model; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import net.fortuna.ical4j.model.property.Action; import net.fortuna.ical4j.model.property.Attach; import net.fortuna.ical4j.model.property.Attendee; import net.fortuna.ical4j.model.property.CalScale; import net.fortuna.ical4j.model.property.Categories; import net.fortuna.ical4j.model.property.Clazz; import net.fortuna.ical4j.model.property.Comment; import net.fortuna.ical4j.model.property.Completed; import net.fortuna.ical4j.model.property.Contact; import net.fortuna.ical4j.model.property.Country; import net.fortuna.ical4j.model.property.Created; import net.fortuna.ical4j.model.property.Description; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Due; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.ExRule; import net.fortuna.ical4j.model.property.ExtendedAddress; import net.fortuna.ical4j.model.property.FreeBusy; import net.fortuna.ical4j.model.property.Geo; import net.fortuna.ical4j.model.property.LastModified; import net.fortuna.ical4j.model.property.Locality; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.LocationType; import net.fortuna.ical4j.model.property.Method; import net.fortuna.ical4j.model.property.Name; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.PercentComplete; import net.fortuna.ical4j.model.property.Postalcode; import net.fortuna.ical4j.model.property.Priority; import net.fortuna.ical4j.model.property.ProdId; import net.fortuna.ical4j.model.property.RDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.RecurrenceId; import net.fortuna.ical4j.model.property.Region; import net.fortuna.ical4j.model.property.RelatedTo; import net.fortuna.ical4j.model.property.Repeat; import net.fortuna.ical4j.model.property.RequestStatus; import net.fortuna.ical4j.model.property.Resources; import net.fortuna.ical4j.model.property.Sequence; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.StreetAddress; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Tel; import net.fortuna.ical4j.model.property.Transp; import net.fortuna.ical4j.model.property.Trigger; import net.fortuna.ical4j.model.property.TzId; import net.fortuna.ical4j.model.property.TzName; import net.fortuna.ical4j.model.property.TzOffsetFrom; import net.fortuna.ical4j.model.property.TzOffsetTo; import net.fortuna.ical4j.model.property.TzUrl; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Url; import net.fortuna.ical4j.model.property.Version; import net.fortuna.ical4j.model.property.XProperty; /** * A factory for creating iCalendar properties. Note that if relaxed parsing is enabled (via specifying the system * property: icalj.parsing.relaxed=true) illegal property names are allowed. * @author Ben Fortuna */ public final class PropertyFactoryImpl extends AbstractContentFactory implements PropertyFactory { private static PropertyFactoryImpl instance = new PropertyFactoryImpl(); /** * Constructor made private to prevent instantiation. */ private PropertyFactoryImpl() { factories.put(Property.ACTION, createActionFactory()); factories.put(Property.ATTACH, createAttachFactory()); factories.put(Property.ATTENDEE, createAttendeeFactory()); factories.put(Property.CALSCALE, createCalScaleFactory()); factories.put(Property.CATEGORIES, createCategoriesFactory()); factories.put(Property.CLASS, createClazzFactory()); factories.put(Property.COMMENT, createCommentFactory()); factories.put(Property.COMPLETED, createCompletedFactory()); factories.put(Property.CONTACT, createContactFactory()); factories.put(Property.COUNTRY, createCountryFactory()); factories.put(Property.CREATED, createCreatedFactory()); factories.put(Property.DESCRIPTION, createDescriptionFactory()); factories.put(Property.DTEND, createDtEndFactory()); factories.put(Property.DTSTAMP, createDtStampFactory()); factories.put(Property.DTSTART, createDtStartFactory()); factories.put(Property.DUE, createDueFactory()); factories.put(Property.DURATION, createDurationFactory()); factories.put(Property.EXDATE, createExDateFactory()); factories.put(Property.EXRULE, createExRuleFactory()); factories.put(Property.EXTENDED_ADDRESS, createExtendedAddressFactory()); factories.put(Property.FREEBUSY, createFreeBusyFactory()); factories.put(Property.GEO, createGeoFactory()); factories.put(Property.LAST_MODIFIED, createLastModifiedFactory()); factories.put(Property.LOCALITY, createLocalityFactory()); factories.put(Property.LOCATION, createLocationFactory()); factories.put(Property.LOCATION_TYPE, createLocationTypeFactory()); factories.put(Property.METHOD, createMethodFactory()); factories.put(Property.NAME, createNameFactory()); factories.put(Property.ORGANIZER, createOrganizerFactory()); factories .put(Property.PERCENT_COMPLETE, createPercentCompleteFactory()); factories.put(Property.POSTALCODE, createPostalcodeFactory()); factories.put(Property.PRIORITY, createPriorityFactory()); factories.put(Property.PRODID, createProdIdFactory()); factories.put(Property.RDATE, createRDateFactory()); factories.put(Property.RECURRENCE_ID, createRecurrenceIdFactory()); factories.put(Property.REGION, createRegionFactory()); factories.put(Property.RELATED_TO, createRelatedToFactory()); factories.put(Property.REPEAT, createRepeatFactory()); factories.put(Property.REQUEST_STATUS, createRequestStatusFactory()); factories.put(Property.RESOURCES, createResourcesFactory()); factories.put(Property.RRULE, createRRuleFactory()); factories.put(Property.SEQUENCE, createSequenceFactory()); factories.put(Property.STATUS, createStatusFactory()); factories.put(Property.STREET_ADDRESS, createStreetAddressFactory()); factories.put(Property.SUMMARY, createSummaryFactory()); factories.put(Property.TEL, createTelFactory()); factories.put(Property.TRANSP, createTranspFactory()); factories.put(Property.TRIGGER, createTriggerFactory()); factories.put(Property.TZID, createTzIdFactory()); factories.put(Property.TZNAME, createTzNameFactory()); factories.put(Property.TZOFFSETFROM, createTzOffsetFromFactory()); factories.put(Property.TZOFFSETTO, createTzOffsetToFactory()); factories.put(Property.TZURL, createTzUrlFactory()); factories.put(Property.UID, createUidFactory()); factories.put(Property.URL, createUrlFactory()); factories.put(Property.VERSION, createVersionFactory()); } /** * @return */ private PropertyFactory createActionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Action(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Action(); } }; } /** * @return */ private PropertyFactory createAttachFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Attach(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Attach(); } }; } /** * @return */ private PropertyFactory createAttendeeFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Attendee(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Attendee(); } }; } /** * @return */ private PropertyFactory createCalScaleFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new CalScale(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new CalScale(); } }; } /** * @return */ private PropertyFactory createCategoriesFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Categories(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Categories(); } }; } /** * @return */ private PropertyFactory createClazzFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Clazz(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Clazz(); } }; } /** * @return */ private PropertyFactory createCommentFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Comment(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Comment(); } }; } /** * @return */ private PropertyFactory createCompletedFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Completed(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Completed(); } }; } /** * @return */ private PropertyFactory createContactFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Contact(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Contact(); } }; } /** * @return */ private PropertyFactory createCountryFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Country(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Country(); } }; } /** * @return */ private PropertyFactory createCreatedFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Created(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Created(); } }; } /** * @return */ private PropertyFactory createDescriptionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Description(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Description(); } }; } /** * @return */ private PropertyFactory createDtEndFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new DtEnd(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new DtEnd(); } }; } /** * @return */ private PropertyFactory createDtStampFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new DtStamp(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new DtStamp(); } }; } /** * @return */ private PropertyFactory createDtStartFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new DtStart(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new DtStart(); } }; } /** * @return */ private PropertyFactory createDueFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Due(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Due(); } }; } /** * @return */ private PropertyFactory createDurationFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Duration(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Duration(); } }; } /** * @return */ private PropertyFactory createExDateFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ExDate(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ExDate(); } }; } /** * @return */ private PropertyFactory createExRuleFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ExRule(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ExRule(); } }; } /** * @return */ private PropertyFactory createExtendedAddressFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ExtendedAddress(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ExtendedAddress(); } }; } /** * @return */ private PropertyFactory createFreeBusyFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new FreeBusy(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new FreeBusy(); } }; } /** * @return */ private PropertyFactory createGeoFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Geo(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Geo(); } }; } /** * @return */ private PropertyFactory createLastModifiedFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new LastModified(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new LastModified(); } }; } /** * @return */ private PropertyFactory createLocalityFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Locality(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Locality(); } }; } /** * @return */ private PropertyFactory createLocationFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Location(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Location(); } }; } /** * @return */ private PropertyFactory createLocationTypeFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new LocationType(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new LocationType(); } }; } /** * @return */ private PropertyFactory createMethodFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Method(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Method(); } }; } /** * @return */ private PropertyFactory createNameFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Name(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Name(); } }; } /** * @return */ private PropertyFactory createOrganizerFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Organizer(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Organizer(); } }; } /** * @return */ private PropertyFactory createPercentCompleteFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new PercentComplete(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new PercentComplete(); } }; } /** * @return */ private PropertyFactory createPostalcodeFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Postalcode(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Postalcode(); } }; } /** * @return */ private PropertyFactory createPriorityFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Priority(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Priority(); } }; } /** * @return */ private PropertyFactory createProdIdFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new ProdId(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new ProdId(); } }; } /** * @return */ private PropertyFactory createRDateFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RDate(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RDate(); } }; } /** * @return */ private PropertyFactory createRecurrenceIdFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RecurrenceId(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RecurrenceId(); } }; } /** * @return */ private PropertyFactory createRegionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Region(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Region(); } }; } /** * @return */ private PropertyFactory createRelatedToFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RelatedTo(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RelatedTo(); } }; } /** * @return */ private PropertyFactory createRepeatFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Repeat(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Repeat(); } }; } /** * @return */ private PropertyFactory createRequestStatusFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RequestStatus(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RequestStatus(); } }; } /** * @return */ private PropertyFactory createResourcesFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Resources(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Resources(); } }; } /** * @return */ private PropertyFactory createRRuleFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new RRule(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new RRule(); } }; } /** * @return */ private PropertyFactory createSequenceFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Sequence(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Sequence(); } }; } /** * @return */ private PropertyFactory createStatusFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Status(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Status(); } }; } /** * @return */ private PropertyFactory createStreetAddressFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new StreetAddress(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new StreetAddress(); } }; } /** * @return */ private PropertyFactory createSummaryFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Summary(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Summary(); } }; } /** * @return */ private PropertyFactory createTelFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Tel(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Tel(); } }; } /** * @return */ private PropertyFactory createTranspFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Transp(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Transp(); } }; } /** * @return */ private PropertyFactory createTriggerFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Trigger(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Trigger(); } }; } /** * @return */ private PropertyFactory createTzIdFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzId(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzId(); } }; } /** * @return */ private PropertyFactory createTzNameFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzName(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzName(); } }; } /** * @return */ private PropertyFactory createTzOffsetFromFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzOffsetFrom(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzOffsetFrom(); } }; } /** * @return */ private PropertyFactory createTzOffsetToFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzOffsetTo(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzOffsetTo(); } }; } /** * @return */ private PropertyFactory createTzUrlFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new TzUrl(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new TzUrl(); } }; } /** * @return */ private PropertyFactory createUidFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Uid(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Uid(); } }; } /** * @return */ private PropertyFactory createUrlFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Url(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Url(); } }; } /** * @return */ private PropertyFactory createVersionFactory() { return new PropertyFactory() { /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String, * net.fortuna.ical4j.model.ParameterList, java.lang.String) */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { return new Version(parameters, value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.PropertyFactory#createProperty(java.lang.String) */ public Property createProperty(final String name) { return new Version(); } }; } /** * @return Returns the instance. */ public static PropertyFactoryImpl getInstance() { return instance; } /** * Creates an uninitialised property. * @param name name of the property * @return a property */ public Property createProperty(final String name) { PropertyFactory factory = (PropertyFactory) factories.get(name); if (factory != null) { return factory.createProperty(name); } else if (isExperimentalName(name)) { return new XProperty(name); } else if (allowIllegalNames()) { return new XProperty(name); } else { throw new IllegalArgumentException("Illegal property [" + name + "]"); } } /** * Creates a property. * @param name name of the property * @param parameters a list of property parameters * @param value a property value * @return a component */ public Property createProperty(final String name, final ParameterList parameters, final String value) throws IOException, URISyntaxException, ParseException { PropertyFactory factory = (PropertyFactory) factories.get(name); if (factory != null) { return factory.createProperty(name, parameters, value); } else if (isExperimentalName(name)) { return new XProperty(name, parameters, value); } else if (allowIllegalNames()) { return new XProperty(name); } else { throw new IllegalArgumentException("Illegal property [" + name + "]"); } } /** * @param name * @return */ private boolean isExperimentalName(final String name) { return name.startsWith(Property.EXPERIMENTAL_PREFIX) && name.length() > Property.EXPERIMENTAL_PREFIX.length(); } }
pass parameters, value for to XProperty constructor
source/net/fortuna/ical4j/model/PropertyFactoryImpl.java
pass parameters, value for to XProperty constructor
<ide><path>ource/net/fortuna/ical4j/model/PropertyFactoryImpl.java <ide> return new XProperty(name, parameters, value); <ide> } <ide> else if (allowIllegalNames()) { <del> return new XProperty(name); <add> return new XProperty(name, parameters, value); <ide> } <ide> else { <ide> throw new IllegalArgumentException("Illegal property [" + name
JavaScript
mit
3526b27b1890ba5237ac8244004e84699739c027
0
hakovala/elec-trans
"use strict"; // RegExp for checking if string is HTML const re_html = /^\s*<(\w+|!)[^>]*>/; /** * DomUtil class contains collection of static methods for common * DOM functions. */ class DomUtil { /** * Check whether the given object is a DOM Element. */ static isElement(obj) { return !!(obj && obj.nodeType === 1); } /** * Check whether the given object is a DOM Text Node. */ static isTextNode(obj) { return !!(obj && obj.nodeType === 3); } /** * Check whether the given object is a DOM Document. */ static isDocument(obj) { return !!(obj && obj.nodeType === 9); } /** * Check whether the given object is a DOM Document Fragment. */ static isDocumentFragment(obj) { return !!(obj && obj.nodeType === 11); } /** * Check whether the given string is HTML. */ static isHTML(str) { return re_html.test(str); } /** * Query given selector from element or from whole document. */ static query(selector, parent) { parent = parent || document; return parent.querySelector(selector); } /** * Query given selector from element or from whole document. */ static queryAll(selector, parent) { parent = parent || document; return Array.from(parent.querySelectorAll(selector)); } /** * Check whether the given element matches the selector. */ static matches(element, selector) { if (!selector || !DomUtil.isElement(element)) { return false; } return element.matches(selector); } /** * Filter array of elements using given query selector. */ static filter(elements, selector) { // convert array-like objects to array and wrap anything else in array. elements = Array.from(elements); let result; if (typeof selector === 'undefined') { // return all elements if no selector is given result = elements; } else if (typeof selector === 'function') { // use given function as a callback for the Array filter result = elements.filter(selector); } else { result = elements.filter((e) => DomUtil.matches(e, selector)); } return result; } /** * Find a parent element that satisfies the query selector. */ static findParent(element, selector, until) { if (!DomUtil.isElement(element)) { return null; } while (element) { if (DomUtil.matches(element, selector)) { return element; } else if (until && DomUtil.matches(element, until)) { return false; } element = element.parentElement; } return false; } } module.exports = DomUtil;
lib/dom-util.js
"use strict"; // RegExp for checking if string is HTML const re_html = /^\s*<(\w+|!)[^>]*>/; /** * Check whether the given object is a DOM Element. */ function isElement(obj) { return !!(obj && obj.nodeType === 1); } /** * Check whether the given object is a DOM Text Node. */ function isTextNode(obj) { return !!(obj && obj.nodeType === 3); } /** * Check whether the given object is a DOM Document. */ function isDocument(obj) { return !!(obj && obj.nodeType === 9); } /** * Check whether the given object is a DOM Document Fragment. */ function isDocumentFragment(obj) { return !!(obj && obj.nodeType === 11); } /** * Check whether the given string is HTML. */ function isHTML(str) { return re_html.test(str); } /** * Query given selector from element or from whole document. */ function query(selector, parent) { parent = parent || document; return parent.querySelector(selector); } /** * Query given selector from element or from whole document. */ function queryAll(selector, parent) { parent = parent || document; return Array.from(parent.querySelectorAll(selector)); } /** * Check whether the given element matches the selector. */ function matches(element, selector) { if (!selector || !isElement(element)) return false; return element.matches(selector); } /** * Filter array of elements using given query selector. */ function filter(elements, selector) { // convert array-like objects to array and wrap anything else in array. elements = Array.from(elements); let result; if (typeof selector === 'undefined') { // return all elements if no selector is given result = elements; } else if (typeof selector === 'function') { // use given function as a callback for the Array filter result = elements.filter(selector); } else { result = elements.filter((e) => matches(e, selector)); } return result; } /** * Find a parent element that satisfies the query selector. */ function findParent(element, selector, until) { if (!isElement(element)) return null; while (element) { if (matches(element, selector)) { return element; } else if (until && matches(element, until)) { return false; } element = element.parentElement; } return false; } module.exports = { isElement, isTextNode, isDocument, isDocumentFragment, isHTML, query, queryAll, matches, filter, findParent, };
Refactor DomUtil to class with static methods Signed-off-by: Harri Kovalainen <[email protected]>
lib/dom-util.js
Refactor DomUtil to class with static methods
<ide><path>ib/dom-util.js <ide> const re_html = /^\s*<(\w+|!)[^>]*>/; <ide> <ide> /** <del> * Check whether the given object is a DOM Element. <add> * DomUtil class contains collection of static methods for common <add> * DOM functions. <ide> */ <del>function isElement(obj) { <del> return !!(obj && obj.nodeType === 1); <del>} <add>class DomUtil { <ide> <del>/** <del> * Check whether the given object is a DOM Text Node. <del> */ <del>function isTextNode(obj) { <del> return !!(obj && obj.nodeType === 3); <del>} <add> /** <add> * Check whether the given object is a DOM Element. <add> */ <add> static isElement(obj) { <add> return !!(obj && obj.nodeType === 1); <add> } <ide> <del>/** <del> * Check whether the given object is a DOM Document. <del> */ <del>function isDocument(obj) { <del> return !!(obj && obj.nodeType === 9); <del>} <add> /** <add> * Check whether the given object is a DOM Text Node. <add> */ <add> static isTextNode(obj) { <add> return !!(obj && obj.nodeType === 3); <add> } <ide> <del>/** <del> * Check whether the given object is a DOM Document Fragment. <del> */ <del>function isDocumentFragment(obj) { <del> return !!(obj && obj.nodeType === 11); <del>} <add> /** <add> * Check whether the given object is a DOM Document. <add> */ <add> static isDocument(obj) { <add> return !!(obj && obj.nodeType === 9); <add> } <ide> <del>/** <del> * Check whether the given string is HTML. <del> */ <del>function isHTML(str) { <del> return re_html.test(str); <del>} <add> /** <add> * Check whether the given object is a DOM Document Fragment. <add> */ <add> static isDocumentFragment(obj) { <add> return !!(obj && obj.nodeType === 11); <add> } <ide> <del>/** <del> * Query given selector from element or from whole document. <del> */ <del>function query(selector, parent) { <del> parent = parent || document; <del> return parent.querySelector(selector); <del>} <add> /** <add> * Check whether the given string is HTML. <add> */ <add> static isHTML(str) { <add> return re_html.test(str); <add> } <ide> <del>/** <del> * Query given selector from element or from whole document. <del> */ <del>function queryAll(selector, parent) { <del> parent = parent || document; <del> return Array.from(parent.querySelectorAll(selector)); <del>} <add> /** <add> * Query given selector from element or from whole document. <add> */ <add> static query(selector, parent) { <add> parent = parent || document; <add> return parent.querySelector(selector); <add> } <ide> <del>/** <del> * Check whether the given element matches the selector. <del> */ <del>function matches(element, selector) { <del> if (!selector || !isElement(element)) <del> return false; <del> return element.matches(selector); <del>} <add> /** <add> * Query given selector from element or from whole document. <add> */ <add> static queryAll(selector, parent) { <add> parent = parent || document; <add> return Array.from(parent.querySelectorAll(selector)); <add> } <ide> <del>/** <del> * Filter array of elements using given query selector. <del> */ <del>function filter(elements, selector) { <del> // convert array-like objects to array and wrap anything else in array. <del> elements = Array.from(elements); <del> <del> let result; <del> if (typeof selector === 'undefined') { <del> // return all elements if no selector is given <del> result = elements; <del> } else if (typeof selector === 'function') { <del> // use given function as a callback for the Array filter <del> result = elements.filter(selector); <del> } else { <del> result = elements.filter((e) => matches(e, selector)); <del> } <del> return result; <del>} <del> <del>/** <del> * Find a parent element that satisfies the query selector. <del> */ <del>function findParent(element, selector, until) { <del> if (!isElement(element)) <del> return null; <del> <del> while (element) { <del> if (matches(element, selector)) { <del> return element; <del> } else if (until && matches(element, until)) { <add> /** <add> * Check whether the given element matches the selector. <add> */ <add> static matches(element, selector) { <add> if (!selector || !DomUtil.isElement(element)) { <ide> return false; <ide> } <add> return element.matches(selector); <add> } <ide> <del> element = element.parentElement; <add> /** <add> * Filter array of elements using given query selector. <add> */ <add> static filter(elements, selector) { <add> // convert array-like objects to array and wrap anything else in array. <add> elements = Array.from(elements); <add> <add> let result; <add> if (typeof selector === 'undefined') { <add> // return all elements if no selector is given <add> result = elements; <add> } else if (typeof selector === 'function') { <add> // use given function as a callback for the Array filter <add> result = elements.filter(selector); <add> } else { <add> result = elements.filter((e) => DomUtil.matches(e, selector)); <add> } <add> return result; <ide> } <del> return false; <add> <add> /** <add> * Find a parent element that satisfies the query selector. <add> */ <add> static findParent(element, selector, until) { <add> if (!DomUtil.isElement(element)) { <add> return null; <add> } <add> <add> while (element) { <add> if (DomUtil.matches(element, selector)) { <add> return element; <add> } else if (until && DomUtil.matches(element, until)) { <add> return false; <add> } <add> <add> element = element.parentElement; <add> } <add> return false; <add> } <ide> } <del> <del>module.exports = { <del> isElement, <del> isTextNode, <del> isDocument, <del> isDocumentFragment, <del> isHTML, <del> <del> query, <del> queryAll, <del> matches, <del> filter, <del> findParent, <del>}; <add>module.exports = DomUtil;
JavaScript
apache-2.0
eb2451916e09bf525e42657ee3423249a738ecef
0
mdmower/doi-resolver-chrome,mdmower/doi-resolver-chrome,mdmower/doi-resolver-chrome
/*! Copyright (C) 2016 Matthew D. Mower 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. */ var definitions = { findDoi: /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/ig, findUrl: /^(?:https?\:\/\/)(?:dx\.)?doi\.org\/(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)$/ig }; setDefinitions() .then(replaceDOIsWithLinks) .catch((error) => { console.log("DOI autolink could not run; message: " + error); }); function setDefinitions() { return new Promise((resolve, reject) => { chrome.runtime.sendMessage({ cmd: "autolink_vars" }, function (response) { if (!response) { return reject("Invalid response when fetching definitions"); } var requiredDefinitions = [ "autolinkRewrite", "doiResolver" ]; for (var i = 0; i < requiredDefinitions.length; i++) { if (response[requiredDefinitions[i]] === undefined) { return reject("Missing required definition: " + requiredDefinitions[i]); } definitions[requiredDefinitions[i]] = response[requiredDefinitions[i]]; } resolve(); }); }); } // https://stackoverflow.com/questions/1444409/in-javascript-how-can-i-replace-text-in-an-html-page-without-affecting-the-tags function replaceDOIsWithLinks() { try { replaceInElement(document.body, definitions.findDoi, function(match) { var link = document.createElement('a'); link.href = definitions.doiResolver + match[0]; link.appendChild(document.createTextNode(match[0])); return link; }); } catch (ex) { console.log("DOI autolink encountered an exception", ex); } } // iterate over child nodes in reverse, as replacement may increase length of child node list. function replaceInElement(element, find, replace) { // don't touch these elements var forbiddenTags = ["a", "input", "script", "style", "textarea"]; for (var i = element.childNodes.length - 1; i >= 0; i--) { var child = element.childNodes[i]; if (child.nodeType === Node.ELEMENT_NODE) { if (forbiddenTags.indexOf(child.nodeName.toLowerCase()) < 0) { replaceInElement(child, find, replace); } else if (definitions.autolinkRewrite && child.nodeName.toLowerCase() == "a") { if (definitions.findUrl.test(child.href)) { child.href = child.href.replace(definitions.findUrl, definitions.doiResolver + "$1"); } } } else if (child.nodeType === Node.TEXT_NODE) { replaceInText(child, find, replace); } } } function replaceInText(text, find, replace) { var matches = []; var match = find.exec(text.data); while (match !== null) { matches.push(match); match = find.exec(text.data); } for (var i = matches.length - 1; i >= 0; i--) { match = matches[i]; text.splitText(match.index); text.nextSibling.splitText(match[0].length); text.parentNode.replaceChild(replace(match), text.nextSibling); } }
autolink.js
/*! Copyright (C) 2016 Matthew D. Mower 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. */ var definitions = { findDoi: /\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/ig, findUrl: /^(?:https?\:\/\/)(?:dx\.)?doi\.org\/(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)$/ig }; setDefinitions() .then(replaceDOIsWithLinks) .catch((error) => { console.log("DOI autolink could not run; message: " + error); }); function setDefinitions() { return new Promise((resolve, reject) => { chrome.runtime.sendMessage({ cmd: "autolink_vars" }, function (response) { if (!response) { return reject("Invalid response when fetching definitions"); } var requiredDefinitions = [ "autolinkRewrite", "doiResolver" ]; for (var i = 0; i < requiredDefinitions.length; i++) { if (response[requiredDefinitions[i]] === undefined) { return reject("Missing required definition: " + requiredDefinitions[i]); } definitions[requiredDefinitions[i]] = response[requiredDefinitions[i]]; } resolve(); }); }); } // https://stackoverflow.com/questions/1444409/in-javascript-how-can-i-replace-text-in-an-html-page-without-affecting-the-tags function replaceDOIsWithLinks() { replaceInElement(document.body, definitions.findDoi, function(match) { var link = document.createElement('a'); link.href = definitions.doiResolver + match[0]; link.appendChild(document.createTextNode(match[0])); return link; }); } // iterate over child nodes in reverse, as replacement may increase length of child node list. function replaceInElement(element, find, replace) { // don't touch these elements var forbiddenTags = ["a", "input", "script", "style", "textarea"]; for (var i = element.childNodes.length - 1; i >= 0; i--) { var child = element.childNodes[i]; if (child.nodeType === Node.ELEMENT_NODE) { if (forbiddenTags.indexOf(child.nodeName.toLowerCase()) < 0) { replaceInElement(child, find, replace); } else if (definitions.autolinkRewrite && child.nodeName.toLowerCase() == "a") { if (definitions.findUrl.test(child.href)) { child.href = child.href.replace(definitions.findUrl, definitions.doiResolver + "$1"); } } } else if (child.nodeType === Node.TEXT_NODE) { replaceInText(child, find, replace); } } } function replaceInText(text, find, replace) { var matches = []; var match = find.exec(text.data); while (match !== null) { matches.push(match); match = find.exec(text.data); } for (var i = matches.length - 1; i >= 0; i--) { match = matches[i]; text.splitText(match.index); text.nextSibling.splitText(match[0].length); text.parentNode.replaceChild(replace(match), text.nextSibling); } }
Autolink: Try/Catch main routine
autolink.js
Autolink: Try/Catch main routine
<ide><path>utolink.js <ide> <ide> // https://stackoverflow.com/questions/1444409/in-javascript-how-can-i-replace-text-in-an-html-page-without-affecting-the-tags <ide> function replaceDOIsWithLinks() { <del> replaceInElement(document.body, definitions.findDoi, function(match) { <del> var link = document.createElement('a'); <del> link.href = definitions.doiResolver + match[0]; <del> link.appendChild(document.createTextNode(match[0])); <del> return link; <del> }); <add> try { <add> replaceInElement(document.body, definitions.findDoi, function(match) { <add> var link = document.createElement('a'); <add> link.href = definitions.doiResolver + match[0]; <add> link.appendChild(document.createTextNode(match[0])); <add> return link; <add> }); <add> } catch (ex) { <add> console.log("DOI autolink encountered an exception", ex); <add> } <ide> } <ide> <ide> // iterate over child nodes in reverse, as replacement may increase length of child node list.
JavaScript
apache-2.0
720d2298cec7548dc0a0f3f3b7d8d84f398b4291
0
raunakkathuria/binary-static,fayland/binary-static,4p00rv/binary-static,ashkanx/binary-static,ashkanx/binary-static,binary-com/binary-static,binary-com/binary-static,4p00rv/binary-static,raunakkathuria/binary-static,fayland/binary-static,teo-binary/binary-static,4p00rv/binary-static,kellybinary/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,binary-static-deployed/binary-static,negar-binary/binary-static,fayland/binary-static,kellybinary/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,teo-binary/binary-static,binary-com/binary-static,teo-binary/binary-static,negar-binary/binary-static,negar-binary/binary-static,teo-binary/binary-static,binary-static-deployed/binary-static,fayland/binary-static
var Platforms = (function () { var sections = []; function init() { sections = ['more-tools', 'trading-platforms', 'platforms-comparison']; var sidebarListItem = $('.sidebar-nav li'); sidebarListItem.click(function(e) { sidebarListItem.removeClass('selected'); $(this).addClass('selected'); }); $(window).on('hashchange', function(){ showSelectedDiv(); }); checkWidth(); $(window).resize(checkWidth); $('.inner').scroll(checkScroll); } function checkScroll() { var $elem = $('.inner'), $fade = $('.fade-to-right'); var newScrollLeft = $elem.scrollLeft(), width = $elem.width(), scrollWidth = $elem.get(0).scrollWidth; if (scrollWidth - newScrollLeft - width === 0) { $fade.css('opacity', '0'); } } function checkWidth() { if ($('.sidebar-left').is(':visible')) { showSelectedDiv(); } else { $('.sections').removeClass('invisible'); } } function get_hash() { return ( page.url.location.hash && $.inArray(page.url.location.hash.substring(1), sections) !== -1 ? page.url.location.hash : '#trading-platforms' ); } function showSelectedDiv() { if ($('.sections[id="' + get_hash().substring(1) + '"]').is(':visible') && $('.sections:visible').length === 1) return; $('.sections').addClass('invisible'); $('.sections[id="' + get_hash().substring(1) + '"]').removeClass('invisible'); $('.sidebar-nav a[href="' + get_hash() + '"]').parent().addClass('selected'); } return { init: init }; })(); module.exports = { Platforms: Platforms, };
src/javascript/binary/static_pages/platforms.js
var Platforms = (function () { var sections = []; function init() { sections = ['more-tools', 'trading-platforms', 'platforms-comparison']; var sidebarListItem = $('.sidebar-nav li'); sidebarListItem.click(function(e) { sidebarListItem.removeClass('selected'); $(this).addClass('selected'); }); $(window).on('hashchange', function(){ showSelectedDiv(); }); checkWidth(); $(window).resize(checkWidth); $('.inner').scroll(checkScroll); } function checkScroll() { var $elem = $('.inner'), $fade = $('.fade-to-right'); var newScrollLeft = $elem.scrollLeft(), width = $elem.width(), scrollWidth = $elem.get(0).scrollWidth; if (scrollWidth - newScrollLeft - width === 0) { $fade.css('opacity', '0'); } } function checkWidth() { if ($('.sidebar-left').is(':visible')) { showSelectedDiv(); } else { $('.sections').removeClass('invisible'); } } function get_hash() { return ( page.url.location.hash && $.inArray(page.url.location.hash.substring(1), sections) !== -1 ? page.url.location.hash : '#trading-platforms' ); } function showSelectedDiv() { if ($('.sections[id="' + get_hash().substring(1) + '"]').is(':visible')) return; $('.sections').addClass('invisible'); $('.sections[id="' + get_hash().substring(1) + '"]').removeClass('invisible'); $('.sidebar-nav a[href="' + get_hash() + '"]').parent().addClass('selected'); } return { init: init }; })(); module.exports = { Platforms: Platforms, };
hide all sections on resize from mobile
src/javascript/binary/static_pages/platforms.js
hide all sections on resize from mobile
<ide><path>rc/javascript/binary/static_pages/platforms.js <ide> ); <ide> } <ide> function showSelectedDiv() { <del> if ($('.sections[id="' + get_hash().substring(1) + '"]').is(':visible')) return; <add> if ($('.sections[id="' + get_hash().substring(1) + '"]').is(':visible') && <add> $('.sections:visible').length === 1) return; <ide> $('.sections').addClass('invisible'); <ide> $('.sections[id="' + get_hash().substring(1) + '"]').removeClass('invisible'); <ide> $('.sidebar-nav a[href="' + get_hash() + '"]').parent().addClass('selected');
Java
mit
error: pathspec 'SecurityServicesAndApplications/SSA_RSA/src/uma/seguridad/RSA.java' did not match any file(s) known to git
f50d5d6912937f1ffb0bc243234985ffc6a84bb0
1
frisinacho/UMA,frisinacho/UMA
package uma.seguridad; /************************************************************************* * Compilation: javac RSA.java * Execution: java RSA N * * Generate an N-bit public and private RSA key and use to encrypt * and decrypt a random message. * * % java RSA 50 * public = 65537 * private = 553699199426609 * modulus = 825641896390631 * message = 48194775244950 * encrpyted = 321340212160104 * decrypted = 48194775244950 * * Known bugs (not addressed for simplicity) * ----------------------------------------- * - It could be the case that the message >= modulus. To avoid, use * a do-while loop to generate key until modulus happen to be exactly N bits. * * - It's possible that gcd(phi, publicKey) != 1 in which case * the key generation fails. This will only happen if phi is a * multiple of 65537. To avoid, use a do-while loop to generate * keys until the gcd is 1. * *************************************************************************/ import java.math.BigInteger; import java.security.SecureRandom; public class RSA { private final static BigInteger one = new BigInteger("1"); private final static SecureRandom random = new SecureRandom(); private BigInteger p; private BigInteger q; private BigInteger n; RSA(int N) { // Crear Modulo do { p = BigInteger.probablePrime(N / 2, random); q = BigInteger.probablePrime(N / 2, random); } while (p == q); // Comprueba que no sean iguales. n = p.multiply(q); System.out.println("p= " + p + "\nq= " + q + "\nn= " + n + "\n"); } public void crearClave(int N) { BigInteger phi = (p.subtract(one).multiply(q.subtract(one))); BigInteger publicKey = BigInteger.probablePrime(N, random); // Clave Publica (e) BigInteger privateKey = publicKey.modInverse(phi); // Clave Privada (d) System.out.println("Clave Publica: " + publicKey + "\nClave Privada: "+ privateKey + "\n"); } public static BigInteger cifrar(BigInteger m, BigInteger e, BigInteger n) { BigInteger cifrado = m.modPow(e, n); System.out.println("Mensaje cifrado: " + cifrado + "\n"); return cifrado; } public static BigInteger descifrar(BigInteger c, BigInteger d, BigInteger n) { BigInteger descifrado = c.modPow(d, n); System.out.println("Mensaje descifrado: " + descifrado + "\n"); return descifrado; } public static void main(String[] args) { RSA rsa = new RSA(50); rsa.crearClave(50); BigInteger m = new BigInteger("14091990"); // Ejecutar Foro /* Crear BigInteger mensaje = new BigInteger("-"); BigInteger clavePublica = new BigInteger("-"); BigInteger modulo = new BigInteger("-"); BigInteger mensajeCifrado = rsa.cifrar(mensaje, clavePublica, modulo); System.out.println("Mensaje Cifrado: "+ mensajeCifrado +"\n"); */ // Prueba Cifrar: Juan Antonio Reyes BigInteger pruebaM = m; BigInteger pruebaE = new BigInteger("896538328575859"); BigInteger pruebaN = new BigInteger("468923008163681"); cifrar(pruebaM, pruebaE, pruebaN); /* Descifrar: * Datos Foro: * Modulo (n): 492783521272631 * Clave Publica: 578360836703581 * Clave Privada: 178194759786373 * Mensaje foro: 311441762046542 */ BigInteger mensaje = new BigInteger("311441762046542"); BigInteger clavePrivada = new BigInteger("178194759786373"); BigInteger modulo = new BigInteger("492783521272631"); descifrar(mensaje, clavePrivada, modulo); //*/ } }
SecurityServicesAndApplications/SSA_RSA/src/uma/seguridad/RSA.java
RSA java Main RSA file
SecurityServicesAndApplications/SSA_RSA/src/uma/seguridad/RSA.java
RSA java
<ide><path>ecurityServicesAndApplications/SSA_RSA/src/uma/seguridad/RSA.java <add>package uma.seguridad; <add> <add>/************************************************************************* <add> * Compilation: javac RSA.java <add> * Execution: java RSA N <add> * <add> * Generate an N-bit public and private RSA key and use to encrypt <add> * and decrypt a random message. <add> * <add> * % java RSA 50 <add> * public = 65537 <add> * private = 553699199426609 <add> * modulus = 825641896390631 <add> * message = 48194775244950 <add> * encrpyted = 321340212160104 <add> * decrypted = 48194775244950 <add> * <add> * Known bugs (not addressed for simplicity) <add> * ----------------------------------------- <add> * - It could be the case that the message >= modulus. To avoid, use <add> * a do-while loop to generate key until modulus happen to be exactly N bits. <add> * <add> * - It's possible that gcd(phi, publicKey) != 1 in which case <add> * the key generation fails. This will only happen if phi is a <add> * multiple of 65537. To avoid, use a do-while loop to generate <add> * keys until the gcd is 1. <add> * <add> *************************************************************************/ <add> <add>import java.math.BigInteger; <add>import java.security.SecureRandom; <add> <add>public class RSA { <add> private final static BigInteger one = new BigInteger("1"); <add> private final static SecureRandom random = new SecureRandom(); <add> <add> private BigInteger p; <add> private BigInteger q; <add> private BigInteger n; <add> <add> RSA(int N) { <add> // Crear Modulo <add> do { <add> p = BigInteger.probablePrime(N / 2, random); <add> q = BigInteger.probablePrime(N / 2, random); <add> } while (p == q); // Comprueba que no sean iguales. <add> <add> n = p.multiply(q); <add> <add> System.out.println("p= " + p + "\nq= " + q + "\nn= " + n + "\n"); <add> } <add> <add> public void crearClave(int N) { <add> BigInteger phi = (p.subtract(one).multiply(q.subtract(one))); <add> <add> BigInteger publicKey = BigInteger.probablePrime(N, random); // Clave Publica (e) <add> BigInteger privateKey = publicKey.modInverse(phi); // Clave Privada (d) <add> <add> System.out.println("Clave Publica: " + publicKey + "\nClave Privada: "+ privateKey + "\n"); <add> } <add> <add> public static BigInteger cifrar(BigInteger m, BigInteger e, BigInteger n) { <add> BigInteger cifrado = m.modPow(e, n); <add> System.out.println("Mensaje cifrado: " + cifrado + "\n"); <add> return cifrado; <add> } <add> <add> public static BigInteger descifrar(BigInteger c, BigInteger d, BigInteger n) { <add> BigInteger descifrado = c.modPow(d, n); <add> System.out.println("Mensaje descifrado: " + descifrado + "\n"); <add> return descifrado; <add> } <add> <add> public static void main(String[] args) { <add> RSA rsa = new RSA(50); <add> rsa.crearClave(50); <add> <add> BigInteger m = new BigInteger("14091990"); <add> <add> // Ejecutar Foro <add> <add> /* Crear <add> BigInteger mensaje = new BigInteger("-"); <add> BigInteger clavePublica = new BigInteger("-"); <add> BigInteger modulo = new BigInteger("-"); <add> <add> BigInteger mensajeCifrado = rsa.cifrar(mensaje, clavePublica, modulo); <add> System.out.println("Mensaje Cifrado: "+ mensajeCifrado +"\n"); <add> */ <add> <add> // Prueba Cifrar: Juan Antonio Reyes <add> BigInteger pruebaM = m; <add> BigInteger pruebaE = new BigInteger("896538328575859"); <add> BigInteger pruebaN = new BigInteger("468923008163681"); <add> <add> cifrar(pruebaM, pruebaE, pruebaN); <add> <add> /* Descifrar: <add> * Datos Foro: <add> * Modulo (n): 492783521272631 <add> * Clave Publica: 578360836703581 <add> * Clave Privada: 178194759786373 <add> * Mensaje foro: 311441762046542 <add> */ <add> BigInteger mensaje = new BigInteger("311441762046542"); <add> BigInteger clavePrivada = new BigInteger("178194759786373"); <add> BigInteger modulo = new BigInteger("492783521272631"); <add> <add> descifrar(mensaje, clavePrivada, modulo); <add> //*/ <add> } <add>}
Java
apache-2.0
ba5b6b152e7c4a9fe8140b79d4bc38e900cdaab1
0
DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,jcshen007/cloudstack
// // 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.cloud.utils; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.owasp.esapi.StringUtilities; public class StringUtils { private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static Charset preferredACSCharset; { String preferredCharset = "UTF-8"; if (Charset.isSupported(preferredCharset)) { preferredACSCharset = Charset.forName(preferredCharset); } else { preferredACSCharset = Charset.defaultCharset(); } } public static Charset getPreferredCharset() { return preferredACSCharset; } public static String join(Iterable<? extends Object> iterable, String delim) { StringBuilder sb = new StringBuilder(); if (iterable != null) { Iterator<? extends Object> iter = iterable.iterator(); if (iter.hasNext()) { Object next = iter.next(); sb.append(next.toString()); } while (iter.hasNext()) { Object next = iter.next(); sb.append(delim + next.toString()); } } return sb.toString(); } public static String join(final String delimiter, final Object... components) { return org.apache.commons.lang.StringUtils.join(components, delimiter); } public static boolean isNotBlank(String str) { if (str != null && str.trim().length() > 0) { return true; } return false; } public static String cleanupTags(String tags) { if (tags != null) { String[] tokens = tags.split(","); StringBuilder t = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { t.append(tokens[i].trim()).append(","); } t.delete(t.length() - 1, t.length()); tags = t.toString(); } return tags; } /** * @param tags * @return List of tags */ public static List<String> csvTagsToList(String tags) { List<String> tagsList = new ArrayList<String>(); if (tags != null) { String[] tokens = tags.split(","); for (int i = 0; i < tokens.length; i++) { tagsList.add(tokens[i].trim()); } } return tagsList; } /** * Converts a List of tags to a comma separated list * @param tags * @return String containing a comma separated list of tags */ public static String listToCsvTags(List<String> tagsList) { StringBuilder tags = new StringBuilder(); if (tagsList.size() > 0) { for (int i = 0; i < tagsList.size(); i++) { tags.append(tagsList.get(i)); if (i != tagsList.size() - 1) { tags.append(','); } } } return tags.toString(); } public static String getExceptionStackInfo(Throwable e) { StringBuffer sb = new StringBuffer(); sb.append(e.toString()).append("\n"); StackTraceElement[] elemnents = e.getStackTrace(); for (StackTraceElement element : elemnents) { sb.append(element.getClassName()).append("."); sb.append(element.getMethodName()).append("("); sb.append(element.getFileName()).append(":"); sb.append(element.getLineNumber()).append(")"); sb.append("\n"); } return sb.toString(); } public static String unicodeEscape(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ((c >> 7) > 0) { sb.append("\\u"); sb.append(hexChar[(c >> 12) & 0xF]); // append the hex character for the left-most 4-bits sb.append(hexChar[(c >> 8) & 0xF]); // hex for the second group of 4-bits from the left sb.append(hexChar[(c >> 4) & 0xF]); // hex for the third group sb.append(hexChar[c & 0xF]); // hex for the last group, e.g., the right most 4-bits } else { sb.append(c); } } return sb.toString(); } public static String getMaskedPasswordForDisplay(String password) { if (password == null || password.isEmpty()) { return "*"; } StringBuffer sb = new StringBuffer(); sb.append(password.charAt(0)); for (int i = 1; i < password.length(); i++) { sb.append("*"); } return sb.toString(); } // removes a password request param and it's value, also considering password is in query parameter value which has been url encoded private static final Pattern REGEX_PASSWORD_QUERYSTRING = Pattern.compile("(&|%26)?[^(&|%26)]*((p|P)assword|accesskey|secretkey)(=|%3D).*?(?=(%26|[&'\"]|$))"); // removes a password/accesskey/ property from a response json object private static final Pattern REGEX_PASSWORD_JSON = Pattern.compile("\"((p|P)assword|accesskey|secretkey)\":\\s?\".*?\",?"); private static final Pattern REGEX_PASSWORD_DETAILS = Pattern.compile("(&|%26)?details(\\[|%5B)\\d*(\\]|%5D)\\.key(=|%3D)((p|P)assword|accesskey|secretkey)(?=(%26|[&'\"]))"); private static final Pattern REGEX_PASSWORD_DETAILS_INDEX = Pattern.compile("details(\\[|%5B)\\d*(\\]|%5D)"); private static final Pattern REGEX_REDUNDANT_AND = Pattern.compile("(&|%26)(&|%26)+"); // Responsible for stripping sensitive content from request and response strings public static String cleanString(String stringToClean) { String cleanResult = ""; if (stringToClean != null) { cleanResult = REGEX_PASSWORD_QUERYSTRING.matcher(stringToClean).replaceAll(""); cleanResult = REGEX_PASSWORD_JSON.matcher(cleanResult).replaceAll(""); Matcher detailsMatcher = REGEX_PASSWORD_DETAILS.matcher(cleanResult); while (detailsMatcher.find()) { Matcher detailsIndexMatcher = REGEX_PASSWORD_DETAILS_INDEX.matcher(detailsMatcher.group()); if (detailsIndexMatcher.find()) { cleanResult = cleanDetails(cleanResult, detailsIndexMatcher.group()); } } } return cleanResult; } public static String cleanDetails(String stringToClean, String detailsIndexSting) { String cleanResult = stringToClean; for (String log : stringToClean.split("&|%26")) { if (log.contains(detailsIndexSting)) { cleanResult = cleanResult.replace(log, ""); } } cleanResult = REGEX_REDUNDANT_AND.matcher(cleanResult).replaceAll("&"); return cleanResult; } public static boolean areTagsEqual(String tags1, String tags2) { if (tags1 == null && tags2 == null) { return true; } if (tags1 != null && tags2 == null) { return false; } if (tags1 == null && tags2 != null) { return false; } final String delimiter = ","; List<String> lstTags1 = new ArrayList<String>(); String[] aTags1 = tags1.split(delimiter); for (String tag1 : aTags1) { lstTags1.add(tag1.toLowerCase()); } List<String> lstTags2 = new ArrayList<String>(); String[] aTags2 = tags2.split(delimiter); for (String tag2 : aTags2) { lstTags2.add(tag2.toLowerCase()); } return lstTags1.containsAll(lstTags2) && lstTags2.containsAll(lstTags1); } public static String stripControlCharacters(String s) { return StringUtilities.stripControls(s); } public static int formatForOutput(String text, int start, int columns, char separator) { if (start >= text.length()) { return -1; } int end = start + columns; if (end > text.length()) { end = text.length(); } String searchable = text.substring(start, end); int found = searchable.lastIndexOf(separator); return found > 0 ? found : end - start; } public static Map<String, String> stringToMap(String s) { Map<String, String> map = new HashMap<String, String>(); String[] elements = s.split(";"); for (String parts : elements) { String[] keyValue = parts.split(":"); map.put(keyValue[0], keyValue[1]); } return map; } public static String mapToString(Map<String, String> map) { String s = ""; for (Map.Entry<String, String> entry : map.entrySet()) { s += entry.getKey() + ":" + entry.getValue() + ";"; } if (s.length() > 0) { s = s.substring(0, s.length() - 1); } return s; } public static <T> List<T> applyPagination(List<T> originalList, Long startIndex, Long pageSizeVal) { // Most likely pageSize will never exceed int value, and we need integer to partition the listToReturn boolean applyPagination = startIndex != null && pageSizeVal != null && startIndex <= Integer.MAX_VALUE && startIndex >= Integer.MIN_VALUE && pageSizeVal <= Integer.MAX_VALUE && pageSizeVal >= Integer.MIN_VALUE; List<T> listWPagination = null; if (applyPagination) { listWPagination = new ArrayList<>(); int index = startIndex.intValue() == 0 ? 0 : startIndex.intValue() / pageSizeVal.intValue(); List<List<T>> partitions = StringUtils.partitionList(originalList, pageSizeVal.intValue()); if (index < partitions.size()) { listWPagination = partitions.get(index); } } return listWPagination; } private static <T> List<List<T>> partitionList(List<T> originalList, int chunkSize) { List<List<T>> listOfChunks = new ArrayList<List<T>>(); for (int i = 0; i < originalList.size() / chunkSize; i++) { listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize + chunkSize)); } if (originalList.size() % chunkSize != 0) { listOfChunks.add(originalList.subList(originalList.size() - originalList.size() % chunkSize, originalList.size())); } return listOfChunks; } }
utils/src/com/cloud/utils/StringUtils.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.cloud.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.owasp.esapi.StringUtilities; public class StringUtils { private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static String join(Iterable<? extends Object> iterable, String delim) { StringBuilder sb = new StringBuilder(); if (iterable != null) { Iterator<? extends Object> iter = iterable.iterator(); if (iter.hasNext()) { Object next = iter.next(); sb.append(next.toString()); } while (iter.hasNext()) { Object next = iter.next(); sb.append(delim + next.toString()); } } return sb.toString(); } public static String join(final String delimiter, final Object... components) { return org.apache.commons.lang.StringUtils.join(components, delimiter); } public static boolean isNotBlank(String str) { if (str != null && str.trim().length() > 0) { return true; } return false; } public static String cleanupTags(String tags) { if (tags != null) { String[] tokens = tags.split(","); StringBuilder t = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { t.append(tokens[i].trim()).append(","); } t.delete(t.length() - 1, t.length()); tags = t.toString(); } return tags; } /** * @param tags * @return List of tags */ public static List<String> csvTagsToList(String tags) { List<String> tagsList = new ArrayList<String>(); if (tags != null) { String[] tokens = tags.split(","); for (int i = 0; i < tokens.length; i++) { tagsList.add(tokens[i].trim()); } } return tagsList; } /** * Converts a List of tags to a comma separated list * @param tags * @return String containing a comma separated list of tags */ public static String listToCsvTags(List<String> tagsList) { StringBuilder tags = new StringBuilder(); if (tagsList.size() > 0) { for (int i = 0; i < tagsList.size(); i++) { tags.append(tagsList.get(i)); if (i != tagsList.size() - 1) { tags.append(','); } } } return tags.toString(); } public static String getExceptionStackInfo(Throwable e) { StringBuffer sb = new StringBuffer(); sb.append(e.toString()).append("\n"); StackTraceElement[] elemnents = e.getStackTrace(); for (StackTraceElement element : elemnents) { sb.append(element.getClassName()).append("."); sb.append(element.getMethodName()).append("("); sb.append(element.getFileName()).append(":"); sb.append(element.getLineNumber()).append(")"); sb.append("\n"); } return sb.toString(); } public static String unicodeEscape(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ((c >> 7) > 0) { sb.append("\\u"); sb.append(hexChar[(c >> 12) & 0xF]); // append the hex character for the left-most 4-bits sb.append(hexChar[(c >> 8) & 0xF]); // hex for the second group of 4-bits from the left sb.append(hexChar[(c >> 4) & 0xF]); // hex for the third group sb.append(hexChar[c & 0xF]); // hex for the last group, e.g., the right most 4-bits } else { sb.append(c); } } return sb.toString(); } public static String getMaskedPasswordForDisplay(String password) { if (password == null || password.isEmpty()) { return "*"; } StringBuffer sb = new StringBuffer(); sb.append(password.charAt(0)); for (int i = 1; i < password.length(); i++) { sb.append("*"); } return sb.toString(); } // removes a password request param and it's value, also considering password is in query parameter value which has been url encoded private static final Pattern REGEX_PASSWORD_QUERYSTRING = Pattern.compile("(&|%26)?[^(&|%26)]*((p|P)assword|accesskey|secretkey)(=|%3D).*?(?=(%26|[&'\"]|$))"); // removes a password/accesskey/ property from a response json object private static final Pattern REGEX_PASSWORD_JSON = Pattern.compile("\"((p|P)assword|accesskey|secretkey)\":\\s?\".*?\",?"); private static final Pattern REGEX_PASSWORD_DETAILS = Pattern.compile("(&|%26)?details(\\[|%5B)\\d*(\\]|%5D)\\.key(=|%3D)((p|P)assword|accesskey|secretkey)(?=(%26|[&'\"]))"); private static final Pattern REGEX_PASSWORD_DETAILS_INDEX = Pattern.compile("details(\\[|%5B)\\d*(\\]|%5D)"); private static final Pattern REGEX_REDUNDANT_AND = Pattern.compile("(&|%26)(&|%26)+"); // Responsible for stripping sensitive content from request and response strings public static String cleanString(String stringToClean) { String cleanResult = ""; if (stringToClean != null) { cleanResult = REGEX_PASSWORD_QUERYSTRING.matcher(stringToClean).replaceAll(""); cleanResult = REGEX_PASSWORD_JSON.matcher(cleanResult).replaceAll(""); Matcher detailsMatcher = REGEX_PASSWORD_DETAILS.matcher(cleanResult); while (detailsMatcher.find()) { Matcher detailsIndexMatcher = REGEX_PASSWORD_DETAILS_INDEX.matcher(detailsMatcher.group()); if (detailsIndexMatcher.find()) { cleanResult = cleanDetails(cleanResult, detailsIndexMatcher.group()); } } } return cleanResult; } public static String cleanDetails(String stringToClean, String detailsIndexSting) { String cleanResult = stringToClean; for (String log : stringToClean.split("&|%26")) { if (log.contains(detailsIndexSting)) { cleanResult = cleanResult.replace(log, ""); } } cleanResult = REGEX_REDUNDANT_AND.matcher(cleanResult).replaceAll("&"); return cleanResult; } public static boolean areTagsEqual(String tags1, String tags2) { if (tags1 == null && tags2 == null) { return true; } if (tags1 != null && tags2 == null) { return false; } if (tags1 == null && tags2 != null) { return false; } final String delimiter = ","; List<String> lstTags1 = new ArrayList<String>(); String[] aTags1 = tags1.split(delimiter); for (String tag1 : aTags1) { lstTags1.add(tag1.toLowerCase()); } List<String> lstTags2 = new ArrayList<String>(); String[] aTags2 = tags2.split(delimiter); for (String tag2 : aTags2) { lstTags2.add(tag2.toLowerCase()); } return lstTags1.containsAll(lstTags2) && lstTags2.containsAll(lstTags1); } public static String stripControlCharacters(String s) { return StringUtilities.stripControls(s); } public static int formatForOutput(String text, int start, int columns, char separator) { if (start >= text.length()) { return -1; } int end = start + columns; if (end > text.length()) { end = text.length(); } String searchable = text.substring(start, end); int found = searchable.lastIndexOf(separator); return found > 0 ? found : end - start; } public static Map<String, String> stringToMap(String s) { Map<String, String> map = new HashMap<String, String>(); String[] elements = s.split(";"); for (String parts : elements) { String[] keyValue = parts.split(":"); map.put(keyValue[0], keyValue[1]); } return map; } public static String mapToString(Map<String, String> map) { String s = ""; for (Map.Entry<String, String> entry : map.entrySet()) { s += entry.getKey() + ":" + entry.getValue() + ";"; } if (s.length() > 0) { s = s.substring(0, s.length() - 1); } return s; } public static <T> List<T> applyPagination(List<T> originalList, Long startIndex, Long pageSizeVal) { // Most likely pageSize will never exceed int value, and we need integer to partition the listToReturn boolean applyPagination = startIndex != null && pageSizeVal != null && startIndex <= Integer.MAX_VALUE && startIndex >= Integer.MIN_VALUE && pageSizeVal <= Integer.MAX_VALUE && pageSizeVal >= Integer.MIN_VALUE; List<T> listWPagination = null; if (applyPagination) { listWPagination = new ArrayList<>(); int index = startIndex.intValue() == 0 ? 0 : startIndex.intValue() / pageSizeVal.intValue(); List<List<T>> partitions = StringUtils.partitionList(originalList, pageSizeVal.intValue()); if (index < partitions.size()) { listWPagination = partitions.get(index); } } return listWPagination; } private static <T> List<List<T>> partitionList(List<T> originalList, int chunkSize) { List<List<T>> listOfChunks = new ArrayList<List<T>>(); for (int i = 0; i < originalList.size() / chunkSize; i++) { listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize + chunkSize)); } if (originalList.size() % chunkSize != 0) { listOfChunks.add(originalList.subList(originalList.size() - originalList.size() % chunkSize, originalList.size())); } return listOfChunks; } }
findbugs: deal with all the encoding issues in a unified way further getBytes() calls can getBytes(StringUtils.getPrefferedCharset()) instead Signed-off-by: Daan Hoogland <[email protected]> This closes #467 This closes #467
utils/src/com/cloud/utils/StringUtils.java
findbugs: deal with all the encoding issues in a unified way further getBytes() calls can getBytes(StringUtils.getPrefferedCharset()) instead
<ide><path>tils/src/com/cloud/utils/StringUtils.java <ide> <ide> package com.cloud.utils; <ide> <add>import java.nio.charset.Charset; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.Iterator; <ide> <ide> public class StringUtils { <ide> private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; <add> <add> private static Charset preferredACSCharset; <add> <add> { <add> String preferredCharset = "UTF-8"; <add> if (Charset.isSupported(preferredCharset)) { <add> preferredACSCharset = Charset.forName(preferredCharset); <add> } else { <add> preferredACSCharset = Charset.defaultCharset(); <add> } <add> } <add> <add> public static Charset getPreferredCharset() { <add> return preferredACSCharset; <add> } <ide> <ide> public static String join(Iterable<? extends Object> iterable, String delim) { <ide> StringBuilder sb = new StringBuilder();
Java
mit
48157f558a625e33340f74d36d10bb87ffd8e5f9
0
bewitharindam/GSOC_PSU_PCBAutoplacer
/* * Copyright 2014 Arindam Bannerjee * This work is distributed under the terms of the "MIT license". Please see the file * LICENSE in this distribution for license terms. * */ package edu.pdx.partitioner; import java.util.*; import edu.pdx.placer.*; import edu.pdx.pcbparser.*; import edu.pdx.parser.*; /** * @author Arindam Banerjee * */ public class FmHeuristic { String netlistFile=""; String pcbFile=""; List<String> leftBucket = new ArrayList<String>(); List<String> rightBucket = new ArrayList<String>(); public List<String> topLeftBucket = new ArrayList<String>(); public List<String> bottomLeftBucket = new ArrayList<String>(); public List<String> topRightBucket = new ArrayList<String>(); public List<String> bottomRightBucket = new ArrayList<String>(); List<ComponentGain> compGainList = new ArrayList<ComponentGain>(); public FmHeuristic(String netlistFile, String pcbFile){ this.netlistFile = netlistFile; this.pcbFile = pcbFile; } public void FmVerticalPartitioner(){ try{ NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); for(int i=0;i<(netparser.numberOfComponents/2);i++){ leftBucket.add(netparser.compList.get(i).nameOfComp); } for(int i=(netparser.numberOfComponents/2);i<netparser.numberOfComponents;i++){ rightBucket.add(netparser.compList.get(i).nameOfComp); } CorePartitioner(leftBucket, rightBucket); }catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }//FmVerticalPartitioner() ends public void FmHorizontalPartitioner(){ NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); for(int i=0;i<leftBucket.size()/2;i++){ topLeftBucket.add(leftBucket.get(i)); } for(int i=leftBucket.size()/2;i<leftBucket.size();i++){ bottomLeftBucket.add(leftBucket.get(i)); } CorePartitioner(topLeftBucket, bottomLeftBucket); for(int i=0;i<rightBucket.size()/2;i++){ topRightBucket.add(rightBucket.get(i)); } for(int i=rightBucket.size()/2;i<rightBucket.size();i++){ bottomRightBucket.add(rightBucket.get(i)); } CorePartitioner(topRightBucket, bottomRightBucket); CorePartitioner(topLeftBucket, bottomLeftBucket); }//FmHorizontalPartitioner() ends public void CorePartitioner(List<String> firstBucket, List<String> secondBucket){ try{ int totalPrevGain = 999, totalCurrentGain = 998; int numberOfPass=1; int areaConstraintMin = ((firstBucket.size()+secondBucket.size()) * 40)/100; List<String> tempFirstBucket = new ArrayList<String>(); List<String> tempSecondBucket = new ArrayList<String>(); List<String> prevFirstBucket = new ArrayList<String>(); List<String> prevSecondBucket = new ArrayList<String>(); NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); while((totalCurrentGain < totalPrevGain)&&(numberOfPass<=netparser.compList.size())){ prevFirstBucket.clear(); prevSecondBucket.clear(); prevFirstBucket.addAll(firstBucket); prevSecondBucket.addAll(secondBucket); numberOfPass++; totalPrevGain = totalCurrentGain; totalCurrentGain=0; compGainList.clear(); /*Gain calculation*/ /*Initialize compGainList with zero gain for each component for each pass*/ for(int i=0; i<netparser.compList.size(); i++){ compGainList.add(new ComponentGain(netparser.compList.get(i).nameOfComp, 0)); } for(int i=1;i<=netparser.netId;i++){ //netId = number of nets tempFirstBucket.clear(); tempSecondBucket.clear(); for(int j=0;j<netparser.netList.size();j++){ if(netparser.netList.get(j).netId == i){ if(firstBucket.contains(netparser.netList.get(j).compName)){ tempFirstBucket.add(netparser.netList.get(j).compName); } else{ tempSecondBucket.add(netparser.netList.get(j).compName); } } } /*Removing duplicate entries from tempFirstBucket and tempSecondBucket*/ tempFirstBucket = RemoveDuplicates(tempFirstBucket); tempSecondBucket = RemoveDuplicates(tempSecondBucket); if(tempFirstBucket.size()==1){ //gain++ for(int m=0; m<=compGainList.size();m++){ if(compGainList.get(m).nameOfComp.equals(tempFirstBucket.get(0))){ compGainList.get(m).gain++; break; } } } if(tempSecondBucket.size()==1){ //gain++ for(int m=0; m<=compGainList.size();m++){ if(compGainList.get(m).nameOfComp.equals(tempSecondBucket.get(0))){ compGainList.get(m).gain++; break; } } } if(tempFirstBucket.isEmpty()){ //gain-- for(int k=0; k<tempSecondBucket.size(); k++){ for(int m=0; m<compGainList.size(); m++){ if(compGainList.get(m).nameOfComp.equals(tempSecondBucket.get(k))){ compGainList.get(m).gain--; } } } } if(tempSecondBucket.isEmpty()){ //gain-- for(int k=0; k<tempFirstBucket.size(); k++){ for(int m=0; m<compGainList.size(); m++){ if(compGainList.get(m).nameOfComp.equals(tempFirstBucket.get(k))){ compGainList.get(m).gain--; } } } } } /*sorting component gain to get maximum gain */ ComponentGain temp = new ComponentGain(); for(int pass=compGainList.size()-1;pass>=0;pass--){ for(int i=0;i<pass;i++){ if(compGainList.get(i).gain<compGainList.get(i+1).gain){ temp.nameOfComp = compGainList.get(i).nameOfComp; temp.gain = compGainList.get(i).gain; compGainList.get(i).nameOfComp = compGainList.get(i+1).nameOfComp; compGainList.get(i).gain = compGainList.get(i+1).gain; compGainList.get(i+1).nameOfComp = temp.nameOfComp; compGainList.get(i+1).gain = temp.gain; } } } /*swap the nodes considering area constraint*/ for(int i=0; i<compGainList.size(); i++){ if(firstBucket.contains(compGainList.get(i).nameOfComp)){ if((firstBucket.size()-1)>=areaConstraintMin){ firstBucket.remove(compGainList.get(i).nameOfComp); secondBucket.add(compGainList.get(i).nameOfComp); break; } } else{ if((secondBucket.size()-1)>=areaConstraintMin){ secondBucket.remove(compGainList.get(i).nameOfComp); firstBucket.add(compGainList.get(i).nameOfComp); break; } } } /*calculate total gain for current combination*/ for(int i=0;i<compGainList.size();i++){ totalCurrentGain = totalCurrentGain + compGainList.get(i).gain; } }//while loop ends firstBucket.clear(); firstBucket.addAll(prevFirstBucket); secondBucket.clear(); secondBucket.addAll(prevSecondBucket); }catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } public List<String> RemoveDuplicates(List<String> listName){ Set<String> setItem = new LinkedHashSet<String>(listName); listName.clear(); listName.addAll(setItem); return listName; } public float CalculateHpwl(String pcbFile){ float minX, maxX, minY, maxY, hpwl=0; PcbParser pcbparser = new PcbParser(pcbFile); pcbparser.pcbParse(); NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); for(int i=1; i<=netparser.netId;i++){ //netId = number of nets minX = minY = 9999.99f; maxX = maxY = 0; for(int j=0; j<netparser.netList.size(); j++){ if(netparser.netList.get(j).netId>i) break; //break from for-j if(netparser.netList.get(j).netId==i){ for(int k=0; k<pcbparser.moduleList.size(); k++){ if(netparser.netList.get(j).compName.equals(pcbparser.moduleList.get(k).moduleName)){ if(pcbparser.moduleList.get(k).positionX < minX){ minX = pcbparser.moduleList.get(k).positionX; } if(pcbparser.moduleList.get(k).positionX > maxX){ maxX = pcbparser.moduleList.get(k).positionX; } if(pcbparser.moduleList.get(k).positionY < minY){ minY = pcbparser.moduleList.get(k).positionY; } if(pcbparser.moduleList.get(k).positionY > maxY){ maxY = pcbparser.moduleList.get(k).positionY; } break; //break from for-k } } } } hpwl = hpwl + (maxX-minX)+(maxY-minY); } return hpwl; } }
src/edu/pdx/partitioner/FmHeuristic.java
/** * */ package edu.pdx.partitioner; import java.util.*; import edu.pdx.placer.*; import edu.pdx.pcbparser.*; import edu.pdx.parser.*; /** * @author Arindam Banerjee * */ public class FmHeuristic { String netlistFile=""; String pcbFile=""; List<String> leftBucket = new ArrayList<String>(); List<String> rightBucket = new ArrayList<String>(); public List<String> topLeftBucket = new ArrayList<String>(); public List<String> bottomLeftBucket = new ArrayList<String>(); public List<String> topRightBucket = new ArrayList<String>(); public List<String> bottomRightBucket = new ArrayList<String>(); List<ComponentGain> compGainList = new ArrayList<ComponentGain>(); public FmHeuristic(String netlistFile, String pcbFile){ this.netlistFile = netlistFile; this.pcbFile = pcbFile; } public void FmVerticalPartitioner(){ try{ NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); for(int i=0;i<(netparser.numberOfComponents/2);i++){ leftBucket.add(netparser.compList.get(i).nameOfComp); } for(int i=(netparser.numberOfComponents/2);i<netparser.numberOfComponents;i++){ rightBucket.add(netparser.compList.get(i).nameOfComp); } CorePartitioner(leftBucket, rightBucket); }catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }//FmVerticalPartitioner() ends public void FmHorizontalPartitioner(){ NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); for(int i=0;i<leftBucket.size()/2;i++){ topLeftBucket.add(leftBucket.get(i)); } for(int i=leftBucket.size()/2;i<leftBucket.size();i++){ bottomLeftBucket.add(leftBucket.get(i)); } CorePartitioner(topLeftBucket, bottomLeftBucket); for(int i=0;i<rightBucket.size()/2;i++){ topRightBucket.add(rightBucket.get(i)); } for(int i=rightBucket.size()/2;i<rightBucket.size();i++){ bottomRightBucket.add(rightBucket.get(i)); } CorePartitioner(topRightBucket, bottomRightBucket); CorePartitioner(topLeftBucket, bottomLeftBucket); }//FmHorizontalPartitioner() ends public void CorePartitioner(List<String> firstBucket, List<String> secondBucket){ try{ int totalPrevGain = 999, totalCurrentGain = 998; int numberOfPass=1; int areaConstraintMin = ((firstBucket.size()+secondBucket.size()) * 40)/100; List<String> tempFirstBucket = new ArrayList<String>(); List<String> tempSecondBucket = new ArrayList<String>(); List<String> prevFirstBucket = new ArrayList<String>(); List<String> prevSecondBucket = new ArrayList<String>(); NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); while((totalCurrentGain < totalPrevGain)&&(numberOfPass<=netparser.compList.size())){ prevFirstBucket.clear(); prevSecondBucket.clear(); prevFirstBucket.addAll(firstBucket); prevSecondBucket.addAll(secondBucket); numberOfPass++; totalPrevGain = totalCurrentGain; totalCurrentGain=0; compGainList.clear(); /*Gain calculation*/ /*Initialize compGainList with zero gain for each component for each pass*/ for(int i=0; i<netparser.compList.size(); i++){ compGainList.add(new ComponentGain(netparser.compList.get(i).nameOfComp, 0)); } for(int i=1;i<=netparser.netId;i++){ //netId = number of nets tempFirstBucket.clear(); tempSecondBucket.clear(); for(int j=0;j<netparser.netList.size();j++){ if(netparser.netList.get(j).netId == i){ if(firstBucket.contains(netparser.netList.get(j).compName)){ tempFirstBucket.add(netparser.netList.get(j).compName); } else{ tempSecondBucket.add(netparser.netList.get(j).compName); } } } /*Removing duplicate entries from tempFirstBucket and tempSecondBucket*/ tempFirstBucket = RemoveDuplicates(tempFirstBucket); tempSecondBucket = RemoveDuplicates(tempSecondBucket); if(tempFirstBucket.size()==1){ //gain++ for(int m=0; m<=compGainList.size();m++){ if(compGainList.get(m).nameOfComp.equals(tempFirstBucket.get(0))){ compGainList.get(m).gain++; break; } } } if(tempSecondBucket.size()==1){ //gain++ for(int m=0; m<=compGainList.size();m++){ if(compGainList.get(m).nameOfComp.equals(tempSecondBucket.get(0))){ compGainList.get(m).gain++; break; } } } if(tempFirstBucket.isEmpty()){ //gain-- for(int k=0; k<tempSecondBucket.size(); k++){ for(int m=0; m<compGainList.size(); m++){ if(compGainList.get(m).nameOfComp.equals(tempSecondBucket.get(k))){ compGainList.get(m).gain--; } } } } if(tempSecondBucket.isEmpty()){ //gain-- for(int k=0; k<tempFirstBucket.size(); k++){ for(int m=0; m<compGainList.size(); m++){ if(compGainList.get(m).nameOfComp.equals(tempFirstBucket.get(k))){ compGainList.get(m).gain--; } } } } } /*sorting component gain to get maximum gain */ ComponentGain temp = new ComponentGain(); for(int pass=compGainList.size()-1;pass>=0;pass--){ for(int i=0;i<pass;i++){ if(compGainList.get(i).gain<compGainList.get(i+1).gain){ temp.nameOfComp = compGainList.get(i).nameOfComp; temp.gain = compGainList.get(i).gain; compGainList.get(i).nameOfComp = compGainList.get(i+1).nameOfComp; compGainList.get(i).gain = compGainList.get(i+1).gain; compGainList.get(i+1).nameOfComp = temp.nameOfComp; compGainList.get(i+1).gain = temp.gain; } } } /*swap the nodes considering area constraint*/ for(int i=0; i<compGainList.size(); i++){ if(firstBucket.contains(compGainList.get(i).nameOfComp)){ if((firstBucket.size()-1)>=areaConstraintMin){ firstBucket.remove(compGainList.get(i).nameOfComp); secondBucket.add(compGainList.get(i).nameOfComp); break; } } else{ if((secondBucket.size()-1)>=areaConstraintMin){ secondBucket.remove(compGainList.get(i).nameOfComp); firstBucket.add(compGainList.get(i).nameOfComp); break; } } } /*calculate total gain for current combination*/ for(int i=0;i<compGainList.size();i++){ totalCurrentGain = totalCurrentGain + compGainList.get(i).gain; } }//while loop ends firstBucket.clear(); firstBucket.addAll(prevFirstBucket); secondBucket.clear(); secondBucket.addAll(prevSecondBucket); }catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } public List<String> RemoveDuplicates(List<String> listName){ Set<String> setItem = new LinkedHashSet<String>(listName); listName.clear(); listName.addAll(setItem); return listName; } public float CalculateHpwl(String pcbFile){ float minX, maxX, minY, maxY, hpwl=0; PcbParser pcbparser = new PcbParser(pcbFile); pcbparser.pcbParse(); NetlistParser netparser = new NetlistParser(netlistFile); netparser.parse(); for(int i=1; i<=netparser.netId;i++){ //netId = number of nets minX = minY = 9999.99f; maxX = maxY = 0; for(int j=0; j<netparser.netList.size(); j++){ if(netparser.netList.get(j).netId>i) break; //break from for-j if(netparser.netList.get(j).netId==i){ for(int k=0; k<pcbparser.moduleList.size(); k++){ if(netparser.netList.get(j).compName.equals(pcbparser.moduleList.get(k).moduleName)){ if(pcbparser.moduleList.get(k).positionX < minX){ minX = pcbparser.moduleList.get(k).positionX; } if(pcbparser.moduleList.get(k).positionX > maxX){ maxX = pcbparser.moduleList.get(k).positionX; } if(pcbparser.moduleList.get(k).positionY < minY){ minY = pcbparser.moduleList.get(k).positionY; } if(pcbparser.moduleList.get(k).positionY > maxY){ maxY = pcbparser.moduleList.get(k).positionY; } break; //break from for-k } } } } hpwl = hpwl + (maxX-minX)+(maxY-minY); } return hpwl; } }
added License pointer in Partitioner file
src/edu/pdx/partitioner/FmHeuristic.java
added License pointer in Partitioner file
<ide><path>rc/edu/pdx/partitioner/FmHeuristic.java <del>/** <del> * <del> */ <add>/* <add>* Copyright 2014 Arindam Bannerjee <add>* This work is distributed under the terms of the "MIT license". Please see the file <add>* LICENSE in this distribution for license terms. <add>* <add>*/ <add> <ide> package edu.pdx.partitioner; <ide> <ide> import java.util.*; <ide> * @author Arindam Banerjee <ide> * <ide> */ <add> <ide> public class FmHeuristic { <ide> String netlistFile=""; <ide> String pcbFile="";
Java
mit
a80acc136e316d4d82bc8585af9c7547de83bc16
0
jbosboom/streamjit,jbosboom/streamjit
package edu.mit.streamjit.impl.compiler; import edu.mit.streamjit.api.Identity; import edu.mit.streamjit.impl.common.MethodNodeBuilder; import edu.mit.streamjit.impl.compiler.insts.CallInst; import edu.mit.streamjit.impl.compiler.insts.ReturnInst; import edu.mit.streamjit.impl.compiler.types.MethodType; import edu.mit.streamjit.impl.compiler.types.ReferenceType; import edu.mit.streamjit.impl.compiler.types.ReturnType; import edu.mit.streamjit.impl.compiler.types.Type; import edu.mit.streamjit.impl.compiler.types.TypeFactory; import edu.mit.streamjit.impl.compiler.types.VoidType; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.List; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FrameNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; /** * Resolves methods. * * This class assumes it's parsing valid bytecode, so it asserts rather than * throws on simple checks like "aload_0 is loading a reference type". * @author Jeffrey Bosboom <[email protected]> * @since 4/12/2013 */ public final class MethodResolver { public static void resolve(Method m) { new MethodResolver(m).resolve(); } private final Method method; private final MethodNode methodNode; private final List<BBInfo> blocks = new ArrayList<>(); private final Module module; private final TypeFactory typeFactory; private MethodResolver(Method m) { this.method = m; this.module = method.getParent().getParent(); this.typeFactory = module.types(); try { this.methodNode = MethodNodeBuilder.buildMethodNode(method); } catch (IOException | NoSuchMethodException ex) { throw new RuntimeException(ex); } } private void resolve() { findBlockBoundaries(); for (BBInfo block : blocks) buildInstructions(block); } private void findBlockBoundaries() { InsnList insns = methodNode.instructions; int lastEnd = 0; for (int i = 0; i < insns.size(); ++i) { AbstractInsnNode insn = insns.get(i); int opcode = insn.getOpcode(); if (insn instanceof JumpInsnNode || insn instanceof LookupSwitchInsnNode || insn instanceof TableSwitchInsnNode || opcode == Opcodes.ATHROW || opcode == Opcodes.IRETURN || opcode == Opcodes.LRETURN || opcode == Opcodes.FRETURN || opcode == Opcodes.DRETURN || opcode == Opcodes.ARETURN || opcode == Opcodes.RETURN) { int end = i+1; blocks.add(new BBInfo(lastEnd, end)); lastEnd = end; } } } private void buildInstructions(BBInfo block) { FrameState frame = block.entryState.copy(); for (int i = block.start; i < block.end; ++i) { AbstractInsnNode insn = methodNode.instructions.get(i); if (insn.getOpcode() == -1) continue;//pseudo-instruction node if (insn instanceof FieldInsnNode) interpret((FieldInsnNode)insn, frame, block); else if (insn instanceof IincInsnNode) interpret((IincInsnNode)insn, frame, block); else if (insn instanceof InsnNode) interpret((InsnNode)insn, frame, block); else if (insn instanceof IntInsnNode) interpret((IntInsnNode)insn, frame, block); else if (insn instanceof InvokeDynamicInsnNode) interpret((InvokeDynamicInsnNode)insn, frame, block); else if (insn instanceof JumpInsnNode) interpret((JumpInsnNode)insn, frame, block); else if (insn instanceof LdcInsnNode) interpret((LdcInsnNode)insn, frame, block); else if (insn instanceof LookupSwitchInsnNode) interpret((LookupSwitchInsnNode)insn, frame, block); else if (insn instanceof MethodInsnNode) interpret((MethodInsnNode)insn, frame, block); else if (insn instanceof MultiANewArrayInsnNode) interpret((MultiANewArrayInsnNode)insn, frame, block); else if (insn instanceof TableSwitchInsnNode) interpret((TableSwitchInsnNode)insn, frame, block); else if (insn instanceof TypeInsnNode) interpret((TypeInsnNode)insn, frame, block); else if (insn instanceof VarInsnNode) interpret((VarInsnNode)insn, frame, block); } //TODO: merge state with successors } private void interpret(FieldInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(IincInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(InsnNode insn, FrameState frame, BBInfo block) { ReturnType returnType = block.block.getParent().getType().getReturnType(); switch (insn.getOpcode()) { case Opcodes.IRETURN: assert returnType.isSubtypeOf(typeFactory.getType(int.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.LRETURN: assert returnType.isSubtypeOf(typeFactory.getType(long.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.FRETURN: assert returnType.isSubtypeOf(typeFactory.getType(float.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.DRETURN: assert returnType.isSubtypeOf(typeFactory.getType(double.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.ARETURN: assert returnType.isSubtypeOf(typeFactory.getType(Object.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.RETURN: assert returnType instanceof VoidType; block.block.instructions().add(new ReturnInst(returnType)); break; default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(IntInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(InvokeDynamicInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(JumpInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(LdcInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(LookupSwitchInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(MethodInsnNode insn, FrameState frame, BBInfo block) { Class<?> c = null; try { c = Class.forName(insn.owner.replace('/', '.')); } catch (ClassNotFoundException ex) { Thread.currentThread().stop(ex); } Klass k = module.getKlass(c); MethodType mt = typeFactory.getMethodType(insn.desc); Method m; if (insn.getOpcode() == Opcodes.INVOKESTATIC || //TODO: invokespecial rules are more complex than this (insn.getOpcode() == Opcodes.INVOKESPECIAL && insn.name.equals("<init>"))) m = k.getMethod(insn.name, mt); else { //The receiver argument is not in the descriptor, but we represent it in //the IR type system. if (insn.getOpcode() != Opcodes.INVOKESTATIC) mt = mt.prependArgument(typeFactory.getRegularType(k)); m = k.getMethodByVirtual(insn.name, mt); } CallInst inst = new CallInst(m); block.block.instructions().add(inst); //Args are pushed from left-to-right, popped from right-to-left. for (int i = mt.getParameterTypes().size()-1; i >= 0; --i) inst.setArgument(i, frame.stack.pop()); if (!(mt.getReturnType() instanceof VoidType)) frame.stack.push(inst); } private void interpret(MultiANewArrayInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(TableSwitchInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(TypeInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(VarInsnNode insn, FrameState frame, BBInfo block) { int var = insn.var; switch (insn.getOpcode()) { case Opcodes.ILOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(int.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.LLOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(long.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.FLOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(float.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.DLOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(double.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.ALOAD: assert frame.locals[var].getType() instanceof ReferenceType; frame.stack.push(frame.locals[var]); break; case Opcodes.ISTORE: assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(int.class)); frame.locals[var] = frame.stack.pop(); break; case Opcodes.LSTORE: assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(long.class)); frame.locals[var] = frame.stack.pop(); break; case Opcodes.FSTORE: assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(float.class)); frame.locals[var] = frame.stack.pop(); break; case Opcodes.DSTORE: assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(double.class)); frame.locals[var] = frame.stack.pop(); break; case Opcodes.ASTORE: assert frame.stack.peek().getType() instanceof ReferenceType; frame.locals[var] = frame.stack.pop(); break; default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private final class BBInfo { private final BasicBlock block; //The index of the first and one-past-the-last instructions. private final int start, end; private FrameState entryState; private final FrameNode frame; private BBInfo(int start, int end) { this.block = new BasicBlock(method.getParent().getParent()); method.basicBlocks().add(this.block); this.start = start; this.end = end; if (start == 0) { //first block starts with args and empty stack this.entryState = new FrameState(methodNode.maxLocals); Value[] entryLocals = entryState.locals; int i = 0; //If the method is a constructor, it begins with an //UninitializedThis object in local variable 0. if (method.getName().equals("<init>")) entryLocals[i++] = new UninitializedValue(typeFactory.getType(method.getParent()), "uninitializedThis"); for (Argument a : method.arguments()) { entryLocals[i] = a; Type argType = a.getType(); if (argType.equals(typeFactory.getType(long.class)) || argType.equals(typeFactory.getType(double.class))) i += 2; else ++i; } } this.frame = findOnlyFrameNode(); } private FrameNode findOnlyFrameNode() { FrameNode f = null; for (int i = start; i != end; ++i) { AbstractInsnNode insn = methodNode.instructions.get(i); if (insn instanceof FrameNode) { assert f == null : f + " " +insn; f = (FrameNode)insn; } } return f; } } private final class FrameState { private final Value[] locals; private final Deque<Value> stack; private FrameState(int localSize) { this.locals = new Value[localSize]; this.stack = new ArrayDeque<>(); } private FrameState copy() { FrameState s = new FrameState(locals.length); System.arraycopy(locals, 0, s.locals, 0, locals.length); return s; } @Override public String toString() { return "Locals: "+Arrays.toString(locals)+", Stack: "+stack.toString(); } } /** * A dummy value used when building SSA form. Exists only to get RAUW'd to * the result of the constructor call. * * Has the type of the object under construction. */ private static class UninitializedValue extends Value { private UninitializedValue(Type type, String name) { super(type, name); } @Override public String toString() { return getName(); } } public static void main(String[] args) { Module m = new Module(); Klass k = m.getKlass(MethodResolver.class); k.getMethods("buildInstructions").iterator().next().resolve(); } }
src/edu/mit/streamjit/impl/compiler/MethodResolver.java
package edu.mit.streamjit.impl.compiler; import edu.mit.streamjit.api.Identity; import edu.mit.streamjit.impl.common.MethodNodeBuilder; import edu.mit.streamjit.impl.compiler.insts.CallInst; import edu.mit.streamjit.impl.compiler.insts.ReturnInst; import edu.mit.streamjit.impl.compiler.types.MethodType; import edu.mit.streamjit.impl.compiler.types.ReferenceType; import edu.mit.streamjit.impl.compiler.types.ReturnType; import edu.mit.streamjit.impl.compiler.types.Type; import edu.mit.streamjit.impl.compiler.types.TypeFactory; import edu.mit.streamjit.impl.compiler.types.VoidType; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.List; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FrameNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; /** * Resolves methods. * * This class assumes it's parsing valid bytecode, so it asserts rather than * throws on simple checks like "aload_0 is loading a reference type". * @author Jeffrey Bosboom <[email protected]> * @since 4/12/2013 */ public final class MethodResolver { public static void resolve(Method m) { new MethodResolver(m).resolve(); } private final Method method; private final MethodNode methodNode; private final List<BBInfo> blocks = new ArrayList<>(); private final Module module; private final TypeFactory typeFactory; private MethodResolver(Method m) { this.method = m; this.module = method.getParent().getParent(); this.typeFactory = module.types(); try { this.methodNode = MethodNodeBuilder.buildMethodNode(method); } catch (IOException | NoSuchMethodException ex) { throw new RuntimeException(ex); } } private void resolve() { findBlockBoundaries(); for (BBInfo block : blocks) buildInstructions(block); } private void findBlockBoundaries() { InsnList insns = methodNode.instructions; int lastEnd = 0; for (int i = 0; i < insns.size(); ++i) { AbstractInsnNode insn = insns.get(i); int opcode = insn.getOpcode(); if (insn instanceof JumpInsnNode || insn instanceof LookupSwitchInsnNode || insn instanceof TableSwitchInsnNode || opcode == Opcodes.ATHROW || opcode == Opcodes.IRETURN || opcode == Opcodes.LRETURN || opcode == Opcodes.FRETURN || opcode == Opcodes.DRETURN || opcode == Opcodes.ARETURN || opcode == Opcodes.RETURN) { int end = i+1; blocks.add(new BBInfo(lastEnd, end)); lastEnd = end; } } } private void buildInstructions(BBInfo block) { FrameState frame = block.entryState.copy(); for (int i = block.start; i < block.end; ++i) { AbstractInsnNode insn = methodNode.instructions.get(i); if (insn.getOpcode() == -1) continue;//pseudo-instruction node if (insn instanceof FieldInsnNode) interpret((FieldInsnNode)insn, frame, block); else if (insn instanceof IincInsnNode) interpret((IincInsnNode)insn, frame, block); else if (insn instanceof InsnNode) interpret((InsnNode)insn, frame, block); else if (insn instanceof IntInsnNode) interpret((IntInsnNode)insn, frame, block); else if (insn instanceof InvokeDynamicInsnNode) interpret((InvokeDynamicInsnNode)insn, frame, block); else if (insn instanceof JumpInsnNode) interpret((JumpInsnNode)insn, frame, block); else if (insn instanceof LdcInsnNode) interpret((LdcInsnNode)insn, frame, block); else if (insn instanceof LookupSwitchInsnNode) interpret((LookupSwitchInsnNode)insn, frame, block); else if (insn instanceof MethodInsnNode) interpret((MethodInsnNode)insn, frame, block); else if (insn instanceof MultiANewArrayInsnNode) interpret((MultiANewArrayInsnNode)insn, frame, block); else if (insn instanceof TableSwitchInsnNode) interpret((TableSwitchInsnNode)insn, frame, block); else if (insn instanceof TypeInsnNode) interpret((TypeInsnNode)insn, frame, block); else if (insn instanceof VarInsnNode) interpret((VarInsnNode)insn, frame, block); } //TODO: merge state with successors } private void interpret(FieldInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(IincInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(InsnNode insn, FrameState frame, BBInfo block) { ReturnType returnType = block.block.getParent().getType().getReturnType(); switch (insn.getOpcode()) { case Opcodes.IRETURN: assert returnType.isSubtypeOf(typeFactory.getType(int.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.LRETURN: assert returnType.isSubtypeOf(typeFactory.getType(long.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.FRETURN: assert returnType.isSubtypeOf(typeFactory.getType(float.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.DRETURN: assert returnType.isSubtypeOf(typeFactory.getType(double.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.ARETURN: assert returnType.isSubtypeOf(typeFactory.getType(Object.class)); assert frame.stack.peek().getType().isSubtypeOf(returnType); block.block.instructions().add(new ReturnInst(returnType, frame.stack.pop())); break; case Opcodes.RETURN: assert returnType instanceof VoidType; block.block.instructions().add(new ReturnInst(returnType)); break; default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(IntInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(InvokeDynamicInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(JumpInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(LdcInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(LookupSwitchInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(MethodInsnNode insn, FrameState frame, BBInfo block) { Class<?> c = null; try { c = Class.forName(insn.owner.replace('/', '.')); } catch (ClassNotFoundException ex) { Thread.currentThread().stop(ex); } Klass k = module.getKlass(c); MethodType mt = typeFactory.getMethodType(insn.desc); Method m; if (insn.getOpcode() == Opcodes.INVOKESTATIC || //TODO: invokespecial rules are more complex than this (insn.getOpcode() == Opcodes.INVOKESPECIAL && insn.name.equals("<init>"))) m = k.getMethod(insn.name, mt); else { //The receiver argument is not in the descriptor, but we represent it in //the IR type system. if (insn.getOpcode() != Opcodes.INVOKESTATIC) mt = mt.prependArgument(typeFactory.getRegularType(k)); m = k.getMethodByVirtual(insn.name, mt); } CallInst inst = new CallInst(m); block.block.instructions().add(inst); //Args are pushed from left-to-right, popped from right-to-left. for (int i = mt.getParameterTypes().size()-1; i >= 0; --i) inst.setArgument(i, frame.stack.pop()); if (!(mt.getReturnType() instanceof VoidType)) frame.stack.push(inst); } private void interpret(MultiANewArrayInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(TableSwitchInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(TypeInsnNode insn, FrameState frame, BBInfo block) { switch (insn.getOpcode()) { default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private void interpret(VarInsnNode insn, FrameState frame, BBInfo block) { int var = insn.var; switch (insn.getOpcode()) { case Opcodes.ILOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(int.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.LLOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(long.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.FLOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(float.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.DLOAD: assert frame.locals[var].getType().isSubtypeOf(typeFactory.getType(double.class)); frame.stack.push(frame.locals[var]); break; case Opcodes.ALOAD: assert frame.locals[var].getType() instanceof ReferenceType; frame.stack.push(frame.locals[var]); break; default: throw new UnsupportedOperationException(""+insn.getOpcode()); } } private final class BBInfo { private final BasicBlock block; //The index of the first and one-past-the-last instructions. private final int start, end; private FrameState entryState; private final FrameNode frame; private BBInfo(int start, int end) { this.block = new BasicBlock(method.getParent().getParent()); method.basicBlocks().add(this.block); this.start = start; this.end = end; if (start == 0) { //first block starts with args and empty stack this.entryState = new FrameState(methodNode.maxLocals); Value[] entryLocals = entryState.locals; int i = 0; //If the method is a constructor, it begins with an //UninitializedThis object in local variable 0. if (method.getName().equals("<init>")) entryLocals[i++] = new UninitializedValue(typeFactory.getType(method.getParent()), "uninitializedThis"); for (Argument a : method.arguments()) { entryLocals[i] = a; Type argType = a.getType(); if (argType.equals(typeFactory.getType(long.class)) || argType.equals(typeFactory.getType(double.class))) i += 2; else ++i; } } this.frame = findOnlyFrameNode(); } private FrameNode findOnlyFrameNode() { FrameNode f = null; for (int i = start; i != end; ++i) { AbstractInsnNode insn = methodNode.instructions.get(i); if (insn instanceof FrameNode) { assert f == null : f + " " +insn; f = (FrameNode)insn; } } return f; } } private final class FrameState { private final Value[] locals; private final Deque<Value> stack; private FrameState(int localSize) { this.locals = new Value[localSize]; this.stack = new ArrayDeque<>(); } private FrameState copy() { FrameState s = new FrameState(locals.length); System.arraycopy(locals, 0, s.locals, 0, locals.length); return s; } @Override public String toString() { return "Locals: "+Arrays.toString(locals)+", Stack: "+stack.toString(); } } /** * A dummy value used when building SSA form. Exists only to get RAUW'd to * the result of the constructor call. * * Has the type of the object under construction. */ private static class UninitializedValue extends Value { private UninitializedValue(Type type, String name) { super(type, name); } @Override public String toString() { return getName(); } } public static void main(String[] args) { Module m = new Module(); Klass k = m.getKlass(MethodResolver.class); k.getMethods("buildInstructions").iterator().next().resolve(); } }
MethodResolver: istore and friends
src/edu/mit/streamjit/impl/compiler/MethodResolver.java
MethodResolver: istore and friends
<ide><path>rc/edu/mit/streamjit/impl/compiler/MethodResolver.java <ide> assert frame.locals[var].getType() instanceof ReferenceType; <ide> frame.stack.push(frame.locals[var]); <ide> break; <add> case Opcodes.ISTORE: <add> assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(int.class)); <add> frame.locals[var] = frame.stack.pop(); <add> break; <add> case Opcodes.LSTORE: <add> assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(long.class)); <add> frame.locals[var] = frame.stack.pop(); <add> break; <add> case Opcodes.FSTORE: <add> assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(float.class)); <add> frame.locals[var] = frame.stack.pop(); <add> break; <add> case Opcodes.DSTORE: <add> assert frame.stack.peek().getType().isSubtypeOf(typeFactory.getType(double.class)); <add> frame.locals[var] = frame.stack.pop(); <add> break; <add> case Opcodes.ASTORE: <add> assert frame.stack.peek().getType() instanceof ReferenceType; <add> frame.locals[var] = frame.stack.pop(); <add> break; <ide> default: <ide> throw new UnsupportedOperationException(""+insn.getOpcode()); <ide> }
JavaScript
mit
a901e247a723a17154c8ee4d60c5663ad84a7dd0
0
ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ArgumentsRequired, AuthenticationError, ExchangeError, InsufficientFunds, InvalidOrder, BadSymbol, PermissionDenied, BadRequest } = require ('./base/errors'); const { TICK_SIZE } = require ('./base/functions/number'); // --------------------------------------------------------------------------- module.exports = class ascendex extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'ascendex', 'name': 'AscendEX', 'countries': [ 'SG' ], // Singapore 'rateLimit': 500, 'certified': true, // new metainfo interface 'has': { 'cancelAllOrders': true, 'cancelOrder': true, 'CORS': undefined, 'createOrder': true, 'fetchAccounts': true, 'fetchBalance': true, 'fetchClosedOrders': true, 'fetchCurrencies': true, 'fetchDepositAddress': true, 'fetchDeposits': true, 'fetchFundingRates': true, 'fetchMarkets': true, 'fetchOHLCV': true, 'fetchOpenOrders': true, 'fetchOrder': true, 'fetchOrderBook': true, 'fetchOrders': false, 'fetchPositions': true, 'fetchTicker': true, 'fetchTickers': true, 'fetchTrades': true, 'fetchTransactions': true, 'fetchWithdrawals': true, 'setLeverage': true, 'setMarginMode': true, }, 'timeframes': { '1m': '1', '5m': '5', '15m': '15', '30m': '30', '1h': '60', '2h': '120', '4h': '240', '6h': '360', '12h': '720', '1d': '1d', '1w': '1w', '1M': '1m', }, 'version': 'v2', 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/112027508-47984600-8b48-11eb-9e17-d26459cc36c6.jpg', 'api': 'https://ascendex.com', 'test': 'https://bitmax-test.io', 'www': 'https://ascendex.com', 'doc': [ 'https://bitmax-exchange.github.io/bitmax-pro-api/#bitmax-pro-api-documentation', ], 'fees': 'https://ascendex.com/en/feerate/transactionfee-traderate', 'referral': { 'url': 'https://ascendex.com/en-us/register?inviteCode=EL6BXBQM', 'discount': 0.25, }, }, 'api': { 'v1': { 'public': { 'get': [ 'assets', 'products', 'ticker', 'barhist/info', 'barhist', 'depth', 'trades', 'cash/assets', // not documented 'cash/products', // not documented 'margin/assets', // not documented 'margin/products', // not documented 'futures/collateral', 'futures/contracts', 'futures/ref-px', 'futures/market-data', 'futures/funding-rates', ], }, 'private': { 'get': [ 'info', 'wallet/transactions', 'wallet/deposit/address', // not documented 'data/balance/snapshot', 'data/balance/history', ], 'accountCategory': { 'get': [ 'balance', 'order/open', 'order/status', 'order/hist/current', 'risk', ], 'post': [ 'order', 'order/batch', ], 'delete': [ 'order', 'order/all', 'order/batch', ], }, 'accountGroup': { 'get': [ 'cash/balance', 'margin/balance', 'margin/risk', 'transfer', 'futures/collateral-balance', 'futures/position', 'futures/risk', 'futures/funding-payments', 'order/hist', ], 'post': [ 'futures/transfer/deposit', 'futures/transfer/withdraw', ], }, }, }, 'v2': { 'public': { 'get': [ 'assets', 'futures/contract', 'futures/collateral', 'futures/pricing-data', ], }, 'private': { 'get': [ 'account/info', ], 'accountGroup': { 'get': [ 'order/hist', 'futures/position', 'futures/free-margin', 'futures/order/hist/current', 'futures/order/status', ], 'post': [ 'futures/isolated-position-margin', 'futures/margin-type', 'futures/leverage', 'futures/transfer/deposit', 'futures/transfer/withdraw', 'futures/order', 'futures/order/batch', 'futures/order/open', 'subuser/subuser-transfer', 'subuser/subuser-transfer-hist', ], 'delete': [ 'futures/order', 'futures/order/batch', 'futures/order/all', ], }, }, }, }, 'fees': { 'trading': { 'feeSide': 'get', 'tierBased': true, 'percentage': true, 'taker': this.parseNumber ('0.002'), 'maker': this.parseNumber ('0.002'), }, }, 'precisionMode': TICK_SIZE, 'options': { 'account-category': 'cash', // 'cash'/'margin'/'futures' 'account-group': undefined, 'fetchClosedOrders': { 'method': 'v1PrivateAccountGroupGetOrderHist', // 'v1PrivateAccountGroupGetAccountCategoryOrderHistCurrent' }, }, 'exceptions': { 'exact': { // not documented '1900': BadRequest, // {"code":1900,"message":"Invalid Http Request Input"} '2100': AuthenticationError, // {"code":2100,"message":"ApiKeyFailure"} '5002': BadSymbol, // {"code":5002,"message":"Invalid Symbol"} '6001': BadSymbol, // {"code":6001,"message":"Trading is disabled on symbol."} '6010': InsufficientFunds, // {'code': 6010, 'message': 'Not enough balance.'} '60060': InvalidOrder, // { 'code': 60060, 'message': 'The order is already filled or canceled.' } '600503': InvalidOrder, // {"code":600503,"message":"Notional is too small."} // documented '100001': BadRequest, // INVALID_HTTP_INPUT Http request is invalid '100002': BadRequest, // DATA_NOT_AVAILABLE Some required data is missing '100003': BadRequest, // KEY_CONFLICT The same key exists already '100004': BadRequest, // INVALID_REQUEST_DATA The HTTP request contains invalid field or argument '100005': BadRequest, // INVALID_WS_REQUEST_DATA Websocket request contains invalid field or argument '100006': BadRequest, // INVALID_ARGUMENT The arugment is invalid '100007': BadRequest, // ENCRYPTION_ERROR Something wrong with data encryption '100008': BadSymbol, // SYMBOL_ERROR Symbol does not exist or not valid for the request '100009': AuthenticationError, // AUTHORIZATION_NEEDED Authorization is require for the API access or request '100010': BadRequest, // INVALID_OPERATION The action is invalid or not allowed for the account '100011': BadRequest, // INVALID_TIMESTAMP Not a valid timestamp '100012': BadRequest, // INVALID_STR_FORMAT String format does not '100013': BadRequest, // INVALID_NUM_FORMAT Invalid number input '100101': ExchangeError, // UNKNOWN_ERROR Some unknown error '150001': BadRequest, // INVALID_JSON_FORMAT Require a valid json object '200001': AuthenticationError, // AUTHENTICATION_FAILED Authorization failed '200002': ExchangeError, // TOO_MANY_ATTEMPTS Tried and failed too many times '200003': ExchangeError, // ACCOUNT_NOT_FOUND Account not exist '200004': ExchangeError, // ACCOUNT_NOT_SETUP Account not setup properly '200005': ExchangeError, // ACCOUNT_ALREADY_EXIST Account already exist '200006': ExchangeError, // ACCOUNT_ERROR Some error related with error '200007': ExchangeError, // CODE_NOT_FOUND '200008': ExchangeError, // CODE_EXPIRED Code expired '200009': ExchangeError, // CODE_MISMATCH Code does not match '200010': AuthenticationError, // PASSWORD_ERROR Wrong assword '200011': ExchangeError, // CODE_GEN_FAILED Do not generate required code promptly '200012': ExchangeError, // FAKE_COKE_VERIFY '200013': ExchangeError, // SECURITY_ALERT Provide security alert message '200014': PermissionDenied, // RESTRICTED_ACCOUNT Account is restricted for certain activity, such as trading, or withdraw. '200015': PermissionDenied, // PERMISSION_DENIED No enough permission for the operation '300001': InvalidOrder, // INVALID_PRICE Order price is invalid '300002': InvalidOrder, // INVALID_QTY Order size is invalid '300003': InvalidOrder, // INVALID_SIDE Order side is invalid '300004': InvalidOrder, // INVALID_NOTIONAL Notional is too small or too large '300005': InvalidOrder, // INVALID_TYPE Order typs is invalid '300006': InvalidOrder, // INVALID_ORDER_ID Order id is invalid '300007': InvalidOrder, // INVALID_TIME_IN_FORCE Time In Force in order request is invalid '300008': InvalidOrder, // INVALID_ORDER_PARAMETER Some order parameter is invalid '300009': InvalidOrder, // TRADING_VIOLATION Trading violation on account or asset '300011': InsufficientFunds, // INVALID_BALANCE No enough account or asset balance for the trading '300012': BadSymbol, // INVALID_PRODUCT Not a valid product supported by exchange '300013': InvalidOrder, // INVALID_BATCH_ORDER Some or all orders are invalid in batch order request '300014': InvalidOrder, // {"code":300014,"message":"Order price doesn't conform to the required tick size: 0.1","reason":"TICK_SIZE_VIOLATION"} '300020': InvalidOrder, // TRADING_RESTRICTED There is some trading restriction on account or asset '300021': InvalidOrder, // TRADING_DISABLED Trading is disabled on account or asset '300031': InvalidOrder, // NO_MARKET_PRICE No market price for market type order trading '310001': InsufficientFunds, // INVALID_MARGIN_BALANCE No enough margin balance '310002': InvalidOrder, // INVALID_MARGIN_ACCOUNT Not a valid account for margin trading '310003': InvalidOrder, // MARGIN_TOO_RISKY Leverage is too high '310004': BadSymbol, // INVALID_MARGIN_ASSET This asset does not support margin trading '310005': InvalidOrder, // INVALID_REFERENCE_PRICE There is no valid reference price '510001': ExchangeError, // SERVER_ERROR Something wrong with server. '900001': ExchangeError, // HUMAN_CHALLENGE Human change do not pass }, 'broad': {}, }, 'commonCurrencies': { 'BOND': 'BONDED', 'BTCBEAR': 'BEAR', 'BTCBULL': 'BULL', 'BYN': 'BeyondFi', }, }); } getAccount (params = {}) { // get current or provided bitmax sub-account const account = this.safeValue (params, 'account', this.options['account']); return account.toLowerCase ().capitalize (); } async fetchCurrencies (params = {}) { const assets = await this.v1PublicGetAssets (params); // // { // "code":0, // "data":[ // { // "assetCode" : "LTCBULL", // "assetName" : "3X Long LTC Token", // "precisionScale" : 9, // "nativeScale" : 4, // "withdrawalFee" : "0.2", // "minWithdrawalAmt" : "1.0", // "status" : "Normal" // }, // ] // } // const margin = await this.v1PublicGetMarginAssets (params); // // { // "code":0, // "data":[ // { // "assetCode":"BTT", // "borrowAssetCode":"BTT-B", // "interestAssetCode":"BTT-I", // "nativeScale":0, // "numConfirmations":1, // "withdrawFee":"100.0", // "minWithdrawalAmt":"1000.0", // "statusCode":"Normal", // "statusMessage":"", // "interestRate":"0.001" // } // ] // } // const cash = await this.v1PublicGetCashAssets (params); // // { // "code":0, // "data":[ // { // "assetCode":"LTCBULL", // "nativeScale":4, // "numConfirmations":20, // "withdrawFee":"0.2", // "minWithdrawalAmt":"1.0", // "statusCode":"Normal", // "statusMessage":"" // } // ] // } // const assetsData = this.safeValue (assets, 'data', []); const marginData = this.safeValue (margin, 'data', []); const cashData = this.safeValue (cash, 'data', []); const assetsById = this.indexBy (assetsData, 'assetCode'); const marginById = this.indexBy (marginData, 'assetCode'); const cashById = this.indexBy (cashData, 'assetCode'); const dataById = this.deepExtend (assetsById, marginById, cashById); const ids = Object.keys (dataById); const result = {}; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const currency = dataById[id]; const code = this.safeCurrencyCode (id); const precision = this.safeString2 (currency, 'precisionScale', 'nativeScale'); const minAmount = this.parsePrecision (precision); // why would the exchange API have different names for the same field const fee = this.safeNumber2 (currency, 'withdrawFee', 'withdrawalFee'); const status = this.safeString2 (currency, 'status', 'statusCode'); const active = (status === 'Normal'); const margin = ('borrowAssetCode' in currency); result[code] = { 'id': id, 'code': code, 'info': currency, 'type': undefined, 'margin': margin, 'name': this.safeString (currency, 'assetName'), 'active': active, 'fee': fee, 'precision': parseInt (precision), 'limits': { 'amount': { 'min': this.parseNumber (minAmount), 'max': undefined, }, 'withdraw': { 'min': this.safeNumber (currency, 'minWithdrawalAmt'), 'max': undefined, }, }, }; } return result; } async fetchMarkets (params = {}) { const products = await this.v1PublicGetProducts (params); // // { // "code":0, // "data":[ // { // "symbol":"LBA/BTC", // "baseAsset":"LBA", // "quoteAsset":"BTC", // "status":"Normal", // "minNotional":"0.000625", // "maxNotional":"6.25", // "marginTradable":false, // "commissionType":"Quote", // "commissionReserveRate":"0.001", // "tickSize":"0.000000001", // "lotSize":"1" // }, // ] // } // const cash = await this.v1PublicGetCashProducts (params); // // { // "code":0, // "data":[ // { // "symbol":"QTUM/BTC", // "domain":"BTC", // "tradingStartTime":1569506400000, // "collapseDecimals":"0.0001,0.000001,0.00000001", // "minQty":"0.000000001", // "maxQty":"1000000000", // "minNotional":"0.000625", // "maxNotional":"12.5", // "statusCode":"Normal", // "statusMessage":"", // "tickSize":"0.00000001", // "useTick":false, // "lotSize":"0.1", // "useLot":false, // "commissionType":"Quote", // "commissionReserveRate":"0.001", // "qtyScale":1, // "priceScale":8, // "notionalScale":4 // } // ] // } // const perpetuals = await this.v2PublicGetFuturesContract (params); // // { // "code":0, // "data":[ // { // "symbol":"BTC-PERP", // "status":"Normal", // "displayName":"BTCUSDT", // "settlementAsset":"USDT", // "underlying":"BTC/USDT", // "tradingStartTime":1579701600000, // "priceFilter":{"minPrice":"1","maxPrice":"1000000","tickSize":"1"}, // "lotSizeFilter":{"minQty":"0.0001","maxQty":"1000000000","lotSize":"0.0001"}, // "commissionType":"Quote", // "commissionReserveRate":"0.001", // "marketOrderPriceMarkup":"0.03", // "marginRequirements":[ // {"positionNotionalLowerBound":"0","positionNotionalUpperBound":"50000","initialMarginRate":"0.01","maintenanceMarginRate":"0.006"}, // {"positionNotionalLowerBound":"50000","positionNotionalUpperBound":"200000","initialMarginRate":"0.02","maintenanceMarginRate":"0.012"}, // {"positionNotionalLowerBound":"200000","positionNotionalUpperBound":"2000000","initialMarginRate":"0.04","maintenanceMarginRate":"0.024"}, // {"positionNotionalLowerBound":"2000000","positionNotionalUpperBound":"20000000","initialMarginRate":"0.1","maintenanceMarginRate":"0.06"}, // {"positionNotionalLowerBound":"20000000","positionNotionalUpperBound":"40000000","initialMarginRate":"0.2","maintenanceMarginRate":"0.12"}, // {"positionNotionalLowerBound":"40000000","positionNotionalUpperBound":"1000000000","initialMarginRate":"0.333333","maintenanceMarginRate":"0.2"} // ] // } // ] // } // const productsData = this.safeValue (products, 'data', []); const productsById = this.indexBy (productsData, 'symbol'); const cashData = this.safeValue (cash, 'data', []); const perpetualsData = this.safeValue (perpetuals, 'data', []); const cashAndPerpetualsData = this.arrayConcat (cashData, perpetualsData); const cashAndPerpetualsById = this.indexBy (cashAndPerpetualsData, 'symbol'); const dataById = this.deepExtend (productsById, cashAndPerpetualsById); const ids = Object.keys (dataById); const result = []; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const market = dataById[id]; let baseId = this.safeString (market, 'baseAsset'); let quoteId = this.safeString (market, 'quoteAsset'); const settleId = this.safeValue (market, 'settlementAsset'); let base = this.safeCurrencyCode (baseId); let quote = this.safeCurrencyCode (quoteId); const settle = this.safeCurrencyCode (settleId); const precision = { 'amount': this.safeNumber (market, 'lotSize'), 'price': this.safeNumber (market, 'tickSize'), }; const status = this.safeString (market, 'status'); const active = (status === 'Normal'); const type = (settle !== undefined) ? 'swap' : 'spot'; const spot = (type === 'spot'); const swap = (type === 'swap'); const margin = this.safeValue (market, 'marginTradable', false); const contract = swap; const derivative = contract; const linear = contract ? true : undefined; const contractSize = contract ? 1 : undefined; let minQty = this.safeNumber (market, 'minQty'); let maxQty = this.safeNumber (market, 'maxQty'); let minPrice = this.safeNumber (market, 'tickSize'); let maxPrice = undefined; let symbol = base + '/' + quote; if (contract) { const lotSizeFilter = this.safeValue (market, 'lotSizeFilter'); minQty = this.safeNumber (lotSizeFilter, 'minQty'); maxQty = this.safeNumber (lotSizeFilter, 'maxQty'); const priceFilter = this.safeValue (market, 'priceFilter'); minPrice = this.safeNumber (priceFilter, 'minPrice'); maxPrice = this.safeNumber (priceFilter, 'maxPrice'); const underlying = this.safeString (market, 'underlying'); const parts = underlying.split ('/'); baseId = this.safeString (parts, 0); quoteId = this.safeString (parts, 1); base = this.safeCurrencyCode (baseId); quote = this.safeCurrencyCode (quoteId); symbol = base + '/' + quote + ':' + settle; } const fee = this.safeNumber (market, 'commissionReserveRate'); result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'settle': settle, 'baseId': baseId, 'quoteId': quoteId, 'settleId': settleId, 'type': type, 'spot': spot, 'margin': margin, 'swap': swap, 'future': false, 'option': false, 'active': active, 'derivative': derivative, 'contract': contract, 'linear': linear, 'inverse': contract ? !linear : undefined, 'taker': fee, 'maker': fee, 'contractSize': contractSize, 'expiry': undefined, 'expiryDatetime': undefined, 'strike': undefined, 'optionType': undefined, 'precision': precision, 'limits': { 'leverage': { 'min': undefined, 'max': undefined, }, 'amount': { 'min': minQty, 'max': maxQty, }, 'price': { 'min': minPrice, 'max': maxPrice, }, 'cost': { 'min': this.safeNumber (market, 'minNotional'), 'max': this.safeNumber (market, 'maxNotional'), }, }, 'info': market, }); } return result; } async fetchAccounts (params = {}) { let accountGroup = this.safeString (this.options, 'account-group'); let response = undefined; if (accountGroup === undefined) { response = await this.v1PrivateGetInfo (params); // // { // "code":0, // "data":{ // "email":"[email protected]", // "accountGroup":8, // "viewPermission":true, // "tradePermission":true, // "transferPermission":true, // "cashAccount":["cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda"], // "marginAccount":["martXoh1v1N3EMQC5FDtSj5VHso8aI2Z"], // "futuresAccount":["futc9r7UmFJAyBY2rE3beA2JFxav2XFF"], // "userUID":"U6491137460" // } // } // const data = this.safeValue (response, 'data', {}); accountGroup = this.safeString (data, 'accountGroup'); this.options['account-group'] = accountGroup; } return [ { 'id': accountGroup, 'type': undefined, 'currency': undefined, 'info': response, }, ]; } async fetchBalance (params = {}) { await this.loadMarkets (); await this.loadAccounts (); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'fetchBalance', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, }; let method = 'v1PrivateAccountCategoryGetBalance'; if (accountCategory === 'futures') { method = 'v1PrivateAccountGroupGetFuturesCollateralBalance'; } else { request['account-category'] = accountCategory; } const response = await this[method] (this.extend (request, params)); // // cash // // { // 'code': 0, // 'data': [ // { // 'asset': 'BCHSV', // 'totalBalance': '64.298000048', // 'availableBalance': '64.298000048', // }, // ] // } // // margin // // { // 'code': 0, // 'data': [ // { // 'asset': 'BCHSV', // 'totalBalance': '64.298000048', // 'availableBalance': '64.298000048', // 'borrowed': '0', // 'interest': '0', // }, // ] // } // // futures // // { // "code":0, // "data":[ // {"asset":"BTC","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"9456.59"}, // {"asset":"ETH","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"235.95"}, // {"asset":"USDT","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1"}, // {"asset":"USDC","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1.00035"}, // {"asset":"PAX","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1.00045"}, // {"asset":"USDTR","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1"} // ] // } // const result = { 'info': response, 'timestamp': undefined, 'datetime': undefined, }; const balances = this.safeValue (response, 'data', []); for (let i = 0; i < balances.length; i++) { const balance = balances[i]; const code = this.safeCurrencyCode (this.safeString (balance, 'asset')); const account = this.account (); account['free'] = this.safeString (balance, 'availableBalance'); account['total'] = this.safeString (balance, 'totalBalance'); result[code] = account; } return this.parseBalance (result); } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.v1PublicGetDepth (this.extend (request, params)); // // { // "code":0, // "data":{ // "m":"depth-snapshot", // "symbol":"BTC-PERP", // "data":{ // "ts":1590223998202, // "seqnum":115444921, // "asks":[ // ["9207.5","18.2383"], // ["9207.75","18.8235"], // ["9208","10.7873"], // ], // "bids":[ // ["9207.25","0.4009"], // ["9207","0.003"], // ["9206.5","0.003"], // ] // } // } // } // const data = this.safeValue (response, 'data', {}); const orderbook = this.safeValue (data, 'data', {}); const timestamp = this.safeInteger (orderbook, 'ts'); const result = this.parseOrderBook (orderbook, symbol, timestamp); result['nonce'] = this.safeInteger (orderbook, 'seqnum'); return result; } parseTicker (ticker, market = undefined) { // // { // "symbol":"QTUM/BTC", // "open":"0.00016537", // "close":"0.00019077", // "high":"0.000192", // "low":"0.00016537", // "volume":"846.6", // "ask":["0.00018698","26.2"], // "bid":["0.00018408","503.7"], // "type":"spot" // } // const timestamp = undefined; const marketId = this.safeString (ticker, 'symbol'); const type = this.safeString (ticker, 'type'); const delimiter = (type === 'spot') ? '/' : undefined; const symbol = this.safeSymbol (marketId, market, delimiter); const close = this.safeNumber (ticker, 'close'); const bid = this.safeValue (ticker, 'bid', []); const ask = this.safeValue (ticker, 'ask', []); const open = this.safeNumber (ticker, 'open'); return this.safeTicker ({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': undefined, 'high': this.safeNumber (ticker, 'high'), 'low': this.safeNumber (ticker, 'low'), 'bid': this.safeNumber (bid, 0), 'bidVolume': this.safeNumber (bid, 1), 'ask': this.safeNumber (ask, 0), 'askVolume': this.safeNumber (ask, 1), 'vwap': undefined, 'open': open, 'close': close, 'last': close, 'previousClose': undefined, // previous day close 'change': undefined, 'percentage': undefined, 'average': undefined, 'baseVolume': this.safeNumber (ticker, 'volume'), 'quoteVolume': undefined, 'info': ticker, }, market); } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.v1PublicGetTicker (this.extend (request, params)); // // { // "code":0, // "data":{ // "symbol":"BTC-PERP", // or "BTC/USDT" // "open":"9073", // "close":"9185.75", // "high":"9185.75", // "low":"9185.75", // "volume":"576.8334", // "ask":["9185.75","15.5863"], // "bid":["9185.5","0.003"], // "type":"derivatives", // or "spot" // } // } // const data = this.safeValue (response, 'data', {}); return this.parseTicker (data, market); } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); const request = {}; if (symbols !== undefined) { const marketIds = this.marketIds (symbols); request['symbol'] = marketIds.join (','); } const response = await this.v1PublicGetTicker (this.extend (request, params)); // // { // "code":0, // "data":[ // { // "symbol":"QTUM/BTC", // "open":"0.00016537", // "close":"0.00019077", // "high":"0.000192", // "low":"0.00016537", // "volume":"846.6", // "ask":["0.00018698","26.2"], // "bid":["0.00018408","503.7"], // "type":"spot" // } // ] // } // const data = this.safeValue (response, 'data', []); return this.parseTickers (data, symbols); } parseOHLCV (ohlcv, market = undefined) { // // { // "m":"bar", // "s":"BTC/USDT", // "data":{ // "i":"1", // "ts":1590228000000, // "o":"9139.59", // "c":"9131.94", // "h":"9139.99", // "l":"9121.71", // "v":"25.20648" // } // } // const data = this.safeValue (ohlcv, 'data', {}); return [ this.safeInteger (data, 'ts'), this.safeNumber (data, 'o'), this.safeNumber (data, 'h'), this.safeNumber (data, 'l'), this.safeNumber (data, 'c'), this.safeNumber (data, 'v'), ]; } async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], 'interval': this.timeframes[timeframe], }; // if since and limit are not specified // the exchange will return just 1 last candle by default const duration = this.parseTimeframe (timeframe); const options = this.safeValue (this.options, 'fetchOHLCV', {}); const defaultLimit = this.safeInteger (options, 'limit', 500); if (since !== undefined) { request['from'] = since; if (limit === undefined) { limit = defaultLimit; } else { limit = Math.min (limit, defaultLimit); } request['to'] = this.sum (since, limit * duration * 1000, 1); } else if (limit !== undefined) { request['n'] = limit; // max 500 } const response = await this.v1PublicGetBarhist (this.extend (request, params)); // // { // "code":0, // "data":[ // { // "m":"bar", // "s":"BTC/USDT", // "data":{ // "i":"1", // "ts":1590228000000, // "o":"9139.59", // "c":"9131.94", // "h":"9139.99", // "l":"9121.71", // "v":"25.20648" // } // } // ] // } // const data = this.safeValue (response, 'data', []); return this.parseOHLCVs (data, market, timeframe, since, limit); } parseTrade (trade, market = undefined) { // // public fetchTrades // // { // "p":"9128.5", // price // "q":"0.0030", // quantity // "ts":1590229002385, // timestamp // "bm":false, // if true, the buyer is the market maker, we only use this field to "define the side" of a public trade // "seqnum":180143985289898554 // } // const timestamp = this.safeInteger (trade, 'ts'); const priceString = this.safeString2 (trade, 'price', 'p'); const amountString = this.safeString (trade, 'q'); const buyerIsMaker = this.safeValue (trade, 'bm', false); const makerOrTaker = buyerIsMaker ? 'maker' : 'taker'; const side = buyerIsMaker ? 'buy' : 'sell'; let symbol = undefined; if ((symbol === undefined) && (market !== undefined)) { symbol = market['symbol']; } return this.safeTrade ({ 'info': trade, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'id': undefined, 'order': undefined, 'type': undefined, 'takerOrMaker': makerOrTaker, 'side': side, 'price': priceString, 'amount': amountString, 'cost': undefined, 'fee': undefined, }, market); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; if (limit !== undefined) { request['n'] = limit; // max 100 } const response = await this.v1PublicGetTrades (this.extend (request, params)); // // { // "code":0, // "data":{ // "m":"trades", // "symbol":"BTC-PERP", // "data":[ // {"p":"9128.5","q":"0.0030","ts":1590229002385,"bm":false,"seqnum":180143985289898554}, // {"p":"9129","q":"0.0030","ts":1590229002642,"bm":false,"seqnum":180143985289898587}, // {"p":"9129.5","q":"0.0030","ts":1590229021306,"bm":false,"seqnum":180143985289899043} // ] // } // } // const records = this.safeValue (response, 'data', []); const trades = this.safeValue (records, 'data', []); return this.parseTrades (trades, market, since, limit); } parseOrderStatus (status) { const statuses = { 'PendingNew': 'open', 'New': 'open', 'PartiallyFilled': 'open', 'Filled': 'closed', 'Canceled': 'canceled', 'Rejected': 'rejected', }; return this.safeString (statuses, status, status); } parseOrder (order, market = undefined) { // // createOrder // // { // "id": "16e607e2b83a8bXHbAwwoqDo55c166fa", // "orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830", // "orderType": "Market", // "symbol": "BTC/USDT", // "timestamp": 1573576916201 // } // // fetchOrder, fetchOpenOrders, fetchClosedOrders // // { // "symbol": "BTC/USDT", // "price": "8131.22", // "orderQty": "0.00082", // "orderType": "Market", // "avgPx": "7392.02", // "cumFee": "0.005152238", // "cumFilledQty": "0.00082", // "errorCode": "", // "feeAsset": "USDT", // "lastExecTime": 1575953151764, // "orderId": "a16eee20b6750866943712zWEDdAjt3", // "seqNum": 2623469, // "side": "Buy", // "status": "Filled", // "stopPrice": "", // "execInst": "NULL_VAL" // } // // { // "ac": "FUTURES", // "accountId": "testabcdefg", // "avgPx": "0", // "cumFee": "0", // "cumQty": "0", // "errorCode": "NULL_VAL", // "execInst": "NULL_VAL", // "feeAsset": "USDT", // "lastExecTime": 1584072844085, // "orderId": "r170d21956dd5450276356bbtcpKa74", // "orderQty": "1.1499", // "orderType": "Limit", // "price": "4000", // "sendingTime": 1584072841033, // "seqNum": 24105338, // "side": "Buy", // "status": "Canceled", // "stopPrice": "", // "symbol": "BTC-PERP" // }, // const status = this.parseOrderStatus (this.safeString (order, 'status')); const marketId = this.safeString (order, 'symbol'); const symbol = this.safeSymbol (marketId, market, '/'); const timestamp = this.safeInteger2 (order, 'timestamp', 'sendingTime'); const lastTradeTimestamp = this.safeInteger (order, 'lastExecTime'); const price = this.safeString (order, 'price'); const amount = this.safeString (order, 'orderQty'); const average = this.safeString (order, 'avgPx'); const filled = this.safeString2 (order, 'cumFilledQty', 'cumQty'); const id = this.safeString (order, 'orderId'); let clientOrderId = this.safeString (order, 'id'); if (clientOrderId !== undefined) { if (clientOrderId.length < 1) { clientOrderId = undefined; } } const type = this.safeStringLower (order, 'orderType'); const side = this.safeStringLower (order, 'side'); const feeCost = this.safeNumber (order, 'cumFee'); let fee = undefined; if (feeCost !== undefined) { const feeCurrencyId = this.safeString (order, 'feeAsset'); const feeCurrencyCode = this.safeCurrencyCode (feeCurrencyId); fee = { 'cost': feeCost, 'currency': feeCurrencyCode, }; } const stopPrice = this.safeNumber (order, 'stopPrice'); return this.safeOrder2 ({ 'info': order, 'id': id, 'clientOrderId': clientOrderId, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': lastTradeTimestamp, 'symbol': symbol, 'type': type, 'timeInForce': undefined, 'postOnly': undefined, 'side': side, 'price': price, 'stopPrice': stopPrice, 'amount': amount, 'cost': undefined, 'average': average, 'filled': filled, 'remaining': undefined, 'status': status, 'fee': fee, 'trades': undefined, }, market); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'createOrder', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const clientOrderId = this.safeString2 (params, 'clientOrderId', 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'symbol': market['id'], 'time': this.milliseconds (), 'orderQty': this.amountToPrecision (symbol, amount), 'orderType': type, // "limit", "market", "stop_market", "stop_limit" 'side': side, // "buy" or "sell" // 'orderPrice': this.priceToPrecision (symbol, price), // 'stopPrice': this.priceToPrecision (symbol, stopPrice), // required for stop orders // 'postOnly': 'false', // 'false', 'true' // 'timeInForce': 'GTC', // GTC, IOC, FOK // 'respInst': 'ACK', // ACK, 'ACCEPT, DONE }; if (clientOrderId !== undefined) { request['id'] = clientOrderId; params = this.omit (params, [ 'clientOrderId', 'id' ]); } if ((type === 'limit') || (type === 'stop_limit')) { request['orderPrice'] = this.priceToPrecision (symbol, price); } if ((type === 'stop_limit') || (type === 'stop_market')) { const stopPrice = this.safeNumber (params, 'stopPrice'); if (stopPrice === undefined) { throw new InvalidOrder (this.id + ' createOrder() requires a stopPrice parameter for ' + type + ' orders'); } else { request['stopPrice'] = this.priceToPrecision (symbol, stopPrice); params = this.omit (params, 'stopPrice'); } } const response = await this.v1PrivateAccountCategoryPostOrder (this.extend (request, params)); // // { // "code": 0, // "data": { // "ac": "MARGIN", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "action": "place-order", // "info": { // "id": "16e607e2b83a8bXHbAwwoqDo55c166fa", // "orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830", // "orderType": "Market", // "symbol": "BTC/USDT", // "timestamp": 1573576916201 // }, // "status": "Ack" // } // } // const data = this.safeValue (response, 'data', {}); const info = this.safeValue (data, 'info', {}); return this.parseOrder (info, market); } async fetchOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'fetchOrder', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'orderId': id, }; const response = await this.v1PrivateAccountCategoryGetOrderStatus (this.extend (request, params)); // // { // "code": 0, // "accountCategory": "CASH", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "data": [ // { // "symbol": "BTC/USDT", // "price": "8131.22", // "orderQty": "0.00082", // "orderType": "Market", // "avgPx": "7392.02", // "cumFee": "0.005152238", // "cumFilledQty": "0.00082", // "errorCode": "", // "feeAsset": "USDT", // "lastExecTime": 1575953151764, // "orderId": "a16eee20b6750866943712zWEDdAjt3", // "seqNum": 2623469, // "side": "Buy", // "status": "Filled", // "stopPrice": "", // "execInst": "NULL_VAL" // } // ] // } // const data = this.safeValue (response, 'data', {}); return this.parseOrder (data); } async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'fetchOpenOrders', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, }; const response = await this.v1PrivateAccountCategoryGetOrderOpen (this.extend (request, params)); // // { // "ac": "CASH", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "code": 0, // "data": [ // { // "avgPx": "0", // Average filled price of the order // "cumFee": "0", // cumulative fee paid for this order // "cumFilledQty": "0", // cumulative filled quantity // "errorCode": "", // error code; could be empty // "feeAsset": "USDT", // fee asset // "lastExecTime": 1576019723550, // The last execution time of the order // "orderId": "s16ef21882ea0866943712034f36d83", // server provided orderId // "orderQty": "0.0083", // order quantity // "orderType": "Limit", // order type // "price": "7105", // order price // "seqNum": 8193258, // sequence number // "side": "Buy", // order side // "status": "New", // order status on matching engine // "stopPrice": "", // only available for stop market and stop limit orders; otherwise empty // "symbol": "BTC/USDT", // "execInst": "NULL_VAL" // execution instruction // }, // ] // } // const data = this.safeValue (response, 'data', []); if (accountCategory === 'futures') { return this.parseOrders (data, market, since, limit); } // a workaround for https://github.com/ccxt/ccxt/issues/7187 const orders = []; for (let i = 0; i < data.length; i++) { const order = this.parseOrder (data[i], market); orders.push (order); } return this.filterBySymbolSinceLimit (orders, symbol, since, limit); } async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const defaultAccountCategory = this.safeString (this.options, 'account-category'); const options = this.safeValue (this.options, 'fetchClosedOrders', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, // 'category': accountCategory, // 'symbol': market['id'], // 'orderType': 'market', // optional, string // 'side': 'buy', // or 'sell', optional, case insensitive. // 'status': 'Filled', // "Filled", "Canceled", or "Rejected" // 'startTime': exchange.milliseconds (), // 'endTime': exchange.milliseconds (), // 'page': 1, // 'pageSize': 100, }; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } let method = this.safeValue (options, 'method', 'v1PrivateAccountGroupGetOrderHist'); if (market['swap']) { method = 'v2PrivateAccountGroupGetFuturesOrderHistCurrent'; } if (method === 'v1PrivateAccountGroupGetOrderHist') { if (accountCategory !== undefined) { request['category'] = accountCategory; } } else { request['account-category'] = accountCategory; } if (since !== undefined) { request['startTime'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this[method] (this.extend (request, params)); // // accountCategoryGetOrderHistCurrent // // { // "code":0, // "accountId":"cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda", // "ac":"CASH", // "data":[ // { // "seqNum":15561826728, // "orderId":"a17294d305c0U6491137460bethu7kw9", // "symbol":"ETH/USDT", // "orderType":"Limit", // "lastExecTime":1591635618200, // "price":"200", // "orderQty":"0.1", // "side":"Buy", // "status":"Canceled", // "avgPx":"0", // "cumFilledQty":"0", // "stopPrice":"", // "errorCode":"", // "cumFee":"0", // "feeAsset":"USDT", // "execInst":"NULL_VAL" // } // ] // } // // accountGroupGetOrderHist // // { // "code": 0, // "data": { // "data": [ // { // "ac": "FUTURES", // "accountId": "testabcdefg", // "avgPx": "0", // "cumFee": "0", // "cumQty": "0", // "errorCode": "NULL_VAL", // "execInst": "NULL_VAL", // "feeAsset": "USDT", // "lastExecTime": 1584072844085, // "orderId": "r170d21956dd5450276356bbtcpKa74", // "orderQty": "1.1499", // "orderType": "Limit", // "price": "4000", // "sendingTime": 1584072841033, // "seqNum": 24105338, // "side": "Buy", // "status": "Canceled", // "stopPrice": "", // "symbol": "BTC-PERP" // }, // ], // "hasNext": False, // "limit": 500, // "page": 1, // "pageSize": 20 // } // } // let data = this.safeValue (response, 'data'); const isArray = Array.isArray (data); if (!isArray) { data = this.safeValue (data, 'data', []); } return this.parseOrders (data, market, since, limit); } async cancelOrder (id, symbol = undefined, params = {}) { if (symbol === undefined) { throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument'); } await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'cancelOrder', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const clientOrderId = this.safeString2 (params, 'clientOrderId', 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'symbol': market['id'], 'time': this.milliseconds (), 'id': 'foobar', }; if (clientOrderId === undefined) { request['orderId'] = id; } else { request['id'] = clientOrderId; params = this.omit (params, [ 'clientOrderId', 'id' ]); } const response = await this.v1PrivateAccountCategoryDeleteOrder (this.extend (request, params)); // // { // "code": 0, // "data": { // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "ac": "CASH", // "action": "cancel-order", // "status": "Ack", // "info": { // "id": "wv8QGquoeamhssvQBeHOHGQCGlcBjj23", // "orderId": "16e6198afb4s8bXHbAwwoqDo2ebc19dc", // "orderType": "", // could be empty // "symbol": "ETH/USDT", // "timestamp": 1573594877822 // } // } // } // const data = this.safeValue (response, 'data', {}); const info = this.safeValue (data, 'info', {}); return this.parseOrder (info, market); } async cancelAllOrders (symbol = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'cancelAllOrders', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'time': this.milliseconds (), }; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } const response = await this.v1PrivateAccountCategoryDeleteOrderAll (this.extend (request, params)); // // { // "code": 0, // "data": { // "ac": "CASH", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "action": "cancel-all", // "info": { // "id": "2bmYvi7lyTrneMzpcJcf2D7Pe9V1P9wy", // "orderId": "", // "orderType": "NULL_VAL", // "symbol": "", // "timestamp": 1574118495462 // }, // "status": "Ack" // } // } // return response; } parseDepositAddress (depositAddress, currency = undefined) { // // { // address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722", // destTag: "", // tagType: "", // tagId: "", // chainName: "ERC20", // numConfirmations: 20, // withdrawalFee: 1, // nativeScale: 4, // tips: [] // } // const address = this.safeString (depositAddress, 'address'); const tagId = this.safeString (depositAddress, 'tagId'); const tag = this.safeString (depositAddress, tagId); this.checkAddress (address); const code = (currency === undefined) ? undefined : currency['code']; return { 'currency': code, 'address': address, 'tag': tag, 'network': undefined, // TODO: parse network 'info': depositAddress, }; } async fetchDepositAddress (code, params = {}) { await this.loadMarkets (); const currency = this.currency (code); const chainName = this.safeString (params, 'chainName'); params = this.omit (params, 'chainName'); const request = { 'asset': currency['id'], }; const response = await this.v1PrivateGetWalletDepositAddress (this.extend (request, params)); // // { // "code":0, // "data":{ // "asset":"USDT", // "assetName":"Tether", // "address":[ // { // "address":"1N22odLHXnLPCjC8kwBJPTayarr9RtPod6", // "destTag":"", // "tagType":"", // "tagId":"", // "chainName":"Omni", // "numConfirmations":3, // "withdrawalFee":4.7, // "nativeScale":4, // "tips":[] // }, // { // "address":"0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722", // "destTag":"", // "tagType":"", // "tagId":"", // "chainName":"ERC20", // "numConfirmations":20, // "withdrawalFee":1.0, // "nativeScale":4, // "tips":[] // } // ] // } // } // const data = this.safeValue (response, 'data', {}); const addresses = this.safeValue (data, 'address', []); const numAddresses = addresses.length; let address = undefined; if (numAddresses > 1) { const addressesByChainName = this.indexBy (addresses, 'chainName'); if (chainName === undefined) { const chainNames = Object.keys (addressesByChainName); const chains = chainNames.join (', '); throw new ArgumentsRequired (this.id + ' fetchDepositAddress returned more than one address, a chainName parameter is required, one of ' + chains); } address = this.safeValue (addressesByChainName, chainName, {}); } else { // first address address = this.safeValue (addresses, 0, {}); } const result = this.parseDepositAddress (address, currency); return this.extend (result, { 'info': response, }); } async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) { const request = { 'txType': 'deposit', }; return await this.fetchTransactions (code, since, limit, this.extend (request, params)); } async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) { const request = { 'txType': 'withdrawal', }; return await this.fetchTransactions (code, since, limit, this.extend (request, params)); } async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const request = { // 'asset': currency['id'], // 'page': 1, // 'pageSize': 20, // 'startTs': this.milliseconds (), // 'endTs': this.milliseconds (), // 'txType': undefned, // deposit, withdrawal }; let currency = undefined; if (code !== undefined) { currency = this.currency (code); request['asset'] = currency['id']; } if (since !== undefined) { request['startTs'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.v1PrivateGetWalletTransactions (this.extend (request, params)); // // { // code: 0, // data: { // data: [ // { // requestId: "wuzd1Ojsqtz4bCA3UXwtUnnJDmU8PiyB", // time: 1591606166000, // asset: "USDT", // transactionType: "deposit", // amount: "25", // commission: "0", // networkTransactionId: "0xbc4eabdce92f14dbcc01d799a5f8ca1f02f4a3a804b6350ea202be4d3c738fce", // status: "pending", // numConfirmed: 8, // numConfirmations: 20, // destAddress: { address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722" } // } // ], // page: 1, // pageSize: 20, // hasNext: false // } // } // const data = this.safeValue (response, 'data', {}); const transactions = this.safeValue (data, 'data', []); return this.parseTransactions (transactions, currency, since, limit); } parseTransactionStatus (status) { const statuses = { 'reviewing': 'pending', 'pending': 'pending', 'confirmed': 'ok', 'rejected': 'rejected', }; return this.safeString (statuses, status, status); } parseTransaction (transaction, currency = undefined) { // // { // requestId: "wuzd1Ojsqtz4bCA3UXwtUnnJDmU8PiyB", // time: 1591606166000, // asset: "USDT", // transactionType: "deposit", // amount: "25", // commission: "0", // networkTransactionId: "0xbc4eabdce92f14dbcc01d799a5f8ca1f02f4a3a804b6350ea202be4d3c738fce", // status: "pending", // numConfirmed: 8, // numConfirmations: 20, // destAddress: { // address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722", // destTag: "..." // for currencies that have it // } // } // const id = this.safeString (transaction, 'requestId'); const amount = this.safeNumber (transaction, 'amount'); const destAddress = this.safeValue (transaction, 'destAddress', {}); const address = this.safeString (destAddress, 'address'); const tag = this.safeString (destAddress, 'destTag'); const txid = this.safeString (transaction, 'networkTransactionId'); const type = this.safeString (transaction, 'transactionType'); const timestamp = this.safeInteger (transaction, 'time'); const currencyId = this.safeString (transaction, 'asset'); const code = this.safeCurrencyCode (currencyId, currency); const status = this.parseTransactionStatus (this.safeString (transaction, 'status')); const feeCost = this.safeNumber (transaction, 'commission'); return { 'info': transaction, 'id': id, 'currency': code, 'amount': amount, 'address': address, 'addressTo': address, 'addressFrom': undefined, 'tag': tag, 'tagTo': tag, 'tagFrom': undefined, 'status': status, 'type': type, 'updated': undefined, 'txid': txid, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'fee': { 'currency': code, 'cost': feeCost, }, }; } async fetchPositions (symbols = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, }; return await this.v2PrivateAccountGroupGetFuturesPosition (this.extend (request, params)); } parseFundingRate (fundingRate, market = undefined) { // // { // "time": 1640061364830, // "symbol": "EOS-PERP", // "markPrice": "3.353854865", // "indexPrice": "3.3542", // "openInterest": "14242", // "fundingRate": "-0.000073026", // "nextFundingTime": 1640073600000 // } // const marketId = this.safeString (fundingRate, 'symbol'); const symbol = this.safeSymbol (marketId, market); const currentTime = this.safeInteger (fundingRate, 'time'); const nextFundingRate = this.safeNumber (fundingRate, 'fundingRate'); const nextFundingRateTimestamp = this.safeInteger (fundingRate, 'nextFundingTime'); const previousFundingTimestamp = undefined; return { 'info': fundingRate, 'symbol': symbol, 'markPrice': this.safeNumber (fundingRate, 'markPrice'), 'indexPrice': this.safeNumber (fundingRate, 'indexPrice'), 'interestRate': this.parseNumber ('0'), 'estimatedSettlePrice': undefined, 'timestamp': currentTime, 'datetime': this.iso8601 (currentTime), 'previousFundingRate': undefined, 'nextFundingRate': nextFundingRate, 'previousFundingTimestamp': previousFundingTimestamp, 'nextFundingTimestamp': nextFundingRateTimestamp, 'previousFundingDatetime': this.iso8601 (previousFundingTimestamp), 'nextFundingDatetime': this.iso8601 (nextFundingRateTimestamp), }; } async fetchFundingRates (symbols, params = {}) { await this.loadMarkets (); const response = await this.v2PublicGetFuturesPricingData (params); // // { // "code": 0, // "data": { // "contracts": [ // { // "time": 1640061364830, // "symbol": "EOS-PERP", // "markPrice": "3.353854865", // "indexPrice": "3.3542", // "openInterest": "14242", // "fundingRate": "-0.000073026", // "nextFundingTime": 1640073600000 // }, // ], // "collaterals": [ // { // "asset": "USDTR", // "referencePrice": "1" // }, // ] // } // } // const data = this.safeValue (response, 'data', {}); const contracts = this.safeValue (data, 'contracts', []); const result = this.parseFundingRates (contracts); return this.filterByArray (result, 'symbol', symbols); } async setLeverage (leverage, symbol = undefined, params = {}) { if (symbol === undefined) { throw new ArgumentsRequired (this.id + ' setLeverage() requires a symbol argument'); } if ((leverage < 1) || (leverage > 100)) { throw new BadRequest (this.id + ' leverage should be between 1 and 100'); } await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); if (market['type'] !== 'future') { throw new BadSymbol (this.id + ' setLeverage() supports futures contracts only'); } const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, 'symbol': market['id'], 'leverage': leverage, }; return await this.v2PrivateAccountGroupPostFuturesLeverage (this.extend (request, params)); } async setMarginMode (marginType, symbol = undefined, params = {}) { if (marginType !== 'isolated' && marginType !== 'crossed') { throw new BadRequest (this.id + ' setMarginMode() marginType argument should be isolated or crossed'); } await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, 'symbol': market['id'], 'marginType': marginType, }; if (market['type'] !== 'future') { throw new BadSymbol (this.id + ' setMarginMode() supports futures contracts only'); } return await this.v2PrivateAccountGroupPostFuturesMarginType (this.extend (request, params)); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { const version = api[0]; const access = api[1]; const type = this.safeString (api, 2); let url = ''; let query = params; const accountCategory = (type === 'accountCategory'); if (accountCategory || (type === 'accountGroup')) { url += this.implodeParams ('/{account-group}', params); query = this.omit (params, 'account-group'); } let request = this.implodeParams (path, query); url += '/api/pro/'; if (version === 'v2') { request = version + '/' + request; } else { url += version; } if (accountCategory) { url += this.implodeParams ('/{account-category}', query); query = this.omit (query, 'account-category'); } url += '/' + request; if ((version === 'v1') && (request === 'cash/balance') || (request === 'margin/balance')) { request = 'balance'; } if (request.indexOf ('subuser') >= 0) { const parts = request.split ('/'); request = parts[2]; } query = this.omit (query, this.extractParams (path)); if (access === 'public') { if (Object.keys (query).length) { url += '?' + this.urlencode (query); } } else { this.checkRequiredCredentials (); const timestamp = this.milliseconds ().toString (); const payload = timestamp + '+' + request; const hmac = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'base64'); headers = { 'x-auth-key': this.apiKey, 'x-auth-timestamp': timestamp, 'x-auth-signature': hmac, }; if (method === 'GET') { if (Object.keys (query).length) { url += '?' + this.urlencode (query); } } else { headers['Content-Type'] = 'application/json'; body = this.json (query); } } url = this.urls['api'] + url; return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) { if (response === undefined) { return; // fallback to default error handler } // // {'code': 6010, 'message': 'Not enough balance.'} // {'code': 60060, 'message': 'The order is already filled or canceled.'} // {"code":2100,"message":"ApiKeyFailure"} // {"code":300001,"message":"Price is too low from market price.","reason":"INVALID_PRICE","accountId":"cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda","ac":"CASH","action":"place-order","status":"Err","info":{"symbol":"BTC/USDT"}} // const code = this.safeString (response, 'code'); const message = this.safeString (response, 'message'); const error = (code !== undefined) && (code !== '0'); if (error || (message !== undefined)) { const feedback = this.id + ' ' + body; this.throwExactlyMatchedException (this.exceptions['exact'], code, feedback); this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback); this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback); throw new ExchangeError (feedback); // unknown message } } };
js/ascendex.js
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ArgumentsRequired, AuthenticationError, ExchangeError, InsufficientFunds, InvalidOrder, BadSymbol, PermissionDenied, BadRequest } = require ('./base/errors'); const { TICK_SIZE } = require ('./base/functions/number'); // --------------------------------------------------------------------------- module.exports = class ascendex extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'ascendex', 'name': 'AscendEX', 'countries': [ 'SG' ], // Singapore 'rateLimit': 500, 'certified': true, // new metainfo interface 'has': { 'cancelAllOrders': true, 'cancelOrder': true, 'CORS': undefined, 'createOrder': true, 'fetchAccounts': true, 'fetchBalance': true, 'fetchClosedOrders': true, 'fetchCurrencies': true, 'fetchDepositAddress': true, 'fetchDeposits': true, 'fetchFundingRates': true, 'fetchMarkets': true, 'fetchOHLCV': true, 'fetchOpenOrders': true, 'fetchOrder': true, 'fetchOrderBook': true, 'fetchOrders': false, 'fetchPositions': true, 'fetchTicker': true, 'fetchTickers': true, 'fetchTrades': true, 'fetchTransactions': true, 'fetchWithdrawals': true, 'setLeverage': true, 'setMarginMode': true, }, 'timeframes': { '1m': '1', '5m': '5', '15m': '15', '30m': '30', '1h': '60', '2h': '120', '4h': '240', '6h': '360', '12h': '720', '1d': '1d', '1w': '1w', '1M': '1m', }, 'version': 'v2', 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/112027508-47984600-8b48-11eb-9e17-d26459cc36c6.jpg', 'api': 'https://ascendex.com', 'test': 'https://bitmax-test.io', 'www': 'https://ascendex.com', 'doc': [ 'https://bitmax-exchange.github.io/bitmax-pro-api/#bitmax-pro-api-documentation', ], 'fees': 'https://ascendex.com/en/feerate/transactionfee-traderate', 'referral': { 'url': 'https://ascendex.com/en-us/register?inviteCode=EL6BXBQM', 'discount': 0.25, }, }, 'api': { 'v1': { 'public': { 'get': [ 'assets', 'products', 'ticker', 'barhist/info', 'barhist', 'depth', 'trades', 'cash/assets', // not documented 'cash/products', // not documented 'margin/assets', // not documented 'margin/products', // not documented 'futures/collateral', 'futures/contracts', 'futures/ref-px', 'futures/market-data', 'futures/funding-rates', ], }, 'private': { 'get': [ 'info', 'wallet/transactions', 'wallet/deposit/address', // not documented 'data/balance/snapshot', 'data/balance/history', ], 'accountCategory': { 'get': [ 'balance', 'order/open', 'order/status', 'order/hist/current', 'risk', ], 'post': [ 'order', 'order/batch', ], 'delete': [ 'order', 'order/all', 'order/batch', ], }, 'accountGroup': { 'get': [ 'cash/balance', 'margin/balance', 'margin/risk', 'transfer', 'futures/collateral-balance', 'futures/position', 'futures/risk', 'futures/funding-payments', 'order/hist', ], 'post': [ 'futures/transfer/deposit', 'futures/transfer/withdraw', ], }, }, }, 'v2': { 'public': { 'get': [ 'assets', 'futures/contract', 'futures/collateral', 'futures/pricing-data', ], }, 'private': { 'get': [ 'account/info', ], 'accountGroup': { 'get': [ 'order/hist', 'futures/position', 'futures/free-margin', 'futures/order/hist/current', 'futures/order/status', ], 'post': [ 'futures/isolated-position-margin', 'futures/margin-type', 'futures/leverage', 'futures/transfer/deposit', 'futures/transfer/withdraw', 'futures/order', 'futures/order/batch', 'futures/order/open', 'subuser/subuser-transfer', 'subuser/subuser-transfer-hist', ], 'delete': [ 'futures/order', 'futures/order/batch', 'futures/order/all', ], }, }, }, }, 'fees': { 'trading': { 'feeSide': 'get', 'tierBased': true, 'percentage': true, 'taker': this.parseNumber ('0.002'), 'maker': this.parseNumber ('0.002'), }, }, 'precisionMode': TICK_SIZE, 'options': { 'account-category': 'cash', // 'cash'/'margin'/'futures' 'account-group': undefined, 'fetchClosedOrders': { 'method': 'v1PrivateAccountGroupGetOrderHist', // 'v1PrivateAccountGroupGetAccountCategoryOrderHistCurrent' }, }, 'exceptions': { 'exact': { // not documented '1900': BadRequest, // {"code":1900,"message":"Invalid Http Request Input"} '2100': AuthenticationError, // {"code":2100,"message":"ApiKeyFailure"} '5002': BadSymbol, // {"code":5002,"message":"Invalid Symbol"} '6001': BadSymbol, // {"code":6001,"message":"Trading is disabled on symbol."} '6010': InsufficientFunds, // {'code': 6010, 'message': 'Not enough balance.'} '60060': InvalidOrder, // { 'code': 60060, 'message': 'The order is already filled or canceled.' } '600503': InvalidOrder, // {"code":600503,"message":"Notional is too small."} // documented '100001': BadRequest, // INVALID_HTTP_INPUT Http request is invalid '100002': BadRequest, // DATA_NOT_AVAILABLE Some required data is missing '100003': BadRequest, // KEY_CONFLICT The same key exists already '100004': BadRequest, // INVALID_REQUEST_DATA The HTTP request contains invalid field or argument '100005': BadRequest, // INVALID_WS_REQUEST_DATA Websocket request contains invalid field or argument '100006': BadRequest, // INVALID_ARGUMENT The arugment is invalid '100007': BadRequest, // ENCRYPTION_ERROR Something wrong with data encryption '100008': BadSymbol, // SYMBOL_ERROR Symbol does not exist or not valid for the request '100009': AuthenticationError, // AUTHORIZATION_NEEDED Authorization is require for the API access or request '100010': BadRequest, // INVALID_OPERATION The action is invalid or not allowed for the account '100011': BadRequest, // INVALID_TIMESTAMP Not a valid timestamp '100012': BadRequest, // INVALID_STR_FORMAT String format does not '100013': BadRequest, // INVALID_NUM_FORMAT Invalid number input '100101': ExchangeError, // UNKNOWN_ERROR Some unknown error '150001': BadRequest, // INVALID_JSON_FORMAT Require a valid json object '200001': AuthenticationError, // AUTHENTICATION_FAILED Authorization failed '200002': ExchangeError, // TOO_MANY_ATTEMPTS Tried and failed too many times '200003': ExchangeError, // ACCOUNT_NOT_FOUND Account not exist '200004': ExchangeError, // ACCOUNT_NOT_SETUP Account not setup properly '200005': ExchangeError, // ACCOUNT_ALREADY_EXIST Account already exist '200006': ExchangeError, // ACCOUNT_ERROR Some error related with error '200007': ExchangeError, // CODE_NOT_FOUND '200008': ExchangeError, // CODE_EXPIRED Code expired '200009': ExchangeError, // CODE_MISMATCH Code does not match '200010': AuthenticationError, // PASSWORD_ERROR Wrong assword '200011': ExchangeError, // CODE_GEN_FAILED Do not generate required code promptly '200012': ExchangeError, // FAKE_COKE_VERIFY '200013': ExchangeError, // SECURITY_ALERT Provide security alert message '200014': PermissionDenied, // RESTRICTED_ACCOUNT Account is restricted for certain activity, such as trading, or withdraw. '200015': PermissionDenied, // PERMISSION_DENIED No enough permission for the operation '300001': InvalidOrder, // INVALID_PRICE Order price is invalid '300002': InvalidOrder, // INVALID_QTY Order size is invalid '300003': InvalidOrder, // INVALID_SIDE Order side is invalid '300004': InvalidOrder, // INVALID_NOTIONAL Notional is too small or too large '300005': InvalidOrder, // INVALID_TYPE Order typs is invalid '300006': InvalidOrder, // INVALID_ORDER_ID Order id is invalid '300007': InvalidOrder, // INVALID_TIME_IN_FORCE Time In Force in order request is invalid '300008': InvalidOrder, // INVALID_ORDER_PARAMETER Some order parameter is invalid '300009': InvalidOrder, // TRADING_VIOLATION Trading violation on account or asset '300011': InsufficientFunds, // INVALID_BALANCE No enough account or asset balance for the trading '300012': BadSymbol, // INVALID_PRODUCT Not a valid product supported by exchange '300013': InvalidOrder, // INVALID_BATCH_ORDER Some or all orders are invalid in batch order request '300014': InvalidOrder, // {"code":300014,"message":"Order price doesn't conform to the required tick size: 0.1","reason":"TICK_SIZE_VIOLATION"} '300020': InvalidOrder, // TRADING_RESTRICTED There is some trading restriction on account or asset '300021': InvalidOrder, // TRADING_DISABLED Trading is disabled on account or asset '300031': InvalidOrder, // NO_MARKET_PRICE No market price for market type order trading '310001': InsufficientFunds, // INVALID_MARGIN_BALANCE No enough margin balance '310002': InvalidOrder, // INVALID_MARGIN_ACCOUNT Not a valid account for margin trading '310003': InvalidOrder, // MARGIN_TOO_RISKY Leverage is too high '310004': BadSymbol, // INVALID_MARGIN_ASSET This asset does not support margin trading '310005': InvalidOrder, // INVALID_REFERENCE_PRICE There is no valid reference price '510001': ExchangeError, // SERVER_ERROR Something wrong with server. '900001': ExchangeError, // HUMAN_CHALLENGE Human change do not pass }, 'broad': {}, }, 'commonCurrencies': { 'BOND': 'BONDED', 'BTCBEAR': 'BEAR', 'BTCBULL': 'BULL', 'BYN': 'BeyondFi', }, }); } getAccount (params = {}) { // get current or provided bitmax sub-account const account = this.safeValue (params, 'account', this.options['account']); return account.toLowerCase ().capitalize (); } async fetchCurrencies (params = {}) { const assets = await this.v1PublicGetAssets (params); // // { // "code":0, // "data":[ // { // "assetCode" : "LTCBULL", // "assetName" : "3X Long LTC Token", // "precisionScale" : 9, // "nativeScale" : 4, // "withdrawalFee" : "0.2", // "minWithdrawalAmt" : "1.0", // "status" : "Normal" // }, // ] // } // const margin = await this.v1PublicGetMarginAssets (params); // // { // "code":0, // "data":[ // { // "assetCode":"BTT", // "borrowAssetCode":"BTT-B", // "interestAssetCode":"BTT-I", // "nativeScale":0, // "numConfirmations":1, // "withdrawFee":"100.0", // "minWithdrawalAmt":"1000.0", // "statusCode":"Normal", // "statusMessage":"", // "interestRate":"0.001" // } // ] // } // const cash = await this.v1PublicGetCashAssets (params); // // { // "code":0, // "data":[ // { // "assetCode":"LTCBULL", // "nativeScale":4, // "numConfirmations":20, // "withdrawFee":"0.2", // "minWithdrawalAmt":"1.0", // "statusCode":"Normal", // "statusMessage":"" // } // ] // } // const assetsData = this.safeValue (assets, 'data', []); const marginData = this.safeValue (margin, 'data', []); const cashData = this.safeValue (cash, 'data', []); const assetsById = this.indexBy (assetsData, 'assetCode'); const marginById = this.indexBy (marginData, 'assetCode'); const cashById = this.indexBy (cashData, 'assetCode'); const dataById = this.deepExtend (assetsById, marginById, cashById); const ids = Object.keys (dataById); const result = {}; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const currency = dataById[id]; const code = this.safeCurrencyCode (id); const precision = this.safeString2 (currency, 'precisionScale', 'nativeScale'); const minAmount = this.parsePrecision (precision); // why would the exchange API have different names for the same field const fee = this.safeNumber2 (currency, 'withdrawFee', 'withdrawalFee'); const status = this.safeString2 (currency, 'status', 'statusCode'); const active = (status === 'Normal'); const margin = ('borrowAssetCode' in currency); result[code] = { 'id': id, 'code': code, 'info': currency, 'type': undefined, 'margin': margin, 'name': this.safeString (currency, 'assetName'), 'active': active, 'fee': fee, 'precision': parseInt (precision), 'limits': { 'amount': { 'min': this.parseNumber (minAmount), 'max': undefined, }, 'withdraw': { 'min': this.safeNumber (currency, 'minWithdrawalAmt'), 'max': undefined, }, }, }; } return result; } async fetchMarkets (params = {}) { const products = await this.v1PublicGetProducts (params); // // { // "code":0, // "data":[ // { // "symbol":"LBA/BTC", // "baseAsset":"LBA", // "quoteAsset":"BTC", // "status":"Normal", // "minNotional":"0.000625", // "maxNotional":"6.25", // "marginTradable":false, // "commissionType":"Quote", // "commissionReserveRate":"0.001", // "tickSize":"0.000000001", // "lotSize":"1" // }, // ] // } // const cash = await this.v1PublicGetCashProducts (params); // // { // "code":0, // "data":[ // { // "symbol":"QTUM/BTC", // "domain":"BTC", // "tradingStartTime":1569506400000, // "collapseDecimals":"0.0001,0.000001,0.00000001", // "minQty":"0.000000001", // "maxQty":"1000000000", // "minNotional":"0.000625", // "maxNotional":"12.5", // "statusCode":"Normal", // "statusMessage":"", // "tickSize":"0.00000001", // "useTick":false, // "lotSize":"0.1", // "useLot":false, // "commissionType":"Quote", // "commissionReserveRate":"0.001", // "qtyScale":1, // "priceScale":8, // "notionalScale":4 // } // ] // } // const perpetuals = await this.v2PublicGetFuturesContract (params); // // { // "code":0, // "data":[ // { // "symbol":"BTC-PERP", // "status":"Normal", // "displayName":"BTCUSDT", // "settlementAsset":"USDT", // "underlying":"BTC/USDT", // "tradingStartTime":1579701600000, // "priceFilter":{"minPrice":"1","maxPrice":"1000000","tickSize":"1"}, // "lotSizeFilter":{"minQty":"0.0001","maxQty":"1000000000","lotSize":"0.0001"}, // "commissionType":"Quote", // "commissionReserveRate":"0.001", // "marketOrderPriceMarkup":"0.03", // "marginRequirements":[ // {"positionNotionalLowerBound":"0","positionNotionalUpperBound":"50000","initialMarginRate":"0.01","maintenanceMarginRate":"0.006"}, // {"positionNotionalLowerBound":"50000","positionNotionalUpperBound":"200000","initialMarginRate":"0.02","maintenanceMarginRate":"0.012"}, // {"positionNotionalLowerBound":"200000","positionNotionalUpperBound":"2000000","initialMarginRate":"0.04","maintenanceMarginRate":"0.024"}, // {"positionNotionalLowerBound":"2000000","positionNotionalUpperBound":"20000000","initialMarginRate":"0.1","maintenanceMarginRate":"0.06"}, // {"positionNotionalLowerBound":"20000000","positionNotionalUpperBound":"40000000","initialMarginRate":"0.2","maintenanceMarginRate":"0.12"}, // {"positionNotionalLowerBound":"40000000","positionNotionalUpperBound":"1000000000","initialMarginRate":"0.333333","maintenanceMarginRate":"0.2"} // ] // } // ] // } // const productsData = this.safeValue (products, 'data', []); const productsById = this.indexBy (productsData, 'symbol'); const cashData = this.safeValue (cash, 'data', []); const perpetualsData = this.safeValue (perpetuals, 'data', []); const cashAndPerpetualsData = this.arrayConcat (cashData, perpetualsData); const cashAndPerpetualsById = this.indexBy (cashAndPerpetualsData, 'symbol'); const dataById = this.deepExtend (productsById, cashAndPerpetualsById); const ids = Object.keys (dataById); const result = []; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const market = dataById[id]; let baseId = this.safeString (market, 'baseAsset'); let quoteId = this.safeString (market, 'quoteAsset'); const settleId = this.safeValue (market, 'settlementAsset'); let base = this.safeCurrencyCode (baseId); let quote = this.safeCurrencyCode (quoteId); const settle = this.safeCurrencyCode (settleId); const precision = { 'amount': this.safeNumber (market, 'lotSize'), 'price': this.safeNumber (market, 'tickSize'), }; const status = this.safeString (market, 'status'); const active = (status === 'Normal'); const type = (settle !== undefined) ? 'swap' : 'spot'; const spot = (type === 'spot'); const swap = (type === 'swap'); const margin = this.safeValue (market, 'marginTradable', false); const contract = swap; const derivative = contract; const linear = contract ? true : undefined; const contractSize = contract ? 1 : undefined; let minQty = this.safeNumber (market, 'minQty'); let maxQty = this.safeNumber (market, 'maxQty'); let minPrice = this.safeNumber (market, 'tickSize'); let maxPrice = undefined; let symbol = base + '/' + quote; if (contract) { const lotSizeFilter = this.safeValue (market, 'lotSizeFilter'); minQty = this.safeNumber (lotSizeFilter, 'minQty'); maxQty = this.safeNumber (lotSizeFilter, 'maxQty'); const priceFilter = this.safeValue (market, 'priceFilter'); minPrice = this.safeNumber (priceFilter, 'minPrice'); maxPrice = this.safeNumber (priceFilter, 'maxPrice'); const underlying = this.safeString (market, 'underlying'); const parts = underlying.split ('/'); baseId = this.safeString (parts, 0); quoteId = this.safeString (parts, 1); base = this.safeCurrencyCode (baseId); quote = this.safeCurrencyCode (quoteId); symbol = base + '/' + quote + ':' + settle; } const fee = this.safeNumber (market, 'commissionReserveRate'); result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'settle': settle, 'baseId': baseId, 'quoteId': quoteId, 'settleId': settleId, 'type': type, 'spot': spot, 'margin': margin, 'swap': swap, 'future': false, 'option': false, 'active': active, 'derivative': derivative, 'contract': contract, 'linear': linear, 'inverse': contract ? !linear : undefined, 'taker': fee, 'maker': fee, 'contractSize': contractSize, 'expiry': undefined, 'expiryDatetime': undefined, 'strike': undefined, 'optionType': undefined, 'precision': precision, 'limits': { 'leverage': { 'min': undefined, 'max': undefined, }, 'amount': { 'min': minQty, 'max': maxQty, }, 'price': { 'min': minPrice, 'max': maxPrice, }, 'cost': { 'min': this.safeNumber (market, 'minNotional'), 'max': this.safeNumber (market, 'maxNotional'), }, }, 'info': market, }); } return result; } async fetchAccounts (params = {}) { let accountGroup = this.safeString (this.options, 'account-group'); let response = undefined; if (accountGroup === undefined) { response = await this.v1PrivateGetInfo (params); // // { // "code":0, // "data":{ // "email":"[email protected]", // "accountGroup":8, // "viewPermission":true, // "tradePermission":true, // "transferPermission":true, // "cashAccount":["cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda"], // "marginAccount":["martXoh1v1N3EMQC5FDtSj5VHso8aI2Z"], // "futuresAccount":["futc9r7UmFJAyBY2rE3beA2JFxav2XFF"], // "userUID":"U6491137460" // } // } // const data = this.safeValue (response, 'data', {}); accountGroup = this.safeString (data, 'accountGroup'); this.options['account-group'] = accountGroup; } return [ { 'id': accountGroup, 'type': undefined, 'currency': undefined, 'info': response, }, ]; } async fetchBalance (params = {}) { await this.loadMarkets (); await this.loadAccounts (); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'fetchBalance', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, }; let method = 'v1PrivateAccountCategoryGetBalance'; if (accountCategory === 'futures') { method = 'v1PrivateAccountGroupGetFuturesCollateralBalance'; } else { request['account-category'] = accountCategory; } const response = await this[method] (this.extend (request, params)); // // cash // // { // 'code': 0, // 'data': [ // { // 'asset': 'BCHSV', // 'totalBalance': '64.298000048', // 'availableBalance': '64.298000048', // }, // ] // } // // margin // // { // 'code': 0, // 'data': [ // { // 'asset': 'BCHSV', // 'totalBalance': '64.298000048', // 'availableBalance': '64.298000048', // 'borrowed': '0', // 'interest': '0', // }, // ] // } // // futures // // { // "code":0, // "data":[ // {"asset":"BTC","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"9456.59"}, // {"asset":"ETH","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"235.95"}, // {"asset":"USDT","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1"}, // {"asset":"USDC","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1.00035"}, // {"asset":"PAX","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1.00045"}, // {"asset":"USDTR","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1"} // ] // } // const result = { 'info': response, 'timestamp': undefined, 'datetime': undefined, }; const balances = this.safeValue (response, 'data', []); for (let i = 0; i < balances.length; i++) { const balance = balances[i]; const code = this.safeCurrencyCode (this.safeString (balance, 'asset')); const account = this.account (); account['free'] = this.safeString (balance, 'availableBalance'); account['total'] = this.safeString (balance, 'totalBalance'); result[code] = account; } return this.parseBalance (result); } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.v1PublicGetDepth (this.extend (request, params)); // // { // "code":0, // "data":{ // "m":"depth-snapshot", // "symbol":"BTC-PERP", // "data":{ // "ts":1590223998202, // "seqnum":115444921, // "asks":[ // ["9207.5","18.2383"], // ["9207.75","18.8235"], // ["9208","10.7873"], // ], // "bids":[ // ["9207.25","0.4009"], // ["9207","0.003"], // ["9206.5","0.003"], // ] // } // } // } // const data = this.safeValue (response, 'data', {}); const orderbook = this.safeValue (data, 'data', {}); const timestamp = this.safeInteger (orderbook, 'ts'); const result = this.parseOrderBook (orderbook, symbol, timestamp); result['nonce'] = this.safeInteger (orderbook, 'seqnum'); return result; } parseTicker (ticker, market = undefined) { // // { // "symbol":"QTUM/BTC", // "open":"0.00016537", // "close":"0.00019077", // "high":"0.000192", // "low":"0.00016537", // "volume":"846.6", // "ask":["0.00018698","26.2"], // "bid":["0.00018408","503.7"], // "type":"spot" // } // const timestamp = undefined; const marketId = this.safeString (ticker, 'symbol'); const type = this.safeString (ticker, 'type'); const delimiter = (type === 'spot') ? '/' : undefined; const symbol = this.safeSymbol (marketId, market, delimiter); const close = this.safeNumber (ticker, 'close'); const bid = this.safeValue (ticker, 'bid', []); const ask = this.safeValue (ticker, 'ask', []); const open = this.safeNumber (ticker, 'open'); return this.safeTicker ({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': undefined, 'high': this.safeNumber (ticker, 'high'), 'low': this.safeNumber (ticker, 'low'), 'bid': this.safeNumber (bid, 0), 'bidVolume': this.safeNumber (bid, 1), 'ask': this.safeNumber (ask, 0), 'askVolume': this.safeNumber (ask, 1), 'vwap': undefined, 'open': open, 'close': close, 'last': close, 'previousClose': undefined, // previous day close 'change': undefined, 'percentage': undefined, 'average': undefined, 'baseVolume': this.safeNumber (ticker, 'volume'), 'quoteVolume': undefined, 'info': ticker, }, market); } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; const response = await this.v1PublicGetTicker (this.extend (request, params)); // // { // "code":0, // "data":{ // "symbol":"BTC-PERP", // or "BTC/USDT" // "open":"9073", // "close":"9185.75", // "high":"9185.75", // "low":"9185.75", // "volume":"576.8334", // "ask":["9185.75","15.5863"], // "bid":["9185.5","0.003"], // "type":"derivatives", // or "spot" // } // } // const data = this.safeValue (response, 'data', {}); return this.parseTicker (data, market); } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); const request = {}; if (symbols !== undefined) { const marketIds = this.marketIds (symbols); request['symbol'] = marketIds.join (','); } const response = await this.v1PublicGetTicker (this.extend (request, params)); // // { // "code":0, // "data":[ // { // "symbol":"QTUM/BTC", // "open":"0.00016537", // "close":"0.00019077", // "high":"0.000192", // "low":"0.00016537", // "volume":"846.6", // "ask":["0.00018698","26.2"], // "bid":["0.00018408","503.7"], // "type":"spot" // } // ] // } // const data = this.safeValue (response, 'data', []); return this.parseTickers (data, symbols); } parseOHLCV (ohlcv, market = undefined) { // // { // "m":"bar", // "s":"BTC/USDT", // "data":{ // "i":"1", // "ts":1590228000000, // "o":"9139.59", // "c":"9131.94", // "h":"9139.99", // "l":"9121.71", // "v":"25.20648" // } // } // const data = this.safeValue (ohlcv, 'data', {}); return [ this.safeInteger (data, 'ts'), this.safeNumber (data, 'o'), this.safeNumber (data, 'h'), this.safeNumber (data, 'l'), this.safeNumber (data, 'c'), this.safeNumber (data, 'v'), ]; } async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], 'interval': this.timeframes[timeframe], }; // if since and limit are not specified // the exchange will return just 1 last candle by default const duration = this.parseTimeframe (timeframe); const options = this.safeValue (this.options, 'fetchOHLCV', {}); const defaultLimit = this.safeInteger (options, 'limit', 500); if (since !== undefined) { request['from'] = since; if (limit === undefined) { limit = defaultLimit; } else { limit = Math.min (limit, defaultLimit); } request['to'] = this.sum (since, limit * duration * 1000, 1); } else if (limit !== undefined) { request['n'] = limit; // max 500 } const response = await this.v1PublicGetBarhist (this.extend (request, params)); // // { // "code":0, // "data":[ // { // "m":"bar", // "s":"BTC/USDT", // "data":{ // "i":"1", // "ts":1590228000000, // "o":"9139.59", // "c":"9131.94", // "h":"9139.99", // "l":"9121.71", // "v":"25.20648" // } // } // ] // } // const data = this.safeValue (response, 'data', []); return this.parseOHLCVs (data, market, timeframe, since, limit); } parseTrade (trade, market = undefined) { // // public fetchTrades // // { // "p":"9128.5", // price // "q":"0.0030", // quantity // "ts":1590229002385, // timestamp // "bm":false, // if true, the buyer is the market maker, we only use this field to "define the side" of a public trade // "seqnum":180143985289898554 // } // const timestamp = this.safeInteger (trade, 'ts'); const priceString = this.safeString2 (trade, 'price', 'p'); const amountString = this.safeString (trade, 'q'); const buyerIsMaker = this.safeValue (trade, 'bm', false); const makerOrTaker = buyerIsMaker ? 'maker' : 'taker'; const side = buyerIsMaker ? 'buy' : 'sell'; let symbol = undefined; if ((symbol === undefined) && (market !== undefined)) { symbol = market['symbol']; } return this.safeTrade ({ 'info': trade, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': symbol, 'id': undefined, 'order': undefined, 'type': undefined, 'takerOrMaker': makerOrTaker, 'side': side, 'price': priceString, 'amount': amountString, 'cost': undefined, 'fee': undefined, }, market); } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const market = this.market (symbol); const request = { 'symbol': market['id'], }; if (limit !== undefined) { request['n'] = limit; // max 100 } const response = await this.v1PublicGetTrades (this.extend (request, params)); // // { // "code":0, // "data":{ // "m":"trades", // "symbol":"BTC-PERP", // "data":[ // {"p":"9128.5","q":"0.0030","ts":1590229002385,"bm":false,"seqnum":180143985289898554}, // {"p":"9129","q":"0.0030","ts":1590229002642,"bm":false,"seqnum":180143985289898587}, // {"p":"9129.5","q":"0.0030","ts":1590229021306,"bm":false,"seqnum":180143985289899043} // ] // } // } // const records = this.safeValue (response, 'data', []); const trades = this.safeValue (records, 'data', []); return this.parseTrades (trades, market, since, limit); } parseOrderStatus (status) { const statuses = { 'PendingNew': 'open', 'New': 'open', 'PartiallyFilled': 'open', 'Filled': 'closed', 'Canceled': 'canceled', 'Rejected': 'rejected', }; return this.safeString (statuses, status, status); } parseOrder (order, market = undefined) { // // createOrder // // { // "id": "16e607e2b83a8bXHbAwwoqDo55c166fa", // "orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830", // "orderType": "Market", // "symbol": "BTC/USDT", // "timestamp": 1573576916201 // } // // fetchOrder, fetchOpenOrders, fetchClosedOrders // // { // "symbol": "BTC/USDT", // "price": "8131.22", // "orderQty": "0.00082", // "orderType": "Market", // "avgPx": "7392.02", // "cumFee": "0.005152238", // "cumFilledQty": "0.00082", // "errorCode": "", // "feeAsset": "USDT", // "lastExecTime": 1575953151764, // "orderId": "a16eee20b6750866943712zWEDdAjt3", // "seqNum": 2623469, // "side": "Buy", // "status": "Filled", // "stopPrice": "", // "execInst": "NULL_VAL" // } // // { // "ac": "FUTURES", // "accountId": "testabcdefg", // "avgPx": "0", // "cumFee": "0", // "cumQty": "0", // "errorCode": "NULL_VAL", // "execInst": "NULL_VAL", // "feeAsset": "USDT", // "lastExecTime": 1584072844085, // "orderId": "r170d21956dd5450276356bbtcpKa74", // "orderQty": "1.1499", // "orderType": "Limit", // "price": "4000", // "sendingTime": 1584072841033, // "seqNum": 24105338, // "side": "Buy", // "status": "Canceled", // "stopPrice": "", // "symbol": "BTC-PERP" // }, // const status = this.parseOrderStatus (this.safeString (order, 'status')); const marketId = this.safeString (order, 'symbol'); const symbol = this.safeSymbol (marketId, market, '/'); const timestamp = this.safeInteger2 (order, 'timestamp', 'sendingTime'); const lastTradeTimestamp = this.safeInteger (order, 'lastExecTime'); const price = this.safeString (order, 'price'); const amount = this.safeString (order, 'orderQty'); const average = this.safeString (order, 'avgPx'); const filled = this.safeString2 (order, 'cumFilledQty', 'cumQty'); const id = this.safeString (order, 'orderId'); let clientOrderId = this.safeString (order, 'id'); if (clientOrderId !== undefined) { if (clientOrderId.length < 1) { clientOrderId = undefined; } } const type = this.safeStringLower (order, 'orderType'); const side = this.safeStringLower (order, 'side'); const feeCost = this.safeNumber (order, 'cumFee'); let fee = undefined; if (feeCost !== undefined) { const feeCurrencyId = this.safeString (order, 'feeAsset'); const feeCurrencyCode = this.safeCurrencyCode (feeCurrencyId); fee = { 'cost': feeCost, 'currency': feeCurrencyCode, }; } const stopPrice = this.safeNumber (order, 'stopPrice'); return this.safeOrder2 ({ 'info': order, 'id': id, 'clientOrderId': clientOrderId, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': lastTradeTimestamp, 'symbol': symbol, 'type': type, 'timeInForce': undefined, 'postOnly': undefined, 'side': side, 'price': price, 'stopPrice': stopPrice, 'amount': amount, 'cost': undefined, 'average': average, 'filled': filled, 'remaining': undefined, 'status': status, 'fee': fee, 'trades': undefined, }, market); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'createOrder', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const clientOrderId = this.safeString2 (params, 'clientOrderId', 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'symbol': market['id'], 'time': this.milliseconds (), 'orderQty': this.amountToPrecision (symbol, amount), 'orderType': type, // "limit", "market", "stop_market", "stop_limit" 'side': side, // "buy" or "sell" // 'orderPrice': this.priceToPrecision (symbol, price), // 'stopPrice': this.priceToPrecision (symbol, stopPrice), // required for stop orders // 'postOnly': 'false', // 'false', 'true' // 'timeInForce': 'GTC', // GTC, IOC, FOK // 'respInst': 'ACK', // ACK, 'ACCEPT, DONE }; if (clientOrderId !== undefined) { request['id'] = clientOrderId; params = this.omit (params, [ 'clientOrderId', 'id' ]); } if ((type === 'limit') || (type === 'stop_limit')) { request['orderPrice'] = this.priceToPrecision (symbol, price); } if ((type === 'stop_limit') || (type === 'stop_market')) { const stopPrice = this.safeNumber (params, 'stopPrice'); if (stopPrice === undefined) { throw new InvalidOrder (this.id + ' createOrder() requires a stopPrice parameter for ' + type + ' orders'); } else { request['stopPrice'] = this.priceToPrecision (symbol, stopPrice); params = this.omit (params, 'stopPrice'); } } const response = await this.v1PrivateAccountCategoryPostOrder (this.extend (request, params)); // // { // "code": 0, // "data": { // "ac": "MARGIN", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "action": "place-order", // "info": { // "id": "16e607e2b83a8bXHbAwwoqDo55c166fa", // "orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830", // "orderType": "Market", // "symbol": "BTC/USDT", // "timestamp": 1573576916201 // }, // "status": "Ack" // } // } // const data = this.safeValue (response, 'data', {}); const info = this.safeValue (data, 'info', {}); return this.parseOrder (info, market); } async fetchOrder (id, symbol = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'fetchOrder', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'orderId': id, }; const response = await this.v1PrivateAccountCategoryGetOrderStatus (this.extend (request, params)); // // { // "code": 0, // "accountCategory": "CASH", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "data": [ // { // "symbol": "BTC/USDT", // "price": "8131.22", // "orderQty": "0.00082", // "orderType": "Market", // "avgPx": "7392.02", // "cumFee": "0.005152238", // "cumFilledQty": "0.00082", // "errorCode": "", // "feeAsset": "USDT", // "lastExecTime": 1575953151764, // "orderId": "a16eee20b6750866943712zWEDdAjt3", // "seqNum": 2623469, // "side": "Buy", // "status": "Filled", // "stopPrice": "", // "execInst": "NULL_VAL" // } // ] // } // const data = this.safeValue (response, 'data', {}); return this.parseOrder (data); } async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'fetchOpenOrders', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, }; const response = await this.v1PrivateAccountCategoryGetOrderOpen (this.extend (request, params)); // // { // "ac": "CASH", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "code": 0, // "data": [ // { // "avgPx": "0", // Average filled price of the order // "cumFee": "0", // cumulative fee paid for this order // "cumFilledQty": "0", // cumulative filled quantity // "errorCode": "", // error code; could be empty // "feeAsset": "USDT", // fee asset // "lastExecTime": 1576019723550, // The last execution time of the order // "orderId": "s16ef21882ea0866943712034f36d83", // server provided orderId // "orderQty": "0.0083", // order quantity // "orderType": "Limit", // order type // "price": "7105", // order price // "seqNum": 8193258, // sequence number // "side": "Buy", // order side // "status": "New", // order status on matching engine // "stopPrice": "", // only available for stop market and stop limit orders; otherwise empty // "symbol": "BTC/USDT", // "execInst": "NULL_VAL" // execution instruction // }, // ] // } // const data = this.safeValue (response, 'data', []); if (accountCategory === 'futures') { return this.parseOrders (data, market, since, limit); } // a workaround for https://github.com/ccxt/ccxt/issues/7187 const orders = []; for (let i = 0; i < data.length; i++) { const order = this.parseOrder (data[i], market); orders.push (order); } return this.filterBySymbolSinceLimit (orders, symbol, since, limit); } async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); let market = undefined; if (symbol !== undefined) { market = this.market (symbol); } const defaultAccountCategory = this.safeString (this.options, 'account-category'); const options = this.safeValue (this.options, 'fetchClosedOrders', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, // 'category': accountCategory, // 'symbol': market['id'], // 'orderType': 'market', // optional, string // 'side': 'buy', // or 'sell', optional, case insensitive. // 'status': 'Filled', // "Filled", "Canceled", or "Rejected" // 'startTime': exchange.milliseconds (), // 'endTime': exchange.milliseconds (), // 'page': 1, // 'pageSize': 100, }; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } const method = this.safeValue (options, 'method', 'v1PrivateAccountGroupGetOrderHist'); if (method === 'v1PrivateAccountGroupGetOrderHist') { if (accountCategory !== undefined) { request['category'] = accountCategory; } } else { request['account-category'] = accountCategory; } if (since !== undefined) { request['startTime'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this[method] (this.extend (request, params)); // // accountCategoryGetOrderHistCurrent // // { // "code":0, // "accountId":"cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda", // "ac":"CASH", // "data":[ // { // "seqNum":15561826728, // "orderId":"a17294d305c0U6491137460bethu7kw9", // "symbol":"ETH/USDT", // "orderType":"Limit", // "lastExecTime":1591635618200, // "price":"200", // "orderQty":"0.1", // "side":"Buy", // "status":"Canceled", // "avgPx":"0", // "cumFilledQty":"0", // "stopPrice":"", // "errorCode":"", // "cumFee":"0", // "feeAsset":"USDT", // "execInst":"NULL_VAL" // } // ] // } // // accountGroupGetOrderHist // // { // "code": 0, // "data": { // "data": [ // { // "ac": "FUTURES", // "accountId": "testabcdefg", // "avgPx": "0", // "cumFee": "0", // "cumQty": "0", // "errorCode": "NULL_VAL", // "execInst": "NULL_VAL", // "feeAsset": "USDT", // "lastExecTime": 1584072844085, // "orderId": "r170d21956dd5450276356bbtcpKa74", // "orderQty": "1.1499", // "orderType": "Limit", // "price": "4000", // "sendingTime": 1584072841033, // "seqNum": 24105338, // "side": "Buy", // "status": "Canceled", // "stopPrice": "", // "symbol": "BTC-PERP" // }, // ], // "hasNext": False, // "limit": 500, // "page": 1, // "pageSize": 20 // } // } // let data = this.safeValue (response, 'data'); const isArray = Array.isArray (data); if (!isArray) { data = this.safeValue (data, 'data', []); } return this.parseOrders (data, market, since, limit); } async cancelOrder (id, symbol = undefined, params = {}) { if (symbol === undefined) { throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument'); } await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'cancelOrder', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const clientOrderId = this.safeString2 (params, 'clientOrderId', 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'symbol': market['id'], 'time': this.milliseconds (), 'id': 'foobar', }; if (clientOrderId === undefined) { request['orderId'] = id; } else { request['id'] = clientOrderId; params = this.omit (params, [ 'clientOrderId', 'id' ]); } const response = await this.v1PrivateAccountCategoryDeleteOrder (this.extend (request, params)); // // { // "code": 0, // "data": { // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "ac": "CASH", // "action": "cancel-order", // "status": "Ack", // "info": { // "id": "wv8QGquoeamhssvQBeHOHGQCGlcBjj23", // "orderId": "16e6198afb4s8bXHbAwwoqDo2ebc19dc", // "orderType": "", // could be empty // "symbol": "ETH/USDT", // "timestamp": 1573594877822 // } // } // } // const data = this.safeValue (response, 'data', {}); const info = this.safeValue (data, 'info', {}); return this.parseOrder (info, market); } async cancelAllOrders (symbol = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const defaultAccountCategory = this.safeString (this.options, 'account-category', 'cash'); const options = this.safeValue (this.options, 'cancelAllOrders', {}); let accountCategory = this.safeString (options, 'account-category', defaultAccountCategory); accountCategory = this.safeString (params, 'account-category', accountCategory); params = this.omit (params, 'account-category'); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeValue (account, 'id'); const request = { 'account-group': accountGroup, 'account-category': accountCategory, 'time': this.milliseconds (), }; let market = undefined; if (symbol !== undefined) { market = this.market (symbol); request['symbol'] = market['id']; } const response = await this.v1PrivateAccountCategoryDeleteOrderAll (this.extend (request, params)); // // { // "code": 0, // "data": { // "ac": "CASH", // "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo", // "action": "cancel-all", // "info": { // "id": "2bmYvi7lyTrneMzpcJcf2D7Pe9V1P9wy", // "orderId": "", // "orderType": "NULL_VAL", // "symbol": "", // "timestamp": 1574118495462 // }, // "status": "Ack" // } // } // return response; } parseDepositAddress (depositAddress, currency = undefined) { // // { // address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722", // destTag: "", // tagType: "", // tagId: "", // chainName: "ERC20", // numConfirmations: 20, // withdrawalFee: 1, // nativeScale: 4, // tips: [] // } // const address = this.safeString (depositAddress, 'address'); const tagId = this.safeString (depositAddress, 'tagId'); const tag = this.safeString (depositAddress, tagId); this.checkAddress (address); const code = (currency === undefined) ? undefined : currency['code']; return { 'currency': code, 'address': address, 'tag': tag, 'network': undefined, // TODO: parse network 'info': depositAddress, }; } async fetchDepositAddress (code, params = {}) { await this.loadMarkets (); const currency = this.currency (code); const chainName = this.safeString (params, 'chainName'); params = this.omit (params, 'chainName'); const request = { 'asset': currency['id'], }; const response = await this.v1PrivateGetWalletDepositAddress (this.extend (request, params)); // // { // "code":0, // "data":{ // "asset":"USDT", // "assetName":"Tether", // "address":[ // { // "address":"1N22odLHXnLPCjC8kwBJPTayarr9RtPod6", // "destTag":"", // "tagType":"", // "tagId":"", // "chainName":"Omni", // "numConfirmations":3, // "withdrawalFee":4.7, // "nativeScale":4, // "tips":[] // }, // { // "address":"0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722", // "destTag":"", // "tagType":"", // "tagId":"", // "chainName":"ERC20", // "numConfirmations":20, // "withdrawalFee":1.0, // "nativeScale":4, // "tips":[] // } // ] // } // } // const data = this.safeValue (response, 'data', {}); const addresses = this.safeValue (data, 'address', []); const numAddresses = addresses.length; let address = undefined; if (numAddresses > 1) { const addressesByChainName = this.indexBy (addresses, 'chainName'); if (chainName === undefined) { const chainNames = Object.keys (addressesByChainName); const chains = chainNames.join (', '); throw new ArgumentsRequired (this.id + ' fetchDepositAddress returned more than one address, a chainName parameter is required, one of ' + chains); } address = this.safeValue (addressesByChainName, chainName, {}); } else { // first address address = this.safeValue (addresses, 0, {}); } const result = this.parseDepositAddress (address, currency); return this.extend (result, { 'info': response, }); } async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) { const request = { 'txType': 'deposit', }; return await this.fetchTransactions (code, since, limit, this.extend (request, params)); } async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) { const request = { 'txType': 'withdrawal', }; return await this.fetchTransactions (code, since, limit, this.extend (request, params)); } async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); const request = { // 'asset': currency['id'], // 'page': 1, // 'pageSize': 20, // 'startTs': this.milliseconds (), // 'endTs': this.milliseconds (), // 'txType': undefned, // deposit, withdrawal }; let currency = undefined; if (code !== undefined) { currency = this.currency (code); request['asset'] = currency['id']; } if (since !== undefined) { request['startTs'] = since; } if (limit !== undefined) { request['pageSize'] = limit; } const response = await this.v1PrivateGetWalletTransactions (this.extend (request, params)); // // { // code: 0, // data: { // data: [ // { // requestId: "wuzd1Ojsqtz4bCA3UXwtUnnJDmU8PiyB", // time: 1591606166000, // asset: "USDT", // transactionType: "deposit", // amount: "25", // commission: "0", // networkTransactionId: "0xbc4eabdce92f14dbcc01d799a5f8ca1f02f4a3a804b6350ea202be4d3c738fce", // status: "pending", // numConfirmed: 8, // numConfirmations: 20, // destAddress: { address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722" } // } // ], // page: 1, // pageSize: 20, // hasNext: false // } // } // const data = this.safeValue (response, 'data', {}); const transactions = this.safeValue (data, 'data', []); return this.parseTransactions (transactions, currency, since, limit); } parseTransactionStatus (status) { const statuses = { 'reviewing': 'pending', 'pending': 'pending', 'confirmed': 'ok', 'rejected': 'rejected', }; return this.safeString (statuses, status, status); } parseTransaction (transaction, currency = undefined) { // // { // requestId: "wuzd1Ojsqtz4bCA3UXwtUnnJDmU8PiyB", // time: 1591606166000, // asset: "USDT", // transactionType: "deposit", // amount: "25", // commission: "0", // networkTransactionId: "0xbc4eabdce92f14dbcc01d799a5f8ca1f02f4a3a804b6350ea202be4d3c738fce", // status: "pending", // numConfirmed: 8, // numConfirmations: 20, // destAddress: { // address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722", // destTag: "..." // for currencies that have it // } // } // const id = this.safeString (transaction, 'requestId'); const amount = this.safeNumber (transaction, 'amount'); const destAddress = this.safeValue (transaction, 'destAddress', {}); const address = this.safeString (destAddress, 'address'); const tag = this.safeString (destAddress, 'destTag'); const txid = this.safeString (transaction, 'networkTransactionId'); const type = this.safeString (transaction, 'transactionType'); const timestamp = this.safeInteger (transaction, 'time'); const currencyId = this.safeString (transaction, 'asset'); const code = this.safeCurrencyCode (currencyId, currency); const status = this.parseTransactionStatus (this.safeString (transaction, 'status')); const feeCost = this.safeNumber (transaction, 'commission'); return { 'info': transaction, 'id': id, 'currency': code, 'amount': amount, 'address': address, 'addressTo': address, 'addressFrom': undefined, 'tag': tag, 'tagTo': tag, 'tagFrom': undefined, 'status': status, 'type': type, 'updated': undefined, 'txid': txid, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'fee': { 'currency': code, 'cost': feeCost, }, }; } async fetchPositions (symbols = undefined, params = {}) { await this.loadMarkets (); await this.loadAccounts (); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, }; return await this.v2PrivateAccountGroupGetFuturesPosition (this.extend (request, params)); } parseFundingRate (fundingRate, market = undefined) { // // { // "time": 1640061364830, // "symbol": "EOS-PERP", // "markPrice": "3.353854865", // "indexPrice": "3.3542", // "openInterest": "14242", // "fundingRate": "-0.000073026", // "nextFundingTime": 1640073600000 // } // const marketId = this.safeString (fundingRate, 'symbol'); const symbol = this.safeSymbol (marketId, market); const currentTime = this.safeInteger (fundingRate, 'time'); const nextFundingRate = this.safeNumber (fundingRate, 'fundingRate'); const nextFundingRateTimestamp = this.safeInteger (fundingRate, 'nextFundingTime'); const previousFundingTimestamp = undefined; return { 'info': fundingRate, 'symbol': symbol, 'markPrice': this.safeNumber (fundingRate, 'markPrice'), 'indexPrice': this.safeNumber (fundingRate, 'indexPrice'), 'interestRate': this.parseNumber ('0'), 'estimatedSettlePrice': undefined, 'timestamp': currentTime, 'datetime': this.iso8601 (currentTime), 'previousFundingRate': undefined, 'nextFundingRate': nextFundingRate, 'previousFundingTimestamp': previousFundingTimestamp, 'nextFundingTimestamp': nextFundingRateTimestamp, 'previousFundingDatetime': this.iso8601 (previousFundingTimestamp), 'nextFundingDatetime': this.iso8601 (nextFundingRateTimestamp), }; } async fetchFundingRates (symbols, params = {}) { await this.loadMarkets (); const response = await this.v2PublicGetFuturesPricingData (params); // // { // "code": 0, // "data": { // "contracts": [ // { // "time": 1640061364830, // "symbol": "EOS-PERP", // "markPrice": "3.353854865", // "indexPrice": "3.3542", // "openInterest": "14242", // "fundingRate": "-0.000073026", // "nextFundingTime": 1640073600000 // }, // ], // "collaterals": [ // { // "asset": "USDTR", // "referencePrice": "1" // }, // ] // } // } // const data = this.safeValue (response, 'data', {}); const contracts = this.safeValue (data, 'contracts', []); const result = this.parseFundingRates (contracts); return this.filterByArray (result, 'symbol', symbols); } async setLeverage (leverage, symbol = undefined, params = {}) { if (symbol === undefined) { throw new ArgumentsRequired (this.id + ' setLeverage() requires a symbol argument'); } if ((leverage < 1) || (leverage > 100)) { throw new BadRequest (this.id + ' leverage should be between 1 and 100'); } await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); if (market['type'] !== 'future') { throw new BadSymbol (this.id + ' setLeverage() supports futures contracts only'); } const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, 'symbol': market['id'], 'leverage': leverage, }; return await this.v2PrivateAccountGroupPostFuturesLeverage (this.extend (request, params)); } async setMarginMode (marginType, symbol = undefined, params = {}) { if (marginType !== 'isolated' && marginType !== 'crossed') { throw new BadRequest (this.id + ' setMarginMode() marginType argument should be isolated or crossed'); } await this.loadMarkets (); await this.loadAccounts (); const market = this.market (symbol); const account = this.safeValue (this.accounts, 0, {}); const accountGroup = this.safeString (account, 'id'); const request = { 'account-group': accountGroup, 'symbol': market['id'], 'marginType': marginType, }; if (market['type'] !== 'future') { throw new BadSymbol (this.id + ' setMarginMode() supports futures contracts only'); } return await this.v2PrivateAccountGroupPostFuturesMarginType (this.extend (request, params)); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { const version = api[0]; const access = api[1]; const type = this.safeString (api, 2); let url = ''; let query = params; const accountCategory = (type === 'accountCategory'); if (accountCategory || (type === 'accountGroup')) { url += this.implodeParams ('/{account-group}', params); query = this.omit (params, 'account-group'); } let request = this.implodeParams (path, query); url += '/api/pro/'; if (version === 'v2') { request = version + '/' + request; } else { url += version; } if (accountCategory) { url += this.implodeParams ('/{account-category}', query); query = this.omit (query, 'account-category'); } url += '/' + request; if ((version === 'v1') && (request === 'cash/balance') || (request === 'margin/balance')) { request = 'balance'; } if (request.indexOf ('subuser') >= 0) { const parts = request.split ('/'); request = parts[2]; } query = this.omit (query, this.extractParams (path)); if (access === 'public') { if (Object.keys (query).length) { url += '?' + this.urlencode (query); } } else { this.checkRequiredCredentials (); const timestamp = this.milliseconds ().toString (); const payload = timestamp + '+' + request; const hmac = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'base64'); headers = { 'x-auth-key': this.apiKey, 'x-auth-timestamp': timestamp, 'x-auth-signature': hmac, }; if (method === 'GET') { if (Object.keys (query).length) { url += '?' + this.urlencode (query); } } else { headers['Content-Type'] = 'application/json'; body = this.json (query); } } url = this.urls['api'] + url; return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) { if (response === undefined) { return; // fallback to default error handler } // // {'code': 6010, 'message': 'Not enough balance.'} // {'code': 60060, 'message': 'The order is already filled or canceled.'} // {"code":2100,"message":"ApiKeyFailure"} // {"code":300001,"message":"Price is too low from market price.","reason":"INVALID_PRICE","accountId":"cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda","ac":"CASH","action":"place-order","status":"Err","info":{"symbol":"BTC/USDT"}} // const code = this.safeString (response, 'code'); const message = this.safeString (response, 'message'); const error = (code !== undefined) && (code !== '0'); if (error || (message !== undefined)) { const feedback = this.id + ' ' + body; this.throwExactlyMatchedException (this.exceptions['exact'], code, feedback); this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback); this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback); throw new ExchangeError (feedback); // unknown message } } };
Ascendex fetchClosedOrders() Swap Functionality https://ascendex.github.io/ascendex-futures-pro-api-v2/#list-current-history-orders
js/ascendex.js
Ascendex fetchClosedOrders() Swap Functionality
<ide><path>s/ascendex.js <ide> market = this.market (symbol); <ide> request['symbol'] = market['id']; <ide> } <del> const method = this.safeValue (options, 'method', 'v1PrivateAccountGroupGetOrderHist'); <add> let method = this.safeValue (options, 'method', 'v1PrivateAccountGroupGetOrderHist'); <add> if (market['swap']) { <add> method = 'v2PrivateAccountGroupGetFuturesOrderHistCurrent'; <add> } <ide> if (method === 'v1PrivateAccountGroupGetOrderHist') { <ide> if (accountCategory !== undefined) { <ide> request['category'] = accountCategory;
Java
apache-2.0
error: pathspec 'src/main/java/com/redhat/ceylon/compiler/js/DocVisitor.java' did not match any file(s) known to git
e7c739047e90c3eed2e269f13f989c0dda358c8f
1
ceylon/ceylon-js,ceylon/ceylon-js,ceylon/ceylon-js
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MemberOrTypeExpression; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; /** A Visitor that gathers ceylondoc info for each node's declaration. * * @author Enrique Zamudio */ public class DocVisitor extends Visitor { /** Here we store all the docs, as they are encountered */ private List<String> docs = new ArrayList<String>(); /** Here we store all the refs to the docs (index in the 'docs' list), keyed by location. */ private Map<String, Integer> locs = new HashMap<String, Integer>(); @Override public void visit(MemberOrTypeExpression that) { for (Annotation ann : that.getDeclaration().getAnnotations()) { if ("doc".equals(ann.getName()) && !ann.getPositionalArguments().isEmpty()) { String doc = ann.getPositionalArguments().get(0); if (doc.charAt(0) == '"' && doc.charAt(doc.length()-1) == '"') { doc = doc.substring(1, doc.length()-1); } int idx = docs.indexOf(doc); if (idx < 0) { idx = docs.size(); docs.add(doc); } locs.put(that.getLocation(), idx); } } super.visit(that); } public List<String> getDocs() { return docs; } public Map<String, Integer> getLocations() { return locs; } }
src/main/java/com/redhat/ceylon/compiler/js/DocVisitor.java
This visitor gathers all references to available ceylondoc descriptions. This is why the "doc" annotation kicks javadoc's comments' ass any day.
src/main/java/com/redhat/ceylon/compiler/js/DocVisitor.java
This visitor gathers all references to available ceylondoc descriptions. This is why the "doc" annotation kicks javadoc's comments' ass any day.
<ide><path>rc/main/java/com/redhat/ceylon/compiler/js/DocVisitor.java <add>package com.redhat.ceylon.compiler.js; <add> <add>import java.util.ArrayList; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add> <add>import com.redhat.ceylon.compiler.typechecker.model.Annotation; <add>import com.redhat.ceylon.compiler.typechecker.tree.Tree.MemberOrTypeExpression; <add>import com.redhat.ceylon.compiler.typechecker.tree.Visitor; <add> <add>/** A Visitor that gathers ceylondoc info for each node's declaration. <add> * <add> * @author Enrique Zamudio <add> */ <add>public class DocVisitor extends Visitor { <add> <add> /** Here we store all the docs, as they are encountered */ <add> private List<String> docs = new ArrayList<String>(); <add> /** Here we store all the refs to the docs (index in the 'docs' list), keyed by location. */ <add> private Map<String, Integer> locs = new HashMap<String, Integer>(); <add> <add> @Override <add> public void visit(MemberOrTypeExpression that) { <add> for (Annotation ann : that.getDeclaration().getAnnotations()) { <add> if ("doc".equals(ann.getName()) && !ann.getPositionalArguments().isEmpty()) { <add> String doc = ann.getPositionalArguments().get(0); <add> if (doc.charAt(0) == '"' && doc.charAt(doc.length()-1) == '"') { <add> doc = doc.substring(1, doc.length()-1); <add> } <add> int idx = docs.indexOf(doc); <add> if (idx < 0) { <add> idx = docs.size(); <add> docs.add(doc); <add> } <add> locs.put(that.getLocation(), idx); <add> } <add> } <add> super.visit(that); <add> } <add> <add> public List<String> getDocs() { <add> return docs; <add> } <add> public Map<String, Integer> getLocations() { <add> return locs; <add> } <add> <add>}
JavaScript
mit
e1f89ccac12cc15d6d636d3360fba43d3fb13af0
0
sibartlett/jquery-ui-lookup
๏ปฟ/*! * jQuery UI Lookup 0.1.0 * * Copyright 2011, Simon Bartlett * Dual licensed under the MIT or GPL Version 2 licenses. * * https://github.com/SimonBartlett/jquery-ui-lookup */ (function ($) { $.lookup = { createBodyTemplate: function (name) { return '<div id="' + name + '" style="display:none;">' + '<div style="height: 30px;"><label style="display: inline;">Search: <input type="text" class="ui-widget-content ui-corner-all" style="padding: 2px;" /></label></div>' + '<div class="ui-lookup-results"></div>' + '</div>'; } }; $.widget("ui.lookup", { version: "0.1.0", options: { cancelText: 'Cancel', delay: 300, disabled: null, height: 400, minLength: 1, modal: 400, name: null, okText: 'Ok', select: null, source: null, title: 'Search', value: null, width: 600 }, _create: function () { if (this.options.name === null) { this.options.name = 'dialog_' + Math.floor(Math.random() * 10001).toString(); } var $this = this, dialogBody = $.lookup.createBodyTemplate($this.options.name), buttons = { }; buttons[$this.options.okText] = function () { $this.options.value = $this.options._value; if ($this.options.select) { $this.options.select($this.options.value); } $(this).dialog("close"); }; buttons[$this.options.cancelText] = function () { $(this).dialog("close"); }; $this._dialog = $(dialogBody).dialog({ autoOpen: false, height: $this.options.height, modal: true, resizable: false, title: $this.options.title, width: $this.options.width, buttons: buttons, open: function (dialogEvent, dialogUi) { $this._autocomplete = $('input', $this._dialog) .autocomplete({ appendTo: '#' + $this.options.name + ' .ui-lookup-results', delay: $this.options.delay, minLength: $this.options.minLength, source: $this.options.source, open: function (event, ui) { $('.ui-lookup-results ul', $this._dialog).css({ top: '', left: '', width: $('.ui-lookup-results', $this._dialog).width(), height: $this._dialog.height() - $('div:first', $this._dialog).height(), overflowY: 'auto', overflowX: 'hidden' }); }, close: function (event, ui) { setTimeout(function () { $('#' + $this.options.name + ' .ui-lookup-results ul').show(); }, 10); return false; }, select: function (event, ui) { var selected = $('#ui-active-menuitem'); setTimeout(function () { $this._dialog.find('.ui-lookup-results ul li a').removeClass('ui-state-active'); selected.addClass('ui-state-active'); }, 10); $this.options._value = ui.item; return false; }, focus: function (event, ui) { var focused = $('#ui-active-menuitem'); if (!focused.hasClass('ui-state-active')) { focused.addClass('ui-state-hover'); } return false; } }) .focus(); } }); $this.element.bind('focus', function () { if (!$this.options.disabled) { $this._dialog.dialog('open'); } }); }, value: function () { return this.options.value; }, destroy: function () { this._autocomplete.autocomplete('destroy'); this._dialog.dialog('destroy'); $.Widget.prototype.destroy.apply(this, arguments); }, disable: function () { this.options.disabled = true; }, enable: function () { this.options.disabled = false; } }); }(jQuery));
jquery.ui.lookup.js
๏ปฟ/*! * jQuery UI Lookup 0.1.0 * * Copyright 2011, Simon Bartlett * Dual licensed under the MIT or GPL Version 2 licenses. * * https://github.com/SimonBartlett/jquery-ui-lookup */ (function ($) { $.lookup = { createBodyTemplate: function (name) { return '<div id="' + name + '" style="display:none;">' + '<div style="height: 30px;"><label style="display: inline;">Search: <input type="text" class="ui-widget-content ui-corner-all" style="padding: 2px;" /></label></div>' + '<div class="ui-lookup-results"></div>' + '</div>'; } }; $.widget("ui.lookup", { version: "0.1.0", options: { cancelText: 'Cancel', delay: 300, disabled: null, height: 400, minLength: 1, modal: 400, name: null, okText: 'Ok', select: null, source: null, title: 'Search', value: null, width: 600 }, _create: function () { if (this.options.name === null) { this.options.name = 'dialog_' + Math.floor(Math.random() * 10001).toString(); } var $this = this, dialogBody = $.lookup.createBodyTemplate($this.options.name), buttons = { }; buttons[$this.options.okText] = function () { $this.options.value = $this.options._value; if ($this.options.select) { $this.options.select($this.options.value); } $(this).dialog("close"); }; buttons[$this.options.cancelText] = function () { $(this).dialog("close"); }; $this._dialog = $(dialogBody).dialog({ autoOpen: false, height: $this.options.height, modal: true, resizable: false, title: $this.options.title, width: $this.options.width, buttons: buttons, open: function (dialogEvent, dialogUi) { $this._autocomplete = $('input', $this._dialog) .autocomplete({ appendTo: '#' + $this.options.name + ' .ui-lookup-results', delay: $this.options.delay, minLength: $this.options.minLength, source: $this.options.source, open: function (event, ui) { $('.ui-lookup-results ul', $this._dialog).css({ top: '', left: '', width: $('.ui-lookup-results', $this._dialog).width(), height: $this._dialog.height() - $('div:first', $this._dialog).height(), overflowY: 'auto', overflowX: 'hidden' }); }, close: function (event, ui) { setTimeout(function () { $('#' + $this.options.name + ' .ui-lookup-results ul').show(); }, 10); return false; }, select: function (event, ui) { var selected = $('#ui-active-menuitem'); setTimeout(function () { $this._dialog.find('.ui-lookup-results ul li a').removeClass('ui-state-active'); selected.addClass('ui-state-active'); }, 10); $this.options._value = ui.item; return false; }, focus: function (event, ui) { var focused = $('#ui-active-menuitem'); if (!focused.hasClass('ui-state-active')) { focused.addClass('ui-state-hover'); } return false; } }) .focus(); } }); $this.element.bind('focus', function () { if (!$this.options.disabled) { $this._dialog.dialog('open'); } }); }, value: function () { return this.options.value; }, destroy: function () { this._autocomplete.autocomplete('destroy'); this._dialog.dialog('destroy'); $.Widget.prototype.destroy.apply(this, arguments); }, disable: function () { this.options.disabled = true; }, enable: function () { this.options.disabled = false; } }); }(jQuery));
Fixing whitespace.
jquery.ui.lookup.js
Fixing whitespace.
<ide><path>query.ui.lookup.js <ide> <ide> (function ($) { <ide> <del> $.lookup = { <add> $.lookup = { <ide> <del> createBodyTemplate: function (name) { <del> return '<div id="' + name + '" style="display:none;">' + <del> '<div style="height: 30px;"><label style="display: inline;">Search: <input type="text" class="ui-widget-content ui-corner-all" style="padding: 2px;" /></label></div>' + <del> '<div class="ui-lookup-results"></div>' + <del> '</div>'; <del> } <add> createBodyTemplate: function (name) { <add> return '<div id="' + name + '" style="display:none;">' + <add> '<div style="height: 30px;"><label style="display: inline;">Search: <input type="text" class="ui-widget-content ui-corner-all" style="padding: 2px;" /></label></div>' + <add> '<div class="ui-lookup-results"></div>' + <add> '</div>'; <add> } <ide> <del> }; <add> }; <ide> <del> $.widget("ui.lookup", { <del> version: "0.1.0", <del> options: { <del> cancelText: 'Cancel', <del> delay: 300, <del> disabled: null, <del> height: 400, <del> minLength: 1, <del> modal: 400, <del> name: null, <del> okText: 'Ok', <del> select: null, <del> source: null, <del> title: 'Search', <del> value: null, <del> width: 600 <del> }, <del> _create: function () { <add> $.widget("ui.lookup", { <add> version: "0.1.0", <add> options: { <add> cancelText: 'Cancel', <add> delay: 300, <add> disabled: null, <add> height: 400, <add> minLength: 1, <add> modal: 400, <add> name: null, <add> okText: 'Ok', <add> select: null, <add> source: null, <add> title: 'Search', <add> value: null, <add> width: 600 <add> }, <add> _create: function () { <ide> <del> if (this.options.name === null) { <del> this.options.name = 'dialog_' + Math.floor(Math.random() * 10001).toString(); <del> } <add> if (this.options.name === null) { <add> this.options.name = 'dialog_' + Math.floor(Math.random() * 10001).toString(); <add> } <ide> <del> var $this = this, <add> var $this = this, <ide> dialogBody = $.lookup.createBodyTemplate($this.options.name), <ide> buttons = { }; <ide> <del> buttons[$this.options.okText] = function () { <del> $this.options.value = $this.options._value; <del> if ($this.options.select) { <del> $this.options.select($this.options.value); <del> } <del> $(this).dialog("close"); <del> }; <del> buttons[$this.options.cancelText] = function () { <del> $(this).dialog("close"); <del> }; <add> buttons[$this.options.okText] = function () { <add> $this.options.value = $this.options._value; <add> if ($this.options.select) { <add> $this.options.select($this.options.value); <add> } <add> $(this).dialog("close"); <add> }; <add> buttons[$this.options.cancelText] = function () { <add> $(this).dialog("close"); <add> }; <ide> <del> $this._dialog = $(dialogBody).dialog({ <del> autoOpen: false, <del> height: $this.options.height, <del> modal: true, <del> resizable: false, <del> title: $this.options.title, <del> width: $this.options.width, <del> buttons: buttons, <del> open: function (dialogEvent, dialogUi) { <del> $this._autocomplete = $('input', $this._dialog) <add> $this._dialog = $(dialogBody).dialog({ <add> autoOpen: false, <add> height: $this.options.height, <add> modal: true, <add> resizable: false, <add> title: $this.options.title, <add> width: $this.options.width, <add> buttons: buttons, <add> open: function (dialogEvent, dialogUi) { <add> $this._autocomplete = $('input', $this._dialog) <ide> .autocomplete({ <ide> appendTo: '#' + $this.options.name + ' .ui-lookup-results', <ide> delay: $this.options.delay, <ide> } <ide> }) <ide> .focus(); <del> } <del> }); <add> } <add> }); <ide> <del> $this.element.bind('focus', function () { <del> if (!$this.options.disabled) { <del> $this._dialog.dialog('open'); <del> } <del> }); <del> }, <del> value: function () { <del> return this.options.value; <del> }, <del> destroy: function () { <add> $this.element.bind('focus', function () { <add> if (!$this.options.disabled) { <add> $this._dialog.dialog('open'); <add> } <add> }); <add> }, <add> value: function () { <add> return this.options.value; <add> }, <add> destroy: function () { <ide> this._autocomplete.autocomplete('destroy'); <del> this._dialog.dialog('destroy'); <del> $.Widget.prototype.destroy.apply(this, arguments); <del> }, <del> disable: function () { <del> this.options.disabled = true; <del> }, <del> enable: function () { <del> this.options.disabled = false; <del> } <del> }); <add> this._dialog.dialog('destroy'); <add> $.Widget.prototype.destroy.apply(this, arguments); <add> }, <add> disable: function () { <add> this.options.disabled = true; <add> }, <add> enable: function () { <add> this.options.disabled = false; <add> } <add> }); <ide> <ide> }(jQuery));
Java
apache-2.0
83540fe9500d91932545bcce87453ca835318dec
0
mark-friedman/web-appinventor,weihuali0509/web-appinventor,weihuali0509/web-appinventor,mark-friedman/web-appinventor,weihuali0509/web-appinventor,mark-friedman/web-appinventor,weihuali0509/web-appinventor,mark-friedman/web-appinventor,weihuali0509/web-appinventor,mark-friedman/web-appinventor
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.server.storage; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreInputStream; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.files.AppEngineFile; import com.google.appengine.api.files.FileService; import com.google.appengine.api.files.FileServiceFactory; import com.google.appengine.api.files.FileWriteChannel; import com.google.appengine.api.memcache.ErrorHandlers; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.appengine.api.memcache.Expiration; import com.google.appinventor.server.CrashReport; import com.google.appinventor.server.FileExporter; import com.google.appinventor.server.flags.Flag; import com.google.appinventor.server.storage.StoredData.CorruptionRecord; import com.google.appinventor.server.storage.StoredData.FeedbackData; import com.google.appinventor.server.storage.StoredData.FileData; import com.google.appinventor.server.storage.StoredData.MotdData; import com.google.appinventor.server.storage.StoredData.NonceData; import com.google.appinventor.server.storage.StoredData.ProjectData; import com.google.appinventor.server.storage.StoredData.UserData; import com.google.appinventor.server.storage.StoredData.UserFileData; import com.google.appinventor.server.storage.StoredData.UserProjectData; import com.google.appinventor.server.storage.StoredData.RendezvousData; import com.google.appinventor.server.storage.StoredData.WhiteListData; import com.google.appinventor.shared.rpc.BlocksTruncatedException; import com.google.appinventor.shared.rpc.Motd; import com.google.appinventor.shared.rpc.Nonce; import com.google.appinventor.shared.rpc.project.*; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode; import com.google.appinventor.shared.rpc.user.User; import com.google.appinventor.shared.storage.StorageUtil; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.io.ByteSource; import com.google.common.io.ByteStreams; import com.googlecode.objectify.Key; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.Query; import java.io.ByteArrayOutputStream; // GCS imports import com.google.appengine.tools.cloudstorage.GcsFileOptions; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsInputChannel; import com.google.appengine.tools.cloudstorage.GcsOutputChannel; import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import java.util.Date; import javax.annotation.Nullable; /** * Implements the StorageIo interface using Objectify as the underlying data * store. * * @author [email protected] (Sharon Perl) * */ public class ObjectifyStorageIo implements StorageIo { static final Flag<Boolean> requireTos = Flag.createFlag("require.tos", false); private static final Logger LOG = Logger.getLogger(ObjectifyStorageIo.class.getName()); private static final String DEFAULT_ENCODING = "UTF-8"; private static final long MOTD_ID = 1; // TODO(user): need a way to modify this. Also, what is really a good value? private static final int MAX_JOB_RETRIES = 10; private final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); private final GcsService gcsService; private final String GCS_BUCKET_NAME = Flag.createFlag("gcs.bucket", "").get(); private static final long TWENTYFOURHOURS = 24*3600*1000; // 24 hours in milliseconds private final boolean useGcs = Flag.createFlag("use.gcs", false).get(); // Use this class to define the work of a job that can be // retried. The "datastore" argument to run() is the Objectify // object for this job (created with // ObjectifyService.beginTransaction() if a transaction is used or // ObjectifyService.begin if no transaction is used). Note that all // operations on "datastore" should be for objects in the same // entity group if a transaction is used. // Note: 1/25/2015: Added code to make the use of a transaction // optional. In general we only need to use a // transaction where there work we would need to // rollback if an operation on the datastore // failed. We have not necessarily converted all // cases yet (out of a sense of caution). However // we have removed transaction in places where // doing so permits Objectify to use its global // cache (memcache) in a way that helps // performance. @VisibleForTesting abstract class JobRetryHelper { public abstract void run(Objectify datastore) throws ObjectifyException; /* * Called before retrying the job. Note that the underlying datastore * still has the transaction active, so restrictions about operations * over multiple entity groups still apply. */ public void onNonFatalError() { // Default is to do nothing } } // Create a final object of this class to hold a modifiable result value that // can be used in a method of an inner class. private class Result<T> { T t; } private FileService fileService; static { // Register the data object classes stored in the database ObjectifyService.register(UserData.class); ObjectifyService.register(ProjectData.class); ObjectifyService.register(UserProjectData.class); ObjectifyService.register(FileData.class); ObjectifyService.register(UserFileData.class); ObjectifyService.register(MotdData.class); ObjectifyService.register(RendezvousData.class); ObjectifyService.register(WhiteListData.class); ObjectifyService.register(FeedbackData.class); ObjectifyService.register(NonceData.class); ObjectifyService.register(CorruptionRecord.class); } ObjectifyStorageIo() { fileService = FileServiceFactory.getFileService(); RetryParams retryParams = new RetryParams.Builder().initialRetryDelayMillis(100) .retryMaxAttempts(10) .totalRetryPeriodMillis(10000).build(); LOG.log(Level.INFO, "RetryParams: getInitialRetryDelayMillis() = " + retryParams.getInitialRetryDelayMillis()); LOG.log(Level.INFO, "RetryParams: getRequestTimeoutMillis() = " + retryParams.getRequestTimeoutMillis()); LOG.log(Level.INFO, "RetryParams: getRetryDelayBackoffFactor() = " + retryParams.getRetryDelayBackoffFactor()); LOG.log(Level.INFO, "RetryParams: getRetryMaxAttempts() = " + retryParams.getRetryMaxAttempts()); LOG.log(Level.INFO, "RetryParams: getRetryMinAttempts() = " + retryParams.getRetryMinAttempts()); LOG.log(Level.INFO, "RetryParams: getTotalRetryPeriodMillis() = " + retryParams.getTotalRetryPeriodMillis()); gcsService = GcsServiceFactory.createGcsService(retryParams); memcache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); initMotd(); } // for testing ObjectifyStorageIo(FileService fileService) { this.fileService = fileService; RetryParams retryParams = new RetryParams.Builder().initialRetryDelayMillis(100) .retryMaxAttempts(10) .totalRetryPeriodMillis(10000).build(); gcsService = GcsServiceFactory.createGcsService(retryParams); initMotd(); } @Override public User getUser(String userId) { return getUser(userId, null); } /* * Note that the User returned by this method will always have isAdmin set to * false. We leave it to the caller to determine whether the user has admin * priviledges. */ @Override public User getUser(final String userId, final String email) { String cachekey = User.usercachekey + "|" + userId; User tuser = (User) memcache.get(cachekey); if (tuser != null && tuser.getUserTosAccepted() && ((email == null) || (tuser.getUserEmail().equals(email)))) { if (tuser.getUserName()==null) { setUserName(userId,tuser.getDefaultName()); tuser.setUserName(tuser.getDefaultName()); } return tuser; } else { // If not in memcache, or tos // not yet accepted, fetch from datastore tuser = new User(userId, email, null, null, false, false, 0, null); } final User user = tuser; try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData == null) { userData = createUser(datastore, userId, email); } else if (email != null && !email.equals(userData.email)) { userData.email = email; datastore.put(userData); } user.setUserEmail(userData.email); user.setUserName(userData.name); user.setUserLink(userData.link); user.setType(userData.type); user.setUserTosAccepted(userData.tosAccepted || !requireTos.get()); user.setSessionId(userData.sessionid); } }, false); // Transaction not needed. If we fail there is nothing to rollback } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute // The choice of one minute here is arbitrary. getUser() is called on every authenticated // RPC call to the system (out of OdeAuthFilter), so using memcache will save a significant // number of calls to the datastore. If someone is idle for more then a minute, it isn't // unreasonable to hit the datastore again. By pruning memcache ourselves, we have a // bit more control (maybe) of how things are flushed from memcache. Otherwise we are // at the whim of whatever algorithm App Engine employs now or in the future. return user; } private UserData createUser(Objectify datastore, String userId, String email) { UserData userData = new UserData(); userData.id = userId; userData.tosAccepted = false; userData.settings = ""; userData.email = email == null ? "" : email; userData.name = User.getDefaultName(email); userData.type = User.USER; userData.link = ""; datastore.put(userData); return userData; } @Override public void setTosAccepted(final String userId) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.tosAccepted = true; datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserEmail(final String userId, final String email) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.email = email; datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserName(final String userId, final String name) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.name = name; datastore.put(userData); } // we need to change the memcache version of user User user = new User(userData.id,userData.email,name, userData.link, userData.tosAccepted, false, userData.type, userData.sessionid); String cachekey = User.usercachekey + "|" + userId; memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserLink(final String userId, final String link) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.link = link; datastore.put(userData); } // we need to change the memcache version of user User user = new User(userData.id,userData.email,userData.name,link,userData.tosAccepted, false, userData.type, userData.sessionid); String cachekey = User.usercachekey + "|" + userId; memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserSessionId(final String userId, final String sessionId) { String cachekey = User.usercachekey + "|" + userId; try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.sessionid = sessionId; datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } memcache.delete(cachekey); // Flush cached copy because it changed } @Override public String loadSettings(final String userId) { final Result<String> settings = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(UserData.class, userId); if (userData != null) { settings.t = userData.settings; } else { settings.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return settings.t; } @Override public String getUserName(final String userId) { final Result<String> name = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(UserData.class, userId); if (userData != null) { name.t = userData.name; } else { name.t = "unknown"; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return name.t; } @Override public String getUserLink(final String userId) { final Result<String> link = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(UserData.class, userId); if (userData != null) { link.t = userData.link; } else { link.t = "unknown"; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return link.t; } @Override public void storeSettings(final String userId, final String settings) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.settings = settings; userData.visited = new Date(); // Indicate that this person was active now datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public long createProject(final String userId, final Project project, final String projectSettings) { final Result<Long> projectId = new Result<Long>(); final List<String> blobsToDelete = new ArrayList<String>(); final List<FileData> addedFiles = new ArrayList<FileData>(); try { // first job is on the project entity, creating the ProjectData object // and the associated files. runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) throws ObjectifyException { long date = System.currentTimeMillis(); ProjectData pd = new ProjectData(); pd.id = null; // let Objectify auto-generate the project id pd.dateCreated = date; pd.dateModified = date; pd.history = project.getProjectHistory(); pd.name = project.getProjectName(); pd.settings = projectSettings; pd.type = project.getProjectType(); pd.galleryId = UserProject.NOTPUBLISHED; pd.attributionId = UserProject.FROMSCRATCH; datastore.put(pd); // put the project in the db so that it gets assigned an id assert pd.id != null; projectId.t = pd.id; // After the job commits projectId.t should end up with the last value // we've gotten for pd.id (i.e. the one that committed if there // was no error). // Note that while we cannot expect to read back a value that we've // written in this job, reading the assigned id from pd should work. Key<ProjectData> projectKey = projectKey(projectId.t); for (TextFile file : project.getSourceFiles()) { try { addedFiles.add(createRawFile(projectKey, FileData.RoleEnum.SOURCE, file.getFileName(), file.getContent().getBytes(DEFAULT_ENCODING))); } catch (BlobWriteException e) { rememberBlobsToDelete(); // Note that this makes the BlobWriteException fatal. The job will // not be retried if we get this exception. throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } catch (IOException e) { // GCS throws this throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } } for (RawFile file : project.getRawSourceFiles()) { try { addedFiles.add(createRawFile(projectKey, FileData.RoleEnum.SOURCE, file.getFileName(), file.getContent())); } catch (BlobWriteException e) { rememberBlobsToDelete(); // Note that this makes the BlobWriteException fatal. The job will // not be retried if we get this exception. throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } } datastore.put(addedFiles); // batch put } @Override public void onNonFatalError() { rememberBlobsToDelete(); } private void rememberBlobsToDelete() { for (FileData addedFile : addedFiles) { if (addedFile.isBlob && addedFile.blobstorePath != null) { blobsToDelete.add(addedFile.blobstorePath); } } // clear addedFiles in case we end up here more than once addedFiles.clear(); } }, true); // second job is on the user entity runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserProjectData upd = new UserProjectData(); upd.projectId = projectId.t; upd.settings = projectSettings; upd.state = UserProjectData.StateEnum.OPEN; upd.userKey = userKey(userId); datastore.put(upd); } }, true); } catch (ObjectifyException e) { for (FileData addedFile : addedFiles) { if (addedFile.isBlob && addedFile.blobstorePath != null) { blobsToDelete.add(addedFile.blobstorePath); } } // clear addedFiles in case we end up here more than once addedFiles.clear(); throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId.t), e); } finally { // Need to delete any orphaned blobs outside of the transaction to avoid multiple entity // group errors. The lookup of the blob key seems to be the thing that // triggers the error. for (String blobToDelete: blobsToDelete) { deleteBlobstoreFile(blobToDelete); } } return projectId.t; } /* * Creates and returns a new FileData object with the specified fields. * Does not check for the existence of the object and does not update * the database. */ private FileData createRawFile(Key<ProjectData> projectKey, FileData.RoleEnum role, String fileName, byte[] content) throws BlobWriteException, ObjectifyException, IOException { FileData file = new FileData(); file.fileName = fileName; file.projectKey = projectKey; file.role = role; if (useGCSforFile(fileName, content.length)) { file.isGCS = true; file.gcsName = makeGCSfileName(fileName, projectKey.getId()); GcsOutputChannel outputChannel = gcsService.createOrReplace(new GcsFilename(GCS_BUCKET_NAME, file.gcsName), GcsFileOptions.getDefaultInstance()); outputChannel.write(ByteBuffer.wrap(content)); outputChannel.close(); } else if (useBlobstoreForFile(fileName, content.length)) { file.isBlob = true; file.blobstorePath = uploadToBlobstore(content, makeBlobName(projectKey.getId(), fileName)); } else { file.content = content; } return file; } @Override public void deleteProject(final String userId, final long projectId) { // blobs associated with the project final List<String> blobPaths = new ArrayList<String>(); final List<String> gcsPaths = new ArrayList<String>(); try { // first job deletes the UserProjectData in the user's entity group runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { // delete the UserProjectData object Key<UserData> userKey = userKey(userId); datastore.delete(userProjectKey(userKey, projectId)); // delete any FileData objects associated with this project } }, true); // second job deletes the project files and ProjectData in the project's // entity group runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<ProjectData> projectKey = projectKey(projectId); Query<FileData> fdq = datastore.query(FileData.class).ancestor(projectKey); for (FileData fd: fdq) { if (fd.isGCS) { gcsPaths.add(fd.gcsName); } else if (fd.isBlob) { blobPaths.add(fd.blobstorePath); } } datastore.delete(fdq); // finally, delete the ProjectData object datastore.delete(projectKey); } }, true); // have to delete the blobs outside of the user and project jobs for (String blobPath: blobPaths) { deleteBlobstoreFile(blobPath); } // Now delete the gcs files for (String gcsName: gcsPaths) { try { gcsService.delete(new GcsFilename(GCS_BUCKET_NAME, gcsName)); } catch (IOException e) { LOG.log(Level.WARNING, "Unable to delete " + gcsName + " from GCS while deleting project", e); } } } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } } @Override public void setProjectGalleryId(final String userId, final long projectId,final long galleryId) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData projectData = datastore.find(projectKey(projectId)); if (projectData != null) { projectData.galleryId = galleryId; datastore.put(projectData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setProjectAttributionId(final String userId, final long projectId,final long attributionId) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData projectData = datastore.find(projectKey(projectId)); if (projectData != null) { projectData.attributionId = attributionId; datastore.put(projectData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null,"error in setProjectAttributionId", e); } } @Override public List<Long> getProjects(final String userId) { final List<Long> projects = new ArrayList<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserData> userKey = userKey(userId); for (UserProjectData upd : datastore.query(UserProjectData.class).ancestor(userKey)) { projects.add(upd.projectId); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return projects; } @Override public String loadProjectSettings(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<String> settings = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { settings.t = pd.settings; } else { settings.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return settings.t; } @Override public void storeProjectSettings(final String userId, final long projectId, final String settings) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { pd.settings = settings; datastore.put(pd); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } } @Override public String getProjectType(final String userId, final long projectId) { // final Result<String> projectType = new Result<String>(); // try { // runJobWithRetries(new JobRetryHelper() { // @Override // public void run(Objectify datastore) { // ProjectData pd = datastore.find(projectKey(projectId)); // if (pd != null) { // projectType.t = pd.type; // } else { // projectType.t = ""; // } // } // }); // } catch (ObjectifyException e) { // throw CrashReport.createAndLogError(LOG, null, // collectUserProjectErrorInfo(userId, projectId), e); // } // We only have one project type, no need to ask about it return YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE; } @Override public UserProject getUserProject(final String userId, final long projectId) { final Result<ProjectData> projectData = new Result<ProjectData>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { projectData.t = pd; } else { projectData.t = null; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } if (projectData == null) { return null; } else { return new UserProject(projectId, projectData.t.name, projectData.t.type, projectData.t.dateCreated, projectData.t.dateModified, projectData.t.galleryId, projectData.t.attributionId); } } @Override public String getProjectName(final String userId, final long projectId) { final Result<String> projectName = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { projectName.t = pd.name; } else { projectName.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return projectName.t; } @Override public long getProjectDateModified(final String userId, final long projectId) { final Result<Long> modDate = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { modDate.t = pd.dateModified; } else { modDate.t = Long.valueOf(0); } } }, false); // Transaction not needed, and we want the caching we get if we don't // use them. } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return modDate.t; } @Override public String getProjectHistory(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<String> projectHistory = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { projectHistory.t = pd.history; } else { projectHistory.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return projectHistory.t; } // JIS XXX @Override public long getProjectDateCreated(final String userId, final long projectId) { final Result<Long> dateCreated = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { dateCreated.t = pd.dateCreated; } else { dateCreated.t = Long.valueOf(0); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return dateCreated.t; } @Override public long getProjectGalleryId(String userId, final long projectId) { final Result<Long> galleryId = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { galleryId.t = pd.galleryId; } else { galleryId.t = Long.valueOf(0); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null,"error in getProjectGalleryId", e); } return galleryId.t; } @Override public long getProjectAttributionId(final long projectId) { final Result<Long> attributionId = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { attributionId.t = pd.attributionId; } else { attributionId.t = Long.valueOf(UserProject.FROMSCRATCH); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, "error in getProjectAttributionId", e); } return attributionId.t; } @Override public void addFilesToUser(final String userId, final String... fileNames) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserData> userKey = userKey(userId); List<UserFileData> addedFiles = new ArrayList<UserFileData>(); for (String fileName : fileNames) { UserFileData ufd = createUserFile(datastore, userKey, fileName); if (ufd != null) { addedFiles.add(ufd); } } datastore.put(addedFiles); // batch put } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileNames[0]), e); } } /* * Creates a UserFileData object for the given userKey and fileName, if it * doesn't already exist. Returns the new UserFileData object, or null if * already existed. This method does not add the UserFileData object to the * datastore. */ private UserFileData createUserFile(Objectify datastore, Key<UserData> userKey, String fileName) { UserFileData ufd = datastore.find(userFileKey(userKey, fileName)); if (ufd == null) { ufd = new UserFileData(); ufd.fileName = fileName; ufd.userKey = userKey; return ufd; } return null; } @Override public List<String> getUserFiles(final String userId) { final List<String> fileList = new ArrayList<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserData> userKey = userKey(userId); for (UserFileData ufd : datastore.query(UserFileData.class).ancestor(userKey)) { fileList.add(ufd.fileName); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return fileList; } @Override public void uploadUserFile(final String userId, final String fileName, final String content, final String encoding) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException e) { // Note: this RuntimeException should propagate up out of runJobWithRetries throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding, " + collectUserErrorInfo(userId, fileName), e); } addUserFileContents(datastore, userId, fileName, bytes); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } } @Override public void uploadRawUserFile(final String userId, final String fileName, final byte[] content) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { addUserFileContents(datastore, userId, fileName, content); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } } /* * We expect the UserFileData object for the given userId and fileName to * already exist in the datastore. Find the object and update its contents. */ private void addUserFileContents(Objectify datastore, String userId, String fileName, byte[] content) { UserFileData ufd = datastore.find(userFileKey(userKey(userId), fileName)); Preconditions.checkState(ufd != null); ufd.content = content; datastore.put(ufd); } @Override public String downloadUserFile(final String userId, final String fileName, final String encoding) { final Result<String> result = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { try { result.t = new String(downloadRawUserFile(userId, fileName), encoding); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding, " + collectUserErrorInfo(userId, fileName), e); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } return result.t; } @Override public byte[] downloadRawUserFile(final String userId, final String fileName) { final Result<byte[]> result = new Result<byte[]>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserFileData ufd = datastore.find(userFileKey(userKey(userId), fileName)); if (ufd != null) { result.t = ufd.content; } else { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), new FileNotFoundException(fileName)); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } return result.t; } @Override public void deleteUserFile(final String userId, final String fileName) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserFileData> ufdKey = userFileKey(userKey(userId), fileName); if (datastore.find(ufdKey) != null) { datastore.delete(ufdKey); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } } @Override public int getMaxJobSizeBytes() { // TODO(user): what should this mean? return 5 * 1024 * 1024; } @Override public void addSourceFilesToProject(final String userId, final long projectId, final boolean changeModDate, final String... fileNames) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { addFilesToProject(datastore, projectId, FileData.RoleEnum.SOURCE, changeModDate, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } @Override public void addOutputFilesToProject(final String userId, final long projectId, final String... fileNames) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { addFilesToProject(datastore, projectId, FileData.RoleEnum.TARGET, false, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } private void addFilesToProject(Objectify datastore, long projectId, FileData.RoleEnum role, boolean changeModDate, String... fileNames) { List<FileData> addedFiles = new ArrayList<FileData>(); Key<ProjectData> projectKey = projectKey(projectId); for (String fileName : fileNames) { FileData fd = createProjectFile(datastore, projectKey, role, fileName); if (fd != null) { addedFiles.add(fd); } } datastore.put(addedFiles); // batch put if (changeModDate) { updateProjectModDate(datastore, projectId); } } private FileData createProjectFile(Objectify datastore, Key<ProjectData> projectKey, FileData.RoleEnum role, String fileName) { FileData fd = datastore.find(projectFileKey(projectKey, fileName)); if (fd == null) { fd = new FileData(); fd.fileName = fileName; fd.projectKey = projectKey; fd.role = role; return fd; } else if (!fd.role.equals(role)) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(null, projectKey.getId(), fileName), new IllegalStateException("File role change is not supported")); } return null; } @Override public void removeSourceFilesFromProject(final String userId, final long projectId, final boolean changeModDate, final String... fileNames) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { removeFilesFromProject(datastore, projectId, FileData.RoleEnum.SOURCE, changeModDate, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } @Override public void removeOutputFilesFromProject(final String userId, final long projectId, final String... fileNames) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { removeFilesFromProject(datastore, projectId, FileData.RoleEnum.TARGET, false, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } private void removeFilesFromProject(Objectify datastore, long projectId, FileData.RoleEnum role, boolean changeModDate, String... fileNames) { Key<ProjectData> projectKey = projectKey(projectId); List<Key<FileData>> filesToRemove = new ArrayList<Key<FileData>>(); for (String fileName : fileNames) { Key<FileData> key = projectFileKey(projectKey, fileName); memcache.delete(key.getString()); // Remove it from memcache (if it is there) FileData fd = datastore.find(key); if (fd != null) { if (fd.role.equals(role)) { filesToRemove.add(projectFileKey(projectKey, fileName)); } else { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(null, projectId, fileName), new IllegalStateException("File role change is not supported")); } } } datastore.delete(filesToRemove); // batch delete if (changeModDate) { updateProjectModDate(datastore, projectId); } } /** * Exports project web files as a zip archive * @param userId a user Id (the request is made on behalf of this user) * @param projectId project ID * @param assetFileIds the asset file ids representing referenced files, e.g. image files. * @param zipName the name of the zip file * @param fatalError set true to cause missing GCS file to throw exception * @return project with the content as requested by params. * @throws IOException if files cannot be written */ @Override public ProjectWebOutputZip exportProjectWebOutputZip(final String userId, final long projectId, final ArrayList<String> assetFileIds, String zipName, final boolean fatalError, @Nullable RawFile importFile) throws IOException { final Result<Integer> fileCount = new Result<Integer>(); fileCount.t = 0; // We collect up all the file data for the project in a transaction but // then we read the data and write the zip file outside of the transaction // to avoid problems reading blobs in a transaction with the wrong // entity group. final List<FileData> fileData = new ArrayList<FileData>(); final Result<String> projectName = new Result<String>(); projectName.t = null; String fileName = null; ByteArrayOutputStream zipFile = new ByteArrayOutputStream(); final ZipOutputStream out = new ZipOutputStream(zipFile); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<ProjectData> projectKey = projectKey(projectId); boolean foundFiles = false; for (FileData fd : datastore.query(FileData.class).ancestor(projectKey)) { // Scan for files built for web output if (fd.role.equals(FileData.RoleEnum.TARGET) && fd.fileName.startsWith("build/web/")) { fileData.add(fd); foundFiles = true; } // Look for reference files for web output. e.g. images else { for (String assetFileID : assetFileIds) { if (fd.role.equals(FileData.RoleEnum.SOURCE) && fd.fileName.equalsIgnoreCase(assetFileID)) { fileData.add(fd); foundFiles = true; } } } } if (foundFiles) { ProjectData pd = datastore.find(projectKey); projectName.t = pd.name; } } },true); // Process the file contents outside of the job since we can't read // blobs in the job. for (FileData fd : fileData) { fileName = fd.fileName; byte[] data = null; if (fd.isBlob) { try { data = getBlobstoreBytes(fd.blobstorePath); } catch (BlobReadException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else if (fd.isGCS) { try { int count; boolean npfHappened = false; boolean recovered = false; for (count = 0; count < 5; count++) { GcsFilename gcsFileName = new GcsFilename(GCS_BUCKET_NAME, fd.gcsName); int bytesRead = 0; int fileSize = 0; ByteBuffer resultBuffer; try { fileSize = (int) gcsService.getMetadata(gcsFileName).getLength(); resultBuffer = ByteBuffer.allocate(fileSize); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0); try { while (bytesRead < fileSize) { bytesRead += readChannel.read(resultBuffer); if (bytesRead < fileSize) { LOG.log(Level.INFO, "readChannel: bytesRead = " + bytesRead + " fileSize = " + fileSize); } } recovered = true; data = resultBuffer.array(); break; // We got the data, break out of the loop! } finally { readChannel.close(); } } catch (NullPointerException e) { // This happens if the object in GCS is non-existent, which would happen // when people uploaded a zero length object. As of this change, we now // store zero length objects into GCS, but there are plenty of older objects // that are missing in GCS. LOG.log(Level.WARNING, "exportProjectFile: NPF recorded for " + fd.gcsName); npfHappened = true; resultBuffer = ByteBuffer.allocate(0); data = resultBuffer.array(); } } // report out on how things went above if (npfHappened) { // We lost at least once if (recovered) { LOG.log(Level.WARNING, "recovered from NPF in exportProjectFile filename = " + fd.gcsName + " count = " + count); } else { LOG.log(Level.WARNING, "FATAL NPF in exportProjectFile filename = " + fd.gcsName); if (fatalError) { throw new IOException("FATAL Error reading file from GCS filename = " + fd.gcsName); } } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else { data = fd.content; } if (data == null) { // This happens if file creation is interrupted data = new byte[0]; } if (fileName.startsWith("assets/")) { out.putNextEntry(new ZipEntry(fileName)); } else { out.putNextEntry(new ZipEntry(StorageUtil.basename(fileName))); } out.write(data, 0, data.length); out.closeEntry(); fileCount.t++; } if (importFile != null) { // Add the bootstrap library to the zip output. String bootstrapFileName = importFile.getFileName(); byte[] bootstrapData = importFile.getContent(); if (bootstrapData == null) { bootstrapData = new byte[0]; } else { out.putNextEntry(new ZipEntry(bootstrapFileName)); } out.write(bootstrapData, 0, bootstrapData.length); out.closeEntry(); fileCount.t++; } } catch (ObjectifyException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } catch (RuntimeException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } if (fileCount.t == 0) { // can't close out since will get a ZipException due to the lack of files throw new IllegalArgumentException("No files to download"); } out.close(); if (zipName == null) { zipName = projectName.t + ".zip"; } ProjectWebOutputZip projectWebOutputZip = new ProjectWebOutputZip(zipName, zipFile.toByteArray(), fileCount.t); projectWebOutputZip.setMetadata(projectName.t); return projectWebOutputZip; } @Override public List<String> getProjectSourceFiles(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<List<String>> result = new Result<List<String>>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { result.t = getProjectFiles(datastore, projectId, FileData.RoleEnum.SOURCE); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return result.t; } @Override public List<String> getProjectOutputFiles(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<List<String>> result = new Result<List<String>>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { result.t = getProjectFiles(datastore, projectId, FileData.RoleEnum.TARGET); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return result.t; } private List<String> getProjectFiles(Objectify datastore, long projectId, FileData.RoleEnum role) { Key<ProjectData> projectKey = projectKey(projectId); List<String> fileList = new ArrayList<String>(); for (FileData fd : datastore.query(FileData.class).ancestor(projectKey)) { if (fd.role.equals(role)) { fileList.add(fd.fileName); } } return fileList; } @Override public long uploadFile(final long projectId, final String fileName, final String userId, final String content, final String encoding) throws BlocksTruncatedException { try { return uploadRawFile(projectId, fileName, userId, false, content.getBytes(encoding)); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding," + collectProjectErrorInfo(null, projectId, fileName), e); } } @Override public long uploadFileForce(final long projectId, final String fileName, final String userId, final String content, final String encoding) { try { return uploadRawFileForce(projectId, fileName, userId, content.getBytes(encoding)); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding," + collectProjectErrorInfo(null, projectId, fileName), e); } } private long updateProjectModDate(Objectify datastore, long projectId) { long modDate = System.currentTimeMillis(); ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { // Only update the ProjectData dateModified if it is more then a minute // in the future. Do this to avoid unnecessary datastore puts if (modDate > (pd.dateModified + 1000*60)) { pd.dateModified = modDate; datastore.put(pd); } else { // return the (old) dateModified modDate = pd.dateModified; } return modDate; } else { throw CrashReport.createAndLogError(LOG, null, null, new IllegalArgumentException("project " + projectId + " doesn't exist")); } } @Override public long uploadRawFileForce(final long projectId, final String fileName, final String userId, final byte[] content) { try { return uploadRawFile(projectId, fileName, userId, true, content); } catch (BlocksTruncatedException e) { // Won't get here, exception isn't thrown when force is true return 0; } } @Override public long uploadRawFile(final long projectId, final String fileName, final String userId, final boolean force, final byte[] content) throws BlocksTruncatedException { final Result<Long> modTime = new Result<Long>(); final boolean useBlobstore = useBlobstoreForFile(fileName, content.length); final boolean useGCS = useGCSforFile(fileName, content.length); final Result<String> oldBlobstorePath = new Result<String>(); final boolean considerBackup = (useGcs?((fileName.contains("src/") && fileName.endsWith(".blk")) // AI1 Blocks Files || (fileName.contains("src/") && fileName.endsWith(".bky")) // Blockly files || (fileName.contains("src/") && fileName.endsWith(".scm"))) // Form Definitions :false); try { runJobWithRetries(new JobRetryHelper() { FileData fd; @Override public void run(Objectify datastore) throws ObjectifyException { Key<FileData> key = projectFileKey(projectKey(projectId), fileName); fd = (FileData) memcache.get(key.getString()); if (fd == null) { fd = datastore.find(projectFileKey(projectKey(projectId), fileName)); } else { LOG.log(Level.INFO, "Fetched " + key.getString() + " from memcache."); } // <Screen>.yail files are missing when user converts AI1 project to AI2 // instead of blowing up, just create a <Screen>.yail file if (fd == null && fileName.endsWith(".yail")){ fd = createProjectFile(datastore, projectKey(projectId), FileData.RoleEnum.SOURCE, fileName); } Preconditions.checkState(fd != null); if ((content.length < 125) && (fileName.endsWith(".bky"))) { // Likely this is an empty blocks workspace if (!force) { // force is true if we *really* want to save it! checkForBlocksTruncation(fd); // See if we had previous content and throw and exception if so } } if (fd.isBlob) { // mark the old blobstore blob for deletion oldBlobstorePath.t = fd.blobstorePath; } if (useGCS) { fd.isGCS = true; fd.gcsName = makeGCSfileName(fileName, projectId); try { GcsOutputChannel outputChannel = gcsService.createOrReplace(new GcsFilename(GCS_BUCKET_NAME, fd.gcsName), GcsFileOptions.getDefaultInstance()); outputChannel.write(ByteBuffer.wrap(content)); outputChannel.close(); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } // If the content was previously stored in the datastore, clear it out. fd.content = null; fd.isBlob = false; // in case we are converting from a blob fd.blobstorePath = null; } else if (useBlobstore) { try { fd.blobstorePath = uploadToBlobstore(content, makeBlobName(projectId, fileName)); } catch (BlobWriteException e) { // Note that this makes the BlobWriteException fatal. The job will // not be retried if we get this exception. throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } // If the content was previously stored in the datastore or GCS, clear it out. fd.isBlob = true; fd.isGCS = false; fd.gcsName = null; fd.content = null; } else { if (fd.isGCS) { // Was a GCS file, must have gotten smaller try { // and is now stored in the data store gcsService.delete(new GcsFilename(GCS_BUCKET_NAME, fd.gcsName)); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } fd.isGCS = false; fd.gcsName = null; } // Note, Don't have to do anything if the file was in the // Blobstore and shrank because the code above (3 lines // into the function) already handles removing the old // contents from the Blobstore. fd.isBlob = false; fd.blobstorePath = null; fd.content = content; } if (considerBackup) { if ((fd.lastBackup + TWENTYFOURHOURS) < System.currentTimeMillis()) { try { String gcsName = makeGCSfileName(fileName + "." + formattedTime() + ".backup", projectId); GcsOutputChannel outputChannel = gcsService.createOrReplace((new GcsFilename(GCS_BUCKET_NAME, gcsName)), GcsFileOptions.getDefaultInstance()); outputChannel.write(ByteBuffer.wrap(content)); outputChannel.close(); fd.lastBackup = System.currentTimeMillis(); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName + "(backup)"), e); } } } datastore.put(fd); memcache.put(key.getString(), fd); // Store the updated data in memcache modTime.t = updateProjectModDate(datastore, projectId); } @Override public void onNonFatalError() { if (fd != null && fd.blobstorePath != null) { oldBlobstorePath.t = fd.blobstorePath; } } }, useBlobstore); // Use transaction for blobstore, otherwise we don't need one // and without one the caching code comes into play. // It would have been convenient to delete the old blobstore file within the run() method // above but that caused an exception where the app engine datastore claimed to be doing // operations on multiple entity groups within the same transaction. Apparently the blobstore // operations are, at least partially, also datastore operations. if (oldBlobstorePath.t != null) { deleteBlobstoreFile(oldBlobstorePath.t); } } catch (ObjectifyException e) { if (e.getMessage().startsWith("Blocks")) { // Convert Exception throw new BlocksTruncatedException(); } throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } return modTime.t; } protected void deleteBlobstoreFile(String blobstorePath) { // It would be nice if there were an AppEngineFile.delete() method but alas there isn't, so we // have to get the BlobKey and delete via the BlobstoreService. BlobKey blobKey = null; try { AppEngineFile blobstoreFile = new AppEngineFile(blobstorePath); blobKey = fileService.getBlobKey(blobstoreFile); BlobstoreServiceFactory.getBlobstoreService().delete(blobKey); } catch (RuntimeException e) { // Log blob delete errors but don't make them fatal CrashReport.createAndLogError(LOG, null, "Error deleting blob with path " + blobstorePath + " and key " + blobKey, e); } } private String uploadToBlobstore(byte[] content, String name) throws BlobWriteException, ObjectifyException { // Create a new Blob file with generic mime-type "application/octet-stream" AppEngineFile blobstoreFile = null; try { blobstoreFile = fileService.createNewBlobFile("application/octet-stream", name); // Open a channel to write to it FileWriteChannel blobstoreWriteChannel = fileService.openWriteChannel(blobstoreFile, true); OutputStream blobstoreOutputStream = Channels.newOutputStream(blobstoreWriteChannel); ByteStreams.copy(ByteSource.wrap(content).openStream(), blobstoreOutputStream); blobstoreOutputStream.flush(); blobstoreOutputStream.close(); blobstoreWriteChannel.closeFinally(); } catch (IOException e) { throw new BlobWriteException(e, "Error writing blob with name " + name); } catch (Exception e) { throw new ObjectifyException(e); } return blobstoreFile.getFullPath(); } @VisibleForTesting boolean useBlobstoreForFile(String fileName, int length) { if (useGcs) return false; // Disable for now boolean shouldUse = fileName.contains("assets/") || fileName.endsWith(".apk"); if (shouldUse) return true; // Use GCS for package output and assets boolean mayUse = (fileName.contains("src/") && fileName.endsWith(".blk")) // AI1 Blocks Files || (fileName.contains("src/") && fileName.endsWith(".bky")); // Blockly files if (mayUse && length > 50000) // Only use Blobstore for larger blocks files return true; return false; } // Experimental -- Use the Google Cloud Store for a file @VisibleForTesting boolean useGCSforFile(String fileName, int length) { if (!useGcs) // Using legacy blob store solution return false; boolean shouldUse = fileName.contains("assets/") || fileName.endsWith(".apk"); if (shouldUse) return true; // Use GCS for package output and assets boolean mayUse = (fileName.contains("src/") && fileName.endsWith(".blk")) // AI1 Blocks Files || (fileName.contains("src/") && fileName.endsWith(".bky")); // Blockly files if (mayUse && length > 50000) // Only use GCS for larger blocks files return true; return false; } // Make a GCS file name String makeGCSfileName(String fileName, long projectId) { return (projectId + "/" + fileName); } @Override public long deleteFile(final String userId, final long projectId, final String fileName) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<Long> modTime = new Result<Long>(); final Result<String> oldBlobstorePath = new Result<String>(); final Result<String> oldgcsName = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName); memcache.delete(fileKey.getString()); FileData fileData = datastore.find(fileKey); if (fileData != null) { oldBlobstorePath.t = fileData.blobstorePath; if (fileData.isGCS) { oldgcsName.t = fileData.gcsName; } } datastore.delete(fileKey); modTime.t = updateProjectModDate(datastore, projectId); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } if (oldBlobstorePath.t != null) { deleteBlobstoreFile(oldBlobstorePath.t); } if (oldgcsName.t != null) { try { gcsService.delete(new GcsFilename(GCS_BUCKET_NAME, oldgcsName.t)); } catch (IOException e) { LOG.log(Level.WARNING, "Unable to delete " + oldgcsName + " from GCS.", e); } } return (modTime.t == null) ? 0 : modTime.t; } // TODO(user) - just use "UTF-8" (instead of having an encoding argument), // which will never cause UnsupportedEncodingException. (Here and in other // methods with the encoding arg. @Override public String downloadFile(final String userId, final long projectId, final String fileName, final String encoding) { try { return new String(downloadRawFile(userId, projectId, fileName), encoding); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding, " + collectProjectErrorInfo(userId, projectId, fileName), e); } } @Override public void recordCorruption(String userId, long projectId, String fileId, String message) { Objectify datastore = ObjectifyService.begin(); final CorruptionRecord data = new CorruptionRecord(); data.timestamp = new Date(); data.id = null; data.userId = userId; data.fileId = fileId; data.projectId = projectId; data.message = message; try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { datastore.put(data); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } @Override public byte[] downloadRawFile(final String userId, final long projectId, final String fileName) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<byte[]> result = new Result<byte[]>(); final Result<FileData> fd = new Result<FileData>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName); fd.t = (FileData) memcache.get(fileKey.getString()); if (fd.t == null) { fd.t = datastore.find(fileKey); } } }, false); // Transaction not needed } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } // read the blob/GCS File outside of the job FileData fileData = fd.t; if (fileData != null) { if (fileData.isGCS) { // It's in the Cloud Store try { int count; boolean npfHappened = false; boolean recovered = false; for (count = 0; count < 5; count++) { GcsFilename gcsFileName = new GcsFilename(GCS_BUCKET_NAME, fileData.gcsName); int bytesRead = 0; int fileSize = 0; ByteBuffer resultBuffer; try { fileSize = (int) gcsService.getMetadata(gcsFileName).getLength(); resultBuffer = ByteBuffer.allocate(fileSize); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0); try { while (bytesRead < fileSize) { bytesRead += readChannel.read(resultBuffer); if (bytesRead < fileSize) { LOG.log(Level.INFO, "readChannel: bytesRead = " + bytesRead + " fileSize = " + fileSize); } } recovered = true; result.t = resultBuffer.array(); break; // We got the data, break out of the loop! } finally { readChannel.close(); } } catch (NullPointerException e) { // This happens if the object in GCS is non-existent, which would happen // when people uploaded a zero length object. As of this change, we now // store zero length objects into GCS, but there are plenty of older objects // that are missing in GCS. LOG.log(Level.WARNING, "downloadrawfile: NPF recorded for " + fileData.gcsName); npfHappened = true; resultBuffer = ByteBuffer.allocate(0); result.t = resultBuffer.array(); } } // report out on how things went above if (npfHappened) { // We lost at least once if (recovered) { LOG.log(Level.WARNING, "recovered from NPF in downloadrawfile filename = " + fileData.gcsName + " count = " + count); } else { LOG.log(Level.WARNING, "FATAL NPF in downloadrawfile filename = " + fileData.gcsName); } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else if (fileData.isBlob) { try { result.t = getBlobstoreBytes(fileData.blobstorePath); } catch (BlobReadException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else { if (fileData.content == null) { result.t = new byte[0]; } else { result.t = fileData.content; } } } else { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), new FileNotFoundException("No data for " + fileName)); } return result.t; } // Note: this must be called outside of any transaction, since getBlobKey() // uses the current transaction and it will most likely have the wrong // entity group! private byte[] getBlobstoreBytes(String blobstorePath) throws BlobReadException { AppEngineFile blobstoreFile = new AppEngineFile(blobstorePath); BlobKey blobKey = fileService.getBlobKey(blobstoreFile); if (blobKey == null) { throw new BlobReadException("getBlobKey() returned null for " + blobstorePath); } try { InputStream blobInputStream = new BlobstoreInputStream(blobKey); return ByteStreams.toByteArray(blobInputStream); } catch (IOException e) { throw new BlobReadException(e, "Error trying to read blob from " + blobstorePath + ", blobkey = " + blobKey); } } /** * Exports project files as a zip archive * @param userId a user Id (the request is made on behalf of this user) * @param projectId project ID * @param includeProjectHistory whether or not to include the project history * @param includeAndroidKeystore whether or not to include the Android keystore * @param zipName the name of the zip file, if a specific one is desired * @return project with the content as requested by params. */ @Override public ProjectSourceZip exportProjectSourceZip(final String userId, final long projectId, final boolean includeProjectHistory, final boolean includeAndroidKeystore, @Nullable String zipName, final boolean fatalError) throws IOException { final Result<Integer> fileCount = new Result<Integer>(); fileCount.t = 0; final Result<String> projectHistory = new Result<String>(); projectHistory.t = null; // We collect up all the file data for the project in a transaction but // then we read the data and write the zip file outside of the transaction // to avoid problems reading blobs in a transaction with the wrong // entity group. final List<FileData> fileData = new ArrayList<FileData>(); final Result<String> projectName = new Result<String>(); projectName.t = null; String fileName = null; ByteArrayOutputStream zipFile = new ByteArrayOutputStream(); final ZipOutputStream out = new ZipOutputStream(zipFile); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<ProjectData> projectKey = projectKey(projectId); boolean foundFiles = false; for (FileData fd : datastore.query(FileData.class).ancestor(projectKey)) { String fileName = fd.fileName; if (fd.role.equals(FileData.RoleEnum.SOURCE)) { if (fileName.equals(FileExporter.REMIX_INFORMATION_FILE_PATH)) { // Skip legacy remix history files that were previous stored with the project continue; } fileData.add(fd); foundFiles = true; } } if (foundFiles) { ProjectData pd = datastore.find(projectKey); projectName.t = pd.name; if (includeProjectHistory && !Strings.isNullOrEmpty(pd.history)) { projectHistory.t = pd.history; } } } }, true); // Process the file contents outside of the job since we can't read // blobs in the job. for (FileData fd : fileData) { fileName = fd.fileName; byte[] data = null; if (fd.isBlob) { try { data = getBlobstoreBytes(fd.blobstorePath); } catch (BlobReadException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else if (fd.isGCS) { try { int count; boolean npfHappened = false; boolean recovered = false; for (count = 0; count < 5; count++) { GcsFilename gcsFileName = new GcsFilename(GCS_BUCKET_NAME, fd.gcsName); int bytesRead = 0; int fileSize = 0; ByteBuffer resultBuffer; try { fileSize = (int) gcsService.getMetadata(gcsFileName).getLength(); resultBuffer = ByteBuffer.allocate(fileSize); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0); try { while (bytesRead < fileSize) { bytesRead += readChannel.read(resultBuffer); if (bytesRead < fileSize) { LOG.log(Level.INFO, "readChannel: bytesRead = " + bytesRead + " fileSize = " + fileSize); } } recovered = true; data = resultBuffer.array(); break; // We got the data, break out of the loop! } finally { readChannel.close(); } } catch (NullPointerException e) { // This happens if the object in GCS is non-existent, which would happen // when people uploaded a zero length object. As of this change, we now // store zero length objects into GCS, but there are plenty of older objects // that are missing in GCS. LOG.log(Level.WARNING, "exportProjectFile: NPF recorded for " + fd.gcsName); npfHappened = true; resultBuffer = ByteBuffer.allocate(0); data = resultBuffer.array(); } } // report out on how things went above if (npfHappened) { // We lost at least once if (recovered) { LOG.log(Level.WARNING, "recovered from NPF in exportProjectFile filename = " + fd.gcsName + " count = " + count); } else { LOG.log(Level.WARNING, "FATAL NPF in exportProjectFile filename = " + fd.gcsName); if (fatalError) { throw new IOException("FATAL Error reading file from GCS filename = " + fd.gcsName); } } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else { data = fd.content; } if (data == null) { // This happens if file creation is interrupted data = new byte[0]; } out.putNextEntry(new ZipEntry(fileName)); out.write(data, 0, data.length); out.closeEntry(); fileCount.t++; } if (projectHistory.t != null) { byte[] data = projectHistory.t.getBytes(StorageUtil.DEFAULT_CHARSET); out.putNextEntry(new ZipEntry(FileExporter.REMIX_INFORMATION_FILE_PATH)); out.write(data, 0, data.length); out.closeEntry(); fileCount.t++; } } catch (ObjectifyException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } catch (RuntimeException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } if (fileCount.t == 0) { // can't close out since will get a ZipException due to the lack of files throw new IllegalArgumentException("No files to download"); } if (includeAndroidKeystore) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { try { Key<UserData> userKey = userKey(userId); for (UserFileData ufd : datastore.query(UserFileData.class).ancestor(userKey)) { if (ufd.fileName.equals(StorageUtil.ANDROID_KEYSTORE_FILENAME) && (ufd.content.length > 0)) { out.putNextEntry(new ZipEntry(StorageUtil.ANDROID_KEYSTORE_FILENAME)); out.write(ufd.content, 0, ufd.content.length); out.closeEntry(); fileCount.t++; } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, StorageUtil.ANDROID_KEYSTORE_FILENAME), e); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } out.close(); if (zipName == null) { zipName = projectName.t + ".wai"; } ProjectSourceZip projectSourceZip = new ProjectSourceZip(zipName, zipFile.toByteArray(), fileCount.t); projectSourceZip.setMetadata(projectName.t); return projectSourceZip; } @Override public Motd getCurrentMotd() { final Result<Motd> motd = new Result<Motd>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { MotdData motdData = datastore.find(MotdData.class, MOTD_ID); if (motdData != null) { // it shouldn't be! motd.t = new Motd(motdData.id, motdData.caption, motdData.content); } else { motd.t = new Motd(MOTD_ID, "Oops, no message of the day!", null); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } return motd.t; } @Override public String findUserByEmail(final String email) throws NoSuchElementException { Objectify datastore = ObjectifyService.begin(); // note: if there are multiple users with the same email we'll only // get the first one. we don't expect this to happen UserData userData = datastore.query(UserData.class).filter("email", email).get(); if (userData == null) { throw new NoSuchElementException("Couldn't find a user with email " + email); } return userData.id; } @Override public String findIpAddressByKey(final String key) { Objectify datastore = ObjectifyService.begin(); RendezvousData data = datastore.query(RendezvousData.class).filter("key", key).get(); if (data == null) { return null; } else { return data.ipAddress; } } @Override public void storeIpAddressByKey(final String key, final String ipAddress) { Objectify datastore = ObjectifyService.begin(); final RendezvousData data = datastore.query(RendezvousData.class).filter("key", key).get(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { RendezvousData new_data = null; if (data == null) { new_data = new RendezvousData(); new_data.id = null; new_data.key = key; new_data.ipAddress = ipAddress; new_data.used = new Date(); // So we can cleanup old entries datastore.put(new_data); } else { new_data = data; new_data.ipAddress = ipAddress; new_data.used = new Date(); datastore.put(new_data); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } @Override public boolean checkWhiteList(String email) { Objectify datastore = ObjectifyService.begin(); WhiteListData data = datastore.query(WhiteListData.class).filter("emailLower", email.toLowerCase()).get(); if (data == null) return false; return true; } @Override public void storeFeedback(final String notes, final String foundIn, final String faultData, final String comments, final String datestamp, final String email, final String projectId) { Objectify datastore = ObjectifyService.begin(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { FeedbackData data = new FeedbackData(); data.id = null; data.notes = notes; data.foundIn = foundIn; data.faultData = faultData; data.comments = comments; data.datestamp = datestamp; data.email = email; data.projectId = projectId; datastore.put(data); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } private void initMotd() { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { MotdData motdData = datastore.find(MotdData.class, MOTD_ID); if (motdData == null) { MotdData firstMotd = new MotdData(); firstMotd.id = MOTD_ID; firstMotd.caption = "Hello!"; firstMotd.content = "Welcome to the experimental App Inventor system from MIT. " + "This is still a prototype. It would be a good idea to frequently back up " + "your projects to local storage."; datastore.put(firstMotd); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, "Initing MOTD", e); } } // Nonce Management Routines. // The Nonce is used to map to userId and ProjectId and is used // for non-authenticated access to a built APK file. public void storeNonce(final String nonceValue, final String userId, final long projectId) { Objectify datastore = ObjectifyService.begin(); final NonceData data = datastore.query(NonceData.class).filter("nonce", nonceValue).get(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { NonceData new_data = null; if (data == null) { new_data = new NonceData(); new_data.id = null; new_data.nonce = nonceValue; new_data.userId = userId; new_data.projectId = projectId; new_data.timestamp = new Date(); datastore.put(new_data); } else { new_data = data; new_data.userId = userId; new_data.projectId = projectId; new_data.timestamp = new Date(); datastore.put(new_data); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } public Nonce getNoncebyValue(String nonceValue) { Objectify datastore = ObjectifyService.begin(); NonceData data = datastore.query(NonceData.class).filter("nonce", nonceValue).get(); if (data == null) { return null; } else { return (new Nonce(nonceValue, data.userId, data.projectId, data.timestamp)); } } // Cleanup expired nonces which are older then 3 hours. Normal Nonce lifetime // is 2 hours. So for one hour they persist and return "link expired" instead of // "link not found" (after the object itself is removed). // // Note: We only process up to 10 here to limit the amount of processing time // we spend here. If we remove up to 10 for each call, we should keep ahead // of the growing garbage. // // Also note that we are not running in a transaction, there is no need public void cleanupNonces() { Objectify datastore = ObjectifyService.begin(); // We do not use runJobWithRetries because if we fail here, we will be // called again the next time someone attempts to download a built APK // via a QR Code. try { datastore.delete(datastore.query(NonceData.class) .filter("timestamp <", new Date((new Date()).getTime() - 3600*3*1000L)) .limit(10).fetchKeys()); } catch (Exception ex) { LOG.log(Level.WARNING, "Exception during cleanupNonces", ex); } } // Create a name for a blob from a project id and file name. This is mostly // to help with debugging and viewing the blobstore via the admin console. // We don't currently use these blob names anywhere else. private String makeBlobName(long projectId, String fileName) { return projectId + "/" + fileName; } private Key<UserData> userKey(String userId) { return new Key<UserData>(UserData.class, userId); } private Key<ProjectData> projectKey(long projectId) { return new Key<ProjectData>(ProjectData.class, projectId); } private Key<UserProjectData> userProjectKey(Key<UserData> userKey, long projectId) { return new Key<UserProjectData>(userKey, UserProjectData.class, projectId); } private Key<UserFileData> userFileKey(Key<UserData> userKey, String fileName) { return new Key<UserFileData>(userKey, UserFileData.class, fileName); } private Key<FileData> projectFileKey(Key<ProjectData> projectKey, String fileName) { return new Key<FileData>(projectKey, FileData.class, fileName); } /** * Call job.run() if we get a {@link java.util.ConcurrentModificationException} * or {@link com.google.appinventor.server.storage.ObjectifyException} * we will retry the job (at most {@code MAX_JOB_RETRIES times}). * Any other exception will cause the job to fail immediately. * If useTransaction is true, create a transaction and run the job in * that transaction. If the job terminates normally, commit the transaction. * * Note: Originally we ran all jobs in a transaction. However in * many places there is no need for a transaction because * there is nothing to rollback on failure. Using transactions * has a performance implication, it disables Objectify's * ability to use memcache. * * @param job * @param useTransaction -- Set to true to run job in a transaction * @throws ObjectifyException */ @VisibleForTesting void runJobWithRetries(JobRetryHelper job, boolean useTransaction) throws ObjectifyException { int tries = 0; while (tries <= MAX_JOB_RETRIES) { Objectify datastore; if (useTransaction) { datastore = ObjectifyService.beginTransaction(); } else { datastore = ObjectifyService.begin(); } try { job.run(datastore); if (useTransaction) { datastore.getTxn().commit(); } break; } catch (ConcurrentModificationException ex) { job.onNonFatalError(); LOG.log(Level.WARNING, "Optimistic concurrency failure", ex); } catch (ObjectifyException oe) { String message = oe.getMessage(); if (message != null && message.startsWith("Blocks")) { // This one is fatal! throw oe; } // maybe this should be a fatal error? I think the only thing // that creates this exception (other than this method) is uploadToBlobstore job.onNonFatalError(); } finally { if (useTransaction && datastore.getTxn().isActive()) { try { datastore.getTxn().rollback(); } catch (RuntimeException e) { LOG.log(Level.WARNING, "Transaction rollback failed", e); } } } tries++; } if (tries > MAX_JOB_RETRIES) { throw new ObjectifyException("Couldn't commit job after max retries."); } } private static String collectUserErrorInfo(final String userId) { return collectUserErrorInfo(userId, CrashReport.NOT_AVAILABLE); } private static String collectUserErrorInfo(final String userId, String fileName) { return "user=" + userId + ", file=" + fileName; } private static String collectProjectErrorInfo(final String userId, final long projectId, final String fileName) { return "user=" + userId + ", project=" + projectId + ", file=" + fileName; } private static String collectUserProjectErrorInfo(final String userId, final long projectId) { return "user=" + userId + ", project=" + projectId; } // ********* METHODS BELOW ARE ONLY FOR TESTING ********* @VisibleForTesting void createRawUserFile(String userId, String fileName, byte[] content) { Objectify datastore = ObjectifyService.begin(); UserFileData ufd = createUserFile(datastore, userKey(userId), fileName); if (ufd != null) { ufd.content = content; datastore.put(ufd); } } @VisibleForTesting boolean isBlobFile(long projectId, String fileName) { Objectify datastore = ObjectifyService.begin(); Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName); FileData fd; fd = (FileData) memcache.get(fileKey.getString()); if (fd == null) { fd = datastore.find(fileKey); } if (fd != null) { return fd.isBlob; } else { return false; } } @VisibleForTesting ProjectData getProject(long projectId) { return ObjectifyService.begin().find(projectKey(projectId)); } // Return time in ISO_8660 format private static String formattedTime() { java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); return formatter.format(new java.util.Date()); } // We are called when our caller detects we are about to write a trivial (empty) // workspace. We check to see if previously the workspace was non-trivial and // if so, throw the BlocksTruncatedException. This will be passed through the RPC // layer to the client code which will put up a dialog box for the user to review // See Ode.java for more information private void checkForBlocksTruncation(FileData fd) throws ObjectifyException { if (fd.isBlob || fd.isGCS || fd.content.length > 120) throw new ObjectifyException("BlocksTruncated"); // Hack // I'm avoiding having to modify every use of runJobWithRetries to handle a new // exception, so we use this dodge. } }
appinventor/appengine/src/com/google/appinventor/server/storage/ObjectifyStorageIo.java
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.server.storage; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreInputStream; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.files.AppEngineFile; import com.google.appengine.api.files.FileService; import com.google.appengine.api.files.FileServiceFactory; import com.google.appengine.api.files.FileWriteChannel; import com.google.appengine.api.memcache.ErrorHandlers; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.appengine.api.memcache.Expiration; import com.google.appinventor.server.CrashReport; import com.google.appinventor.server.FileExporter; import com.google.appinventor.server.flags.Flag; import com.google.appinventor.server.storage.StoredData.CorruptionRecord; import com.google.appinventor.server.storage.StoredData.FeedbackData; import com.google.appinventor.server.storage.StoredData.FileData; import com.google.appinventor.server.storage.StoredData.MotdData; import com.google.appinventor.server.storage.StoredData.NonceData; import com.google.appinventor.server.storage.StoredData.ProjectData; import com.google.appinventor.server.storage.StoredData.UserData; import com.google.appinventor.server.storage.StoredData.UserFileData; import com.google.appinventor.server.storage.StoredData.UserProjectData; import com.google.appinventor.server.storage.StoredData.RendezvousData; import com.google.appinventor.server.storage.StoredData.WhiteListData; import com.google.appinventor.shared.rpc.BlocksTruncatedException; import com.google.appinventor.shared.rpc.Motd; import com.google.appinventor.shared.rpc.Nonce; import com.google.appinventor.shared.rpc.project.*; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode; import com.google.appinventor.shared.rpc.user.User; import com.google.appinventor.shared.storage.StorageUtil; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.io.ByteSource; import com.google.common.io.ByteStreams; import com.googlecode.objectify.Key; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.Query; import java.io.ByteArrayOutputStream; // GCS imports import com.google.appengine.tools.cloudstorage.GcsFileOptions; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.appengine.tools.cloudstorage.GcsInputChannel; import com.google.appengine.tools.cloudstorage.GcsOutputChannel; import com.google.appengine.tools.cloudstorage.GcsService; import com.google.appengine.tools.cloudstorage.GcsServiceFactory; import com.google.appengine.tools.cloudstorage.RetryParams; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import java.util.Date; import javax.annotation.Nullable; /** * Implements the StorageIo interface using Objectify as the underlying data * store. * * @author [email protected] (Sharon Perl) * */ public class ObjectifyStorageIo implements StorageIo { static final Flag<Boolean> requireTos = Flag.createFlag("require.tos", false); private static final Logger LOG = Logger.getLogger(ObjectifyStorageIo.class.getName()); private static final String DEFAULT_ENCODING = "UTF-8"; private static final long MOTD_ID = 1; // TODO(user): need a way to modify this. Also, what is really a good value? private static final int MAX_JOB_RETRIES = 10; private final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); private final GcsService gcsService; private final String GCS_BUCKET_NAME = Flag.createFlag("gcs.bucket", "").get(); private static final long TWENTYFOURHOURS = 24*3600*1000; // 24 hours in milliseconds private final boolean useGcs = Flag.createFlag("use.gcs", false).get(); // Use this class to define the work of a job that can be // retried. The "datastore" argument to run() is the Objectify // object for this job (created with // ObjectifyService.beginTransaction() if a transaction is used or // ObjectifyService.begin if no transaction is used). Note that all // operations on "datastore" should be for objects in the same // entity group if a transaction is used. // Note: 1/25/2015: Added code to make the use of a transaction // optional. In general we only need to use a // transaction where there work we would need to // rollback if an operation on the datastore // failed. We have not necessarily converted all // cases yet (out of a sense of caution). However // we have removed transaction in places where // doing so permits Objectify to use its global // cache (memcache) in a way that helps // performance. @VisibleForTesting abstract class JobRetryHelper { public abstract void run(Objectify datastore) throws ObjectifyException; /* * Called before retrying the job. Note that the underlying datastore * still has the transaction active, so restrictions about operations * over multiple entity groups still apply. */ public void onNonFatalError() { // Default is to do nothing } } // Create a final object of this class to hold a modifiable result value that // can be used in a method of an inner class. private class Result<T> { T t; } private FileService fileService; static { // Register the data object classes stored in the database ObjectifyService.register(UserData.class); ObjectifyService.register(ProjectData.class); ObjectifyService.register(UserProjectData.class); ObjectifyService.register(FileData.class); ObjectifyService.register(UserFileData.class); ObjectifyService.register(MotdData.class); ObjectifyService.register(RendezvousData.class); ObjectifyService.register(WhiteListData.class); ObjectifyService.register(FeedbackData.class); ObjectifyService.register(NonceData.class); ObjectifyService.register(CorruptionRecord.class); } ObjectifyStorageIo() { fileService = FileServiceFactory.getFileService(); RetryParams retryParams = new RetryParams.Builder().initialRetryDelayMillis(100) .retryMaxAttempts(10) .totalRetryPeriodMillis(10000).build(); LOG.log(Level.INFO, "RetryParams: getInitialRetryDelayMillis() = " + retryParams.getInitialRetryDelayMillis()); LOG.log(Level.INFO, "RetryParams: getRequestTimeoutMillis() = " + retryParams.getRequestTimeoutMillis()); LOG.log(Level.INFO, "RetryParams: getRetryDelayBackoffFactor() = " + retryParams.getRetryDelayBackoffFactor()); LOG.log(Level.INFO, "RetryParams: getRetryMaxAttempts() = " + retryParams.getRetryMaxAttempts()); LOG.log(Level.INFO, "RetryParams: getRetryMinAttempts() = " + retryParams.getRetryMinAttempts()); LOG.log(Level.INFO, "RetryParams: getTotalRetryPeriodMillis() = " + retryParams.getTotalRetryPeriodMillis()); gcsService = GcsServiceFactory.createGcsService(retryParams); memcache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); initMotd(); } // for testing ObjectifyStorageIo(FileService fileService) { this.fileService = fileService; RetryParams retryParams = new RetryParams.Builder().initialRetryDelayMillis(100) .retryMaxAttempts(10) .totalRetryPeriodMillis(10000).build(); gcsService = GcsServiceFactory.createGcsService(retryParams); initMotd(); } @Override public User getUser(String userId) { return getUser(userId, null); } /* * Note that the User returned by this method will always have isAdmin set to * false. We leave it to the caller to determine whether the user has admin * priviledges. */ @Override public User getUser(final String userId, final String email) { String cachekey = User.usercachekey + "|" + userId; User tuser = (User) memcache.get(cachekey); if (tuser != null && tuser.getUserTosAccepted() && ((email == null) || (tuser.getUserEmail().equals(email)))) { if (tuser.getUserName()==null) { setUserName(userId,tuser.getDefaultName()); tuser.setUserName(tuser.getDefaultName()); } return tuser; } else { // If not in memcache, or tos // not yet accepted, fetch from datastore tuser = new User(userId, email, null, null, false, false, 0, null); } final User user = tuser; try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData == null) { userData = createUser(datastore, userId, email); } else if (email != null && !email.equals(userData.email)) { userData.email = email; datastore.put(userData); } user.setUserEmail(userData.email); user.setUserName(userData.name); user.setUserLink(userData.link); user.setType(userData.type); user.setUserTosAccepted(userData.tosAccepted || !requireTos.get()); user.setSessionId(userData.sessionid); } }, false); // Transaction not needed. If we fail there is nothing to rollback } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute // The choice of one minute here is arbitrary. getUser() is called on every authenticated // RPC call to the system (out of OdeAuthFilter), so using memcache will save a significant // number of calls to the datastore. If someone is idle for more then a minute, it isn't // unreasonable to hit the datastore again. By pruning memcache ourselves, we have a // bit more control (maybe) of how things are flushed from memcache. Otherwise we are // at the whim of whatever algorithm App Engine employs now or in the future. return user; } private UserData createUser(Objectify datastore, String userId, String email) { UserData userData = new UserData(); userData.id = userId; userData.tosAccepted = false; userData.settings = ""; userData.email = email == null ? "" : email; userData.name = User.getDefaultName(email); userData.type = User.USER; userData.link = ""; datastore.put(userData); return userData; } @Override public void setTosAccepted(final String userId) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.tosAccepted = true; datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserEmail(final String userId, final String email) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.email = email; datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserName(final String userId, final String name) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.name = name; datastore.put(userData); } // we need to change the memcache version of user User user = new User(userData.id,userData.email,name, userData.link, userData.tosAccepted, false, userData.type, userData.sessionid); String cachekey = User.usercachekey + "|" + userId; memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserLink(final String userId, final String link) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.link = link; datastore.put(userData); } // we need to change the memcache version of user User user = new User(userData.id,userData.email,userData.name,link,userData.tosAccepted, false, userData.type, userData.sessionid); String cachekey = User.usercachekey + "|" + userId; memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setUserSessionId(final String userId, final String sessionId) { String cachekey = User.usercachekey + "|" + userId; try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.sessionid = sessionId; datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } memcache.delete(cachekey); // Flush cached copy because it changed } @Override public String loadSettings(final String userId) { final Result<String> settings = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(UserData.class, userId); if (userData != null) { settings.t = userData.settings; } else { settings.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return settings.t; } @Override public String getUserName(final String userId) { final Result<String> name = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(UserData.class, userId); if (userData != null) { name.t = userData.name; } else { name.t = "unknown"; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return name.t; } @Override public String getUserLink(final String userId) { final Result<String> link = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(UserData.class, userId); if (userData != null) { link.t = userData.link; } else { link.t = "unknown"; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return link.t; } @Override public void storeSettings(final String userId, final String settings) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserData userData = datastore.find(userKey(userId)); if (userData != null) { userData.settings = settings; userData.visited = new Date(); // Indicate that this person was active now datastore.put(userData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public long createProject(final String userId, final Project project, final String projectSettings) { final Result<Long> projectId = new Result<Long>(); final List<String> blobsToDelete = new ArrayList<String>(); final List<FileData> addedFiles = new ArrayList<FileData>(); try { // first job is on the project entity, creating the ProjectData object // and the associated files. runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) throws ObjectifyException { long date = System.currentTimeMillis(); ProjectData pd = new ProjectData(); pd.id = null; // let Objectify auto-generate the project id pd.dateCreated = date; pd.dateModified = date; pd.history = project.getProjectHistory(); pd.name = project.getProjectName(); pd.settings = projectSettings; pd.type = project.getProjectType(); pd.galleryId = UserProject.NOTPUBLISHED; pd.attributionId = UserProject.FROMSCRATCH; datastore.put(pd); // put the project in the db so that it gets assigned an id assert pd.id != null; projectId.t = pd.id; // After the job commits projectId.t should end up with the last value // we've gotten for pd.id (i.e. the one that committed if there // was no error). // Note that while we cannot expect to read back a value that we've // written in this job, reading the assigned id from pd should work. Key<ProjectData> projectKey = projectKey(projectId.t); for (TextFile file : project.getSourceFiles()) { try { addedFiles.add(createRawFile(projectKey, FileData.RoleEnum.SOURCE, file.getFileName(), file.getContent().getBytes(DEFAULT_ENCODING))); } catch (BlobWriteException e) { rememberBlobsToDelete(); // Note that this makes the BlobWriteException fatal. The job will // not be retried if we get this exception. throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } catch (IOException e) { // GCS throws this throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } } for (RawFile file : project.getRawSourceFiles()) { try { addedFiles.add(createRawFile(projectKey, FileData.RoleEnum.SOURCE, file.getFileName(), file.getContent())); } catch (BlobWriteException e) { rememberBlobsToDelete(); // Note that this makes the BlobWriteException fatal. The job will // not be retried if we get this exception. throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId.t, file.getFileName()), e); } } datastore.put(addedFiles); // batch put } @Override public void onNonFatalError() { rememberBlobsToDelete(); } private void rememberBlobsToDelete() { for (FileData addedFile : addedFiles) { if (addedFile.isBlob && addedFile.blobstorePath != null) { blobsToDelete.add(addedFile.blobstorePath); } } // clear addedFiles in case we end up here more than once addedFiles.clear(); } }, true); // second job is on the user entity runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserProjectData upd = new UserProjectData(); upd.projectId = projectId.t; upd.settings = projectSettings; upd.state = UserProjectData.StateEnum.OPEN; upd.userKey = userKey(userId); datastore.put(upd); } }, true); } catch (ObjectifyException e) { for (FileData addedFile : addedFiles) { if (addedFile.isBlob && addedFile.blobstorePath != null) { blobsToDelete.add(addedFile.blobstorePath); } } // clear addedFiles in case we end up here more than once addedFiles.clear(); throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId.t), e); } finally { // Need to delete any orphaned blobs outside of the transaction to avoid multiple entity // group errors. The lookup of the blob key seems to be the thing that // triggers the error. for (String blobToDelete: blobsToDelete) { deleteBlobstoreFile(blobToDelete); } } return projectId.t; } /* * Creates and returns a new FileData object with the specified fields. * Does not check for the existence of the object and does not update * the database. */ private FileData createRawFile(Key<ProjectData> projectKey, FileData.RoleEnum role, String fileName, byte[] content) throws BlobWriteException, ObjectifyException, IOException { FileData file = new FileData(); file.fileName = fileName; file.projectKey = projectKey; file.role = role; if (useGCSforFile(fileName, content.length)) { file.isGCS = true; file.gcsName = makeGCSfileName(fileName, projectKey.getId()); GcsOutputChannel outputChannel = gcsService.createOrReplace(new GcsFilename(GCS_BUCKET_NAME, file.gcsName), GcsFileOptions.getDefaultInstance()); outputChannel.write(ByteBuffer.wrap(content)); outputChannel.close(); } else if (useBlobstoreForFile(fileName, content.length)) { file.isBlob = true; file.blobstorePath = uploadToBlobstore(content, makeBlobName(projectKey.getId(), fileName)); } else { file.content = content; } return file; } @Override public void deleteProject(final String userId, final long projectId) { // blobs associated with the project final List<String> blobPaths = new ArrayList<String>(); final List<String> gcsPaths = new ArrayList<String>(); try { // first job deletes the UserProjectData in the user's entity group runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { // delete the UserProjectData object Key<UserData> userKey = userKey(userId); datastore.delete(userProjectKey(userKey, projectId)); // delete any FileData objects associated with this project } }, true); // second job deletes the project files and ProjectData in the project's // entity group runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<ProjectData> projectKey = projectKey(projectId); Query<FileData> fdq = datastore.query(FileData.class).ancestor(projectKey); for (FileData fd: fdq) { if (fd.isGCS) { gcsPaths.add(fd.gcsName); } else if (fd.isBlob) { blobPaths.add(fd.blobstorePath); } } datastore.delete(fdq); // finally, delete the ProjectData object datastore.delete(projectKey); } }, true); // have to delete the blobs outside of the user and project jobs for (String blobPath: blobPaths) { deleteBlobstoreFile(blobPath); } // Now delete the gcs files for (String gcsName: gcsPaths) { try { gcsService.delete(new GcsFilename(GCS_BUCKET_NAME, gcsName)); } catch (IOException e) { LOG.log(Level.WARNING, "Unable to delete " + gcsName + " from GCS while deleting project", e); } } } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } } @Override public void setProjectGalleryId(final String userId, final long projectId,final long galleryId) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData projectData = datastore.find(projectKey(projectId)); if (projectData != null) { projectData.galleryId = galleryId; datastore.put(projectData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } @Override public void setProjectAttributionId(final String userId, final long projectId,final long attributionId) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData projectData = datastore.find(projectKey(projectId)); if (projectData != null) { projectData.attributionId = attributionId; datastore.put(projectData); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null,"error in setProjectAttributionId", e); } } @Override public List<Long> getProjects(final String userId) { final List<Long> projects = new ArrayList<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserData> userKey = userKey(userId); for (UserProjectData upd : datastore.query(UserProjectData.class).ancestor(userKey)) { projects.add(upd.projectId); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return projects; } @Override public String loadProjectSettings(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<String> settings = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { settings.t = pd.settings; } else { settings.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return settings.t; } @Override public void storeProjectSettings(final String userId, final long projectId, final String settings) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { pd.settings = settings; datastore.put(pd); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } } @Override public String getProjectType(final String userId, final long projectId) { // final Result<String> projectType = new Result<String>(); // try { // runJobWithRetries(new JobRetryHelper() { // @Override // public void run(Objectify datastore) { // ProjectData pd = datastore.find(projectKey(projectId)); // if (pd != null) { // projectType.t = pd.type; // } else { // projectType.t = ""; // } // } // }); // } catch (ObjectifyException e) { // throw CrashReport.createAndLogError(LOG, null, // collectUserProjectErrorInfo(userId, projectId), e); // } // We only have one project type, no need to ask about it return YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE; } @Override public UserProject getUserProject(final String userId, final long projectId) { final Result<ProjectData> projectData = new Result<ProjectData>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { projectData.t = pd; } else { projectData.t = null; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } if (projectData == null) { return null; } else { return new UserProject(projectId, projectData.t.name, projectData.t.type, projectData.t.dateCreated, projectData.t.dateModified, projectData.t.galleryId, projectData.t.attributionId); } } @Override public String getProjectName(final String userId, final long projectId) { final Result<String> projectName = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { projectName.t = pd.name; } else { projectName.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return projectName.t; } @Override public long getProjectDateModified(final String userId, final long projectId) { final Result<Long> modDate = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { modDate.t = pd.dateModified; } else { modDate.t = Long.valueOf(0); } } }, false); // Transaction not needed, and we want the caching we get if we don't // use them. } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return modDate.t; } @Override public String getProjectHistory(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<String> projectHistory = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { projectHistory.t = pd.history; } else { projectHistory.t = ""; } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return projectHistory.t; } // JIS XXX @Override public long getProjectDateCreated(final String userId, final long projectId) { final Result<Long> dateCreated = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { dateCreated.t = pd.dateCreated; } else { dateCreated.t = Long.valueOf(0); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return dateCreated.t; } @Override public long getProjectGalleryId(String userId, final long projectId) { final Result<Long> galleryId = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { galleryId.t = pd.galleryId; } else { galleryId.t = Long.valueOf(0); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null,"error in getProjectGalleryId", e); } return galleryId.t; } @Override public long getProjectAttributionId(final long projectId) { final Result<Long> attributionId = new Result<Long>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { attributionId.t = pd.attributionId; } else { attributionId.t = Long.valueOf(UserProject.FROMSCRATCH); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, "error in getProjectAttributionId", e); } return attributionId.t; } @Override public void addFilesToUser(final String userId, final String... fileNames) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserData> userKey = userKey(userId); List<UserFileData> addedFiles = new ArrayList<UserFileData>(); for (String fileName : fileNames) { UserFileData ufd = createUserFile(datastore, userKey, fileName); if (ufd != null) { addedFiles.add(ufd); } } datastore.put(addedFiles); // batch put } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileNames[0]), e); } } /* * Creates a UserFileData object for the given userKey and fileName, if it * doesn't already exist. Returns the new UserFileData object, or null if * already existed. This method does not add the UserFileData object to the * datastore. */ private UserFileData createUserFile(Objectify datastore, Key<UserData> userKey, String fileName) { UserFileData ufd = datastore.find(userFileKey(userKey, fileName)); if (ufd == null) { ufd = new UserFileData(); ufd.fileName = fileName; ufd.userKey = userKey; return ufd; } return null; } @Override public List<String> getUserFiles(final String userId) { final List<String> fileList = new ArrayList<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserData> userKey = userKey(userId); for (UserFileData ufd : datastore.query(UserFileData.class).ancestor(userKey)) { fileList.add(ufd.fileName); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } return fileList; } @Override public void uploadUserFile(final String userId, final String fileName, final String content, final String encoding) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException e) { // Note: this RuntimeException should propagate up out of runJobWithRetries throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding, " + collectUserErrorInfo(userId, fileName), e); } addUserFileContents(datastore, userId, fileName, bytes); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } } @Override public void uploadRawUserFile(final String userId, final String fileName, final byte[] content) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { addUserFileContents(datastore, userId, fileName, content); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } } /* * We expect the UserFileData object for the given userId and fileName to * already exist in the datastore. Find the object and update its contents. */ private void addUserFileContents(Objectify datastore, String userId, String fileName, byte[] content) { UserFileData ufd = datastore.find(userFileKey(userKey(userId), fileName)); Preconditions.checkState(ufd != null); ufd.content = content; datastore.put(ufd); } @Override public String downloadUserFile(final String userId, final String fileName, final String encoding) { final Result<String> result = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { try { result.t = new String(downloadRawUserFile(userId, fileName), encoding); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding, " + collectUserErrorInfo(userId, fileName), e); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } return result.t; } @Override public byte[] downloadRawUserFile(final String userId, final String fileName) { final Result<byte[]> result = new Result<byte[]>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { UserFileData ufd = datastore.find(userFileKey(userKey(userId), fileName)); if (ufd != null) { result.t = ufd.content; } else { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), new FileNotFoundException(fileName)); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } return result.t; } @Override public void deleteUserFile(final String userId, final String fileName) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<UserFileData> ufdKey = userFileKey(userKey(userId), fileName); if (datastore.find(ufdKey) != null) { datastore.delete(ufdKey); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId, fileName), e); } } @Override public int getMaxJobSizeBytes() { // TODO(user): what should this mean? return 5 * 1024 * 1024; } @Override public void addSourceFilesToProject(final String userId, final long projectId, final boolean changeModDate, final String... fileNames) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { addFilesToProject(datastore, projectId, FileData.RoleEnum.SOURCE, changeModDate, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } @Override public void addOutputFilesToProject(final String userId, final long projectId, final String... fileNames) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { addFilesToProject(datastore, projectId, FileData.RoleEnum.TARGET, false, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } private void addFilesToProject(Objectify datastore, long projectId, FileData.RoleEnum role, boolean changeModDate, String... fileNames) { List<FileData> addedFiles = new ArrayList<FileData>(); Key<ProjectData> projectKey = projectKey(projectId); for (String fileName : fileNames) { FileData fd = createProjectFile(datastore, projectKey, role, fileName); if (fd != null) { addedFiles.add(fd); } } datastore.put(addedFiles); // batch put if (changeModDate) { updateProjectModDate(datastore, projectId); } } private FileData createProjectFile(Objectify datastore, Key<ProjectData> projectKey, FileData.RoleEnum role, String fileName) { FileData fd = datastore.find(projectFileKey(projectKey, fileName)); if (fd == null) { fd = new FileData(); fd.fileName = fileName; fd.projectKey = projectKey; fd.role = role; return fd; } else if (!fd.role.equals(role)) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(null, projectKey.getId(), fileName), new IllegalStateException("File role change is not supported")); } return null; } @Override public void removeSourceFilesFromProject(final String userId, final long projectId, final boolean changeModDate, final String... fileNames) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { removeFilesFromProject(datastore, projectId, FileData.RoleEnum.SOURCE, changeModDate, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } @Override public void removeOutputFilesFromProject(final String userId, final long projectId, final String... fileNames) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { removeFilesFromProject(datastore, projectId, FileData.RoleEnum.TARGET, false, fileNames); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileNames[0]), e); } } private void removeFilesFromProject(Objectify datastore, long projectId, FileData.RoleEnum role, boolean changeModDate, String... fileNames) { Key<ProjectData> projectKey = projectKey(projectId); List<Key<FileData>> filesToRemove = new ArrayList<Key<FileData>>(); for (String fileName : fileNames) { Key<FileData> key = projectFileKey(projectKey, fileName); memcache.delete(key.getString()); // Remove it from memcache (if it is there) FileData fd = datastore.find(key); if (fd != null) { if (fd.role.equals(role)) { filesToRemove.add(projectFileKey(projectKey, fileName)); } else { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(null, projectId, fileName), new IllegalStateException("File role change is not supported")); } } } datastore.delete(filesToRemove); // batch delete if (changeModDate) { updateProjectModDate(datastore, projectId); } } /** * Exports project web files as a zip archive * @param userId a user Id (the request is made on behalf of this user) * @param projectId project ID * @param assetFileIds the asset file ids representing referenced files, e.g. image files. * @param zipName the name of the zip file * @param fatalError set true to cause missing GCS file to throw exception * @return project with the content as requested by params. * @throws IOException if files cannot be written */ @Override public ProjectWebOutputZip exportProjectWebOutputZip(final String userId, final long projectId, final ArrayList<String> assetFileIds, String zipName, final boolean fatalError, @Nullable RawFile importFile) throws IOException { final Result<Integer> fileCount = new Result<Integer>(); fileCount.t = 0; // We collect up all the file data for the project in a transaction but // then we read the data and write the zip file outside of the transaction // to avoid problems reading blobs in a transaction with the wrong // entity group. final List<FileData> fileData = new ArrayList<FileData>(); final Result<String> projectName = new Result<String>(); projectName.t = null; String fileName = null; ByteArrayOutputStream zipFile = new ByteArrayOutputStream(); final ZipOutputStream out = new ZipOutputStream(zipFile); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<ProjectData> projectKey = projectKey(projectId); boolean foundFiles = false; for (FileData fd : datastore.query(FileData.class).ancestor(projectKey)) { // Scan for files built for web output if (fd.role.equals(FileData.RoleEnum.TARGET) && fd.fileName.startsWith("build/web/")) { fileData.add(fd); foundFiles = true; } // Look for reference files for web output. e.g. images else { for (String assetFileID : assetFileIds) { if (fd.role.equals(FileData.RoleEnum.SOURCE) && fd.fileName.equalsIgnoreCase(assetFileID)) { fileData.add(fd); foundFiles = true; } } } } if (foundFiles) { ProjectData pd = datastore.find(projectKey); projectName.t = pd.name; } } },true); // Process the file contents outside of the job since we can't read // blobs in the job. for (FileData fd : fileData) { fileName = fd.fileName; byte[] data = null; if (fd.isBlob) { try { data = getBlobstoreBytes(fd.blobstorePath); } catch (BlobReadException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else if (fd.isGCS) { try { int count; boolean npfHappened = false; boolean recovered = false; for (count = 0; count < 5; count++) { GcsFilename gcsFileName = new GcsFilename(GCS_BUCKET_NAME, fd.gcsName); int bytesRead = 0; int fileSize = 0; ByteBuffer resultBuffer; try { fileSize = (int) gcsService.getMetadata(gcsFileName).getLength(); resultBuffer = ByteBuffer.allocate(fileSize); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0); try { while (bytesRead < fileSize) { bytesRead += readChannel.read(resultBuffer); if (bytesRead < fileSize) { LOG.log(Level.INFO, "readChannel: bytesRead = " + bytesRead + " fileSize = " + fileSize); } } recovered = true; data = resultBuffer.array(); break; // We got the data, break out of the loop! } finally { readChannel.close(); } } catch (NullPointerException e) { // This happens if the object in GCS is non-existent, which would happen // when people uploaded a zero length object. As of this change, we now // store zero length objects into GCS, but there are plenty of older objects // that are missing in GCS. LOG.log(Level.WARNING, "exportProjectFile: NPF recorded for " + fd.gcsName); npfHappened = true; resultBuffer = ByteBuffer.allocate(0); data = resultBuffer.array(); } } // report out on how things went above if (npfHappened) { // We lost at least once if (recovered) { LOG.log(Level.WARNING, "recovered from NPF in exportProjectFile filename = " + fd.gcsName + " count = " + count); } else { LOG.log(Level.WARNING, "FATAL NPF in exportProjectFile filename = " + fd.gcsName); if (fatalError) { throw new IOException("FATAL Error reading file from GCS filename = " + fd.gcsName); } } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else { data = fd.content; } if (data == null) { // This happens if file creation is interrupted data = new byte[0]; } if (fileName.startsWith("assets/")) { out.putNextEntry(new ZipEntry(fileName)); } else { out.putNextEntry(new ZipEntry(StorageUtil.basename(fileName))); } out.write(data, 0, data.length); out.closeEntry(); fileCount.t++; } // Add the bootstrap library to the zip output. String bootstrapFileName = importFile.getFileName(); byte[] bootstrapData = importFile.getContent(); if (bootstrapData == null) { bootstrapData = new byte[0]; } else { out.putNextEntry(new ZipEntry(bootstrapFileName)); } out.write(bootstrapData, 0, bootstrapData.length); out.closeEntry(); fileCount.t++; } catch (ObjectifyException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } catch (RuntimeException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } if (fileCount.t == 0) { // can't close out since will get a ZipException due to the lack of files throw new IllegalArgumentException("No files to download"); } out.close(); if (zipName == null) { zipName = projectName.t + ".zip"; } ProjectWebOutputZip projectWebOutputZip = new ProjectWebOutputZip(zipName, zipFile.toByteArray(), fileCount.t); projectWebOutputZip.setMetadata(projectName.t); return projectWebOutputZip; } @Override public List<String> getProjectSourceFiles(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<List<String>> result = new Result<List<String>>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { result.t = getProjectFiles(datastore, projectId, FileData.RoleEnum.SOURCE); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return result.t; } @Override public List<String> getProjectOutputFiles(final String userId, final long projectId) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<List<String>> result = new Result<List<String>>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { result.t = getProjectFiles(datastore, projectId, FileData.RoleEnum.TARGET); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), e); } return result.t; } private List<String> getProjectFiles(Objectify datastore, long projectId, FileData.RoleEnum role) { Key<ProjectData> projectKey = projectKey(projectId); List<String> fileList = new ArrayList<String>(); for (FileData fd : datastore.query(FileData.class).ancestor(projectKey)) { if (fd.role.equals(role)) { fileList.add(fd.fileName); } } return fileList; } @Override public long uploadFile(final long projectId, final String fileName, final String userId, final String content, final String encoding) throws BlocksTruncatedException { try { return uploadRawFile(projectId, fileName, userId, false, content.getBytes(encoding)); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding," + collectProjectErrorInfo(null, projectId, fileName), e); } } @Override public long uploadFileForce(final long projectId, final String fileName, final String userId, final String content, final String encoding) { try { return uploadRawFileForce(projectId, fileName, userId, content.getBytes(encoding)); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding," + collectProjectErrorInfo(null, projectId, fileName), e); } } private long updateProjectModDate(Objectify datastore, long projectId) { long modDate = System.currentTimeMillis(); ProjectData pd = datastore.find(projectKey(projectId)); if (pd != null) { // Only update the ProjectData dateModified if it is more then a minute // in the future. Do this to avoid unnecessary datastore puts if (modDate > (pd.dateModified + 1000*60)) { pd.dateModified = modDate; datastore.put(pd); } else { // return the (old) dateModified modDate = pd.dateModified; } return modDate; } else { throw CrashReport.createAndLogError(LOG, null, null, new IllegalArgumentException("project " + projectId + " doesn't exist")); } } @Override public long uploadRawFileForce(final long projectId, final String fileName, final String userId, final byte[] content) { try { return uploadRawFile(projectId, fileName, userId, true, content); } catch (BlocksTruncatedException e) { // Won't get here, exception isn't thrown when force is true return 0; } } @Override public long uploadRawFile(final long projectId, final String fileName, final String userId, final boolean force, final byte[] content) throws BlocksTruncatedException { final Result<Long> modTime = new Result<Long>(); final boolean useBlobstore = useBlobstoreForFile(fileName, content.length); final boolean useGCS = useGCSforFile(fileName, content.length); final Result<String> oldBlobstorePath = new Result<String>(); final boolean considerBackup = (useGcs?((fileName.contains("src/") && fileName.endsWith(".blk")) // AI1 Blocks Files || (fileName.contains("src/") && fileName.endsWith(".bky")) // Blockly files || (fileName.contains("src/") && fileName.endsWith(".scm"))) // Form Definitions :false); try { runJobWithRetries(new JobRetryHelper() { FileData fd; @Override public void run(Objectify datastore) throws ObjectifyException { Key<FileData> key = projectFileKey(projectKey(projectId), fileName); fd = (FileData) memcache.get(key.getString()); if (fd == null) { fd = datastore.find(projectFileKey(projectKey(projectId), fileName)); } else { LOG.log(Level.INFO, "Fetched " + key.getString() + " from memcache."); } // <Screen>.yail files are missing when user converts AI1 project to AI2 // instead of blowing up, just create a <Screen>.yail file if (fd == null && fileName.endsWith(".yail")){ fd = createProjectFile(datastore, projectKey(projectId), FileData.RoleEnum.SOURCE, fileName); } Preconditions.checkState(fd != null); if ((content.length < 125) && (fileName.endsWith(".bky"))) { // Likely this is an empty blocks workspace if (!force) { // force is true if we *really* want to save it! checkForBlocksTruncation(fd); // See if we had previous content and throw and exception if so } } if (fd.isBlob) { // mark the old blobstore blob for deletion oldBlobstorePath.t = fd.blobstorePath; } if (useGCS) { fd.isGCS = true; fd.gcsName = makeGCSfileName(fileName, projectId); try { GcsOutputChannel outputChannel = gcsService.createOrReplace(new GcsFilename(GCS_BUCKET_NAME, fd.gcsName), GcsFileOptions.getDefaultInstance()); outputChannel.write(ByteBuffer.wrap(content)); outputChannel.close(); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } // If the content was previously stored in the datastore, clear it out. fd.content = null; fd.isBlob = false; // in case we are converting from a blob fd.blobstorePath = null; } else if (useBlobstore) { try { fd.blobstorePath = uploadToBlobstore(content, makeBlobName(projectId, fileName)); } catch (BlobWriteException e) { // Note that this makes the BlobWriteException fatal. The job will // not be retried if we get this exception. throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } // If the content was previously stored in the datastore or GCS, clear it out. fd.isBlob = true; fd.isGCS = false; fd.gcsName = null; fd.content = null; } else { if (fd.isGCS) { // Was a GCS file, must have gotten smaller try { // and is now stored in the data store gcsService.delete(new GcsFilename(GCS_BUCKET_NAME, fd.gcsName)); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } fd.isGCS = false; fd.gcsName = null; } // Note, Don't have to do anything if the file was in the // Blobstore and shrank because the code above (3 lines // into the function) already handles removing the old // contents from the Blobstore. fd.isBlob = false; fd.blobstorePath = null; fd.content = content; } if (considerBackup) { if ((fd.lastBackup + TWENTYFOURHOURS) < System.currentTimeMillis()) { try { String gcsName = makeGCSfileName(fileName + "." + formattedTime() + ".backup", projectId); GcsOutputChannel outputChannel = gcsService.createOrReplace((new GcsFilename(GCS_BUCKET_NAME, gcsName)), GcsFileOptions.getDefaultInstance()); outputChannel.write(ByteBuffer.wrap(content)); outputChannel.close(); fd.lastBackup = System.currentTimeMillis(); } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName + "(backup)"), e); } } } datastore.put(fd); memcache.put(key.getString(), fd); // Store the updated data in memcache modTime.t = updateProjectModDate(datastore, projectId); } @Override public void onNonFatalError() { if (fd != null && fd.blobstorePath != null) { oldBlobstorePath.t = fd.blobstorePath; } } }, useBlobstore); // Use transaction for blobstore, otherwise we don't need one // and without one the caching code comes into play. // It would have been convenient to delete the old blobstore file within the run() method // above but that caused an exception where the app engine datastore claimed to be doing // operations on multiple entity groups within the same transaction. Apparently the blobstore // operations are, at least partially, also datastore operations. if (oldBlobstorePath.t != null) { deleteBlobstoreFile(oldBlobstorePath.t); } } catch (ObjectifyException e) { if (e.getMessage().startsWith("Blocks")) { // Convert Exception throw new BlocksTruncatedException(); } throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } return modTime.t; } protected void deleteBlobstoreFile(String blobstorePath) { // It would be nice if there were an AppEngineFile.delete() method but alas there isn't, so we // have to get the BlobKey and delete via the BlobstoreService. BlobKey blobKey = null; try { AppEngineFile blobstoreFile = new AppEngineFile(blobstorePath); blobKey = fileService.getBlobKey(blobstoreFile); BlobstoreServiceFactory.getBlobstoreService().delete(blobKey); } catch (RuntimeException e) { // Log blob delete errors but don't make them fatal CrashReport.createAndLogError(LOG, null, "Error deleting blob with path " + blobstorePath + " and key " + blobKey, e); } } private String uploadToBlobstore(byte[] content, String name) throws BlobWriteException, ObjectifyException { // Create a new Blob file with generic mime-type "application/octet-stream" AppEngineFile blobstoreFile = null; try { blobstoreFile = fileService.createNewBlobFile("application/octet-stream", name); // Open a channel to write to it FileWriteChannel blobstoreWriteChannel = fileService.openWriteChannel(blobstoreFile, true); OutputStream blobstoreOutputStream = Channels.newOutputStream(blobstoreWriteChannel); ByteStreams.copy(ByteSource.wrap(content).openStream(), blobstoreOutputStream); blobstoreOutputStream.flush(); blobstoreOutputStream.close(); blobstoreWriteChannel.closeFinally(); } catch (IOException e) { throw new BlobWriteException(e, "Error writing blob with name " + name); } catch (Exception e) { throw new ObjectifyException(e); } return blobstoreFile.getFullPath(); } @VisibleForTesting boolean useBlobstoreForFile(String fileName, int length) { if (useGcs) return false; // Disable for now boolean shouldUse = fileName.contains("assets/") || fileName.endsWith(".apk"); if (shouldUse) return true; // Use GCS for package output and assets boolean mayUse = (fileName.contains("src/") && fileName.endsWith(".blk")) // AI1 Blocks Files || (fileName.contains("src/") && fileName.endsWith(".bky")); // Blockly files if (mayUse && length > 50000) // Only use Blobstore for larger blocks files return true; return false; } // Experimental -- Use the Google Cloud Store for a file @VisibleForTesting boolean useGCSforFile(String fileName, int length) { if (!useGcs) // Using legacy blob store solution return false; boolean shouldUse = fileName.contains("assets/") || fileName.endsWith(".apk"); if (shouldUse) return true; // Use GCS for package output and assets boolean mayUse = (fileName.contains("src/") && fileName.endsWith(".blk")) // AI1 Blocks Files || (fileName.contains("src/") && fileName.endsWith(".bky")); // Blockly files if (mayUse && length > 50000) // Only use GCS for larger blocks files return true; return false; } // Make a GCS file name String makeGCSfileName(String fileName, long projectId) { return (projectId + "/" + fileName); } @Override public long deleteFile(final String userId, final long projectId, final String fileName) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<Long> modTime = new Result<Long>(); final Result<String> oldBlobstorePath = new Result<String>(); final Result<String> oldgcsName = new Result<String>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName); memcache.delete(fileKey.getString()); FileData fileData = datastore.find(fileKey); if (fileData != null) { oldBlobstorePath.t = fileData.blobstorePath; if (fileData.isGCS) { oldgcsName.t = fileData.gcsName; } } datastore.delete(fileKey); modTime.t = updateProjectModDate(datastore, projectId); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } if (oldBlobstorePath.t != null) { deleteBlobstoreFile(oldBlobstorePath.t); } if (oldgcsName.t != null) { try { gcsService.delete(new GcsFilename(GCS_BUCKET_NAME, oldgcsName.t)); } catch (IOException e) { LOG.log(Level.WARNING, "Unable to delete " + oldgcsName + " from GCS.", e); } } return (modTime.t == null) ? 0 : modTime.t; } // TODO(user) - just use "UTF-8" (instead of having an encoding argument), // which will never cause UnsupportedEncodingException. (Here and in other // methods with the encoding arg. @Override public String downloadFile(final String userId, final long projectId, final String fileName, final String encoding) { try { return new String(downloadRawFile(userId, projectId, fileName), encoding); } catch (UnsupportedEncodingException e) { throw CrashReport.createAndLogError(LOG, null, "Unsupported file content encoding, " + collectProjectErrorInfo(userId, projectId, fileName), e); } } @Override public void recordCorruption(String userId, long projectId, String fileId, String message) { Objectify datastore = ObjectifyService.begin(); final CorruptionRecord data = new CorruptionRecord(); data.timestamp = new Date(); data.id = null; data.userId = userId; data.fileId = fileId; data.projectId = projectId; data.message = message; try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { datastore.put(data); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } @Override public byte[] downloadRawFile(final String userId, final long projectId, final String fileName) { if (!getProjects(userId).contains(projectId)) { throw CrashReport.createAndLogError(LOG, null, collectUserProjectErrorInfo(userId, projectId), new UnauthorizedAccessException(userId, projectId, null)); } final Result<byte[]> result = new Result<byte[]>(); final Result<FileData> fd = new Result<FileData>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName); fd.t = (FileData) memcache.get(fileKey.getString()); if (fd.t == null) { fd.t = datastore.find(fileKey); } } }, false); // Transaction not needed } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } // read the blob/GCS File outside of the job FileData fileData = fd.t; if (fileData != null) { if (fileData.isGCS) { // It's in the Cloud Store try { int count; boolean npfHappened = false; boolean recovered = false; for (count = 0; count < 5; count++) { GcsFilename gcsFileName = new GcsFilename(GCS_BUCKET_NAME, fileData.gcsName); int bytesRead = 0; int fileSize = 0; ByteBuffer resultBuffer; try { fileSize = (int) gcsService.getMetadata(gcsFileName).getLength(); resultBuffer = ByteBuffer.allocate(fileSize); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0); try { while (bytesRead < fileSize) { bytesRead += readChannel.read(resultBuffer); if (bytesRead < fileSize) { LOG.log(Level.INFO, "readChannel: bytesRead = " + bytesRead + " fileSize = " + fileSize); } } recovered = true; result.t = resultBuffer.array(); break; // We got the data, break out of the loop! } finally { readChannel.close(); } } catch (NullPointerException e) { // This happens if the object in GCS is non-existent, which would happen // when people uploaded a zero length object. As of this change, we now // store zero length objects into GCS, but there are plenty of older objects // that are missing in GCS. LOG.log(Level.WARNING, "downloadrawfile: NPF recorded for " + fileData.gcsName); npfHappened = true; resultBuffer = ByteBuffer.allocate(0); result.t = resultBuffer.array(); } } // report out on how things went above if (npfHappened) { // We lost at least once if (recovered) { LOG.log(Level.WARNING, "recovered from NPF in downloadrawfile filename = " + fileData.gcsName + " count = " + count); } else { LOG.log(Level.WARNING, "FATAL NPF in downloadrawfile filename = " + fileData.gcsName); } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else if (fileData.isBlob) { try { result.t = getBlobstoreBytes(fileData.blobstorePath); } catch (BlobReadException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else { if (fileData.content == null) { result.t = new byte[0]; } else { result.t = fileData.content; } } } else { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), new FileNotFoundException("No data for " + fileName)); } return result.t; } // Note: this must be called outside of any transaction, since getBlobKey() // uses the current transaction and it will most likely have the wrong // entity group! private byte[] getBlobstoreBytes(String blobstorePath) throws BlobReadException { AppEngineFile blobstoreFile = new AppEngineFile(blobstorePath); BlobKey blobKey = fileService.getBlobKey(blobstoreFile); if (blobKey == null) { throw new BlobReadException("getBlobKey() returned null for " + blobstorePath); } try { InputStream blobInputStream = new BlobstoreInputStream(blobKey); return ByteStreams.toByteArray(blobInputStream); } catch (IOException e) { throw new BlobReadException(e, "Error trying to read blob from " + blobstorePath + ", blobkey = " + blobKey); } } /** * Exports project files as a zip archive * @param userId a user Id (the request is made on behalf of this user) * @param projectId project ID * @param includeProjectHistory whether or not to include the project history * @param includeAndroidKeystore whether or not to include the Android keystore * @param zipName the name of the zip file, if a specific one is desired * @return project with the content as requested by params. */ @Override public ProjectSourceZip exportProjectSourceZip(final String userId, final long projectId, final boolean includeProjectHistory, final boolean includeAndroidKeystore, @Nullable String zipName, final boolean fatalError) throws IOException { final Result<Integer> fileCount = new Result<Integer>(); fileCount.t = 0; final Result<String> projectHistory = new Result<String>(); projectHistory.t = null; // We collect up all the file data for the project in a transaction but // then we read the data and write the zip file outside of the transaction // to avoid problems reading blobs in a transaction with the wrong // entity group. final List<FileData> fileData = new ArrayList<FileData>(); final Result<String> projectName = new Result<String>(); projectName.t = null; String fileName = null; ByteArrayOutputStream zipFile = new ByteArrayOutputStream(); final ZipOutputStream out = new ZipOutputStream(zipFile); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { Key<ProjectData> projectKey = projectKey(projectId); boolean foundFiles = false; for (FileData fd : datastore.query(FileData.class).ancestor(projectKey)) { String fileName = fd.fileName; if (fd.role.equals(FileData.RoleEnum.SOURCE)) { if (fileName.equals(FileExporter.REMIX_INFORMATION_FILE_PATH)) { // Skip legacy remix history files that were previous stored with the project continue; } fileData.add(fd); foundFiles = true; } } if (foundFiles) { ProjectData pd = datastore.find(projectKey); projectName.t = pd.name; if (includeProjectHistory && !Strings.isNullOrEmpty(pd.history)) { projectHistory.t = pd.history; } } } }, true); // Process the file contents outside of the job since we can't read // blobs in the job. for (FileData fd : fileData) { fileName = fd.fileName; byte[] data = null; if (fd.isBlob) { try { data = getBlobstoreBytes(fd.blobstorePath); } catch (BlobReadException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else if (fd.isGCS) { try { int count; boolean npfHappened = false; boolean recovered = false; for (count = 0; count < 5; count++) { GcsFilename gcsFileName = new GcsFilename(GCS_BUCKET_NAME, fd.gcsName); int bytesRead = 0; int fileSize = 0; ByteBuffer resultBuffer; try { fileSize = (int) gcsService.getMetadata(gcsFileName).getLength(); resultBuffer = ByteBuffer.allocate(fileSize); GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0); try { while (bytesRead < fileSize) { bytesRead += readChannel.read(resultBuffer); if (bytesRead < fileSize) { LOG.log(Level.INFO, "readChannel: bytesRead = " + bytesRead + " fileSize = " + fileSize); } } recovered = true; data = resultBuffer.array(); break; // We got the data, break out of the loop! } finally { readChannel.close(); } } catch (NullPointerException e) { // This happens if the object in GCS is non-existent, which would happen // when people uploaded a zero length object. As of this change, we now // store zero length objects into GCS, but there are plenty of older objects // that are missing in GCS. LOG.log(Level.WARNING, "exportProjectFile: NPF recorded for " + fd.gcsName); npfHappened = true; resultBuffer = ByteBuffer.allocate(0); data = resultBuffer.array(); } } // report out on how things went above if (npfHappened) { // We lost at least once if (recovered) { LOG.log(Level.WARNING, "recovered from NPF in exportProjectFile filename = " + fd.gcsName + " count = " + count); } else { LOG.log(Level.WARNING, "FATAL NPF in exportProjectFile filename = " + fd.gcsName); if (fatalError) { throw new IOException("FATAL Error reading file from GCS filename = " + fd.gcsName); } } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); } } else { data = fd.content; } if (data == null) { // This happens if file creation is interrupted data = new byte[0]; } out.putNextEntry(new ZipEntry(fileName)); out.write(data, 0, data.length); out.closeEntry(); fileCount.t++; } if (projectHistory.t != null) { byte[] data = projectHistory.t.getBytes(StorageUtil.DEFAULT_CHARSET); out.putNextEntry(new ZipEntry(FileExporter.REMIX_INFORMATION_FILE_PATH)); out.write(data, 0, data.length); out.closeEntry(); fileCount.t++; } } catch (ObjectifyException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } catch (RuntimeException e) { CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, fileName), e); throw new IOException("Reflecting exception for userid " + userId + " projectId " + projectId + ", original exception " + e.getMessage()); } if (fileCount.t == 0) { // can't close out since will get a ZipException due to the lack of files throw new IllegalArgumentException("No files to download"); } if (includeAndroidKeystore) { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { try { Key<UserData> userKey = userKey(userId); for (UserFileData ufd : datastore.query(UserFileData.class).ancestor(userKey)) { if (ufd.fileName.equals(StorageUtil.ANDROID_KEYSTORE_FILENAME) && (ufd.content.length > 0)) { out.putNextEntry(new ZipEntry(StorageUtil.ANDROID_KEYSTORE_FILENAME)); out.write(ufd.content, 0, ufd.content.length); out.closeEntry(); fileCount.t++; } } } catch (IOException e) { throw CrashReport.createAndLogError(LOG, null, collectProjectErrorInfo(userId, projectId, StorageUtil.ANDROID_KEYSTORE_FILENAME), e); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e); } } out.close(); if (zipName == null) { zipName = projectName.t + ".wai"; } ProjectSourceZip projectSourceZip = new ProjectSourceZip(zipName, zipFile.toByteArray(), fileCount.t); projectSourceZip.setMetadata(projectName.t); return projectSourceZip; } @Override public Motd getCurrentMotd() { final Result<Motd> motd = new Result<Motd>(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { MotdData motdData = datastore.find(MotdData.class, MOTD_ID); if (motdData != null) { // it shouldn't be! motd.t = new Motd(motdData.id, motdData.caption, motdData.content); } else { motd.t = new Motd(MOTD_ID, "Oops, no message of the day!", null); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } return motd.t; } @Override public String findUserByEmail(final String email) throws NoSuchElementException { Objectify datastore = ObjectifyService.begin(); // note: if there are multiple users with the same email we'll only // get the first one. we don't expect this to happen UserData userData = datastore.query(UserData.class).filter("email", email).get(); if (userData == null) { throw new NoSuchElementException("Couldn't find a user with email " + email); } return userData.id; } @Override public String findIpAddressByKey(final String key) { Objectify datastore = ObjectifyService.begin(); RendezvousData data = datastore.query(RendezvousData.class).filter("key", key).get(); if (data == null) { return null; } else { return data.ipAddress; } } @Override public void storeIpAddressByKey(final String key, final String ipAddress) { Objectify datastore = ObjectifyService.begin(); final RendezvousData data = datastore.query(RendezvousData.class).filter("key", key).get(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { RendezvousData new_data = null; if (data == null) { new_data = new RendezvousData(); new_data.id = null; new_data.key = key; new_data.ipAddress = ipAddress; new_data.used = new Date(); // So we can cleanup old entries datastore.put(new_data); } else { new_data = data; new_data.ipAddress = ipAddress; new_data.used = new Date(); datastore.put(new_data); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } @Override public boolean checkWhiteList(String email) { Objectify datastore = ObjectifyService.begin(); WhiteListData data = datastore.query(WhiteListData.class).filter("emailLower", email.toLowerCase()).get(); if (data == null) return false; return true; } @Override public void storeFeedback(final String notes, final String foundIn, final String faultData, final String comments, final String datestamp, final String email, final String projectId) { Objectify datastore = ObjectifyService.begin(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { FeedbackData data = new FeedbackData(); data.id = null; data.notes = notes; data.foundIn = foundIn; data.faultData = faultData; data.comments = comments; data.datestamp = datestamp; data.email = email; data.projectId = projectId; datastore.put(data); } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } private void initMotd() { try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { MotdData motdData = datastore.find(MotdData.class, MOTD_ID); if (motdData == null) { MotdData firstMotd = new MotdData(); firstMotd.id = MOTD_ID; firstMotd.caption = "Hello!"; firstMotd.content = "Welcome to the experimental App Inventor system from MIT. " + "This is still a prototype. It would be a good idea to frequently back up " + "your projects to local storage."; datastore.put(firstMotd); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, "Initing MOTD", e); } } // Nonce Management Routines. // The Nonce is used to map to userId and ProjectId and is used // for non-authenticated access to a built APK file. public void storeNonce(final String nonceValue, final String userId, final long projectId) { Objectify datastore = ObjectifyService.begin(); final NonceData data = datastore.query(NonceData.class).filter("nonce", nonceValue).get(); try { runJobWithRetries(new JobRetryHelper() { @Override public void run(Objectify datastore) { NonceData new_data = null; if (data == null) { new_data = new NonceData(); new_data.id = null; new_data.nonce = nonceValue; new_data.userId = userId; new_data.projectId = projectId; new_data.timestamp = new Date(); datastore.put(new_data); } else { new_data = data; new_data.userId = userId; new_data.projectId = projectId; new_data.timestamp = new Date(); datastore.put(new_data); } } }, true); } catch (ObjectifyException e) { throw CrashReport.createAndLogError(LOG, null, null, e); } } public Nonce getNoncebyValue(String nonceValue) { Objectify datastore = ObjectifyService.begin(); NonceData data = datastore.query(NonceData.class).filter("nonce", nonceValue).get(); if (data == null) { return null; } else { return (new Nonce(nonceValue, data.userId, data.projectId, data.timestamp)); } } // Cleanup expired nonces which are older then 3 hours. Normal Nonce lifetime // is 2 hours. So for one hour they persist and return "link expired" instead of // "link not found" (after the object itself is removed). // // Note: We only process up to 10 here to limit the amount of processing time // we spend here. If we remove up to 10 for each call, we should keep ahead // of the growing garbage. // // Also note that we are not running in a transaction, there is no need public void cleanupNonces() { Objectify datastore = ObjectifyService.begin(); // We do not use runJobWithRetries because if we fail here, we will be // called again the next time someone attempts to download a built APK // via a QR Code. try { datastore.delete(datastore.query(NonceData.class) .filter("timestamp <", new Date((new Date()).getTime() - 3600*3*1000L)) .limit(10).fetchKeys()); } catch (Exception ex) { LOG.log(Level.WARNING, "Exception during cleanupNonces", ex); } } // Create a name for a blob from a project id and file name. This is mostly // to help with debugging and viewing the blobstore via the admin console. // We don't currently use these blob names anywhere else. private String makeBlobName(long projectId, String fileName) { return projectId + "/" + fileName; } private Key<UserData> userKey(String userId) { return new Key<UserData>(UserData.class, userId); } private Key<ProjectData> projectKey(long projectId) { return new Key<ProjectData>(ProjectData.class, projectId); } private Key<UserProjectData> userProjectKey(Key<UserData> userKey, long projectId) { return new Key<UserProjectData>(userKey, UserProjectData.class, projectId); } private Key<UserFileData> userFileKey(Key<UserData> userKey, String fileName) { return new Key<UserFileData>(userKey, UserFileData.class, fileName); } private Key<FileData> projectFileKey(Key<ProjectData> projectKey, String fileName) { return new Key<FileData>(projectKey, FileData.class, fileName); } /** * Call job.run() if we get a {@link java.util.ConcurrentModificationException} * or {@link com.google.appinventor.server.storage.ObjectifyException} * we will retry the job (at most {@code MAX_JOB_RETRIES times}). * Any other exception will cause the job to fail immediately. * If useTransaction is true, create a transaction and run the job in * that transaction. If the job terminates normally, commit the transaction. * * Note: Originally we ran all jobs in a transaction. However in * many places there is no need for a transaction because * there is nothing to rollback on failure. Using transactions * has a performance implication, it disables Objectify's * ability to use memcache. * * @param job * @param useTransaction -- Set to true to run job in a transaction * @throws ObjectifyException */ @VisibleForTesting void runJobWithRetries(JobRetryHelper job, boolean useTransaction) throws ObjectifyException { int tries = 0; while (tries <= MAX_JOB_RETRIES) { Objectify datastore; if (useTransaction) { datastore = ObjectifyService.beginTransaction(); } else { datastore = ObjectifyService.begin(); } try { job.run(datastore); if (useTransaction) { datastore.getTxn().commit(); } break; } catch (ConcurrentModificationException ex) { job.onNonFatalError(); LOG.log(Level.WARNING, "Optimistic concurrency failure", ex); } catch (ObjectifyException oe) { String message = oe.getMessage(); if (message != null && message.startsWith("Blocks")) { // This one is fatal! throw oe; } // maybe this should be a fatal error? I think the only thing // that creates this exception (other than this method) is uploadToBlobstore job.onNonFatalError(); } finally { if (useTransaction && datastore.getTxn().isActive()) { try { datastore.getTxn().rollback(); } catch (RuntimeException e) { LOG.log(Level.WARNING, "Transaction rollback failed", e); } } } tries++; } if (tries > MAX_JOB_RETRIES) { throw new ObjectifyException("Couldn't commit job after max retries."); } } private static String collectUserErrorInfo(final String userId) { return collectUserErrorInfo(userId, CrashReport.NOT_AVAILABLE); } private static String collectUserErrorInfo(final String userId, String fileName) { return "user=" + userId + ", file=" + fileName; } private static String collectProjectErrorInfo(final String userId, final long projectId, final String fileName) { return "user=" + userId + ", project=" + projectId + ", file=" + fileName; } private static String collectUserProjectErrorInfo(final String userId, final long projectId) { return "user=" + userId + ", project=" + projectId; } // ********* METHODS BELOW ARE ONLY FOR TESTING ********* @VisibleForTesting void createRawUserFile(String userId, String fileName, byte[] content) { Objectify datastore = ObjectifyService.begin(); UserFileData ufd = createUserFile(datastore, userKey(userId), fileName); if (ufd != null) { ufd.content = content; datastore.put(ufd); } } @VisibleForTesting boolean isBlobFile(long projectId, String fileName) { Objectify datastore = ObjectifyService.begin(); Key<FileData> fileKey = projectFileKey(projectKey(projectId), fileName); FileData fd; fd = (FileData) memcache.get(fileKey.getString()); if (fd == null) { fd = datastore.find(fileKey); } if (fd != null) { return fd.isBlob; } else { return false; } } @VisibleForTesting ProjectData getProject(long projectId) { return ObjectifyService.begin().find(projectKey(projectId)); } // Return time in ISO_8660 format private static String formattedTime() { java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); return formatter.format(new java.util.Date()); } // We are called when our caller detects we are about to write a trivial (empty) // workspace. We check to see if previously the workspace was non-trivial and // if so, throw the BlocksTruncatedException. This will be passed through the RPC // layer to the client code which will put up a dialog box for the user to review // See Ode.java for more information private void checkForBlocksTruncation(FileData fd) throws ObjectifyException { if (fd.isBlob || fd.isGCS || fd.content.length > 120) throw new ObjectifyException("BlocksTruncated"); // Hack // I'm avoiding having to modify every use of runJobWithRetries to handle a new // exception, so we use this dodge. } }
Made pickup change to ObjectifyStorageIO.java
appinventor/appengine/src/com/google/appinventor/server/storage/ObjectifyStorageIo.java
Made pickup change to ObjectifyStorageIO.java
<ide><path>ppinventor/appengine/src/com/google/appinventor/server/storage/ObjectifyStorageIo.java <ide> fileCount.t++; <ide> } <ide> <del> // Add the bootstrap library to the zip output. <del> String bootstrapFileName = importFile.getFileName(); <del> byte[] bootstrapData = importFile.getContent(); <del> <del> if (bootstrapData == null) { <del> bootstrapData = new byte[0]; <add> if (importFile != null) { // Add the bootstrap library to the zip output. <add> String bootstrapFileName = importFile.getFileName(); <add> byte[] bootstrapData = importFile.getContent(); <add> <add> if (bootstrapData == null) { <add> bootstrapData = new byte[0]; <add> } <add> else { <add> out.putNextEntry(new ZipEntry(bootstrapFileName)); <add> } <add> <add> out.write(bootstrapData, 0, bootstrapData.length); <add> out.closeEntry(); <add> fileCount.t++; <ide> } <del> else { <del> out.putNextEntry(new ZipEntry(bootstrapFileName)); <del> } <del> <del> out.write(bootstrapData, 0, bootstrapData.length); <del> out.closeEntry(); <del> fileCount.t++; <ide> <ide> } catch (ObjectifyException e) { <ide> CrashReport.createAndLogError(LOG, null,
Java
apache-2.0
e60bd4b5abd7e6f01966c1b356a931a8ea13c1be
0
d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor
package com.netflix.conductor.dao.es6rest.dao; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.core.config.Configuration; import com.netflix.conductor.dao.MetadataDAO; import com.netflix.conductor.dao.MetricsDAO; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.script.Script; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.avg.ParsedAvg; import org.elasticsearch.search.aggregations.metrics.cardinality.ParsedCardinality; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; /** * @author Oleksiy Lysak */ public class Elasticsearch6RestMetricsDAO extends Elasticsearch6RestAbstractDAO implements MetricsDAO { private static final Logger logger = LoggerFactory.getLogger(Elasticsearch6RestMetricsDAO.class); private static final List<String> WORKFLOW_TODAY_STATUSES = Arrays.asList( Workflow.WorkflowStatus.COMPLETED.name(), Workflow.WorkflowStatus.CANCELLED.name(), Workflow.WorkflowStatus.TIMED_OUT.name(), Workflow.WorkflowStatus.RUNNING.name(), Workflow.WorkflowStatus.FAILED.name() ); private static final List<String> WORKFLOW_OVERALL_STATUSES = Arrays.asList( Workflow.WorkflowStatus.COMPLETED.name(), Workflow.WorkflowStatus.CANCELLED.name(), Workflow.WorkflowStatus.TIMED_OUT.name(), Workflow.WorkflowStatus.FAILED.name() ); private static final List<String> TASK_TYPES = Arrays.asList( "WAIT", "HTTP", "BATCH"); private static final List<String> TASK_STATUSES = Arrays.asList( Task.Status.IN_PROGRESS.name(), Task.Status.COMPLETED.name(), Task.Status.FAILED.name() ); private static final List<String> EVENT_STATUSES = Arrays.asList( EventExecution.Status.COMPLETED.name(), EventExecution.Status.SKIPPED.name(), EventExecution.Status.FAILED.name() ); private static final List<String> SINK_SUBJECTS = Arrays.asList( "deluxe.conductor.deluxeone.compliance.workflow.update", "deluxe.conductor.deluxeone.workflow.update", "deluxe.conductor.workflow.update" ); private static final List<String> WORKFLOWS = Arrays.asList( "deluxe.dependencygraph.conformancegroup.delivery.process", // Conformance Group "deluxe.dependencygraph.assembly.conformancegroup.process", // Sherlock V1 Assembly Conformance "deluxe.dependencygraph.sourcewait.process", // Sherlock V2 Sourcewait "deluxe.dependencygraph.execute.process", // Sherlock V2 Execute "deluxe.deluxeone.sky.compliance.process", // Sky Compliance "deluxe.delivery.itune.process" // iTune ); private static final AvgAggregationBuilder AVERAGE_EXEC_TIME = AggregationBuilders.avg("aggAvg") .script(new Script("doc['endTime'].value != null && doc['endTime'].value > 0 " + " && doc['startTime'].value != null && doc['startTime'].value > 0 " + " ? doc['endTime'].value - doc['startTime'].value : 0")); private static final AvgAggregationBuilder EVENT_AVERAGE_EXEC_TIME = AggregationBuilders.avg("aggAvg") .script(new Script("doc['processed'].value != null && doc['processed'].value > 0 " + " && doc['created'].value != null && doc['created'].value > 0 " + " ? doc['processed'].value - doc['created'].value : 0")); private static final AvgAggregationBuilder EVENT_AVERAGE_WAIT_TIME = AggregationBuilders.avg("aggAvg") .script(new Script("doc['received'].value != null && doc['received'].value > 0 " + " && doc['created'].value != null && doc['created'].value > 0 " + " ? doc['created'].value - doc['received'].value : 0")); private static final String VERSION = "\\.\\d+\\.\\d+"; // covers '.X.Y' where X and Y any number/digit private static final String PREFIX = "deluxe.conductor"; private final MetadataDAO metadataDAO; private final String workflowIndex; private final String deciderIndex; private final String eventExecIndex; private final String eventPubsIndex; private final String taskIndex; @Inject public Elasticsearch6RestMetricsDAO(RestHighLevelClient client, Configuration config, ObjectMapper mapper, MetadataDAO metadataDAO) { super(client, config, mapper, "metrics"); this.metadataDAO = metadataDAO; this.workflowIndex = String.format("conductor.runtime.%s.workflow", config.getStack()); this.deciderIndex = String.format("conductor.queues.%s._deciderqueue", config.getStack()); this.eventExecIndex = String.format("conductor.runtime.%s.event_execution", config.getStack()); this.eventPubsIndex = String.format("conductor.runtime.%s.event_published", config.getStack()); this.taskIndex = String.format("conductor.runtime.%s.task", config.getStack()); } @Override public Map<String, Object> getMetrics() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Main workflow list Set<String> fullNames = getMainWorkflows(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today + overall for (boolean today : Arrays.asList(true, false)) { // then per each short name for (String shortName : WORKFLOWS) { // Filter workflow definitions to have current short related only Set<String> filtered = fullNames.stream().filter(type -> type.startsWith(shortName)).collect(Collectors.toSet()); // Workflow counter per short name futures.add(pool.submit(() -> workflowCounters(metrics, today, shortName, filtered))); // Workflow average per short name futures.add(pool.submit(() -> workflowAverage(metrics, today, shortName, filtered))); } // Task type/refName/status counter futures.add(pool.submit(() -> taskTypeRefNameCounters(metrics, today))); // Task type/refName average futures.add(pool.submit(() -> taskTypeRefNameAverage(metrics, today))); // Event received futures.add(pool.submit(() -> eventReceived(metrics, today))); // Event published futures.add(pool.submit(() -> eventPublished(metrics, today))); // Event execution futures.add(pool.submit(() -> eventExecAverage(metrics, today))); // Event wait futures.add(pool.submit(() -> eventWaitAverage(metrics, today))); } // Admin counters futures.add(pool.submit(() -> adminCounters(metrics))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getAdminCounters() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); adminCounters(metrics); return new HashMap<>(metrics); } @Override public Map<String, Object> getEventReceived() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventReceived(metrics, true))); // overall futures.add(pool.submit(() -> eventReceived(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getEventPublished() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventPublished(metrics, true))); // overall futures.add(pool.submit(() -> eventPublished(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getEventExecAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventExecAverage(metrics, true))); // overall futures.add(pool.submit(() -> eventExecAverage(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getEventWaitAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventWaitAverage(metrics, true))); // overall futures.add(pool.submit(() -> eventWaitAverage(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getTaskCounters() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> taskTypeRefNameCounters(metrics, true))); // overall futures.add(pool.submit(() -> taskTypeRefNameCounters(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getTaskAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> taskTypeRefNameAverage(metrics, true))); // overall futures.add(pool.submit(() -> taskTypeRefNameAverage(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getWorkflowCounters() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Main workflow list Set<String> fullNames = getMainWorkflows(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today + overall for (boolean today : Arrays.asList(true, false)) { // then per each short name for (String shortName : WORKFLOWS) { // Filter workflow definitions to have current short related only Set<String> filtered = fullNames.stream().filter(type -> type.startsWith(shortName)).collect(Collectors.toSet()); // Workflow counter per short name futures.add(pool.submit(() -> workflowCounters(metrics, today, shortName, filtered))); } } // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getWorkflowAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Main workflow list Set<String> fullNames = getMainWorkflows(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today + overall for (boolean today : Arrays.asList(true, false)) { // then per each short name for (String shortName : WORKFLOWS) { // Filter workflow definitions to have current short related only Set<String> filtered = fullNames.stream().filter(type -> type.startsWith(shortName)).collect(Collectors.toSet()); // Workflow average per short name futures.add(pool.submit(() -> workflowAverage(metrics, today, shortName, filtered))); } } // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } private void adminCounters(Map<String, AtomicLong> map) { Set<EventHandler> handlers = getHandlers(); // number of active handlers initMetric(map, String.format("%s.admin.active_handlers", PREFIX)).set(handlers.size()); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.fetchSource(false); sourceBuilder.query(QueryBuilders.matchAllQuery()); sourceBuilder.size(0); SearchRequest searchRequest = new SearchRequest(deciderIndex); searchRequest.source(sourceBuilder); SearchResponse response = search(searchRequest); // number of active handlers initMetric(map, String.format("%s.admin.decider_queue", PREFIX)).set(response.getHits().totalHits); } private void eventPublished(Map<String, AtomicLong> map, boolean today) { for (String subject : SINK_SUBJECTS) { initMetric(map, String.format("%s.event_published%s.%s", PREFIX, toLabel(today), subject)); } QueryBuilder mainQuery = QueryBuilders.termsQuery("subject", SINK_SUBJECTS); if (today) { mainQuery = QueryBuilders.boolQuery().must(mainQuery).must(getStartTimeQuery("published")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject") .subAggregation(AggregationBuilders .cardinality("aggCountPerSubject") .field("id") ); SearchRequest searchRequest = new SearchRequest(eventPubsIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); // Total per subject ParsedCardinality countPerSubject = subjectBucket.getAggregations().get("aggCountPerSubject"); String metricName = String.format("%s.event_published%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set(countPerSubject.getValue()); } } private void eventReceived(Map<String, AtomicLong> map, boolean today) { Set<String> subjects = getSubjects(); for (String subject : subjects) { initMetric(map, String.format("%s.event_received%s.%s", PREFIX, toLabel(today), subject)); for (String status : EVENT_STATUSES) { initMetric(map, String.format("%s.event_%s%s.%s", PREFIX, status.toLowerCase(), toLabel(today), subject)); } } QueryBuilder typeQuery = QueryBuilders.termsQuery("subject.keyword", subjects); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", EVENT_STATUSES); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery("received")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject.keyword") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .cardinality("aggCountPerSubject") .field("messageId") ) .subAggregation(AggregationBuilders .terms("aggStatus") .field("status") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .cardinality("aggCountPerStatus") .field("messageId") ) ); SearchRequest searchRequest = new SearchRequest(eventExecIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); // Total per subject ParsedCardinality countPerSubject = subjectBucket.getAggregations().get("aggCountPerSubject"); String metricName = String.format("%s.event_received%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set(countPerSubject.getValue()); // Per each subject/status ParsedStringTerms aggStatus = subjectBucket.getAggregations().get("aggStatus"); for (Object itemStatus : aggStatus.getBuckets()) { ParsedStringTerms.ParsedBucket statusBucket = (ParsedStringTerms.ParsedBucket) itemStatus; String statusName = statusBucket.getKeyAsString().toLowerCase(); // Per subject/status ParsedCardinality aggCountPerStatus = statusBucket.getAggregations().get("aggCountPerStatus"); metricName = String.format("%s.event_%s%s.%s", PREFIX, statusName, toLabel(today), subjectName); map.get(metricName).addAndGet(aggCountPerStatus.getValue()); } } } private void eventExecAverage(Map<String, AtomicLong> map, boolean today) { Set<String> subjects = getSubjects(); for (String subject : subjects) { initMetric(map, String.format("%s.avg_event_exec_msec%s.%s", PREFIX, toLabel(today), subject)); } QueryBuilder typeQuery = QueryBuilders.termsQuery("subject.keyword", subjects); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", Arrays.asList("COMPLETED", "FAILED")); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery("received")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject.keyword") .size(Integer.MAX_VALUE) .subAggregation(EVENT_AVERAGE_EXEC_TIME); SearchRequest searchRequest = new SearchRequest(eventExecIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); ParsedAvg aggAvg = subjectBucket.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_event_exec_msec%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set((long) avg); } } private void eventWaitAverage(Map<String, AtomicLong> map, boolean today) { Set<String> subjects = getSubjects(); for (String subject : subjects) { initMetric(map, String.format("%s.avg_event_wait_msec%s.%s", PREFIX, toLabel(today), subject)); } QueryBuilder typeQuery = QueryBuilders.termsQuery("subject.keyword", subjects); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", EVENT_STATUSES); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery("received")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject.keyword") .size(Integer.MAX_VALUE) .subAggregation(EVENT_AVERAGE_WAIT_TIME); SearchRequest searchRequest = new SearchRequest(eventExecIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); ParsedAvg aggAvg = subjectBucket.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_event_wait_msec%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set((long) avg); } } private void taskTypeRefNameCounters(Map<String, AtomicLong> map, boolean today) { QueryBuilder typeQuery = QueryBuilders.termsQuery("taskType", TASK_TYPES); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", TASK_STATUSES); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggTaskType") .field("taskType") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggRefName") .field("referenceTaskName") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggStatus") .field("status") .size(Integer.MAX_VALUE) ) ); SearchRequest searchRequest = new SearchRequest(taskIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggTaskType = response.getAggregations().get("aggTaskType"); for (Object itemType : aggTaskType.getBuckets()) { ParsedStringTerms.ParsedBucket typeBucket = (ParsedStringTerms.ParsedBucket) itemType; String typeName = typeBucket.getKeyAsString().toLowerCase(); ParsedStringTerms aggRefName = typeBucket.getAggregations().get("aggRefName"); for (Object itemName : aggRefName.getBuckets()) { ParsedStringTerms.ParsedBucket refBucket = (ParsedStringTerms.ParsedBucket) itemName; String refName = refBucket.getKeyAsString().toLowerCase(); // Init counters. Total per typeName/refName + today/non-today initMetric(map, String.format("%s.task_%s_%s", PREFIX, typeName, refName)); initMetric(map, String.format("%s.task_%s_%s_today", PREFIX, typeName, refName)); // Init counters. Per typeName/refName/status + today/non-today for (String status : TASK_STATUSES) { String statusName = status.toLowerCase(); initMetric(map, String.format("%s.task_%s_%s_%s", PREFIX, typeName, refName, statusName)); initMetric(map, String.format("%s.task_%s_%s_%s_today", PREFIX, typeName, refName, statusName)); } // Per each refName/status ParsedStringTerms aggStatus = refBucket.getAggregations().get("aggStatus"); for (Object itemStatus : aggStatus.getBuckets()) { ParsedStringTerms.ParsedBucket statusBucket = (ParsedStringTerms.ParsedBucket) itemStatus; String statusName = statusBucket.getKeyAsString().toLowerCase(); long docCount = statusBucket.getDocCount(); // Parent typeName + refName String metricName = String.format("%s.task_%s_%s%s", PREFIX, typeName, refName, toLabel(today)); map.get(metricName).addAndGet(docCount); // typeName + refName + status metricName = String.format("%s.task_%s_%s_%s%s", PREFIX, typeName, refName, statusName, toLabel(today)); map.get(metricName).addAndGet(docCount); } } } } private void taskTypeRefNameAverage(Map<String, AtomicLong> map, boolean today) { QueryBuilder typeQuery = QueryBuilders.termsQuery("taskType", TASK_TYPES); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", Task.Status.COMPLETED); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggTaskType") .field("taskType") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggRefName") .field("referenceTaskName") .size(Integer.MAX_VALUE) .subAggregation(AVERAGE_EXEC_TIME) ); SearchRequest searchRequest = new SearchRequest(taskIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggTaskType = response.getAggregations().get("aggTaskType"); for (Object item : aggTaskType.getBuckets()) { ParsedStringTerms.ParsedBucket typeBucket = (ParsedStringTerms.ParsedBucket) item; String typeName = typeBucket.getKeyAsString().toLowerCase(); ParsedStringTerms aggRefName = typeBucket.getAggregations().get("aggRefName"); for (Object item2 : aggRefName.getBuckets()) { ParsedStringTerms.ParsedBucket refBucket = (ParsedStringTerms.ParsedBucket) item2; String refName = refBucket.getKeyAsString().toLowerCase(); // Init both counters right away if any today/non-today returned initMetric(map, String.format("%s.avg_task_execution_msec.%s_%s", PREFIX, typeName, refName)); initMetric(map, String.format("%s.avg_task_execution_msec_today.%s_%s", PREFIX, typeName, refName)); // Per each refName/status ParsedAvg aggAvg = refBucket.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_task_execution_msec%s.%s_%s", PREFIX, toLabel(today), typeName, refName); map.put(metricName, new AtomicLong(Math.round(avg))); } } } private void workflowCounters(Map<String, AtomicLong> map, boolean today, String shortName, Set<String> filtered) { List<String> workflowStatuses = today ? WORKFLOW_TODAY_STATUSES : WORKFLOW_OVERALL_STATUSES; // Init counters initMetric(map, String.format("%s.workflow_started%s", PREFIX, toLabel(today))); // Counter name per status for (String status : workflowStatuses) { initMetric(map, String.format("%s.workflow_%s%s", PREFIX, status.toLowerCase(), toLabel(today))); } // Counter name per workflow type and status initMetric(map, String.format("%s.workflow_started%s.%s", PREFIX, toLabel(today), shortName)); for (String status : workflowStatuses) { String metricName = String.format("%s.workflow_%s%s.%s", PREFIX, status.toLowerCase(), toLabel(today), shortName); initMetric(map, metricName); } // Build the today/not-today query QueryBuilder typeQuery = QueryBuilders.termsQuery("workflowType", filtered); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", workflowStatuses); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } // Aggregation by workflow type and sub aggregation by workflow status TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggWorkflowType") .field("workflowType") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggStatus") .field("status") .size(Integer.MAX_VALUE) ); SearchRequest searchRequest = new SearchRequest(workflowIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggWorkflowType = response.getAggregations().get("aggWorkflowType"); for (Object item : aggWorkflowType.getBuckets()) { ParsedStringTerms.ParsedBucket typeBucket = (ParsedStringTerms.ParsedBucket) item; // Total started String metricName = String.format("%s.workflow_started%s", PREFIX, toLabel(today)); map.get(metricName).addAndGet(typeBucket.getDocCount()); // Started per workflow type metricName = String.format("%s.workflow_started%s.%s", PREFIX, toLabel(today), shortName); map.get(metricName).addAndGet(typeBucket.getDocCount()); // Per each workflow/status ParsedStringTerms aggStatus = typeBucket.getAggregations().get("aggStatus"); for (Object statusItem : aggStatus.getBuckets()) { ParsedStringTerms.ParsedBucket statusBucket = (ParsedStringTerms.ParsedBucket) statusItem; String statusName = statusBucket.getKeyAsString().toLowerCase(); long docCount = statusBucket.getDocCount(); // Counter name per status metricName = String.format("%s.workflow_%s%s", PREFIX, statusName, toLabel(today)); map.get(metricName).addAndGet(docCount); // Counter name per workflow type and status metricName = String.format("%s.workflow_%s%s.%s", PREFIX, statusName, toLabel(today), shortName); map.get(metricName).addAndGet(docCount); } } } private void workflowAverage(Map<String, AtomicLong> map, boolean today, String shortName, Set<String> filtered) { QueryBuilder typesQuery = QueryBuilders.termsQuery("workflowType", filtered); QueryBuilder statusQuery = QueryBuilders.termQuery("status", Workflow.WorkflowStatus.COMPLETED); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typesQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } SearchRequest searchRequest = new SearchRequest(workflowIndex); searchRequest.source(searchSourceBuilder(mainQuery, AVERAGE_EXEC_TIME)); SearchResponse response = search(searchRequest); ParsedAvg aggAvg = response.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_workflow_execution_sec%s.%s", PREFIX, toLabel(today), shortName); map.put(metricName, new AtomicLong(Math.round(avg / 1000))); } private SearchResponse search(SearchRequest request) { try { return client.search(request); } catch (IOException e) { logger.warn("search failed for " + request + " " + e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } } // Filters definitions excluding sub workflows and maintenance workflows private Set<String> getMainWorkflows() { return metadataDAO.findAll().stream() .filter(fullName -> WORKFLOWS.stream().anyMatch(shortName -> fullName.matches(shortName + VERSION))) .collect(Collectors.toSet()); } private Set<EventHandler> getHandlers() { return metadataDAO.getEventHandlers().stream() .filter(EventHandler::isActive).collect(Collectors.toSet()); } // Extracts subject name from each active handler private Set<String> getSubjects() { return getHandlers().stream() .map(eh -> eh.getEvent().split(":")[1]) // 0 - event bus, 1 - subject, 2 - queue .collect(Collectors.toSet()); } // Wait until all futures completed private void waitCompleted(List<Future<?>> futures) { for (Future<?> future : futures) { try { if (future != null) { future.get(); } } catch (Exception ex) { logger.error("Get future failed " + ex.getMessage(), ex); } } } private SearchSourceBuilder searchSourceBuilder(QueryBuilder query, AggregationBuilder aggregation) { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.aggregation(aggregation); sourceBuilder.fetchSource(false); sourceBuilder.query(query); sourceBuilder.size(0); return sourceBuilder; } private RangeQueryBuilder getStartTimeQuery() { return getStartTimeQuery("startTime"); } private RangeQueryBuilder getStartTimeQuery(String field) { TimeZone pst = TimeZone.getTimeZone("UTC"); Calendar calendar = new GregorianCalendar(); calendar.setTimeZone(pst); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return QueryBuilders.rangeQuery(field).gte(calendar.getTimeInMillis()); } private AtomicLong initMetric(Map<String, AtomicLong> map, String metricName) { return map.computeIfAbsent(metricName, s -> new AtomicLong(0)); } private String toLabel(boolean today) { return today ? "_today" : ""; } }
es6rest-persistence/src/main/java/com/netflix/conductor/dao/es6rest/dao/Elasticsearch6RestMetricsDAO.java
package com.netflix.conductor.dao.es6rest.dao; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.core.config.Configuration; import com.netflix.conductor.dao.MetadataDAO; import com.netflix.conductor.dao.MetricsDAO; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.script.Script; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.avg.ParsedAvg; import org.elasticsearch.search.aggregations.metrics.cardinality.ParsedCardinality; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; /** * @author Oleksiy Lysak */ public class Elasticsearch6RestMetricsDAO extends Elasticsearch6RestAbstractDAO implements MetricsDAO { private static final Logger logger = LoggerFactory.getLogger(Elasticsearch6RestMetricsDAO.class); private static final List<String> WORKFLOW_TODAY_STATUSES = Arrays.asList( Workflow.WorkflowStatus.COMPLETED.name(), Workflow.WorkflowStatus.CANCELLED.name(), Workflow.WorkflowStatus.TIMED_OUT.name(), Workflow.WorkflowStatus.RUNNING.name(), Workflow.WorkflowStatus.FAILED.name() ); private static final List<String> WORKFLOW_OVERALL_STATUSES = Arrays.asList( Workflow.WorkflowStatus.COMPLETED.name(), Workflow.WorkflowStatus.CANCELLED.name(), Workflow.WorkflowStatus.TIMED_OUT.name(), Workflow.WorkflowStatus.FAILED.name() ); private static final List<String> TASK_TYPES = Arrays.asList( "WAIT", "HTTP", "BATCH"); private static final List<String> TASK_STATUSES = Arrays.asList( Task.Status.IN_PROGRESS.name(), Task.Status.COMPLETED.name(), Task.Status.FAILED.name() ); private static final List<String> EVENT_STATUSES = Arrays.asList( EventExecution.Status.COMPLETED.name(), EventExecution.Status.SKIPPED.name(), EventExecution.Status.FAILED.name() ); private static final List<String> SINK_SUBJECTS = Arrays.asList( "deluxe.conductor.deluxeone.compliance.workflow.update", "deluxe.conductor.deluxeone.workflow.update", "deluxe.conductor.workflow.update" ); private static final List<String> WORKFLOWS = Arrays.asList( "deluxe.dependencygraph.conformancegroup.delivery.process", // Conformance Group "deluxe.dependencygraph.assembly.conformancegroup.process", // Sherlock V1 Assembly Conformance "deluxe.dependencygraph.sourcewait.process", // Sherlock V2 Sourcewait "deluxe.dependencygraph.execute.process", // Sherlock V2 Execute "deluxe.deluxeone.sky.compliance.process", // Sky Compliance "deluxe.delivery.itune.process" // iTune ); private static final AvgAggregationBuilder AVERAGE_EXEC_TIME = AggregationBuilders.avg("aggAvg") .script(new Script("doc['endTime'].value != null && doc['endTime'].value > 0 " + " && doc['startTime'].value != null && doc['startTime'].value > 0 " + " ? doc['endTime'].value - doc['startTime'].value : 0")); private static final AvgAggregationBuilder EVENT_AVERAGE_EXEC_TIME = AggregationBuilders.avg("aggAvg") .script(new Script("doc['processed'].value != null && doc['processed'].value > 0 " + " && doc['created'].value != null && doc['created'].value > 0 " + " ? doc['processed'].value - doc['created'].value : 0")); private static final AvgAggregationBuilder EVENT_AVERAGE_WAIT_TIME = AggregationBuilders.avg("aggAvg") .script(new Script("doc['received'].value != null && doc['received'].value > 0 " + " && doc['created'].value != null && doc['created'].value > 0 " + " ? doc['created'].value - doc['received'].value : 0")); private static final String VERSION = "\\.\\d+\\.\\d+"; // covers '.X.Y' where X and Y any number/digit private static final String PREFIX = "deluxe.conductor"; private final MetadataDAO metadataDAO; private final String workflowIndex; private final String deciderIndex; private final String eventExecIndex; private final String eventPubsIndex; private final String taskIndex; @Inject public Elasticsearch6RestMetricsDAO(RestHighLevelClient client, Configuration config, ObjectMapper mapper, MetadataDAO metadataDAO) { super(client, config, mapper, "metrics"); this.metadataDAO = metadataDAO; this.workflowIndex = String.format("conductor.runtime.%s.workflow", config.getStack()); this.deciderIndex = String.format("conductor.queues.%s._deciderqueue", config.getStack()); this.eventExecIndex = String.format("conductor.runtime.%s.event_execution", config.getStack()); this.eventPubsIndex = String.format("conductor.runtime.%s.event_published", config.getStack()); this.taskIndex = String.format("conductor.runtime.%s.task", config.getStack()); } @Override public Map<String, Object> getMetrics() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Main workflow list Set<String> fullNames = getMainWorkflows(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today + overall for (boolean today : Arrays.asList(true, false)) { // then per each short name for (String shortName : WORKFLOWS) { // Filter workflow definitions to have current short related only Set<String> filtered = fullNames.stream().filter(type -> type.startsWith(shortName)).collect(Collectors.toSet()); // Workflow counter per short name futures.add(pool.submit(() -> workflowCounters(metrics, today, shortName, filtered))); // Workflow average per short name futures.add(pool.submit(() -> workflowAverage(metrics, today, shortName, filtered))); } // Task type/refName/status counter futures.add(pool.submit(() -> taskTypeRefNameCounters(metrics, today))); // Task type/refName average futures.add(pool.submit(() -> taskTypeRefNameAverage(metrics, today))); // Event received futures.add(pool.submit(() -> eventReceived(metrics, today))); // Event published futures.add(pool.submit(() -> eventPublished(metrics, today))); // Event execution futures.add(pool.submit(() -> eventExecAverage(metrics, today))); // Event wait futures.add(pool.submit(() -> eventWaitAverage(metrics, today))); } // Admin counters futures.add(pool.submit(() -> adminCounters(metrics))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getAdminCounters() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); adminCounters(metrics); return new HashMap<>(metrics); } @Override public Map<String, Object> getEventReceived() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventReceived(metrics, true))); // overall futures.add(pool.submit(() -> eventReceived(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getEventPublished() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventPublished(metrics, true))); // overall futures.add(pool.submit(() -> eventPublished(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getEventExecAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventExecAverage(metrics, true))); // overall futures.add(pool.submit(() -> eventExecAverage(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getEventWaitAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> eventWaitAverage(metrics, true))); // overall futures.add(pool.submit(() -> eventWaitAverage(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getTaskCounters() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> taskTypeRefNameCounters(metrics, true))); // overall futures.add(pool.submit(() -> taskTypeRefNameCounters(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getTaskAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today futures.add(pool.submit(() -> taskTypeRefNameAverage(metrics, true))); // overall futures.add(pool.submit(() -> taskTypeRefNameAverage(metrics, false))); // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getWorkflowCounters() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Main workflow list Set<String> fullNames = getMainWorkflows(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today + overall for (boolean today : Arrays.asList(true, false)) { // then per each short name for (String shortName : WORKFLOWS) { // Filter workflow definitions to have current short related only Set<String> filtered = fullNames.stream().filter(type -> type.startsWith(shortName)).collect(Collectors.toSet()); // Workflow counter per short name futures.add(pool.submit(() -> workflowCounters(metrics, today, shortName, filtered))); } } // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } @Override public Map<String, Object> getWorkflowAverage() { Map<String, AtomicLong> metrics = new ConcurrentHashMap<>(); // Main workflow list Set<String> fullNames = getMainWorkflows(); // Using ExecutorService to process in parallel ExecutorService pool = Executors.newCachedThreadPool(); try { List<Future<?>> futures = new LinkedList<>(); // today + overall for (boolean today : Arrays.asList(true, false)) { // then per each short name for (String shortName : WORKFLOWS) { // Filter workflow definitions to have current short related only Set<String> filtered = fullNames.stream().filter(type -> type.startsWith(shortName)).collect(Collectors.toSet()); // Workflow average per short name futures.add(pool.submit(() -> workflowAverage(metrics, today, shortName, filtered))); } } // Wait until completed waitCompleted(futures); } finally { pool.shutdown(); } return new HashMap<>(metrics); } private void adminCounters(Map<String, AtomicLong> map) { Set<EventHandler> handlers = getHandlers(); // number of active handlers initMetric(map, String.format("%s.admin.active_handlers", PREFIX)).set(handlers.size()); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.fetchSource(false); sourceBuilder.query(QueryBuilders.matchAllQuery()); sourceBuilder.size(0); SearchRequest searchRequest = new SearchRequest(deciderIndex); searchRequest.source(sourceBuilder); SearchResponse response = search(searchRequest); // number of active handlers initMetric(map, String.format("%s.admin.decider_queue", PREFIX)).set(response.getHits().totalHits); } private void eventPublished(Map<String, AtomicLong> map, boolean today) { for (String subject : SINK_SUBJECTS) { initMetric(map, String.format("%s.event_published%s.%s", PREFIX, toLabel(today), subject)); } QueryBuilder mainQuery = QueryBuilders.termsQuery("subject.keyword", SINK_SUBJECTS); if (today) { mainQuery = QueryBuilders.boolQuery().must(mainQuery).must(getStartTimeQuery("published")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .cardinality("aggCountPerSubject") .field("id") ); SearchRequest searchRequest = new SearchRequest(eventPubsIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); // Total per subject ParsedCardinality countPerSubject = subjectBucket.getAggregations().get("aggCountPerSubject"); String metricName = String.format("%s.event_published%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set(countPerSubject.getValue()); } } private void eventReceived(Map<String, AtomicLong> map, boolean today) { Set<String> subjects = getSubjects(); for (String subject : subjects) { initMetric(map, String.format("%s.event_received%s.%s", PREFIX, toLabel(today), subject)); for (String status : EVENT_STATUSES) { initMetric(map, String.format("%s.event_%s%s.%s", PREFIX, status.toLowerCase(), toLabel(today), subject)); } } QueryBuilder typeQuery = QueryBuilders.termsQuery("subject.keyword", subjects); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", EVENT_STATUSES); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery("received")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject.keyword") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .cardinality("aggCountPerSubject") .field("messageId") ) .subAggregation(AggregationBuilders .terms("aggStatus") .field("status") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .cardinality("aggCountPerStatus") .field("messageId") ) ); SearchRequest searchRequest = new SearchRequest(eventExecIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); // Total per subject ParsedCardinality countPerSubject = subjectBucket.getAggregations().get("aggCountPerSubject"); String metricName = String.format("%s.event_received%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set(countPerSubject.getValue()); // Per each subject/status ParsedStringTerms aggStatus = subjectBucket.getAggregations().get("aggStatus"); for (Object itemStatus : aggStatus.getBuckets()) { ParsedStringTerms.ParsedBucket statusBucket = (ParsedStringTerms.ParsedBucket) itemStatus; String statusName = statusBucket.getKeyAsString().toLowerCase(); // Per subject/status ParsedCardinality aggCountPerStatus = statusBucket.getAggregations().get("aggCountPerStatus"); metricName = String.format("%s.event_%s%s.%s", PREFIX, statusName, toLabel(today), subjectName); map.get(metricName).addAndGet(aggCountPerStatus.getValue()); } } } private void eventExecAverage(Map<String, AtomicLong> map, boolean today) { Set<String> subjects = getSubjects(); for (String subject : subjects) { initMetric(map, String.format("%s.avg_event_exec_msec%s.%s", PREFIX, toLabel(today), subject)); } QueryBuilder typeQuery = QueryBuilders.termsQuery("subject.keyword", subjects); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", Arrays.asList("COMPLETED", "FAILED")); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery("received")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject.keyword") .size(Integer.MAX_VALUE) .subAggregation(EVENT_AVERAGE_EXEC_TIME); SearchRequest searchRequest = new SearchRequest(eventExecIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); ParsedAvg aggAvg = subjectBucket.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_event_exec_msec%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set((long) avg); } } private void eventWaitAverage(Map<String, AtomicLong> map, boolean today) { Set<String> subjects = getSubjects(); for (String subject : subjects) { initMetric(map, String.format("%s.avg_event_wait_msec%s.%s", PREFIX, toLabel(today), subject)); } QueryBuilder typeQuery = QueryBuilders.termsQuery("subject.keyword", subjects); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", EVENT_STATUSES); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery("received")); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggSubject") .field("subject.keyword") .size(Integer.MAX_VALUE) .subAggregation(EVENT_AVERAGE_WAIT_TIME); SearchRequest searchRequest = new SearchRequest(eventExecIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggSubject = response.getAggregations().get("aggSubject"); for (Object itemSubject : aggSubject.getBuckets()) { ParsedStringTerms.ParsedBucket subjectBucket = (ParsedStringTerms.ParsedBucket) itemSubject; String subjectName = subjectBucket.getKeyAsString().toLowerCase(); ParsedAvg aggAvg = subjectBucket.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_event_wait_msec%s.%s", PREFIX, toLabel(today), subjectName); map.get(metricName).set((long) avg); } } private void taskTypeRefNameCounters(Map<String, AtomicLong> map, boolean today) { QueryBuilder typeQuery = QueryBuilders.termsQuery("taskType", TASK_TYPES); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", TASK_STATUSES); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggTaskType") .field("taskType") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggRefName") .field("referenceTaskName") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggStatus") .field("status") .size(Integer.MAX_VALUE) ) ); SearchRequest searchRequest = new SearchRequest(taskIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggTaskType = response.getAggregations().get("aggTaskType"); for (Object itemType : aggTaskType.getBuckets()) { ParsedStringTerms.ParsedBucket typeBucket = (ParsedStringTerms.ParsedBucket) itemType; String typeName = typeBucket.getKeyAsString().toLowerCase(); ParsedStringTerms aggRefName = typeBucket.getAggregations().get("aggRefName"); for (Object itemName : aggRefName.getBuckets()) { ParsedStringTerms.ParsedBucket refBucket = (ParsedStringTerms.ParsedBucket) itemName; String refName = refBucket.getKeyAsString().toLowerCase(); // Init counters. Total per typeName/refName + today/non-today initMetric(map, String.format("%s.task_%s_%s", PREFIX, typeName, refName)); initMetric(map, String.format("%s.task_%s_%s_today", PREFIX, typeName, refName)); // Init counters. Per typeName/refName/status + today/non-today for (String status : TASK_STATUSES) { String statusName = status.toLowerCase(); initMetric(map, String.format("%s.task_%s_%s_%s", PREFIX, typeName, refName, statusName)); initMetric(map, String.format("%s.task_%s_%s_%s_today", PREFIX, typeName, refName, statusName)); } // Per each refName/status ParsedStringTerms aggStatus = refBucket.getAggregations().get("aggStatus"); for (Object itemStatus : aggStatus.getBuckets()) { ParsedStringTerms.ParsedBucket statusBucket = (ParsedStringTerms.ParsedBucket) itemStatus; String statusName = statusBucket.getKeyAsString().toLowerCase(); long docCount = statusBucket.getDocCount(); // Parent typeName + refName String metricName = String.format("%s.task_%s_%s%s", PREFIX, typeName, refName, toLabel(today)); map.get(metricName).addAndGet(docCount); // typeName + refName + status metricName = String.format("%s.task_%s_%s_%s%s", PREFIX, typeName, refName, statusName, toLabel(today)); map.get(metricName).addAndGet(docCount); } } } } private void taskTypeRefNameAverage(Map<String, AtomicLong> map, boolean today) { QueryBuilder typeQuery = QueryBuilders.termsQuery("taskType", TASK_TYPES); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", Task.Status.COMPLETED); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggTaskType") .field("taskType") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggRefName") .field("referenceTaskName") .size(Integer.MAX_VALUE) .subAggregation(AVERAGE_EXEC_TIME) ); SearchRequest searchRequest = new SearchRequest(taskIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggTaskType = response.getAggregations().get("aggTaskType"); for (Object item : aggTaskType.getBuckets()) { ParsedStringTerms.ParsedBucket typeBucket = (ParsedStringTerms.ParsedBucket) item; String typeName = typeBucket.getKeyAsString().toLowerCase(); ParsedStringTerms aggRefName = typeBucket.getAggregations().get("aggRefName"); for (Object item2 : aggRefName.getBuckets()) { ParsedStringTerms.ParsedBucket refBucket = (ParsedStringTerms.ParsedBucket) item2; String refName = refBucket.getKeyAsString().toLowerCase(); // Init both counters right away if any today/non-today returned initMetric(map, String.format("%s.avg_task_execution_msec.%s_%s", PREFIX, typeName, refName)); initMetric(map, String.format("%s.avg_task_execution_msec_today.%s_%s", PREFIX, typeName, refName)); // Per each refName/status ParsedAvg aggAvg = refBucket.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_task_execution_msec%s.%s_%s", PREFIX, toLabel(today), typeName, refName); map.put(metricName, new AtomicLong(Math.round(avg))); } } } private void workflowCounters(Map<String, AtomicLong> map, boolean today, String shortName, Set<String> filtered) { List<String> workflowStatuses = today ? WORKFLOW_TODAY_STATUSES : WORKFLOW_OVERALL_STATUSES; // Init counters initMetric(map, String.format("%s.workflow_started%s", PREFIX, toLabel(today))); // Counter name per status for (String status : workflowStatuses) { initMetric(map, String.format("%s.workflow_%s%s", PREFIX, status.toLowerCase(), toLabel(today))); } // Counter name per workflow type and status initMetric(map, String.format("%s.workflow_started%s.%s", PREFIX, toLabel(today), shortName)); for (String status : workflowStatuses) { String metricName = String.format("%s.workflow_%s%s.%s", PREFIX, status.toLowerCase(), toLabel(today), shortName); initMetric(map, metricName); } // Build the today/not-today query QueryBuilder typeQuery = QueryBuilders.termsQuery("workflowType", filtered); QueryBuilder statusQuery = QueryBuilders.termsQuery("status", workflowStatuses); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typeQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } // Aggregation by workflow type and sub aggregation by workflow status TermsAggregationBuilder aggregation = AggregationBuilders .terms("aggWorkflowType") .field("workflowType") .size(Integer.MAX_VALUE) .subAggregation(AggregationBuilders .terms("aggStatus") .field("status") .size(Integer.MAX_VALUE) ); SearchRequest searchRequest = new SearchRequest(workflowIndex); searchRequest.source(searchSourceBuilder(mainQuery, aggregation)); SearchResponse response = search(searchRequest); ParsedStringTerms aggWorkflowType = response.getAggregations().get("aggWorkflowType"); for (Object item : aggWorkflowType.getBuckets()) { ParsedStringTerms.ParsedBucket typeBucket = (ParsedStringTerms.ParsedBucket) item; // Total started String metricName = String.format("%s.workflow_started%s", PREFIX, toLabel(today)); map.get(metricName).addAndGet(typeBucket.getDocCount()); // Started per workflow type metricName = String.format("%s.workflow_started%s.%s", PREFIX, toLabel(today), shortName); map.get(metricName).addAndGet(typeBucket.getDocCount()); // Per each workflow/status ParsedStringTerms aggStatus = typeBucket.getAggregations().get("aggStatus"); for (Object statusItem : aggStatus.getBuckets()) { ParsedStringTerms.ParsedBucket statusBucket = (ParsedStringTerms.ParsedBucket) statusItem; String statusName = statusBucket.getKeyAsString().toLowerCase(); long docCount = statusBucket.getDocCount(); // Counter name per status metricName = String.format("%s.workflow_%s%s", PREFIX, statusName, toLabel(today)); map.get(metricName).addAndGet(docCount); // Counter name per workflow type and status metricName = String.format("%s.workflow_%s%s.%s", PREFIX, statusName, toLabel(today), shortName); map.get(metricName).addAndGet(docCount); } } } private void workflowAverage(Map<String, AtomicLong> map, boolean today, String shortName, Set<String> filtered) { QueryBuilder typesQuery = QueryBuilders.termsQuery("workflowType", filtered); QueryBuilder statusQuery = QueryBuilders.termQuery("status", Workflow.WorkflowStatus.COMPLETED); BoolQueryBuilder mainQuery = QueryBuilders.boolQuery().must(typesQuery).must(statusQuery); if (today) { mainQuery = mainQuery.must(getStartTimeQuery()); } SearchRequest searchRequest = new SearchRequest(workflowIndex); searchRequest.source(searchSourceBuilder(mainQuery, AVERAGE_EXEC_TIME)); SearchResponse response = search(searchRequest); ParsedAvg aggAvg = response.getAggregations().get("aggAvg"); double avg = Double.isInfinite(aggAvg.getValue()) ? 0 : aggAvg.getValue(); String metricName = String.format("%s.avg_workflow_execution_sec%s.%s", PREFIX, toLabel(today), shortName); map.put(metricName, new AtomicLong(Math.round(avg / 1000))); } private SearchResponse search(SearchRequest request) { try { return client.search(request); } catch (IOException e) { logger.warn("search failed for " + request + " " + e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } } // Filters definitions excluding sub workflows and maintenance workflows private Set<String> getMainWorkflows() { return metadataDAO.findAll().stream() .filter(fullName -> WORKFLOWS.stream().anyMatch(shortName -> fullName.matches(shortName + VERSION))) .collect(Collectors.toSet()); } private Set<EventHandler> getHandlers() { return metadataDAO.getEventHandlers().stream() .filter(EventHandler::isActive).collect(Collectors.toSet()); } // Extracts subject name from each active handler private Set<String> getSubjects() { return getHandlers().stream() .map(eh -> eh.getEvent().split(":")[1]) // 0 - event bus, 1 - subject, 2 - queue .collect(Collectors.toSet()); } // Wait until all futures completed private void waitCompleted(List<Future<?>> futures) { for (Future<?> future : futures) { try { if (future != null) { future.get(); } } catch (Exception ex) { logger.error("Get future failed " + ex.getMessage(), ex); } } } private SearchSourceBuilder searchSourceBuilder(QueryBuilder query, AggregationBuilder aggregation) { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.aggregation(aggregation); sourceBuilder.fetchSource(false); sourceBuilder.query(query); sourceBuilder.size(0); return sourceBuilder; } private RangeQueryBuilder getStartTimeQuery() { return getStartTimeQuery("startTime"); } private RangeQueryBuilder getStartTimeQuery(String field) { TimeZone pst = TimeZone.getTimeZone("UTC"); Calendar calendar = new GregorianCalendar(); calendar.setTimeZone(pst); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return QueryBuilders.rangeQuery(field).gte(calendar.getTimeInMillis()); } private AtomicLong initMetric(Map<String, AtomicLong> map, String metricName) { return map.computeIfAbsent(metricName, s -> new AtomicLong(0)); } private String toLabel(boolean today) { return today ? "_today" : ""; } }
ONECOND-1039 Get future failed java.lang.NullPointerException. Minor improvements
es6rest-persistence/src/main/java/com/netflix/conductor/dao/es6rest/dao/Elasticsearch6RestMetricsDAO.java
ONECOND-1039 Get future failed java.lang.NullPointerException. Minor improvements
<ide><path>s6rest-persistence/src/main/java/com/netflix/conductor/dao/es6rest/dao/Elasticsearch6RestMetricsDAO.java <ide> initMetric(map, String.format("%s.event_published%s.%s", PREFIX, toLabel(today), subject)); <ide> } <ide> <del> QueryBuilder mainQuery = QueryBuilders.termsQuery("subject.keyword", SINK_SUBJECTS); <add> QueryBuilder mainQuery = QueryBuilders.termsQuery("subject", SINK_SUBJECTS); <ide> if (today) { <ide> mainQuery = QueryBuilders.boolQuery().must(mainQuery).must(getStartTimeQuery("published")); <ide> } <ide> TermsAggregationBuilder aggregation = AggregationBuilders <ide> .terms("aggSubject") <ide> .field("subject") <del> .size(Integer.MAX_VALUE) <ide> .subAggregation(AggregationBuilders <ide> .cardinality("aggCountPerSubject") <ide> .field("id")
Java
bsd-3-clause
1804af2fcaef4933ac0d6452df20ec727620db37
0
ClemsonRSRG/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,ClemsonRSRG/RESOLVE,mikekab/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,mikekab/RESOLVE
/** * Utilities.java * --------------------------------- * Copyright (c) 2015 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.vcgeneration; /* * Libraries */ import edu.clemson.cs.r2jt.absyn.*; import edu.clemson.cs.r2jt.data.*; import edu.clemson.cs.r2jt.typeandpopulate.*; import edu.clemson.cs.r2jt.typeandpopulate.entry.*; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTFamily; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTGeneric; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; import edu.clemson.cs.r2jt.typeandpopulate.query.*; import edu.clemson.cs.r2jt.misc.SourceErrorException; import java.util.*; /** * TODO: Write a description of this module */ public class Utilities { // =========================================================== // Public Methods // =========================================================== // ----------------------------------------------------------- // Error Handling // ----------------------------------------------------------- public static void ambiguousTy(Ty ty, Location location) { String message = "(VCGenerator) Ty is ambiguous: " + ty.toString(); throw new SourceErrorException(message, location); } public static void expNotHandled(Exp exp, Location l) { String message = "(VCGenerator) Exp type not handled: " + exp.getClass().getCanonicalName(); throw new SourceErrorException(message, l); } public static void illegalOperationEnsures(Location l) { // TODO: Move this to sanity check. String message = "(VCGenerator) Ensures clauses of operations that return a value should be of the form <OperationName> = <value>"; throw new SourceErrorException(message, l); } public static void notAType(SymbolTableEntry entry, Location l) { throw new SourceErrorException("(VCGenerator) " + entry.getSourceModuleIdentifier() .fullyQualifiedRepresentation(entry.getName()) + " is not known to be a type.", l); } public static void notInFreeVarList(PosSymbol name, Location l) { String message = "(VCGenerator) State variable " + name + " not in free variable list"; throw new SourceErrorException(message, l); } public static void noSuchModule(Location location) { throw new SourceErrorException( "(VCGenerator) Module does not exist or is not in scope.", location); } public static void noSuchSymbol(PosSymbol qualifier, String symbolName, Location l) { String message; if (qualifier == null) { message = "(VCGenerator) No such symbol: " + symbolName; } else { message = "(VCGenerator) No such symbol in module: " + qualifier.getName() + "." + symbolName; } throw new SourceErrorException(message, l); } public static void tyNotHandled(Ty ty, Location location) { String message = "(VCGenerator) Ty not handled: " + ty.toString(); throw new SourceErrorException(message, location); } // ----------------------------------------------------------- // VC Generator Utility Methods // ----------------------------------------------------------- /** * <p>This method checks to see if this the expression we passed * is either a variable expression or a dotted expression that * contains a variable expression in the last position.</p> * * @param exp The checking expression. * * @return True if is an expression we can replace, false otherwise. */ public static boolean containsReplaceableExp(Exp exp) { boolean retVal = false; // Case #1: VarExp if (exp instanceof VarExp) { retVal = true; } // Case #2: DotExp else if (exp instanceof DotExp) { DotExp dotExp = (DotExp) exp; List<Exp> dotExpList = dotExp.getSegments(); retVal = containsReplaceableExp(dotExpList .get(dotExpList.size() - 1)); } return retVal; } /** * <p>Converts the different types of <code>Exp</code> to the * ones used by the VC Generator.</p> * * @param oldExp The expression to be converted. * @param scope The module scope to start our search. * * @return An <code>Exp</code>. */ public static Exp convertExp(Exp oldExp, ModuleScope scope) { Exp retExp; // Case #1: ProgramIntegerExp if (oldExp instanceof ProgramIntegerExp) { IntegerExp exp = new IntegerExp(); exp.setValue(((ProgramIntegerExp) oldExp).getValue()); // At this point all programming integer expressions // should be greater than or equals to 0. Negative // numbers should have called the corresponding operation // to convert it to a negative number. Therefore, we // need to locate the type "N" (Natural Number) MathSymbolEntry mse = searchMathSymbol(exp.getLocation(), "N", scope); try { exp.setMathType(mse.getTypeValue()); } catch (SymbolNotOfKindTypeException e) { notAType(mse, exp.getLocation()); } retExp = exp; } // Case #2: ProgramCharacterExp else if (oldExp instanceof ProgramCharExp) { CharExp exp = new CharExp(); exp.setValue(((ProgramCharExp) oldExp).getValue()); exp.setMathType(oldExp.getMathType()); retExp = exp; } // Case #3: ProgramStringExp else if (oldExp instanceof ProgramStringExp) { StringExp exp = new StringExp(); exp.setValue(((ProgramStringExp) oldExp).getValue()); exp.setMathType(oldExp.getMathType()); retExp = exp; } // Case #4: VariableDotExp else if (oldExp instanceof VariableDotExp) { DotExp exp = new DotExp(); List<VariableExp> segments = ((VariableDotExp) oldExp).getSegments(); edu.clemson.cs.r2jt.collections.List<Exp> newSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); // Need to replace each of the segments in a dot expression MTType lastMathType = null; MTType lastMathTypeValue = null; for (VariableExp v : segments) { VarExp varExp = new VarExp(); // Can only be a VariableNameExp. Anything else // is a case we have not handled. if (v instanceof VariableNameExp) { varExp.setName(((VariableNameExp) v).getName()); varExp.setMathType(v.getMathType()); varExp.setMathTypeValue(v.getMathTypeValue()); lastMathType = v.getMathType(); lastMathTypeValue = v.getMathTypeValue(); newSegments.add(varExp); } else { expNotHandled(v, v.getLocation()); } } // Set the segments and the type information. exp.setSegments(newSegments); exp.setMathType(lastMathType); exp.setMathTypeValue(lastMathTypeValue); retExp = exp; } // Case #5: VariableNameExp else if (oldExp instanceof VariableNameExp) { VarExp exp = new VarExp(); exp.setName(((VariableNameExp) oldExp).getName()); exp.setMathType(oldExp.getMathType()); exp.setMathTypeValue(oldExp.getMathTypeValue()); retExp = exp; } // Else simply return oldExp else { retExp = oldExp; } return retExp; } /** * <p>Convert an operation entry into the absyn node representation.</p> * * @param opEntry The operation entry in the symbol table. * * @return An <code>OperationDec</code>. */ public static OperationDec convertToOperationDec(OperationEntry opEntry) { // Obtain an OperationDec from the OperationEntry ResolveConceptualElement element = opEntry.getDefiningElement(); OperationDec opDec; if (element instanceof OperationDec) { opDec = (OperationDec) opEntry.getDefiningElement(); } else { FacilityOperationDec fOpDec = (FacilityOperationDec) opEntry.getDefiningElement(); opDec = new OperationDec(fOpDec.getName(), fOpDec.getParameters(), fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec .getRequires(), fOpDec.getEnsures()); } return opDec; } /** * <p>Creates conceptual variable expression from the * given name.</p> * * @param location Location that wants to create * this conceptual variable expression. * @param name Name of the variable expression. * @param concType Mathematical type of the conceptual variable. * @param booleanType Mathematical boolean type. * * @return The created conceptual variable as a <code>DotExp</code>. */ public static DotExp createConcVarExp(Location location, VarExp name, MTType concType, MTType booleanType) { // Create a variable that refers to the conceptual exemplar VarExp cName = Utilities.createVarExp(null, null, Utilities .createPosSymbol("Conc"), booleanType, null); // Create Conc.[Exemplar] dotted expression edu.clemson.cs.r2jt.collections.List<Exp> dotExpList = new edu.clemson.cs.r2jt.collections.List<Exp>(); dotExpList.add(cName); dotExpList.add(name); DotExp conceptualVar = Utilities.createDotExp(location, dotExpList, concType); return conceptualVar; } /** * <p>Creates dotted expression with the specified list of * expressions.</p> * * @param location Location that wants to create * this dotted expression. * @param dotExpList The list of expressions that form part of * the dotted expression. * @param dotType Mathematical type of the dotted expression. * * @return The created <code>DotExp</code>. */ public static DotExp createDotExp(Location location, edu.clemson.cs.r2jt.collections.List<Exp> dotExpList, MTType dotType) { // Create the DotExp DotExp exp = new DotExp(location, dotExpList, null); exp.setMathType(dotType); return exp; } /** * <p>Creates function expression "Dur_Call" with a specified number * of parameters</p> * * @param loc The location where we are creating this expression. * @param numArg Number of Arguments. * @param integerType Mathematical integer type. * @param realType Mathematical real type. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createDurCallExp(Location loc, String numArg, MTType integerType, MTType realType) { // Obtain the necessary information from the variable VarExp param = createVarExp(loc, null, createPosSymbol(numArg), integerType, null); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param); // Create the duration call exp FunctionExp durCallExp = createFunctionExp(loc, null, createPosSymbol("Dur_Call"), params, realType); return durCallExp; } /** * <p>Creates function expression "F_Dur" for a specified * variable.</p> * * @param var Local Variable. * @param realType Mathematical real type. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createFinalizAnyDur(VarDec var, MTType realType) { // Obtain the necessary information from the variable Ty varTy = var.getTy(); NameTy varNameTy = (NameTy) varTy; VarExp param = createVarExp(var.getLocation(), null, var.getName(), var .getTy().getMathTypeValue(), null); VarExp param1 = createVarExp(varNameTy.getLocation(), null, createPosSymbol(varNameTy.getName().getName()), var .getTy().getMathTypeValue(), null); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param1); params.add(param); // Create the final duration FunctionExp finalDurAnyExp = createFunctionExp(var.getLocation(), null, createPosSymbol("F_Dur"), params, realType); return finalDurAnyExp; } /** * <p>Creates function expression "F_Dur" for a specified * variable expression.</p> * * @param varExp A Variable Expression. * @param realType Mathematical real type. * @param scope The module scope to start our search. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createFinalizAnyDurExp(VariableExp varExp, MTType realType, ModuleScope scope) { if (varExp.getProgramType() instanceof PTFamily) { PTFamily type = (PTFamily) varExp.getProgramType(); Exp param = convertExp(varExp, scope); VarExp param1 = createVarExp(varExp.getLocation(), null, createPosSymbol(type.getName()), varExp .getMathType(), varExp.getMathTypeValue()); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param1); params.add(param); // Create the final duration FunctionExp finalDurAnyExp = createFunctionExp(varExp.getLocation(), null, createPosSymbol("F_Dur"), params, realType); return finalDurAnyExp; } else { throw new RuntimeException(); } } /** * <p>Creates function expression with the specified * name and arguments.</p> * * @param location Location that wants to create * this function expression. * @param qualifier Qualifier for the function expression. * @param name Name of the function expression. * @param argExpList List of arguments to the function expression. * @param funcType Mathematical type for the function expression. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createFunctionExp(Location location, PosSymbol qualifier, PosSymbol name, edu.clemson.cs.r2jt.collections.List<Exp> argExpList, MTType funcType) { // Complicated steps to construct the argument list // YS: No idea why it is so complicated! FunctionArgList argList = new FunctionArgList(); argList.setArguments(argExpList); edu.clemson.cs.r2jt.collections.List<FunctionArgList> functionArgLists = new edu.clemson.cs.r2jt.collections.List<FunctionArgList>(); functionArgLists.add(argList); // Create the function expression FunctionExp exp = new FunctionExp(location, qualifier, name, null, functionArgLists); exp.setMathType(funcType); return exp; } /** * <p>Creates function expression "I_Dur" for a specified * variable.</p> * * @param var Local Variable. * @param realType Mathematical real type. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createInitAnyDur(VarDec var, MTType realType) { // Obtain the necessary information from the variable VarExp param = createVarExp(var.getLocation(), null, createPosSymbol(((NameTy) var.getTy()).getName() .getName()), var.getTy().getMathTypeValue(), null); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param); // Create the final duration FunctionExp initDurExp = createFunctionExp(var.getLocation(), null, createPosSymbol("I_Dur"), params, realType); return initDurExp; } /** * <p>Returns an <code>DotExp</code> with the <code>VarDec</code> * and its initialization ensures clause.</p> * * @param var The declared variable. * @param mType CLS type. * @param booleanType Mathematical boolean type. * * @return The new <code>DotExp</code>. */ public static DotExp createInitExp(VarDec var, MTType mType, MTType booleanType) { // Convert the declared variable into a VarExp VarExp varExp = createVarExp(var.getLocation(), null, var.getName(), var .getTy().getMathTypeValue(), null); // Left hand side of the expression VarExp left = null; // NameTy if (var.getTy() instanceof NameTy) { NameTy ty = (NameTy) var.getTy(); left = createVarExp(ty.getLocation(), ty.getQualifier(), ty .getName(), mType, null); } else { tyNotHandled(var.getTy(), var.getTy().getLocation()); } // Create the "Is_Initial" FunctionExp edu.clemson.cs.r2jt.collections.List<Exp> expList = new edu.clemson.cs.r2jt.collections.List<Exp>(); expList.add(varExp); FunctionExp right = createFunctionExp(var.getLocation(), null, createPosSymbol("Is_Initial"), expList, booleanType); // Create the DotExp edu.clemson.cs.r2jt.collections.List<Exp> exps = new edu.clemson.cs.r2jt.collections.List<Exp>(); exps.add(left); exps.add(right); DotExp exp = createDotExp(var.getLocation(), exps, booleanType); return exp; } /** * <p>Creates a less than equal infix expression.</p> * * @param location Location for the new infix expression. * @param left The left hand side of the less than equal expression. * @param right The right hand side of the less than equal expression. * @param booleanType Mathematical boolean type. * * @return The new <code>InfixExp</code>. */ public static InfixExp createLessThanEqExp(Location location, Exp left, Exp right, MTType booleanType) { // Create the "Less Than Equal" InfixExp InfixExp exp = new InfixExp(location, left, Utilities.createPosSymbol("<="), right); exp.setMathType(booleanType); return exp; } /** * <p>Creates a less than infix expression.</p> * * @param location Location for the new infix expression. * @param left The left hand side of the less than expression. * @param right The right hand side of the less than expression. * @param booleanType Mathematical boolean type. * * @return The new <code>InfixExp</code>. */ public static InfixExp createLessThanExp(Location location, Exp left, Exp right, MTType booleanType) { // Create the "Less Than" InfixExp InfixExp exp = new InfixExp(location, left, Utilities.createPosSymbol("<"), right); exp.setMathType(booleanType); return exp; } /** * <p>Returns a newly created <code>PosSymbol</code> * with the string provided.</p> * * @param name String of the new <code>PosSymbol</code>. * * @return The new <code>PosSymbol</code>. */ public static PosSymbol createPosSymbol(String name) { // Create the PosSymbol PosSymbol posSym = new PosSymbol(); posSym.setSymbol(Symbol.symbol(name)); return posSym; } /** * <p>Creates a variable expression with the name * "P_val" and has type "N".</p> * * @param location Location that wants to create * this variable. * @param scope The module scope to start our search. * * * @return The created <code>VarExp</code>. */ public static VarExp createPValExp(Location location, ModuleScope scope) { // Locate "N" (Natural Number) MathSymbolEntry mse = searchMathSymbol(location, "N", scope); try { // Create a variable with the name P_val return createVarExp(location, null, createPosSymbol("P_val"), mse .getTypeValue(), null); } catch (SymbolNotOfKindTypeException e) { notAType(mse, location); } return null; } /** * <p>Create a question mark variable with the oldVar * passed in.</p> * * @param exp The full expression clause. * @param oldVar The old variable expression. * * @return A new variable with the question mark in <code>VarExp</code> form. */ public static VarExp createQuestionMarkVariable(Exp exp, VarExp oldVar) { // Add an extra question mark to the front of oldVar VarExp newOldVar = new VarExp(null, null, createPosSymbol("?" + oldVar.getName().getName())); newOldVar.setMathType(oldVar.getMathType()); newOldVar.setMathTypeValue(oldVar.getMathTypeValue()); // Applies the question mark to oldVar if it is our first time visiting. if (exp.containsVar(oldVar.getName().getName(), false)) { return createQuestionMarkVariable(exp, newOldVar); } // Don't need to apply the question mark here. else if (exp.containsVar(newOldVar.getName().toString(), false)) { return createQuestionMarkVariable(exp, newOldVar); } else { // Return the new variable expression with the question mark if (oldVar.getName().getName().charAt(0) != '?') { return newOldVar; } } // Return our old self. return oldVar; } /** * <p>Returns a newly created <code>VarExp</code> * with the <code>PosSymbol</code> and math type provided.</p> * * @param loc Location of the new <code>VarExp</code>. * @param qualifier Qualifier of the <code>VarExp</code>. * @param name <code>PosSymbol</code> of the new <code>VarExp</code>. * @param type Math type of the new <code>VarExp</code>. * @param typeValue Math type value of the new <code>VarExp</code>. * * @return The new <code>VarExp</code>. */ public static VarExp createVarExp(Location loc, PosSymbol qualifier, PosSymbol name, MTType type, MTType typeValue) { // Create the VarExp VarExp exp = new VarExp(loc, qualifier, name); exp.setMathType(type); exp.setMathTypeValue(typeValue); return exp; } /** * <p>Gets the current "Cum_Dur" expression. We should only have one in * the current scope.</p> * * @param searchingExp The expression we are searching for "Cum_Dur" * * @return The current "Cum_Dur". */ public static String getCumDur(Exp searchingExp) { String cumDur = "Cum_Dur"; // Loop until we find one while (!searchingExp.containsVar(cumDur, false)) { cumDur = "?" + cumDur; } return cumDur; } /** * <p>Returns the math type for "Z".</p> * * @param location Current location in the AST. * @param scope The module scope to start our search. * * * @return The <code>MTType</code> for "Z". */ public static MTType getMathTypeZ(Location location, ModuleScope scope) { // Locate "Z" (Integer) MathSymbolEntry mse = searchMathSymbol(location, "Z", scope); MTType Z = null; try { Z = mse.getTypeValue(); } catch (SymbolNotOfKindTypeException e) { notAType(mse, location); } return Z; } /** * <p>Gets all the unique symbols in an expression.</p> * * @param exp The searching <code>Exp</code>. * * @return The set of symbols. */ public static Set<String> getSymbols(Exp exp) { // Return value Set<String> symbolsSet = new HashSet<String>(); // Not CharExp, DoubleExp, IntegerExp or StringExp if (!(exp instanceof CharExp) && !(exp instanceof DoubleExp) && !(exp instanceof IntegerExp) && !(exp instanceof StringExp)) { // AlternativeExp if (exp instanceof AlternativeExp) { List<AltItemExp> alternativesList = ((AlternativeExp) exp).getAlternatives(); // Iterate through each of the alternatives for (AltItemExp altExp : alternativesList) { Exp test = altExp.getTest(); Exp assignment = altExp.getAssignment(); // Don't loop if they are null if (test != null) { symbolsSet.addAll(getSymbols(altExp.getTest())); } if (assignment != null) { symbolsSet.addAll(getSymbols(altExp.getAssignment())); } } } // DotExp else if (exp instanceof DotExp) { List<Exp> segExpList = ((DotExp) exp).getSegments(); StringBuffer currentStr = new StringBuffer(); // Iterate through each of the segment expressions for (Exp e : segExpList) { // For each expression, obtain the set of symbols // and form a candidate expression. Set<String> retSet = getSymbols(e); for (String s : retSet) { if (currentStr.length() != 0) { currentStr.append("."); } currentStr.append(s); } symbolsSet.add(currentStr.toString()); } } // EqualsExp else if (exp instanceof EqualsExp) { symbolsSet.addAll(getSymbols(((EqualsExp) exp).getLeft())); symbolsSet.addAll(getSymbols(((EqualsExp) exp).getRight())); } // FunctionExp else if (exp instanceof FunctionExp) { FunctionExp funcExp = (FunctionExp) exp; StringBuffer funcName = new StringBuffer(); // Add the name of the function (including any qualifiers) if (funcExp.getQualifier() != null) { funcName.append(funcExp.getQualifier().getName()); funcName.append("."); } funcName.append(funcExp.getName()); symbolsSet.add(funcName.toString()); // Add all the symbols in the argument list List<FunctionArgList> funcArgList = funcExp.getParamList(); for (FunctionArgList f : funcArgList) { List<Exp> funcArgExpList = f.getArguments(); for (Exp e : funcArgExpList) { symbolsSet.addAll(getSymbols(e)); } } } // If Exp else if (exp instanceof IfExp) { symbolsSet.addAll(getSymbols(((IfExp) exp).getTest())); symbolsSet.addAll(getSymbols(((IfExp) exp).getThenclause())); symbolsSet.addAll(getSymbols(((IfExp) exp).getElseclause())); } // InfixExp else if (exp instanceof InfixExp) { symbolsSet.addAll(getSymbols(((InfixExp) exp).getLeft())); symbolsSet.addAll(getSymbols(((InfixExp) exp).getRight())); } // LambdaExp else if (exp instanceof LambdaExp) { LambdaExp lambdaExp = (LambdaExp) exp; // Add all the parameter variables List<MathVarDec> paramList = lambdaExp.getParameters(); for (MathVarDec v : paramList) { symbolsSet.add(v.getName().getName()); } // Add all the symbols in the body symbolsSet.addAll(getSymbols(lambdaExp.getBody())); } // OldExp else if (exp instanceof OldExp) { symbolsSet.add(exp.toString(0)); } // OutfixExp else if (exp instanceof OutfixExp) { symbolsSet.addAll(getSymbols(((OutfixExp) exp).getArgument())); } // PrefixExp else if (exp instanceof PrefixExp) { symbolsSet.addAll(getSymbols(((PrefixExp) exp).getArgument())); } // SetExp else if (exp instanceof SetExp) { SetExp setExp = (SetExp) exp; // Add all the parts that form the set expression symbolsSet.add(setExp.getVar().getName().getName()); symbolsSet.addAll(getSymbols(((SetExp) exp).getWhere())); symbolsSet.addAll(getSymbols(((SetExp) exp).getBody())); } // SuppositionExp else if (exp instanceof SuppositionExp) { SuppositionExp suppositionExp = (SuppositionExp) exp; // Add all the expressions symbolsSet.addAll(getSymbols(suppositionExp.getExp())); // Add all the variables List<MathVarDec> varList = suppositionExp.getVars(); for (MathVarDec v : varList) { symbolsSet.add(v.getName().getName()); } } // TupleExp else if (exp instanceof TupleExp) { TupleExp tupleExp = (TupleExp) exp; // Add all the expressions in the fields List<Exp> fieldList = tupleExp.getFields(); for (Exp e : fieldList) { symbolsSet.addAll(getSymbols(e)); } } // VarExp else if (exp instanceof VarExp) { VarExp varExp = (VarExp) exp; StringBuffer varName = new StringBuffer(); // Add the name of the variable (including any qualifiers) if (varExp.getQualifier() != null) { varName.append(varExp.getQualifier().getName()); varName.append("."); } varName.append(varExp.getName()); symbolsSet.add(varName.toString()); } // Not Handled! else { expNotHandled(exp, exp.getLocation()); } } return symbolsSet; } /** * <p>Get the <code>PosSymbol</code> associated with the * <code>VariableExp</code> left.</p> * * @param left The variable expression. * * @return The <code>PosSymbol</code> of left. */ public static PosSymbol getVarName(VariableExp left) { // Return value PosSymbol name = null; // Variable Name Expression if (left instanceof VariableNameExp) { name = ((VariableNameExp) left).getName(); } // Variable Dot Expression else if (left instanceof VariableDotExp) { VariableDotExp varDotExp = (VariableDotExp) left; for (VariableExp v : varDotExp.getSegments()) { PosSymbol tempName = getVarName(v); if (name == null) { name = tempName; } else { name = new PosSymbol(name.getLocation(), Symbol .symbol(name.getName() + "_" + tempName.getName())); } } } // Variable Record Expression else if (left instanceof VariableRecordExp) { VariableRecordExp varRecExp = (VariableRecordExp) left; name = varRecExp.getName(); } // // Creates an expression with "false" as its name else { name = createPosSymbol("false"); } return name; } /** * <p>Given the name of an operation check to see if it is a * local operation</p> * * @param name The name of the operation. * @param scope The module scope we are searching. * * @return True if it is a local operation, false otherwise. */ public static boolean isLocationOperation(String name, ModuleScope scope) { boolean isIn; // Query for the corresponding operation List<SymbolTableEntry> entries = scope .query(new NameQuery( null, name, MathSymbolTable.ImportStrategy.IMPORT_NONE, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE, true)); // Not found if (entries.size() == 0) { isIn = false; } // Found one else if (entries.size() == 1) { // If the operation is declared here, then it will be an OperationEntry. // Thus it is a local operation. if (entries.get(0) instanceof OperationEntry) { isIn = true; } else { isIn = false; } } // Found more than one else { //This should be caught earlier, when the duplicate symbol is //created throw new RuntimeException(); } return isIn; } /** * <p>Checks to see if the expression passed in is a * verification variable or not. A verification variable * is either "P_val" or starts with "?".</p> * * @param name Expression that we want to check * * @return True/False */ public static boolean isVerificationVar(Exp name) { // VarExp if (name instanceof VarExp) { String strName = ((VarExp) name).getName().getName(); // Case #1: Question mark variables if (strName.charAt(0) == '?') { return true; } // Case #2: P_val else if (strName.equals("P_val")) { return true; } } // DotExp else if (name instanceof DotExp) { // Recursively call this method until we get // either true or false. List<Exp> names = ((DotExp) name).getSegments(); return isVerificationVar(names.get(0)); } // Definitely not a verification variable. return false; } /** * <p>Negate the incoming expression.</p> * * @param exp Expression to be negated. * @param booleanType Mathematical boolean type. * * @return Negated expression. */ public static Exp negateExp(Exp exp, MTType booleanType) { Exp retExp = Exp.copy(exp); if (exp instanceof EqualsExp) { if (((EqualsExp) exp).getOperator() == EqualsExp.EQUAL) ((EqualsExp) retExp).setOperator(EqualsExp.NOT_EQUAL); else ((EqualsExp) retExp).setOperator(EqualsExp.EQUAL); } else if (exp instanceof PrefixExp) { if (((PrefixExp) exp).getSymbol().getName().toString() .equals("not")) { retExp = ((PrefixExp) exp).getArgument(); } } else { PrefixExp tmp = new PrefixExp(); setLocation(tmp, exp.getLocation()); tmp.setArgument(exp); tmp.setSymbol(createPosSymbol("not")); tmp.setMathType(booleanType); retExp = tmp; } return retExp; } /** * <p>Copy and replace the old <code>Exp</code>.</p> * * @param exp The <code>Exp</code> to be replaced. * @param old The old sub-expression of <code>exp</code>. * @param repl The new sub-expression of <code>exp</code>. * * @return The new <code>Exp</code>. */ public static Exp replace(Exp exp, Exp old, Exp repl) { // Clone old and repl and use the Exp replace to do all its work Exp tmp = Exp.replace(Exp.copy(exp), Exp.copy(old), Exp.copy(repl)); // Return the corresponding Exp if (tmp != null) return tmp; else return exp; } /** * <p>Replace the formal with the actual variables from the facility declaration to * the passed in clause.</p> * * @param opLoc Location of the calling statement. * @param clause The requires/ensures clause. * @param paramList The list of parameter variables. * @param instantiatedFacilityArgMap The map of facility formals to actuals. * @param scope The module scope to start our search. * * @return The clause in <code>Exp</code> form. */ public static Exp replaceFacilityFormalWithActual(Location opLoc, Exp clause, List<ParameterVarDec> paramList, Map<VarExp, FacilityFormalToActuals> instantiatedFacilityArgMap, ModuleScope scope) { // Make a copy of the original clause Exp newClause = Exp.copy(clause); for (ParameterVarDec dec : paramList) { if (dec.getTy() instanceof NameTy) { NameTy ty = (NameTy) dec.getTy(); PosSymbol tyName = ty.getName().copy(); PosSymbol tyQualifier = null; if (ty.getQualifier() != null) { tyQualifier = ty.getQualifier().copy(); } FacilityFormalToActuals formalToActuals = null; for (VarExp v : instantiatedFacilityArgMap.keySet()) { FacilityFormalToActuals temp = null; if (tyQualifier != null) { if (tyQualifier.getName().equals( v.getQualifier().getName()) && tyName.getName().equals( v.getName().getName())) { temp = instantiatedFacilityArgMap.get(v); } } else { if (tyName.getName().equals(v.getName().getName())) { temp = instantiatedFacilityArgMap.get(v); } } // Check to see if we already found one. If we did, it means that // the type is ambiguous and we can't be sure which one it is. if (temp != null) { if (formalToActuals == null) { formalToActuals = temp; } else { Utilities.ambiguousTy(ty, opLoc); } } } if (formalToActuals != null) { // Replace all concept formal arguments with their actuals Map<Exp, Exp> conceptMap = formalToActuals.getConceptArgMap(); for (Exp e : conceptMap.keySet()) { newClause = Utilities.replace(newClause, e, conceptMap .get(e)); } // Replace all concept realization formal arguments with their actuals Map<Exp, Exp> conceptRealizMap = formalToActuals.getConceptRealizArgMap(); for (Exp e : conceptRealizMap.keySet()) { newClause = Utilities.replace(newClause, e, conceptRealizMap.get(e)); } // Replace all enhancement [realization] formal arguments with their actuals for (PosSymbol p : formalToActuals.getEnhancementKeys()) { Map<Exp, Exp> enhancementMap = formalToActuals.getEnhancementArgMap(p); for (Exp e : enhancementMap.keySet()) { newClause = Utilities.replace(newClause, e, enhancementMap.get(e)); } } } else { // Ignore all generic types if (!(ty.getProgramTypeValue() instanceof PTGeneric)) { boolean found = false; // Check to see if the type of this variable is from an imported // concept type family definition. If we find one, we simply ignore this type. Iterator<SymbolTableEntry> programTypeDefIt = scope .query( new EntryTypeQuery<SymbolTableEntry>( ProgramTypeDefinitionEntry.class, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE)) .iterator(); while (programTypeDefIt.hasNext() && !found) { ProgramTypeDefinitionEntry entry = programTypeDefIt .next() .toProgramTypeDefinitionEntry(opLoc); if (entry.getName().equals(tyName.getName())) { found = true; } } if (!found) { // Check to see if the type of this variable is from an local // type representation. If we find one, we simply ignore this type. Iterator<SymbolTableEntry> representationTypeIt = scope .query( new EntryTypeQuery<SymbolTableEntry>( RepresentationTypeEntry.class, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE)) .iterator(); while (representationTypeIt.hasNext() && !found) { RepresentationTypeEntry entry = representationTypeIt.next() .toRepresentationTypeEntry( opLoc); if (entry.getName().equals(tyName.getName())) { found = true; } } // Throw an error if can't find one. if (!found) { Utilities.noSuchSymbol(tyQualifier, tyName .getName(), opLoc); } } } } } } return newClause; } /** * <p>Given a programming type, locate its constraint from the * Symbol Table.</p> * * @param location Location for the searching type. * @param typeAsExp The raw type as a variable expression. * @param varName Name of the variable. * @param scope The module scope to start our search. * * @return The constraint in <code>Exp</code> form if found, null otherwise. */ public static Exp retrieveConstraint(Location location, VarExp typeAsExp, Exp varName, ModuleScope scope) { Exp constraint = null; // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(location, typeAsExp.getQualifier(), typeAsExp.getName(), scope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(location); } else { typeEntry = ste.toRepresentationTypeEntry(location) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); constraint = replace(Exp.copy(type.getConstraint()), exemplar, varName); } else { notAType(typeEntry, location); } return constraint; } /** * <p>Given a math symbol name, locate and return * the <code>MathSymbolEntry</code> stored in the * symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param name The string name of the math symbol. * @param scope The module scope to start our search. * * @return An <code>MathSymbolEntry</code> from the * symbol table. */ public static MathSymbolEntry searchMathSymbol(Location loc, String name, ModuleScope scope) { // Query for the corresponding math symbol MathSymbolEntry ms = null; try { ms = scope .queryForOne( new UnqualifiedNameQuery( name, MathSymbolTable.ImportStrategy.IMPORT_RECURSIVE, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE, true, true)).toMathSymbolEntry(loc); } catch (NoSuchSymbolException nsse) { noSuchSymbol(null, name, loc); } catch (DuplicateSymbolException dse) { //This should be caught earlier, when the duplicate symbol is //created throw new RuntimeException(dse); } return ms; } /** * <p>Given the qualifier, name and the list of argument * types, locate and return the <code>OperationEntry</code> * stored in the symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param qualifier The qualifier of the operation. * @param name The name of the operation. * @param argTypes The list of argument types. * @param scope The module scope to start our search. * * @return An <code>OperationEntry</code> from the * symbol table. */ public static OperationEntry searchOperation(Location loc, PosSymbol qualifier, PosSymbol name, List<PTType> argTypes, ModuleScope scope) { // Query for the corresponding operation OperationEntry op = null; try { op = scope.queryForOne(new OperationQuery(qualifier, name, argTypes)); } catch (NoSuchSymbolException nsse) { noSuchSymbol(null, name.getName(), loc); } catch (DuplicateSymbolException dse) { //This should be caught earlier, when the duplicate operation is //created throw new RuntimeException(dse); } return op; } /** * <p>Given the qualifier, name and the list of argument * types, locate and return the <code>OperationProfileEntry</code> * stored in the symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param qualifier The qualifier of the operation. * @param name The name of the operation. * @param argTypes The list of argument types. * @param scope The module scope to start our search. * * @return An <code>OperationProfileEntry</code> from the * symbol table. */ public static OperationProfileEntry searchOperationProfile(Location loc, PosSymbol qualifier, PosSymbol name, List<PTType> argTypes, ModuleScope scope) { // Query for the corresponding operation profile OperationProfileEntry ope = null; try { ope = scope.queryForOne(new OperationProfileQuery(qualifier, name, argTypes)); } catch (NoSuchSymbolException nsse) { noSuchModule(loc); } catch (DuplicateSymbolException dse) { // This should have been caught earlier, when the duplicate operation is // created. throw new RuntimeException(dse); } return ope; } /** * <p>Given the name of the type locate and return * the <code>SymbolTableEntry</code> stored in the * symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param qualifier The qualifier of the type. * @param name The name of the type. * @param scope The module scope to start our search. * * @return A <code>SymbolTableEntry</code> from the * symbol table. */ public static SymbolTableEntry searchProgramType(Location loc, PosSymbol qualifier, PosSymbol name, ModuleScope scope) { SymbolTableEntry retEntry = null; List<SymbolTableEntry> entries = scope.query(new NameQuery(qualifier, name, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_INSTANTIATE, false)); if (entries.size() == 0) { noSuchSymbol(qualifier, name.getName(), loc); } else if (entries.size() == 1) { retEntry = entries.get(0).toProgramTypeEntry(loc); } else { // When we have more than one, it means that we have a // type representation. In that case, we just need the // type representation. for (int i = 0; i < entries.size() && retEntry == null; i++) { SymbolTableEntry ste = entries.get(i); if (ste instanceof RepresentationTypeEntry) { retEntry = ste.toRepresentationTypeEntry(loc); } } // Throw duplicate symbol error if we don't have a type // representation if (retEntry == null) { //This should be caught earlier, when the duplicate type is //created throw new RuntimeException(); } } return retEntry; } /** * <p>Changes the <code>Exp</code> with the new * <code>Location</code>.</p> * * @param exp The <code>Exp</code> that needs to be modified. * @param loc The new <code>Location</code>. */ public static void setLocation(Exp exp, Location loc) { // Special handling for InfixExp if (exp instanceof InfixExp) { ((InfixExp) exp).setAllLocations(loc); } else { exp.setLocation(loc); } } public static List<Exp> splitConjunctExp(Exp exp, List<Exp> expList) { // Attempt to split the expression if it contains a conjunct if (exp instanceof InfixExp) { InfixExp infixExp = (InfixExp) exp; // Split the expression if it is a conjunct if (infixExp.getOpName().equals("and")) { expList = splitConjunctExp(infixExp.getLeft(), expList); expList = splitConjunctExp(infixExp.getRight(), expList); } // Otherwise simply add it to our list else { expList.add(infixExp); } } // Otherwise it is an individual assume statement we need to deal with. else { expList.add(exp); } return expList; } }
src/main/java/edu/clemson/cs/r2jt/vcgeneration/Utilities.java
/** * Utilities.java * --------------------------------- * Copyright (c) 2015 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.vcgeneration; /* * Libraries */ import edu.clemson.cs.r2jt.absyn.*; import edu.clemson.cs.r2jt.data.*; import edu.clemson.cs.r2jt.typeandpopulate.*; import edu.clemson.cs.r2jt.typeandpopulate.entry.*; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTFamily; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTGeneric; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; import edu.clemson.cs.r2jt.typeandpopulate.query.*; import edu.clemson.cs.r2jt.misc.SourceErrorException; import java.util.*; /** * TODO: Write a description of this module */ public class Utilities { // =========================================================== // Public Methods // =========================================================== // ----------------------------------------------------------- // Error Handling // ----------------------------------------------------------- public static void ambiguousTy(Ty ty, Location location) { String message = "(VCGenerator) Ty is ambiguous: " + ty.toString(); throw new SourceErrorException(message, location); } public static void expNotHandled(Exp exp, Location l) { String message = "(VCGenerator) Exp type not handled: " + exp.getClass().getCanonicalName(); throw new SourceErrorException(message, l); } public static void illegalOperationEnsures(Location l) { // TODO: Move this to sanity check. String message = "(VCGenerator) Ensures clauses of operations that return a value should be of the form <OperationName> = <value>"; throw new SourceErrorException(message, l); } public static void notAType(SymbolTableEntry entry, Location l) { throw new SourceErrorException("(VCGenerator) " + entry.getSourceModuleIdentifier() .fullyQualifiedRepresentation(entry.getName()) + " is not known to be a type.", l); } public static void notInFreeVarList(PosSymbol name, Location l) { String message = "(VCGenerator) State variable " + name + " not in free variable list"; throw new SourceErrorException(message, l); } public static void noSuchModule(Location location) { throw new SourceErrorException( "(VCGenerator) Module does not exist or is not in scope.", location); } public static void noSuchSymbol(PosSymbol qualifier, String symbolName, Location l) { String message; if (qualifier == null) { message = "(VCGenerator) No such symbol: " + symbolName; } else { message = "(VCGenerator) No such symbol in module: " + qualifier.getName() + "." + symbolName; } throw new SourceErrorException(message, l); } public static void tyNotHandled(Ty ty, Location location) { String message = "(VCGenerator) Ty not handled: " + ty.toString(); throw new SourceErrorException(message, location); } // ----------------------------------------------------------- // VC Generator Utility Methods // ----------------------------------------------------------- /** * <p>This method checks to see if this the expression we passed * is either a variable expression or a dotted expression that * contains a variable expression in the last position.</p> * * @param exp The checking expression. * * @return True if is an expression we can replace, false otherwise. */ public static boolean containsReplaceableExp(Exp exp) { boolean retVal = false; // Case #1: VarExp if (exp instanceof VarExp) { retVal = true; } // Case #2: DotExp else if (exp instanceof DotExp) { DotExp dotExp = (DotExp) exp; List<Exp> dotExpList = dotExp.getSegments(); retVal = containsReplaceableExp(dotExpList .get(dotExpList.size() - 1)); } return retVal; } /** * <p>Converts the different types of <code>Exp</code> to the * ones used by the VC Generator.</p> * * @param oldExp The expression to be converted. * @param scope The module scope to start our search. * * @return An <code>Exp</code>. */ public static Exp convertExp(Exp oldExp, ModuleScope scope) { Exp retExp; // Case #1: ProgramIntegerExp if (oldExp instanceof ProgramIntegerExp) { IntegerExp exp = new IntegerExp(); exp.setValue(((ProgramIntegerExp) oldExp).getValue()); // At this point all programming integer expressions // should be greater than or equals to 0. Negative // numbers should have called the corresponding operation // to convert it to a negative number. Therefore, we // need to locate the type "N" (Natural Number) MathSymbolEntry mse = searchMathSymbol(exp.getLocation(), "N", scope); try { exp.setMathType(mse.getTypeValue()); } catch (SymbolNotOfKindTypeException e) { notAType(mse, exp.getLocation()); } retExp = exp; } // Case #2: ProgramCharacterExp else if (oldExp instanceof ProgramCharExp) { CharExp exp = new CharExp(); exp.setValue(((ProgramCharExp) oldExp).getValue()); exp.setMathType(oldExp.getMathType()); retExp = exp; } // Case #3: ProgramStringExp else if (oldExp instanceof ProgramStringExp) { StringExp exp = new StringExp(); exp.setValue(((ProgramStringExp) oldExp).getValue()); exp.setMathType(oldExp.getMathType()); retExp = exp; } // Case #4: VariableDotExp else if (oldExp instanceof VariableDotExp) { DotExp exp = new DotExp(); List<VariableExp> segments = ((VariableDotExp) oldExp).getSegments(); edu.clemson.cs.r2jt.collections.List<Exp> newSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); // Need to replace each of the segments in a dot expression MTType lastMathType = null; MTType lastMathTypeValue = null; for (VariableExp v : segments) { VarExp varExp = new VarExp(); // Can only be a VariableNameExp. Anything else // is a case we have not handled. if (v instanceof VariableNameExp) { varExp.setName(((VariableNameExp) v).getName()); varExp.setMathType(v.getMathType()); varExp.setMathTypeValue(v.getMathTypeValue()); lastMathType = v.getMathType(); lastMathTypeValue = v.getMathTypeValue(); newSegments.add(varExp); } else { expNotHandled(v, v.getLocation()); } } // Set the segments and the type information. exp.setSegments(newSegments); exp.setMathType(lastMathType); exp.setMathTypeValue(lastMathTypeValue); retExp = exp; } // Case #5: VariableNameExp else if (oldExp instanceof VariableNameExp) { VarExp exp = new VarExp(); exp.setName(((VariableNameExp) oldExp).getName()); exp.setMathType(oldExp.getMathType()); exp.setMathTypeValue(oldExp.getMathTypeValue()); retExp = exp; } // Else simply return oldExp else { retExp = oldExp; } return retExp; } /** * <p>Convert an operation entry into the absyn node representation.</p> * * @param opEntry The operation entry in the symbol table. * * @return An <code>OperationDec</code>. */ public static OperationDec convertToOperationDec(OperationEntry opEntry) { // Obtain an OperationDec from the OperationEntry ResolveConceptualElement element = opEntry.getDefiningElement(); OperationDec opDec; if (element instanceof OperationDec) { opDec = (OperationDec) opEntry.getDefiningElement(); } else { FacilityOperationDec fOpDec = (FacilityOperationDec) opEntry.getDefiningElement(); opDec = new OperationDec(fOpDec.getName(), fOpDec.getParameters(), fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec .getRequires(), fOpDec.getEnsures()); } return opDec; } /** * <p>Creates conceptual variable expression from the * given name.</p> * * @param location Location that wants to create * this conceptual variable expression. * @param name Name of the variable expression. * @param concType Mathematical type of the conceptual variable. * @param booleanType Mathematical boolean type. * * @return The created conceptual variable as a <code>DotExp</code>. */ public static DotExp createConcVarExp(Location location, VarExp name, MTType concType, MTType booleanType) { // Create a variable that refers to the conceptual exemplar VarExp cName = Utilities.createVarExp(null, null, Utilities .createPosSymbol("Conc"), booleanType, null); // Create Conc.[Exemplar] dotted expression edu.clemson.cs.r2jt.collections.List<Exp> dotExpList = new edu.clemson.cs.r2jt.collections.List<Exp>(); dotExpList.add(cName); dotExpList.add(name); DotExp conceptualVar = Utilities.createDotExp(location, dotExpList, concType); return conceptualVar; } /** * <p>Creates dotted expression with the specified list of * expressions.</p> * * @param location Location that wants to create * this dotted expression. * @param dotExpList The list of expressions that form part of * the dotted expression. * @param dotType Mathematical type of the dotted expression. * * @return The created <code>DotExp</code>. */ public static DotExp createDotExp(Location location, edu.clemson.cs.r2jt.collections.List<Exp> dotExpList, MTType dotType) { // Create the DotExp DotExp exp = new DotExp(location, dotExpList, null); exp.setMathType(dotType); return exp; } /** * <p>Creates function expression "Dur_Call" with a specified number * of parameters</p> * * @param loc The location where we are creating this expression. * @param numArg Number of Arguments. * @param integerType Mathematical integer type. * @param realType Mathematical real type. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createDurCallExp(Location loc, String numArg, MTType integerType, MTType realType) { // Obtain the necessary information from the variable VarExp param = createVarExp(loc, null, createPosSymbol(numArg), integerType, null); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param); // Create the duration call exp FunctionExp durCallExp = createFunctionExp(loc, null, createPosSymbol("Dur_Call"), params, realType); return durCallExp; } /** * <p>Creates function expression "F_Dur" for a specified * variable.</p> * * @param var Local Variable. * @param realType Mathematical real type. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createFinalizAnyDur(VarDec var, MTType realType) { // Obtain the necessary information from the variable Ty varTy = var.getTy(); NameTy varNameTy = (NameTy) varTy; VarExp param = createVarExp(var.getLocation(), null, var.getName(), var .getTy().getMathTypeValue(), null); VarExp param1 = createVarExp(varNameTy.getLocation(), null, createPosSymbol(varNameTy.getName().getName()), var .getTy().getMathTypeValue(), null); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param1); params.add(param); // Create the final duration FunctionExp finalDurAnyExp = createFunctionExp(var.getLocation(), null, createPosSymbol("F_Dur"), params, realType); return finalDurAnyExp; } /** * <p>Creates function expression "F_Dur" for a specified * variable expression.</p> * * @param varExp A Variable Expression. * @param realType Mathematical real type. * @param scope The module scope to start our search. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createFinalizAnyDurExp(VariableExp varExp, MTType realType, ModuleScope scope) { if (varExp.getProgramType() instanceof PTFamily) { PTFamily type = (PTFamily) varExp.getProgramType(); Exp param = convertExp(varExp, scope); VarExp param1 = createVarExp(varExp.getLocation(), null, createPosSymbol(type.getName()), varExp .getMathType(), varExp.getMathTypeValue()); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param1); params.add(param); // Create the final duration FunctionExp finalDurAnyExp = createFunctionExp(varExp.getLocation(), null, createPosSymbol("F_Dur"), params, realType); return finalDurAnyExp; } else { throw new RuntimeException(); } } /** * <p>Creates function expression with the specified * name and arguments.</p> * * @param location Location that wants to create * this function expression. * @param qualifier Qualifier for the function expression. * @param name Name of the function expression. * @param argExpList List of arguments to the function expression. * @param funcType Mathematical type for the function expression. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createFunctionExp(Location location, PosSymbol qualifier, PosSymbol name, edu.clemson.cs.r2jt.collections.List<Exp> argExpList, MTType funcType) { // Complicated steps to construct the argument list // YS: No idea why it is so complicated! FunctionArgList argList = new FunctionArgList(); argList.setArguments(argExpList); edu.clemson.cs.r2jt.collections.List<FunctionArgList> functionArgLists = new edu.clemson.cs.r2jt.collections.List<FunctionArgList>(); functionArgLists.add(argList); // Create the function expression FunctionExp exp = new FunctionExp(location, qualifier, name, null, functionArgLists); exp.setMathType(funcType); return exp; } /** * <p>Creates function expression "I_Dur" for a specified * variable.</p> * * @param var Local Variable. * @param realType Mathematical real type. * * @return The created <code>FunctionExp</code>. */ public static FunctionExp createInitAnyDur(VarDec var, MTType realType) { // Obtain the necessary information from the variable VarExp param = createVarExp(var.getLocation(), null, createPosSymbol(((NameTy) var.getTy()).getName() .getName()), var.getTy().getMathTypeValue(), null); // Create the list of arguments to the function edu.clemson.cs.r2jt.collections.List<Exp> params = new edu.clemson.cs.r2jt.collections.List<Exp>(); params.add(param); // Create the final duration FunctionExp initDurExp = createFunctionExp(var.getLocation(), null, createPosSymbol("I_Dur"), params, realType); return initDurExp; } /** * <p>Returns an <code>DotExp</code> with the <code>VarDec</code> * and its initialization ensures clause.</p> * * @param var The declared variable. * @param mType CLS type. * @param booleanType Mathematical boolean type. * * @return The new <code>DotExp</code>. */ public static DotExp createInitExp(VarDec var, MTType mType, MTType booleanType) { // Convert the declared variable into a VarExp VarExp varExp = createVarExp(var.getLocation(), null, var.getName(), var .getTy().getMathTypeValue(), null); // Left hand side of the expression VarExp left = null; // NameTy if (var.getTy() instanceof NameTy) { NameTy ty = (NameTy) var.getTy(); left = createVarExp(ty.getLocation(), ty.getQualifier(), ty .getName(), mType, null); } else { tyNotHandled(var.getTy(), var.getTy().getLocation()); } // Create the "Is_Initial" FunctionExp edu.clemson.cs.r2jt.collections.List<Exp> expList = new edu.clemson.cs.r2jt.collections.List<Exp>(); expList.add(varExp); FunctionExp right = createFunctionExp(var.getLocation(), null, createPosSymbol("Is_Initial"), expList, booleanType); // Create the DotExp edu.clemson.cs.r2jt.collections.List<Exp> exps = new edu.clemson.cs.r2jt.collections.List<Exp>(); exps.add(left); exps.add(right); DotExp exp = createDotExp(var.getLocation(), exps, booleanType); return exp; } /** * <p>Creates a less than equal infix expression.</p> * * @param location Location for the new infix expression. * @param left The left hand side of the less than equal expression. * @param right The right hand side of the less than equal expression. * @param booleanType Mathematical boolean type. * * @return The new <code>InfixExp</code>. */ public static InfixExp createLessThanEqExp(Location location, Exp left, Exp right, MTType booleanType) { // Create the "Less Than Equal" InfixExp InfixExp exp = new InfixExp(location, left, Utilities.createPosSymbol("<="), right); exp.setMathType(booleanType); return exp; } /** * <p>Creates a less than infix expression.</p> * * @param location Location for the new infix expression. * @param left The left hand side of the less than expression. * @param right The right hand side of the less than expression. * @param booleanType Mathematical boolean type. * * @return The new <code>InfixExp</code>. */ public static InfixExp createLessThanExp(Location location, Exp left, Exp right, MTType booleanType) { // Create the "Less Than" InfixExp InfixExp exp = new InfixExp(location, left, Utilities.createPosSymbol("<"), right); exp.setMathType(booleanType); return exp; } /** * <p>Returns a newly created <code>PosSymbol</code> * with the string provided.</p> * * @param name String of the new <code>PosSymbol</code>. * * @return The new <code>PosSymbol</code>. */ public static PosSymbol createPosSymbol(String name) { // Create the PosSymbol PosSymbol posSym = new PosSymbol(); posSym.setSymbol(Symbol.symbol(name)); return posSym; } /** * <p>Creates a variable expression with the name * "P_val" and has type "N".</p> * * @param location Location that wants to create * this variable. * @param scope The module scope to start our search. * * * @return The created <code>VarExp</code>. */ public static VarExp createPValExp(Location location, ModuleScope scope) { // Locate "N" (Natural Number) MathSymbolEntry mse = searchMathSymbol(location, "N", scope); try { // Create a variable with the name P_val return createVarExp(location, null, createPosSymbol("P_val"), mse .getTypeValue(), null); } catch (SymbolNotOfKindTypeException e) { notAType(mse, location); } return null; } /** * <p>Create a question mark variable with the oldVar * passed in.</p> * * @param exp The full expression clause. * @param oldVar The old variable expression. * * @return A new variable with the question mark in <code>VarExp</code> form. */ public static VarExp createQuestionMarkVariable(Exp exp, VarExp oldVar) { // Add an extra question mark to the front of oldVar VarExp newOldVar = new VarExp(null, null, createPosSymbol("?" + oldVar.getName().getName())); newOldVar.setMathType(oldVar.getMathType()); newOldVar.setMathTypeValue(oldVar.getMathTypeValue()); // Applies the question mark to oldVar if it is our first time visiting. if (exp.containsVar(oldVar.getName().getName(), false)) { return createQuestionMarkVariable(exp, newOldVar); } // Don't need to apply the question mark here. else if (exp.containsVar(newOldVar.getName().toString(), false)) { return createQuestionMarkVariable(exp, newOldVar); } else { // Return the new variable expression with the question mark if (oldVar.getName().getName().charAt(0) != '?') { return newOldVar; } } // Return our old self. return oldVar; } /** * <p>Returns a newly created <code>VarExp</code> * with the <code>PosSymbol</code> and math type provided.</p> * * @param loc Location of the new <code>VarExp</code>. * @param qualifier Qualifier of the <code>VarExp</code>. * @param name <code>PosSymbol</code> of the new <code>VarExp</code>. * @param type Math type of the new <code>VarExp</code>. * @param typeValue Math type value of the new <code>VarExp</code>. * * @return The new <code>VarExp</code>. */ public static VarExp createVarExp(Location loc, PosSymbol qualifier, PosSymbol name, MTType type, MTType typeValue) { // Create the VarExp VarExp exp = new VarExp(loc, qualifier, name); exp.setMathType(type); exp.setMathTypeValue(typeValue); return exp; } /** * <p>Gets the current "Cum_Dur" expression. We should only have one in * the current scope.</p> * * @param searchingExp The expression we are searching for "Cum_Dur" * * @return The current "Cum_Dur". */ public static String getCumDur(Exp searchingExp) { String cumDur = "Cum_Dur"; // Loop until we find one while (!searchingExp.containsVar(cumDur, false)) { cumDur = "?" + cumDur; } return cumDur; } /** * <p>Returns the math type for "Z".</p> * * @param location Current location in the AST. * @param scope The module scope to start our search. * * * @return The <code>MTType</code> for "Z". */ public static MTType getMathTypeZ(Location location, ModuleScope scope) { // Locate "Z" (Integer) MathSymbolEntry mse = searchMathSymbol(location, "Z", scope); MTType Z = null; try { Z = mse.getTypeValue(); } catch (SymbolNotOfKindTypeException e) { notAType(mse, location); } return Z; } public static Set<String> getSymbols(Exp exp) { // Return value Set<String> symbolsSet = new HashSet<String>(); // Not CharExp, DoubleExp, IntegerExp or StringExp if (!(exp instanceof CharExp) && !(exp instanceof DoubleExp) && !(exp instanceof IntegerExp) && !(exp instanceof StringExp)) { // AlternativeExp if (exp instanceof AlternativeExp) { List<AltItemExp> alternativesList = ((AlternativeExp) exp).getAlternatives(); // Iterate through each of the alternatives for (AltItemExp altExp : alternativesList) { Exp test = altExp.getTest(); Exp assignment = altExp.getAssignment(); // Don't loop if they are null if (test != null) { symbolsSet.addAll(getSymbols(altExp.getTest())); } if (assignment != null) { symbolsSet.addAll(getSymbols(altExp.getAssignment())); } } } // DotExp else if (exp instanceof DotExp) { List<Exp> segExpList = ((DotExp) exp).getSegments(); StringBuffer currentStr = new StringBuffer(); // Iterate through each of the segment expressions for (Exp e : segExpList) { // For each expression, obtain the set of symbols // and form a candidate expression. Set<String> retSet = getSymbols(e); for (String s : retSet) { if (currentStr.length() != 0) { currentStr.append("."); } currentStr.append(s); } symbolsSet.add(currentStr.toString()); } } // EqualsExp else if (exp instanceof EqualsExp) { symbolsSet.addAll(getSymbols(((EqualsExp) exp).getLeft())); symbolsSet.addAll(getSymbols(((EqualsExp) exp).getRight())); } // FunctionExp else if (exp instanceof FunctionExp) { FunctionExp funcExp = (FunctionExp) exp; StringBuffer funcName = new StringBuffer(); // Add the name of the function (including any qualifiers) if (funcExp.getQualifier() != null) { funcName.append(funcExp.getQualifier().getName()); funcName.append("."); } funcName.append(funcExp.getName()); symbolsSet.add(funcName.toString()); // Add all the symbols in the argument list List<FunctionArgList> funcArgList = funcExp.getParamList(); for (FunctionArgList f : funcArgList) { List<Exp> funcArgExpList = f.getArguments(); for (Exp e : funcArgExpList) { symbolsSet.addAll(getSymbols(e)); } } } // If Exp else if (exp instanceof IfExp) { symbolsSet.addAll(getSymbols(((IfExp) exp).getTest())); symbolsSet.addAll(getSymbols(((IfExp) exp).getThenclause())); symbolsSet.addAll(getSymbols(((IfExp) exp).getElseclause())); } // InfixExp else if (exp instanceof InfixExp) { symbolsSet.addAll(getSymbols(((InfixExp) exp).getLeft())); symbolsSet.addAll(getSymbols(((InfixExp) exp).getRight())); } // LambdaExp else if (exp instanceof LambdaExp) { LambdaExp lambdaExp = (LambdaExp) exp; // Add all the parameter variables List<MathVarDec> paramList = lambdaExp.getParameters(); for (MathVarDec v : paramList) { symbolsSet.add(v.getName().getName()); } // Add all the symbols in the body symbolsSet.addAll(getSymbols(lambdaExp.getBody())); } // OldExp else if (exp instanceof OldExp) { symbolsSet.add(exp.toString(0)); } // OutfixExp else if (exp instanceof OutfixExp) { symbolsSet.addAll(getSymbols(((OutfixExp) exp).getArgument())); } // PrefixExp else if (exp instanceof PrefixExp) { symbolsSet.addAll(getSymbols(((PrefixExp) exp).getArgument())); } // SetExp else if (exp instanceof SetExp) { SetExp setExp = (SetExp) exp; // Add all the parts that form the set expression symbolsSet.add(setExp.getVar().getName().getName()); symbolsSet.addAll(getSymbols(((SetExp) exp).getWhere())); symbolsSet.addAll(getSymbols(((SetExp) exp).getBody())); } // SuppositionExp else if (exp instanceof SuppositionExp) { SuppositionExp suppositionExp = (SuppositionExp) exp; // Add all the expressions symbolsSet.addAll(getSymbols(suppositionExp.getExp())); // Add all the variables List<MathVarDec> varList = suppositionExp.getVars(); for (MathVarDec v : varList) { symbolsSet.add(v.getName().getName()); } } // TupleExp else if (exp instanceof TupleExp) { TupleExp tupleExp = (TupleExp) exp; // Add all the expressions in the fields List<Exp> fieldList = tupleExp.getFields(); for (Exp e : fieldList) { symbolsSet.addAll(getSymbols(e)); } } // VarExp else if (exp instanceof VarExp) { VarExp varExp = (VarExp) exp; StringBuffer varName = new StringBuffer(); // Add the name of the variable (including any qualifiers) if (varExp.getQualifier() != null) { varName.append(varExp.getQualifier().getName()); varName.append("."); } varName.append(varExp.getName()); symbolsSet.add(varName.toString()); } // Not Handled! else { expNotHandled(exp, exp.getLocation()); } } return symbolsSet; } /** * <p>Get the <code>PosSymbol</code> associated with the * <code>VariableExp</code> left.</p> * * @param left The variable expression. * * @return The <code>PosSymbol</code> of left. */ public static PosSymbol getVarName(VariableExp left) { // Return value PosSymbol name = null; // Variable Name Expression if (left instanceof VariableNameExp) { name = ((VariableNameExp) left).getName(); } // Variable Dot Expression else if (left instanceof VariableDotExp) { VariableDotExp varDotExp = (VariableDotExp) left; for (VariableExp v : varDotExp.getSegments()) { PosSymbol tempName = getVarName(v); if (name == null) { name = tempName; } else { name = new PosSymbol(name.getLocation(), Symbol .symbol(name.getName() + "_" + tempName.getName())); } } } // Variable Record Expression else if (left instanceof VariableRecordExp) { VariableRecordExp varRecExp = (VariableRecordExp) left; name = varRecExp.getName(); } // // Creates an expression with "false" as its name else { name = createPosSymbol("false"); } return name; } /** * <p>Given the name of an operation check to see if it is a * local operation</p> * * @param name The name of the operation. * @param scope The module scope we are searching. * * @return True if it is a local operation, false otherwise. */ public static boolean isLocationOperation(String name, ModuleScope scope) { boolean isIn; // Query for the corresponding operation List<SymbolTableEntry> entries = scope .query(new NameQuery( null, name, MathSymbolTable.ImportStrategy.IMPORT_NONE, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE, true)); // Not found if (entries.size() == 0) { isIn = false; } // Found one else if (entries.size() == 1) { // If the operation is declared here, then it will be an OperationEntry. // Thus it is a local operation. if (entries.get(0) instanceof OperationEntry) { isIn = true; } else { isIn = false; } } // Found more than one else { //This should be caught earlier, when the duplicate symbol is //created throw new RuntimeException(); } return isIn; } /** * <p>Checks to see if the expression passed in is a * verification variable or not. A verification variable * is either "P_val" or starts with "?".</p> * * @param name Expression that we want to check * * @return True/False */ public static boolean isVerificationVar(Exp name) { // VarExp if (name instanceof VarExp) { String strName = ((VarExp) name).getName().getName(); // Case #1: Question mark variables if (strName.charAt(0) == '?') { return true; } // Case #2: P_val else if (strName.equals("P_val")) { return true; } } // DotExp else if (name instanceof DotExp) { // Recursively call this method until we get // either true or false. List<Exp> names = ((DotExp) name).getSegments(); return isVerificationVar(names.get(0)); } // Definitely not a verification variable. return false; } /** * <p>Negate the incoming expression.</p> * * @param exp Expression to be negated. * @param booleanType Mathematical boolean type. * * @return Negated expression. */ public static Exp negateExp(Exp exp, MTType booleanType) { Exp retExp = Exp.copy(exp); if (exp instanceof EqualsExp) { if (((EqualsExp) exp).getOperator() == EqualsExp.EQUAL) ((EqualsExp) retExp).setOperator(EqualsExp.NOT_EQUAL); else ((EqualsExp) retExp).setOperator(EqualsExp.EQUAL); } else if (exp instanceof PrefixExp) { if (((PrefixExp) exp).getSymbol().getName().toString() .equals("not")) { retExp = ((PrefixExp) exp).getArgument(); } } else { PrefixExp tmp = new PrefixExp(); setLocation(tmp, exp.getLocation()); tmp.setArgument(exp); tmp.setSymbol(createPosSymbol("not")); tmp.setMathType(booleanType); retExp = tmp; } return retExp; } /** * <p>Copy and replace the old <code>Exp</code>.</p> * * @param exp The <code>Exp</code> to be replaced. * @param old The old sub-expression of <code>exp</code>. * @param repl The new sub-expression of <code>exp</code>. * * @return The new <code>Exp</code>. */ public static Exp replace(Exp exp, Exp old, Exp repl) { // Clone old and repl and use the Exp replace to do all its work Exp tmp = Exp.replace(Exp.copy(exp), Exp.copy(old), Exp.copy(repl)); // Return the corresponding Exp if (tmp != null) return tmp; else return exp; } /** * <p>Replace the formal with the actual variables from the facility declaration to * the passed in clause.</p> * * @param opLoc Location of the calling statement. * @param clause The requires/ensures clause. * @param paramList The list of parameter variables. * @param instantiatedFacilityArgMap The map of facility formals to actuals. * @param scope The module scope to start our search. * * @return The clause in <code>Exp</code> form. */ public static Exp replaceFacilityFormalWithActual(Location opLoc, Exp clause, List<ParameterVarDec> paramList, Map<VarExp, FacilityFormalToActuals> instantiatedFacilityArgMap, ModuleScope scope) { // Make a copy of the original clause Exp newClause = Exp.copy(clause); for (ParameterVarDec dec : paramList) { if (dec.getTy() instanceof NameTy) { NameTy ty = (NameTy) dec.getTy(); PosSymbol tyName = ty.getName().copy(); PosSymbol tyQualifier = null; if (ty.getQualifier() != null) { tyQualifier = ty.getQualifier().copy(); } FacilityFormalToActuals formalToActuals = null; for (VarExp v : instantiatedFacilityArgMap.keySet()) { FacilityFormalToActuals temp = null; if (tyQualifier != null) { if (tyQualifier.getName().equals( v.getQualifier().getName()) && tyName.getName().equals( v.getName().getName())) { temp = instantiatedFacilityArgMap.get(v); } } else { if (tyName.getName().equals(v.getName().getName())) { temp = instantiatedFacilityArgMap.get(v); } } // Check to see if we already found one. If we did, it means that // the type is ambiguous and we can't be sure which one it is. if (temp != null) { if (formalToActuals == null) { formalToActuals = temp; } else { Utilities.ambiguousTy(ty, opLoc); } } } if (formalToActuals != null) { // Replace all concept formal arguments with their actuals Map<Exp, Exp> conceptMap = formalToActuals.getConceptArgMap(); for (Exp e : conceptMap.keySet()) { newClause = Utilities.replace(newClause, e, conceptMap .get(e)); } // Replace all concept realization formal arguments with their actuals Map<Exp, Exp> conceptRealizMap = formalToActuals.getConceptRealizArgMap(); for (Exp e : conceptRealizMap.keySet()) { newClause = Utilities.replace(newClause, e, conceptRealizMap.get(e)); } // Replace all enhancement [realization] formal arguments with their actuals for (PosSymbol p : formalToActuals.getEnhancementKeys()) { Map<Exp, Exp> enhancementMap = formalToActuals.getEnhancementArgMap(p); for (Exp e : enhancementMap.keySet()) { newClause = Utilities.replace(newClause, e, enhancementMap.get(e)); } } } else { // Ignore all generic types if (!(ty.getProgramTypeValue() instanceof PTGeneric)) { boolean found = false; // Check to see if the type of this variable is from an imported // concept type family definition. If we find one, we simply ignore this type. Iterator<SymbolTableEntry> programTypeDefIt = scope .query( new EntryTypeQuery<SymbolTableEntry>( ProgramTypeDefinitionEntry.class, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE)) .iterator(); while (programTypeDefIt.hasNext() && !found) { ProgramTypeDefinitionEntry entry = programTypeDefIt .next() .toProgramTypeDefinitionEntry(opLoc); if (entry.getName().equals(tyName.getName())) { found = true; } } if (!found) { // Check to see if the type of this variable is from an local // type representation. If we find one, we simply ignore this type. Iterator<SymbolTableEntry> representationTypeIt = scope .query( new EntryTypeQuery<SymbolTableEntry>( RepresentationTypeEntry.class, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE)) .iterator(); while (representationTypeIt.hasNext() && !found) { RepresentationTypeEntry entry = representationTypeIt.next() .toRepresentationTypeEntry( opLoc); if (entry.getName().equals(tyName.getName())) { found = true; } } // Throw an error if can't find one. if (!found) { Utilities.noSuchSymbol(tyQualifier, tyName .getName(), opLoc); } } } } } } return newClause; } /** * <p>Given a programming type, locate its constraint from the * Symbol Table.</p> * * @param location Location for the searching type. * @param typeAsExp The raw type as a variable expression. * @param varName Name of the variable. * @param scope The module scope to start our search. * * @return The constraint in <code>Exp</code> form if found, null otherwise. */ public static Exp retrieveConstraint(Location location, VarExp typeAsExp, Exp varName, ModuleScope scope) { Exp constraint = null; // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(location, typeAsExp.getQualifier(), typeAsExp.getName(), scope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(location); } else { typeEntry = ste.toRepresentationTypeEntry(location) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); constraint = replace(Exp.copy(type.getConstraint()), exemplar, varName); } else { notAType(typeEntry, location); } return constraint; } /** * <p>Given a math symbol name, locate and return * the <code>MathSymbolEntry</code> stored in the * symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param name The string name of the math symbol. * @param scope The module scope to start our search. * * @return An <code>MathSymbolEntry</code> from the * symbol table. */ public static MathSymbolEntry searchMathSymbol(Location loc, String name, ModuleScope scope) { // Query for the corresponding math symbol MathSymbolEntry ms = null; try { ms = scope .queryForOne( new UnqualifiedNameQuery( name, MathSymbolTable.ImportStrategy.IMPORT_RECURSIVE, MathSymbolTable.FacilityStrategy.FACILITY_IGNORE, true, true)).toMathSymbolEntry(loc); } catch (NoSuchSymbolException nsse) { noSuchSymbol(null, name, loc); } catch (DuplicateSymbolException dse) { //This should be caught earlier, when the duplicate symbol is //created throw new RuntimeException(dse); } return ms; } /** * <p>Given the qualifier, name and the list of argument * types, locate and return the <code>OperationEntry</code> * stored in the symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param qualifier The qualifier of the operation. * @param name The name of the operation. * @param argTypes The list of argument types. * @param scope The module scope to start our search. * * @return An <code>OperationEntry</code> from the * symbol table. */ public static OperationEntry searchOperation(Location loc, PosSymbol qualifier, PosSymbol name, List<PTType> argTypes, ModuleScope scope) { // Query for the corresponding operation OperationEntry op = null; try { op = scope.queryForOne(new OperationQuery(qualifier, name, argTypes)); } catch (NoSuchSymbolException nsse) { noSuchSymbol(null, name.getName(), loc); } catch (DuplicateSymbolException dse) { //This should be caught earlier, when the duplicate operation is //created throw new RuntimeException(dse); } return op; } /** * <p>Given the qualifier, name and the list of argument * types, locate and return the <code>OperationProfileEntry</code> * stored in the symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param qualifier The qualifier of the operation. * @param name The name of the operation. * @param argTypes The list of argument types. * @param scope The module scope to start our search. * * @return An <code>OperationProfileEntry</code> from the * symbol table. */ public static OperationProfileEntry searchOperationProfile(Location loc, PosSymbol qualifier, PosSymbol name, List<PTType> argTypes, ModuleScope scope) { // Query for the corresponding operation profile OperationProfileEntry ope = null; try { ope = scope.queryForOne(new OperationProfileQuery(qualifier, name, argTypes)); } catch (NoSuchSymbolException nsse) { noSuchModule(loc); } catch (DuplicateSymbolException dse) { // This should have been caught earlier, when the duplicate operation is // created. throw new RuntimeException(dse); } return ope; } /** * <p>Given the name of the type locate and return * the <code>SymbolTableEntry</code> stored in the * symbol table.</p> * * @param loc The location in the AST that we are * currently visiting. * @param qualifier The qualifier of the type. * @param name The name of the type. * @param scope The module scope to start our search. * * @return A <code>SymbolTableEntry</code> from the * symbol table. */ public static SymbolTableEntry searchProgramType(Location loc, PosSymbol qualifier, PosSymbol name, ModuleScope scope) { SymbolTableEntry retEntry = null; List<SymbolTableEntry> entries = scope.query(new NameQuery(qualifier, name, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_INSTANTIATE, false)); if (entries.size() == 0) { noSuchSymbol(qualifier, name.getName(), loc); } else if (entries.size() == 1) { retEntry = entries.get(0).toProgramTypeEntry(loc); } else { // When we have more than one, it means that we have a // type representation. In that case, we just need the // type representation. for (int i = 0; i < entries.size() && retEntry == null; i++) { SymbolTableEntry ste = entries.get(i); if (ste instanceof RepresentationTypeEntry) { retEntry = ste.toRepresentationTypeEntry(loc); } } // Throw duplicate symbol error if we don't have a type // representation if (retEntry == null) { //This should be caught earlier, when the duplicate type is //created throw new RuntimeException(); } } return retEntry; } /** * <p>Changes the <code>Exp</code> with the new * <code>Location</code>.</p> * * @param exp The <code>Exp</code> that needs to be modified. * @param loc The new <code>Location</code>. */ public static void setLocation(Exp exp, Location loc) { // Special handling for InfixExp if (exp instanceof InfixExp) { ((InfixExp) exp).setAllLocations(loc); } else { exp.setLocation(loc); } } public static List<Exp> splitConjunctExp(Exp exp, List<Exp> expList) { // Attempt to split the expression if it contains a conjunct if (exp instanceof InfixExp) { InfixExp infixExp = (InfixExp) exp; // Split the expression if it is a conjunct if (infixExp.getOpName().equals("and")) { expList = splitConjunctExp(infixExp.getLeft(), expList); expList = splitConjunctExp(infixExp.getRight(), expList); } // Otherwise simply add it to our list else { expList.add(infixExp); } } // Otherwise it is an individual assume statement we need to deal with. else { expList.add(exp); } return expList; } }
Added javadoc
src/main/java/edu/clemson/cs/r2jt/vcgeneration/Utilities.java
Added javadoc
<ide><path>rc/main/java/edu/clemson/cs/r2jt/vcgeneration/Utilities.java <ide> return Z; <ide> } <ide> <add> /** <add> * <p>Gets all the unique symbols in an expression.</p> <add> * <add> * @param exp The searching <code>Exp</code>. <add> * <add> * @return The set of symbols. <add> */ <ide> public static Set<String> getSymbols(Exp exp) { <ide> // Return value <ide> Set<String> symbolsSet = new HashSet<String>();
Java
apache-2.0
64aaf38dc3d4a079f803cdfb7c713beee0cac681
0
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
/* * Copyright (c) 2002-2015 "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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.impl.notification; import org.junit.Test; import java.util.Set; import java.util.TreeSet; import org.neo4j.graphdb.InputPosition; import org.neo4j.graphdb.Notification; import org.neo4j.graphdb.SeverityLevel; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.neo4j.graphdb.impl.notification.NotificationCode.CARTESIAN_PRODUCT; import static org.neo4j.graphdb.impl.notification.NotificationCode.INDEX_HINT_UNFULFILLABLE; public class NotificationCodeTest { @Test public void shouldConstructNotificationFor_INDEX_HINT_UNFULFILLABLE() { NotificationDetail indexDetail = NotificationDetail.Factory.index( "Person", "name" ); Notification notification = INDEX_HINT_UNFULFILLABLE.notification( InputPosition.empty, indexDetail ); assertThat( notification.getTitle(), equalTo( "The request (directly or indirectly) referred to an index that does not exist." ) ); assertThat( notification.getSeverity(), equalTo( SeverityLevel.WARNING ) ); assertThat( notification.getCode(), equalTo( "Neo.ClientError.Schema.NoSuchIndex" ) ); assertThat( notification.getPosition(), equalTo( InputPosition.empty ) ); assertThat( notification.getDescription(), equalTo( "The hinted index does not exist, please check the schema (hinted index is index on :Person(name))" ) ); } @Test public void shouldConstructNotificationFor_CARTESIAN_PRODUCT() { Set<String> idents = new TreeSet<>(); idents.add( "n" ); idents.add( "node2" ); NotificationDetail identifierDetail = NotificationDetail.Factory.cartesianProduct( idents ); Notification notification = CARTESIAN_PRODUCT.notification( InputPosition.empty, identifierDetail ); assertThat( notification.getTitle(), equalTo( "This query builds a cartesian product between disconnected patterns." ) ); assertThat( notification.getSeverity(), equalTo( SeverityLevel.WARNING ) ); assertThat( notification.getCode(), equalTo( "Neo.ClientNotification.Statement.CartesianProduct" ) ); assertThat( notification.getPosition(), equalTo( InputPosition.empty ) ); assertThat( notification.getDescription(), equalTo( "If a part of a query contains multiple disconnected patterns, this will build a cartesian product " + "between all those parts. This may produce a large amount of data and slow down query processing. While " + "occasionally intended, it may often be possible to reformulate the query that avoids the use of this cross " + "product, perhaps by adding a relationship between the different parts or by using OPTIONAL MATCH " + "(identifiers are: (n, node2))" ) ); } }
community/kernel/src/test/java/org/neo4j/graphdb/impl/notification/NotificationCodeTest.java
/* * Copyright (c) 2002-2015 "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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.impl.notification; import org.junit.Test; import java.util.HashSet; import java.util.Set; import org.neo4j.graphdb.InputPosition; import org.neo4j.graphdb.Notification; import org.neo4j.graphdb.SeverityLevel; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.neo4j.graphdb.impl.notification.NotificationCode.CARTESIAN_PRODUCT; import static org.neo4j.graphdb.impl.notification.NotificationCode.INDEX_HINT_UNFULFILLABLE; public class NotificationCodeTest { @Test public void shouldConstructNotificationFor_INDEX_HINT_UNFULFILLABLE() { NotificationDetail indexDetail = NotificationDetail.Factory.index( "Person", "name" ); Notification notification = INDEX_HINT_UNFULFILLABLE.notification( InputPosition.empty, indexDetail ); assertThat( notification.getTitle(), equalTo( "The request (directly or indirectly) referred to an index that does not exist." ) ); assertThat( notification.getSeverity(), equalTo( SeverityLevel.WARNING ) ); assertThat( notification.getCode(), equalTo( "Neo.ClientError.Schema.NoSuchIndex" ) ); assertThat( notification.getPosition(), equalTo( InputPosition.empty ) ); assertThat( notification.getDescription(), equalTo( "The hinted index does not exist, please check the schema (hinted index is index on :Person(name))" ) ); } @Test public void shouldConstructNotificationFor_CARTESIAN_PRODUCT() { Set<String> idents = new HashSet<>(); idents.add( "n" ); idents.add( "node2" ); NotificationDetail identifierDetail = NotificationDetail.Factory.cartesianProduct( idents ); Notification notification = CARTESIAN_PRODUCT.notification( InputPosition.empty, identifierDetail ); assertThat( notification.getTitle(), equalTo( "This query builds a cartesian product between disconnected patterns." ) ); assertThat( notification.getSeverity(), equalTo( SeverityLevel.WARNING ) ); assertThat( notification.getCode(), equalTo( "Neo.ClientNotification.Statement.CartesianProduct" ) ); assertThat( notification.getPosition(), equalTo( InputPosition.empty ) ); assertThat( notification.getDescription(), equalTo( "If a part of a query contains multiple disconnected patterns, this will build a cartesian product " + "between all those parts. This may produce a large amount of data and slow down query processing. While " + "occasionally intended, it may often be possible to reformulate the query that avoids the use of this cross " + "product, perhaps by adding a relationship between the different parts or by using OPTIONAL MATCH " + "(identifiers are: (n, node2))" ) ); } }
Fix NotificationCodeTest on Java8
community/kernel/src/test/java/org/neo4j/graphdb/impl/notification/NotificationCodeTest.java
Fix NotificationCodeTest on Java8
<ide><path>ommunity/kernel/src/test/java/org/neo4j/graphdb/impl/notification/NotificationCodeTest.java <ide> <ide> import org.junit.Test; <ide> <del>import java.util.HashSet; <ide> import java.util.Set; <add>import java.util.TreeSet; <ide> <ide> import org.neo4j.graphdb.InputPosition; <ide> import org.neo4j.graphdb.Notification; <ide> @Test <ide> public void shouldConstructNotificationFor_CARTESIAN_PRODUCT() <ide> { <del> Set<String> idents = new HashSet<>(); <add> Set<String> idents = new TreeSet<>(); <ide> idents.add( "n" ); <ide> idents.add( "node2" ); <ide> NotificationDetail identifierDetail = NotificationDetail.Factory.cartesianProduct( idents );
JavaScript
agpl-3.0
395d00619dc88eaa385f690c23aaf87e5d03f592
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; ( /** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { var recalcSlideInterval = 30; // Import var CreateAscColor = AscCommon.CreateAscColor; var g_oIdCounter = AscCommon.g_oIdCounter; var g_oTableId = AscCommon.g_oTableId; var isRealObject = AscCommon.isRealObject; var History = AscCommon.History; var c_oAscColor = Asc.c_oAscColor; var c_oAscFill = Asc.c_oAscFill; var asc_CShapeFill = Asc.asc_CShapeFill; var c_oAscFillGradType = Asc.c_oAscFillGradType; var c_oAscFillBlipType = Asc.c_oAscFillBlipType; var c_oAscStrokeType = Asc.c_oAscStrokeType; var asc_CShapeProperty = Asc.asc_CShapeProperty; var g_nodeAttributeStart = AscCommon.g_nodeAttributeStart; var g_nodeAttributeEnd = AscCommon.g_nodeAttributeEnd; var CChangesDrawingsBool = AscDFH.CChangesDrawingsBool; var CChangesDrawingsLong = AscDFH.CChangesDrawingsLong; var CChangesDrawingsDouble = AscDFH.CChangesDrawingsDouble; var CChangesDrawingsString = AscDFH.CChangesDrawingsString; var CChangesDrawingsObjectNoId = AscDFH.CChangesDrawingsObjectNoId; var CChangesDrawingsObject = AscDFH.CChangesDrawingsObject; var CChangesDrawingsContentNoId = AscDFH.CChangesDrawingsContentNoId; var CChangesDrawingsContentLong = AscDFH.CChangesDrawingsContentLong; var CChangesDrawingsContentLongMap = AscDFH.CChangesDrawingsContentLongMap; var CChangesDrawingsContent = AscDFH.CChangesDrawingsContent; function CBaseNoIdObject() { } CBaseNoIdObject.prototype.classType = AscDFH.historyitem_type_Unknown; CBaseNoIdObject.prototype.notAllowedWithoutId = function () { return false; }; CBaseNoIdObject.prototype.getObjectType = function () { return this.classType; }; CBaseNoIdObject.prototype.Get_Id = function () { return this.Id; }; CBaseNoIdObject.prototype.Write_ToBinary2 = function (oWriter) { oWriter.WriteLong(this.getObjectType()); oWriter.WriteString2(this.Get_Id()); }; CBaseNoIdObject.prototype.Read_FromBinary2 = function (oReader) { this.Id = oReader.GetString2(); }; CBaseNoIdObject.prototype.Refresh_RecalcData = function (oChange) { }; //open/save from/to xml CBaseNoIdObject.prototype.readAttr = function (reader) { while (reader.MoveToNextAttribute()) { this.readAttrXml(reader.GetNameNoNS(), reader); } }; CBaseNoIdObject.prototype.readAttrXml = function (name, reader) { //TODO:Implement in children }; CBaseNoIdObject.prototype.readChildXml = function (name, reader) { //TODO:Implement in children }; CBaseNoIdObject.prototype.writeAttrXmlImpl = function (writer) { //TODO:Implement in children }; CBaseNoIdObject.prototype.writeChildrenXml = function (writer) { //TODO:Implement in children }; CBaseNoIdObject.prototype.fromXml = function (reader, bSkipFirstNode) { if (bSkipFirstNode) { if (!reader.ReadNextNode()) { return; } } this.readAttr(reader); var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { var name = reader.GetNameNoNS(); this.readChildXml(name, reader); } }; CBaseNoIdObject.prototype.toXml = function (writer, name) { writer.WriteXmlNodeStart(name); this.writeAttrXml(writer); this.writeChildrenXml(writer); writer.WriteXmlNodeEnd(name); }; CBaseNoIdObject.prototype.writeAttrXml = function (writer) { this.writeAttrXmlImpl(writer); writer.WriteXmlAttributesEnd(); }; function CBaseObject() { CBaseNoIdObject.call(this); this.Id = null; if (AscCommon.g_oIdCounter.m_bLoad || History.CanAddChanges() || this.notAllowedWithoutId()) { this.Id = AscCommon.g_oIdCounter.Get_NewId(); AscCommon.g_oTableId.Add(this, this.Id); } } InitClass(CBaseObject, CBaseNoIdObject, AscDFH.historyitem_type_Unknown); function InitClassWithoutType(fClass, fBase) { fClass.prototype = Object.create(fBase.prototype); fClass.prototype.superclass = fBase; fClass.prototype.constructor = fClass; } function InitClass(fClass, fBase, nType) { InitClassWithoutType(fClass, fBase); fClass.prototype.classType = nType; } function CBaseFormatObject() { CBaseObject.call(this); this.parent = null; } CBaseFormatObject.prototype = Object.create(CBaseObject.prototype); CBaseFormatObject.prototype.constructor = CBaseFormatObject; CBaseFormatObject.prototype.classType = AscDFH.historyitem_type_Unknown; CBaseFormatObject.prototype.getObjectType = function () { return this.classType; }; CBaseFormatObject.prototype.setParent = function (oParent) { History.CanAddChanges() && History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_CommonChartFormat_SetParent, this.parent, oParent)); this.parent = oParent; }; CBaseFormatObject.prototype.getImageFromBulletsMap = function(oImages) {}; CBaseFormatObject.prototype.getDocContentsWithImageBullets = function (arrContents) {}; CBaseFormatObject.prototype.setParentToChild = function (oChild) { if (oChild && oChild.setParent) { oChild.setParent(this); } }; CBaseFormatObject.prototype.createDuplicate = function (oIdMap) { var oCopy = new this.constructor(); this.fillObject(oCopy, oIdMap); return oCopy; }; CBaseFormatObject.prototype.fillObject = function (oCopy, oIdMap) { }; CBaseFormatObject.prototype.fromPPTY = function (pReader) { var oStream = pReader.stream; var nStart = oStream.cur; var nEnd = nStart + oStream.GetULong() + 4; if (this.readAttribute) { this.readAttributes(pReader); } this.readChildren(nEnd, pReader); oStream.Seek2(nEnd); }; CBaseFormatObject.prototype.readAttributes = function (pReader) { var oStream = pReader.stream; oStream.Skip2(1); // start attributes while (true) { var nType = oStream.GetUChar(); if (nType == g_nodeAttributeEnd) break; this.readAttribute(nType, pReader) } }; CBaseFormatObject.prototype.readAttribute = function (nType, pReader) { }; CBaseFormatObject.prototype.readChildren = function (nEnd, pReader) { var oStream = pReader.stream; while (oStream.cur < nEnd) { var nType = oStream.GetUChar(); this.readChild(nType, pReader); } }; CBaseFormatObject.prototype.readChild = function (nType, pReader) { pReader.stream.SkipRecord(); }; CBaseFormatObject.prototype.toPPTY = function (pWriter) { if (this.privateWriteAttributes) { this.writeAttributes(pWriter); } this.writeChildren(pWriter); }; CBaseFormatObject.prototype.writeAttributes = function (pWriter) { pWriter.WriteUChar(g_nodeAttributeStart); this.privateWriteAttributes(pWriter); pWriter.WriteUChar(g_nodeAttributeEnd); }; CBaseFormatObject.prototype.privateWriteAttributes = function (pWriter) { }; CBaseFormatObject.prototype.writeChildren = function (pWriter) { }; CBaseFormatObject.prototype.writeRecord1 = function (pWriter, nType, oChild) { if (AscCommon.isRealObject(oChild)) { pWriter.WriteRecord1(nType, oChild, function (oChild) { oChild.toPPTY(pWriter); }); } else { //TODO: throw an error } }; CBaseFormatObject.prototype.writeRecord2 = function (pWriter, nType, oChild) { if (AscCommon.isRealObject(oChild)) { this.writeRecord1(pWriter, nType, oChild); } }; CBaseFormatObject.prototype.getChildren = function () { return []; }; CBaseFormatObject.prototype.traverse = function (fCallback) { if (fCallback(this)) { return true; } var aChildren = this.getChildren(); for (var nChild = aChildren.length - 1; nChild > -1; --nChild) { var oChild = aChildren[nChild]; if (oChild && oChild.traverse) { if (oChild.traverse(fCallback)) { return true; } } } return false; }; CBaseFormatObject.prototype.handleRemoveObject = function (sObjectId) { return false; }; CBaseFormatObject.prototype.onRemoveChild = function (oChild) { if (this.parent) { this.parent.onRemoveChild(this); } }; CBaseFormatObject.prototype.notAllowedWithoutId = function () { return true; }; CBaseFormatObject.prototype.isEqual = function (oOther) { if (!oOther) { return false; } if (this.getObjectType() !== oOther.getObjectType()) { return false; } var aThisChildren = this.getChildren(); var aOtherChildren = oOther.getChildren(); if (aThisChildren.length !== aOtherChildren.length) { return false; } for (var nChild = 0; nChild < aThisChildren.length; ++nChild) { var oThisChild = aThisChildren[nChild]; var oOtherChild = aOtherChildren[nChild]; if (oThisChild !== this.checkEqualChild(oThisChild, oOtherChild)) { return false; } } return true; }; CBaseFormatObject.prototype.checkEqualChild = function (oThisChild, oOtherChild) { if (AscCommon.isRealObject(oThisChild) && oThisChild.isEqual) { if (!oThisChild.isEqual(oOtherChild)) { return undefined; } } else { if (oThisChild !== oOtherChild) { return undefined; } } return oThisChild; }; //Method for debug CBaseObject.prototype.compareTypes = function (oOther) { if (!oOther || !oOther.compareTypes) { debugger; } for (var sKey in oOther) { if ((oOther[sKey] === null || oOther[sKey] === undefined) && (this[sKey] !== null && this[sKey] !== undefined) || (this[sKey] === null || this[sKey] === undefined) && (oOther[sKey] !== null && oOther[sKey] !== undefined) || (typeof this[sKey]) !== (typeof oOther[sKey])) { debugger; } if (this[sKey] !== this.parent && this[sKey] !== this.group && typeof this[sKey] === "object" && this[sKey] && this[sKey].compareTypes) { this[sKey].compareTypes(oOther[sKey]); } if (Array.isArray(this[sKey])) { if (!Array.isArray(oOther[sKey])) { debugger; } else { var a1 = this[sKey]; var a2 = oOther[sKey]; if (a1.length !== a2.length) { debugger; } else { for (var i = 0; i < a1.length; ++i) { if (!a1[i] || !a2[i]) { debugger; } if (typeof a1[i] === "object" && a1[i] && a1[i].compareTypes) { a1[i].compareTypes(a2[i]); } } } } } } }; function CT_Hyperlink() { CBaseNoIdObject.call(this); this.snd = null; this.id = null; this.invalidUrl = null; this.action = null; this.tgtFrame = null; this.tooltip = null; this.history = null; this.highlightClick = null; this.endSnd = null; } InitClass(CT_Hyperlink, CBaseNoIdObject, 0); CT_Hyperlink.prototype.Write_ToBinary = function (w) { var nStartPos = w.GetCurPosition(); var nFlags = 0; w.WriteLong(0); if (null !== this.snd) { nFlags |= 1; w.WriteString2(this.snd); } if (null !== this.id) { nFlags |= 2; w.WriteString2(this.id); } if (null !== this.invalidUrl) { nFlags |= 4; w.WriteString2(this.invalidUrl); } if (null !== this.action) { nFlags |= 8; w.WriteString2(this.action); } if (null !== this.tgtFrame) { nFlags |= 16; w.WriteString2(this.tgtFrame); } if (null !== this.tooltip) { nFlags |= 32; w.WriteString2(this.tooltip); } if (null !== this.history) { nFlags |= 64; w.WriteBool(this.history); } if (null !== this.highlightClick) { nFlags |= 128; w.WriteBool(this.highlightClick); } if (null !== this.endSnd) { nFlags |= 256; w.WriteBool(this.endSnd); } var nEndPos = w.GetCurPosition(); w.Seek(nStartPos); w.WriteLong(nFlags); w.Seek(nEndPos); }; CT_Hyperlink.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.snd = r.GetString2(); } if (nFlags & 2) { this.id = r.GetString2(); } if (nFlags & 4) { this.invalidUrl = r.GetString2(); } if (nFlags & 8) { this.action = r.GetString2(); } if (nFlags & 16) { this.tgtFrame = r.GetString2(); } if (nFlags & 32) { this.tooltip = r.GetString2(); } if (nFlags & 64) { this.history = r.GetBool(); } if (nFlags & 128) { this.highlightClick = r.GetBool(); } if (nFlags & 256) { this.endSnd = r.GetBool(); } }; CT_Hyperlink.prototype.createDuplicate = function () { var ret = new CT_Hyperlink(); ret.snd = this.snd; ret.id = this.id; ret.invalidUrl = this.invalidUrl; ret.action = this.action; ret.tgtFrame = this.tgtFrame; ret.tooltip = this.tooltip; ret.history = this.history; ret.highlightClick = this.highlightClick; ret.endSnd = this.endSnd; return ret; }; CT_Hyperlink.prototype.readAttrXml = function (name, reader) { switch (name) { case "action": { this.action = reader.GetValue(); break; } case "endSnd": { this.endSnd = reader.GetValueBool(); break; } case "highlightClick": { this.highlightClick = reader.GetValueBool(); break; } case "history": { this.history = reader.GetValueBool(); break; } case "id": { let id = reader.GetValueDecodeXml(); let rel = reader.rels.getRelationship(id); if (rel) { this.id = rel.target; } break; } case "invalidUrl": { this.invalidUrl = reader.GetValue(); break; } case "tgtFrame": { this.tgtFrame = reader.GetValue(); break; } case "tooltip": { this.tooltip = reader.GetValue(); break; } } }; CT_Hyperlink.prototype.writeAttrXmlImpl = function (writer) { if (this.id) { let id = writer.context.part.addRelationship(AscCommon.openXml.Types.hyperlink.relationType, this.id, AscCommon.openXml.TargetMode.external); writer.WriteXmlNullableAttributeString("r:id", id); } writer.WriteXmlNullableAttributeString("invalidUrl", this.invalidUrl); writer.WriteXmlNullableAttributeString("action", this.action); writer.WriteXmlNullableAttributeString("tgtFrame", this.tgtFrame); writer.WriteXmlNullableAttributeBool("history", this.history); writer.WriteXmlNullableAttributeBool("highlightClick", this.highlightClick); writer.WriteXmlNullableAttributeBool("endSnd", this.endSnd); }; var drawingsChangesMap = window['AscDFH'].drawingsChangesMap; var drawingConstructorsMap = window['AscDFH'].drawingsConstructorsMap; var drawingContentChanges = window['AscDFH'].drawingContentChanges; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetSpPr] = function (oClass, value) { oClass.spPr = value; }; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr] = function (oClass, value) { oClass.bodyPr = value; }; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle] = function (oClass, value) { oClass.lstStyle = value; }; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetStyle] = function (oClass, value) { oClass.style = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetId] = function (oClass, value) { oClass.id = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetName] = function (oClass, value) { oClass.name = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetIsHidden] = function (oClass, value) { oClass.isHidden = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetDescr] = function (oClass, value) { oClass.descr = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetTitle] = function (oClass, value) { oClass.title = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetHlinkClick] = function (oClass, value) { oClass.hlinkClick = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetHlinkHover] = function (oClass, value) { oClass.hlinkHover = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetIsPhoto] = function (oClass, value) { oClass.isPhoto = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetUserDrawn] = function (oClass, value) { oClass.userDrawn = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetPh] = function (oClass, value) { oClass.ph = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetHasCustomPrompt] = function (oClass, value) { oClass.hasCustomPrompt = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetIdx] = function (oClass, value) { oClass.idx = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetOrient] = function (oClass, value) { oClass.orient = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetSz] = function (oClass, value) { oClass.sz = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetType] = function (oClass, value) { oClass.type = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetCNvPr] = function (oClass, value) { oClass.cNvPr = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetUniPr] = function (oClass, value) { oClass.uniPr = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetNvPr] = function (oClass, value) { oClass.nvPr = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetLnRef] = function (oClass, value) { oClass.lnRef = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetFillRef] = function (oClass, value) { oClass.fillRef = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetFontRef] = function (oClass, value) { oClass.fontRef = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetEffectRef] = function (oClass, value) { oClass.effectRef = value; }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetParent] = function (oClass, value) { oClass.parent = value; }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetOffX] = function (oClass, value) { oClass.offX = value; oClass.handleUpdatePosition(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetOffY] = function (oClass, value) { oClass.offY = value; oClass.handleUpdatePosition(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetExtX] = function (oClass, value) { oClass.extX = value; oClass.handleUpdateExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetExtY] = function (oClass, value) { oClass.extY = value; oClass.handleUpdateExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChOffX] = function (oClass, value) { oClass.chOffX = value; oClass.handleUpdateChildOffset(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChOffY] = function (oClass, value) { oClass.chOffY = value; oClass.handleUpdateChildOffset(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChExtX] = function (oClass, value) { oClass.chExtX = value; oClass.handleUpdateChildExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChExtY] = function (oClass, value) { oClass.chExtY = value; oClass.handleUpdateChildExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetFlipH] = function (oClass, value) { oClass.flipH = value; oClass.handleUpdateFlip(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetFlipV] = function (oClass, value) { oClass.flipV = value; oClass.handleUpdateFlip(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetRot] = function (oClass, value) { oClass.rot = value; oClass.handleUpdateRot(); }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetParent] = function (oClass, value) { oClass.parent = value; }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetBwMode] = function (oClass, value) { oClass.bwMode = value; }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetXfrm] = function (oClass, value) { oClass.xfrm = value; }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetGeometry] = function (oClass, value) { oClass.geometry = value; oClass.handleUpdateGeometry(); }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetFill] = function (oClass, value, FromLoad) { oClass.Fill = value; oClass.handleUpdateFill(); if (FromLoad) { if (typeof AscCommon.CollaborativeEditing !== "undefined") { if (oClass.Fill && oClass.Fill.fill && oClass.Fill.fill.type === c_oAscFill.FILL_TYPE_BLIP && typeof oClass.Fill.fill.RasterImageId === "string" && oClass.Fill.fill.RasterImageId.length > 0) { AscCommon.CollaborativeEditing.Add_NewImage(oClass.Fill.fill.RasterImageId); } } } }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetLn] = function (oClass, value) { oClass.ln = value; oClass.handleUpdateLn(); }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetEffectPr] = function (oClass, value) { oClass.effectProps = value; oClass.handleUpdateGeometry(); }; drawingsChangesMap[AscDFH.historyitem_ExtraClrScheme_SetClrScheme] = function (oClass, value) { oClass.clrScheme = value; }; drawingsChangesMap[AscDFH.historyitem_ExtraClrScheme_SetClrMap] = function (oClass, value) { oClass.clrMap = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetColorScheme] = function (oClass, value) { oClass.themeElements.clrScheme = value; var oWordGraphicObjects = oClass.GetWordDrawingObjects(); if (oWordGraphicObjects) { oWordGraphicObjects.drawingDocument.CheckGuiControlColors(); oWordGraphicObjects.document.Api.chartPreviewManager.clearPreviews(); oWordGraphicObjects.document.Api.textArtPreviewManager.clear(); } }; drawingsChangesMap[AscDFH.historyitem_ThemeSetFontScheme] = function (oClass, value) { oClass.themeElements.fontScheme = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetFmtScheme] = function (oClass, value, bFromLoad) { oClass.themeElements.fmtScheme = value; if(bFromLoad) { if(typeof AscCommon.CollaborativeEditing !== "undefined") { if(value) { let aImages = []; value.getAllRasterImages(aImages); for(let nImage = 0; nImage < aImages.length; ++nImage) { AscCommon.CollaborativeEditing.Add_NewImage(aImages[nImage]); } } } } }; drawingsChangesMap[AscDFH.historyitem_ThemeSetName] = function (oClass, value) { oClass.name = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetIsThemeOverride] = function (oClass, value) { oClass.isThemeOverride = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetSpDef] = function (oClass, value) { oClass.spDef = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetLnDef] = function (oClass, value) { oClass.lnDef = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetTxDef] = function (oClass, value) { oClass.txDef = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetDt] = function (oClass, value) { oClass.dt = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetFtr] = function (oClass, value) { oClass.ftr = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetHdr] = function (oClass, value) { oClass.hdr = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetSldNum] = function (oClass, value) { oClass.sldNum = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetUniSpPr] = function (oClass, value) { oClass.nvUniSpPr = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetUniMedia] = function (oClass, value) { oClass.unimedia = value; }; drawingContentChanges[AscDFH.historyitem_ClrMap_SetClr] = function (oClass) { return oClass.color_map }; drawingContentChanges[AscDFH.historyitem_ThemeAddExtraClrScheme] = function (oClass) { return oClass.extraClrSchemeLst; }; drawingContentChanges[AscDFH.historyitem_ThemeRemoveExtraClrScheme] = function (oClass) { return oClass.extraClrSchemeLst; }; drawingConstructorsMap[AscDFH.historyitem_ClrMap_SetClr] = CUniColor; drawingConstructorsMap[AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr] = CBodyPr; drawingConstructorsMap[AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle] = TextListStyle; drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetLnRef] = drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetFillRef] = drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetEffectRef] = StyleRef; drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetFontRef] = FontRef; drawingConstructorsMap[AscDFH.historyitem_SpPr_SetFill] = CUniFill; drawingConstructorsMap[AscDFH.historyitem_SpPr_SetLn] = CLn; drawingConstructorsMap[AscDFH.historyitem_SpPr_SetEffectPr] = CEffectProperties; drawingConstructorsMap[AscDFH.historyitem_ThemeSetColorScheme] = ClrScheme; drawingConstructorsMap[AscDFH.historyitem_ThemeSetFontScheme] = FontScheme; drawingConstructorsMap[AscDFH.historyitem_ThemeSetFmtScheme] = FmtScheme; drawingConstructorsMap[AscDFH.historyitem_UniNvPr_SetUniSpPr] = CNvUniSpPr; drawingConstructorsMap[AscDFH.historyitem_CNvPr_SetHlinkClick] = CT_Hyperlink; drawingConstructorsMap[AscDFH.historyitem_CNvPr_SetHlinkHover] = CT_Hyperlink; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetSpPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetStyle] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetId] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetName] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetIsHidden] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetDescr] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetTitle] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetHlinkClick] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetHlinkHover] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetIsPhoto] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetUserDrawn] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetPh] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetUniMedia] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetHasCustomPrompt] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetIdx] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetOrient] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetSz] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetType] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetCNvPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetUniPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetNvPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetUniSpPr] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetLnRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetFillRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetFontRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetEffectRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetParent] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetOffX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetOffY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetExtX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetExtY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChOffX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChOffY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChExtX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChExtY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetFlipH] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetFlipV] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetRot] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetParent] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetBwMode] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetXfrm] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetGeometry] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetFill] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetLn] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetEffectPr] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ClrMap_SetClr] = CChangesDrawingsContentLongMap; AscDFH.changesFactory[AscDFH.historyitem_ExtraClrScheme_SetClrScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ExtraClrScheme_SetClrMap] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetColorScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetFontScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetFmtScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetName] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetIsThemeOverride] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetSpDef] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetLnDef] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetTxDef] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeAddExtraClrScheme] = CChangesDrawingsContent; AscDFH.changesFactory[AscDFH.historyitem_ThemeRemoveExtraClrScheme] = CChangesDrawingsContent; AscDFH.changesFactory[AscDFH.historyitem_HF_SetDt] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HF_SetFtr] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HF_SetHdr] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HF_SetSldNum] = CChangesDrawingsBool; // COLOR ----------------------- /* var map_color_scheme = {}; map_color_scheme["accent1"] = 0; map_color_scheme["accent2"] = 1; map_color_scheme["accent3"] = 2; map_color_scheme["accent4"] = 3; map_color_scheme["accent5"] = 4; map_color_scheme["accent6"] = 5; map_color_scheme["bg1"] = 6; map_color_scheme["bg2"] = 7; map_color_scheme["dk1"] = 8; map_color_scheme["dk2"] = 9; map_color_scheme["folHlink"] = 10; map_color_scheme["hlink"] = 11; map_color_scheme["lt1"] = 12; map_color_scheme["lt2"] = 13; map_color_scheme["phClr"] = 14; map_color_scheme["tx1"] = 15; map_color_scheme["tx2"] = 16; */ //ะขะธะฟั‹ ะธะทะผะตะฝะตะฝะธะน ะฒ ะบะปะฐััะต CTheme function CreateFontRef(idx, color) { var ret = new FontRef(); ret.idx = idx; ret.Color = color; return ret; } function CreateStyleRef(idx, color) { var ret = new StyleRef(); ret.idx = idx; ret.Color = color; return ret; } function CreatePresetColor(id) { var ret = new CPrstColor(); ret.id = id; return ret; } function sRGB_to_scRGB(value) { if (value < 0) return 0; if (value <= 0.04045) return value / 12.92; if (value <= 1) return Math.pow(((value + 0.055) / 1.055), 2.4); return 1; } function scRGB_to_sRGB(value) { if (value < 0) return 0; if (value <= 0.0031308) return value * 12.92; if (value < 1) return 1.055 * (Math.pow(value, (1 / 2.4))) - 0.055; return 1; } function checkRasterImageId(rasterImageId) { var imageLocal = AscCommon.g_oDocumentUrls.getImageLocal(rasterImageId); return imageLocal ? imageLocal : rasterImageId; } var g_oThemeFontsName = {}; g_oThemeFontsName["+mj-cs"] = true; g_oThemeFontsName["+mj-ea"] = true; g_oThemeFontsName["+mj-lt"] = true; g_oThemeFontsName["+mn-cs"] = true; g_oThemeFontsName["+mn-ea"] = true; g_oThemeFontsName["+mn-lt"] = true; g_oThemeFontsName["majorAscii"] = true; g_oThemeFontsName["majorBidi"] = true; g_oThemeFontsName["majorEastAsia"] = true; g_oThemeFontsName["majorHAnsi"] = true; g_oThemeFontsName["minorAscii"] = true; g_oThemeFontsName["minorBidi"] = true; g_oThemeFontsName["minorEastAsia"] = true; g_oThemeFontsName["minorHAnsi"] = true; function isRealNumber(n) { return typeof n === "number" && !isNaN(n); } function isRealBool(b) { return b === true || b === false; } function writeLong(w, val) { w.WriteBool(isRealNumber(val)); if (isRealNumber(val)) { w.WriteLong(val); } } function readLong(r) { var ret; if (r.GetBool()) { ret = r.GetLong(); } else { ret = null; } return ret; } function writeDouble(w, val) { w.WriteBool(isRealNumber(val)); if (isRealNumber(val)) { w.WriteDouble(val); } } function readDouble(r) { var ret; if (r.GetBool()) { ret = r.GetDouble(); } else { ret = null; } return ret; } function writeBool(w, val) { w.WriteBool(isRealBool(val)); if (isRealBool(val)) { w.WriteBool(val); } } function readBool(r) { var ret; if (r.GetBool()) { ret = r.GetBool(); } else { ret = null; } return ret; } function writeString(w, val) { w.WriteBool(typeof val === "string"); if (typeof val === "string") { w.WriteString2(val); } } function readString(r) { var ret; if (r.GetBool()) { ret = r.GetString2(); } else { ret = null; } return ret; } function writeObject(w, val) { w.WriteBool(isRealObject(val)); if (isRealObject(val)) { w.WriteString2(val.Get_Id()); } } function readObject(r) { var ret; if (r.GetBool()) { ret = g_oTableId.Get_ById(r.GetString2()); } else { ret = null; } return ret; } function checkThemeFonts(oFontMap, font_scheme) { if (oFontMap["+mj-lt"]) { if (font_scheme.majorFont && typeof font_scheme.majorFont.latin === "string" && font_scheme.majorFont.latin.length > 0) oFontMap[font_scheme.majorFont.latin] = 1; delete oFontMap["+mj-lt"]; } if (oFontMap["+mj-ea"]) { if (font_scheme.majorFont && typeof font_scheme.majorFont.ea === "string" && font_scheme.majorFont.ea.length > 0) oFontMap[font_scheme.majorFont.ea] = 1; delete oFontMap["+mj-ea"]; } if (oFontMap["+mj-cs"]) { if (font_scheme.majorFont && typeof font_scheme.majorFont.cs === "string" && font_scheme.majorFont.cs.length > 0) oFontMap[font_scheme.majorFont.cs] = 1; delete oFontMap["+mj-cs"]; } if (oFontMap["+mn-lt"]) { if (font_scheme.minorFont && typeof font_scheme.minorFont.latin === "string" && font_scheme.minorFont.latin.length > 0) oFontMap[font_scheme.minorFont.latin] = 1; delete oFontMap["+mn-lt"]; } if (oFontMap["+mn-ea"]) { if (font_scheme.minorFont && typeof font_scheme.minorFont.ea === "string" && font_scheme.minorFont.ea.length > 0) oFontMap[font_scheme.minorFont.ea] = 1; delete oFontMap["+mn-ea"]; } if (oFontMap["+mn-cs"]) { if (font_scheme.minorFont && typeof font_scheme.minorFont.cs === "string" && font_scheme.minorFont.cs.length > 0) oFontMap[font_scheme.minorFont.cs] = 1; delete oFontMap["+mn-cs"]; } } function ExecuteNoHistory(f, oThis, args) { History.TurnOff && History.TurnOff(); var b_table_id = false; if (g_oTableId && !g_oTableId.m_bTurnOff) { g_oTableId.m_bTurnOff = true; b_table_id = true; } var ret = f.apply(oThis, args); History.TurnOn && History.TurnOn(); if (b_table_id) { g_oTableId.m_bTurnOff = false; } return ret; } function checkObjectUnifill(obj, theme, colorMap) { if (obj && obj.Unifill) { obj.Unifill.check(theme, colorMap); var rgba = obj.Unifill.getRGBAColor(); obj.Color = new CDocumentColor(rgba.R, rgba.G, rgba.B, false); } } function checkTableCellPr(cellPr, slide, layout, master, theme) { cellPr.Check_PresentationPr(theme); var color_map, rgba; if (slide.clrMap) { color_map = slide.clrMap; } else if (layout.clrMap) { color_map = layout.clrMap; } else if (master.clrMap) { color_map = master.clrMap; } else { color_map = AscFormat.GetDefaultColorMap(); } checkObjectUnifill(cellPr.Shd, theme, color_map); if (cellPr.TableCellBorders) { checkObjectUnifill(cellPr.TableCellBorders.Left, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.Top, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.Right, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.Bottom, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.InsideH, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.InsideV, theme, color_map); } return cellPr; } var Ax_Counter = { GLOBAL_AX_ID_COUNTER: 1000 }; var TYPE_TRACK = { SHAPE: 0, GROUP: 0, GROUP_PASSIVE: 1, TEXT: 2, EMPTY_PH: 3, CHART_TEXT: 4, CROP: 5 }; var TYPE_KIND = { SLIDE: 0, LAYOUT: 1, MASTER: 2, NOTES: 3, NOTES_MASTER: 4 }; var TYPE_TRACK_SHAPE = 0; var TYPE_TRACK_GROUP = TYPE_TRACK_SHAPE; var TYPE_TRACK_GROUP_PASSIVE = 1; var TYPE_TRACK_TEXT = 2; var TYPE_TRACK_EMPTY_PH = 3; var TYPE_TRACK_CHART = 4; var SLIDE_KIND = 0; var LAYOUT_KIND = 1; var MASTER_KIND = 2; var map_hightlight = {}; map_hightlight["black"] = 0x000000; map_hightlight["blue"] = 0x0000FF; map_hightlight["cyan"] = 0x00FFFF; map_hightlight["darkBlue"] = 0x00008B; map_hightlight["darkCyan"] = 0x008B8B; map_hightlight["darkGray"] = 0x0A9A9A9; map_hightlight["darkGreen"] = 0x006400; map_hightlight["darkMagenta"] = 0x800080; map_hightlight["darkRed"] = 0x8B0000; map_hightlight["darkYellow"] = 0x808000; map_hightlight["green"] = 0x00FF00; map_hightlight["lightGray"] = 0xD3D3D3; map_hightlight["magenta"] = 0xFF00FF; map_hightlight["none"] = 0x000000; map_hightlight["red"] = 0xFF0000; map_hightlight["white"] = 0xFFFFFF; map_hightlight["yellow"] = 0xFFFF00; var map_prst_color = {}; map_prst_color["aliceBlue"] = 0xF0F8FF; map_prst_color["antiqueWhite"] = 0xFAEBD7; map_prst_color["aqua"] = 0x00FFFF; map_prst_color["aquamarine"] = 0x7FFFD4; map_prst_color["azure"] = 0xF0FFFF; map_prst_color["beige"] = 0xF5F5DC; map_prst_color["bisque"] = 0xFFE4C4; map_prst_color["black"] = 0x000000; map_prst_color["blanchedAlmond"] = 0xFFEBCD; map_prst_color["blue"] = 0x0000FF; map_prst_color["blueViolet"] = 0x8A2BE2; map_prst_color["brown"] = 0xA52A2A; map_prst_color["burlyWood"] = 0xDEB887; map_prst_color["cadetBlue"] = 0x5F9EA0; map_prst_color["chartreuse"] = 0x7FFF00; map_prst_color["chocolate"] = 0xD2691E; map_prst_color["coral"] = 0xFF7F50; map_prst_color["cornflowerBlue"] = 0x6495ED; map_prst_color["cornsilk"] = 0xFFF8DC; map_prst_color["crimson"] = 0xDC143C; map_prst_color["cyan"] = 0x00FFFF; map_prst_color["darkBlue"] = 0x00008B; map_prst_color["darkCyan"] = 0x008B8B; map_prst_color["darkGoldenrod"] = 0xB8860B; map_prst_color["darkGray"] = 0xA9A9A9; map_prst_color["darkGreen"] = 0x006400; map_prst_color["darkGrey"] = 0xA9A9A9; map_prst_color["darkKhaki"] = 0xBDB76B; map_prst_color["darkMagenta"] = 0x8B008B; map_prst_color["darkOliveGreen"] = 0x556B2F; map_prst_color["darkOrange"] = 0xFF8C00; map_prst_color["darkOrchid"] = 0x9932CC; map_prst_color["darkRed"] = 0x8B0000; map_prst_color["darkSalmon"] = 0xE9967A; map_prst_color["darkSeaGreen"] = 0x8FBC8F; map_prst_color["darkSlateBlue"] = 0x483D8B; map_prst_color["darkSlateGray"] = 0x2F4F4F; map_prst_color["darkSlateGrey"] = 0x2F4F4F; map_prst_color["darkTurquoise"] = 0x00CED1; map_prst_color["darkViolet"] = 0x9400D3; map_prst_color["deepPink"] = 0xFF1493; map_prst_color["deepSkyBlue"] = 0x00BFFF; map_prst_color["dimGray"] = 0x696969; map_prst_color["dimGrey"] = 0x696969; map_prst_color["dkBlue"] = 0x00008B; map_prst_color["dkCyan"] = 0x008B8B; map_prst_color["dkGoldenrod"] = 0xB8860B; map_prst_color["dkGray"] = 0xA9A9A9; map_prst_color["dkGreen"] = 0x006400; map_prst_color["dkGrey"] = 0xA9A9A9; map_prst_color["dkKhaki"] = 0xBDB76B; map_prst_color["dkMagenta"] = 0x8B008B; map_prst_color["dkOliveGreen"] = 0x556B2F; map_prst_color["dkOrange"] = 0xFF8C00; map_prst_color["dkOrchid"] = 0x9932CC; map_prst_color["dkRed"] = 0x8B0000; map_prst_color["dkSalmon"] = 0xE9967A; map_prst_color["dkSeaGreen"] = 0x8FBC8B; map_prst_color["dkSlateBlue"] = 0x483D8B; map_prst_color["dkSlateGray"] = 0x2F4F4F; map_prst_color["dkSlateGrey"] = 0x2F4F4F; map_prst_color["dkTurquoise"] = 0x00CED1; map_prst_color["dkViolet"] = 0x9400D3; map_prst_color["dodgerBlue"] = 0x1E90FF; map_prst_color["firebrick"] = 0xB22222; map_prst_color["floralWhite"] = 0xFFFAF0; map_prst_color["forestGreen"] = 0x228B22; map_prst_color["fuchsia"] = 0xFF00FF; map_prst_color["gainsboro"] = 0xDCDCDC; map_prst_color["ghostWhite"] = 0xF8F8FF; map_prst_color["gold"] = 0xFFD700; map_prst_color["goldenrod"] = 0xDAA520; map_prst_color["gray"] = 0x808080; map_prst_color["green"] = 0x008000; map_prst_color["greenYellow"] = 0xADFF2F; map_prst_color["grey"] = 0x808080; map_prst_color["honeydew"] = 0xF0FFF0; map_prst_color["hotPink"] = 0xFF69B4; map_prst_color["indianRed"] = 0xCD5C5C; map_prst_color["indigo"] = 0x4B0082; map_prst_color["ivory"] = 0xFFFFF0; map_prst_color["khaki"] = 0xF0E68C; map_prst_color["lavender"] = 0xE6E6FA; map_prst_color["lavenderBlush"] = 0xFFF0F5; map_prst_color["lawnGreen"] = 0x7CFC00; map_prst_color["lemonChiffon"] = 0xFFFACD; map_prst_color["lightBlue"] = 0xADD8E6; map_prst_color["lightCoral"] = 0xF08080; map_prst_color["lightCyan"] = 0xE0FFFF; map_prst_color["lightGoldenrodYellow"] = 0xFAFAD2; map_prst_color["lightGray"] = 0xD3D3D3; map_prst_color["lightGreen"] = 0x90EE90; map_prst_color["lightGrey"] = 0xD3D3D3; map_prst_color["lightPink"] = 0xFFB6C1; map_prst_color["lightSalmon"] = 0xFFA07A; map_prst_color["lightSeaGreen"] = 0x20B2AA; map_prst_color["lightSkyBlue"] = 0x87CEFA; map_prst_color["lightSlateGray"] = 0x778899; map_prst_color["lightSlateGrey"] = 0x778899; map_prst_color["lightSteelBlue"] = 0xB0C4DE; map_prst_color["lightYellow"] = 0xFFFFE0; map_prst_color["lime"] = 0x00FF00; map_prst_color["limeGreen"] = 0x32CD32; map_prst_color["linen"] = 0xFAF0E6; map_prst_color["ltBlue"] = 0xADD8E6; map_prst_color["ltCoral"] = 0xF08080; map_prst_color["ltCyan"] = 0xE0FFFF; map_prst_color["ltGoldenrodYellow"] = 0xFAFA78; map_prst_color["ltGray"] = 0xD3D3D3; map_prst_color["ltGreen"] = 0x90EE90; map_prst_color["ltGrey"] = 0xD3D3D3; map_prst_color["ltPink"] = 0xFFB6C1; map_prst_color["ltSalmon"] = 0xFFA07A; map_prst_color["ltSeaGreen"] = 0x20B2AA; map_prst_color["ltSkyBlue"] = 0x87CEFA; map_prst_color["ltSlateGray"] = 0x778899; map_prst_color["ltSlateGrey"] = 0x778899; map_prst_color["ltSteelBlue"] = 0xB0C4DE; map_prst_color["ltYellow"] = 0xFFFFE0; map_prst_color["magenta"] = 0xFF00FF; map_prst_color["maroon"] = 0x800000; map_prst_color["medAquamarine"] = 0x66CDAA; map_prst_color["medBlue"] = 0x0000CD; map_prst_color["mediumAquamarine"] = 0x66CDAA; map_prst_color["mediumBlue"] = 0x0000CD; map_prst_color["mediumOrchid"] = 0xBA55D3; map_prst_color["mediumPurple"] = 0x9370DB; map_prst_color["mediumSeaGreen"] = 0x3CB371; map_prst_color["mediumSlateBlue"] = 0x7B68EE; map_prst_color["mediumSpringGreen"] = 0x00FA9A; map_prst_color["mediumTurquoise"] = 0x48D1CC; map_prst_color["mediumVioletRed"] = 0xC71585; map_prst_color["medOrchid"] = 0xBA55D3; map_prst_color["medPurple"] = 0x9370DB; map_prst_color["medSeaGreen"] = 0x3CB371; map_prst_color["medSlateBlue"] = 0x7B68EE; map_prst_color["medSpringGreen"] = 0x00FA9A; map_prst_color["medTurquoise"] = 0x48D1CC; map_prst_color["medVioletRed"] = 0xC71585; map_prst_color["midnightBlue"] = 0x191970; map_prst_color["mintCream"] = 0xF5FFFA; map_prst_color["mistyRose"] = 0xFFE4FF; map_prst_color["moccasin"] = 0xFFE4B5; map_prst_color["navajoWhite"] = 0xFFDEAD; map_prst_color["navy"] = 0x000080; map_prst_color["oldLace"] = 0xFDF5E6; map_prst_color["olive"] = 0x808000; map_prst_color["oliveDrab"] = 0x6B8E23; map_prst_color["orange"] = 0xFFA500; map_prst_color["orangeRed"] = 0xFF4500; map_prst_color["orchid"] = 0xDA70D6; map_prst_color["paleGoldenrod"] = 0xEEE8AA; map_prst_color["paleGreen"] = 0x98FB98; map_prst_color["paleTurquoise"] = 0xAFEEEE; map_prst_color["paleVioletRed"] = 0xDB7093; map_prst_color["papayaWhip"] = 0xFFEFD5; map_prst_color["peachPuff"] = 0xFFDAB9; map_prst_color["peru"] = 0xCD853F; map_prst_color["pink"] = 0xFFC0CB; map_prst_color["plum"] = 0xD3A0D3; map_prst_color["powderBlue"] = 0xB0E0E6; map_prst_color["purple"] = 0x800080; map_prst_color["red"] = 0xFF0000; map_prst_color["rosyBrown"] = 0xBC8F8F; map_prst_color["royalBlue"] = 0x4169E1; map_prst_color["saddleBrown"] = 0x8B4513; map_prst_color["salmon"] = 0xFA8072; map_prst_color["sandyBrown"] = 0xF4A460; map_prst_color["seaGreen"] = 0x2E8B57; map_prst_color["seaShell"] = 0xFFF5EE; map_prst_color["sienna"] = 0xA0522D; map_prst_color["silver"] = 0xC0C0C0; map_prst_color["skyBlue"] = 0x87CEEB; map_prst_color["slateBlue"] = 0x6A5AEB; map_prst_color["slateGray"] = 0x708090; map_prst_color["slateGrey"] = 0x708090; map_prst_color["snow"] = 0xFFFAFA; map_prst_color["springGreen"] = 0x00FF7F; map_prst_color["steelBlue"] = 0x4682B4; map_prst_color["tan"] = 0xD2B48C; map_prst_color["teal"] = 0x008080; map_prst_color["thistle"] = 0xD8BFD8; map_prst_color["tomato"] = 0xFF7347; map_prst_color["turquoise"] = 0x40E0D0; map_prst_color["violet"] = 0xEE82EE; map_prst_color["wheat"] = 0xF5DEB3; map_prst_color["white"] = 0xFFFFFF; map_prst_color["whiteSmoke"] = 0xF5F5F5; map_prst_color["yellow"] = 0xFFFF00; map_prst_color["yellowGreen"] = 0x9ACD32; function CColorMod() { this.name = ""; this.val = 0; } CColorMod.prototype.setName = function (name) { this.name = name; }; CColorMod.prototype.setVal = function (val) { this.val = val; }; CColorMod.prototype.createDuplicate = function () { var duplicate = new CColorMod(); duplicate.name = this.name; duplicate.val = this.val; return duplicate; }; CColorMod.prototype.toXml = function (writer) { let sName; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sName = "w14:" + this.name; sAttrNamespace = "w14:"; } else { sName = "a:" + this.name; } let sValAttrName = sAttrNamespace + "val"; writer.WriteXmlNodeStart(sName); writer.WriteXmlNullableAttributeUInt(sValAttrName, this.val); writer.WriteXmlAttributesEnd(true); }; var cd16 = 1.0 / 6.0; var cd13 = 1.0 / 3.0; var cd23 = 2.0 / 3.0; var max_hls = 255.0; var DEC_GAMMA = 2.3; var INC_GAMMA = 1.0 / DEC_GAMMA; var MAX_PERCENT = 100000; function CColorModifiers() { this.Mods = []; } CColorModifiers.prototype.isUsePow = (!AscCommon.AscBrowser.isSailfish || !AscCommon.AscBrowser.isEmulateDevicePixelRatio); CColorModifiers.prototype.getModValue = function (sName) { if (Array.isArray(this.Mods)) { for (var i = 0; i < this.Mods.length; ++i) { if (this.Mods[i] && this.Mods[i].name === sName) { return this.Mods[i].val; } } } return null; }; CColorModifiers.prototype.Write_ToBinary = function (w) { w.WriteLong(this.Mods.length); for (var i = 0; i < this.Mods.length; ++i) { w.WriteString2(this.Mods[i].name); w.WriteLong(this.Mods[i].val); } }; CColorModifiers.prototype.Read_FromBinary = function (r) { var len = r.GetLong(); for (var i = 0; i < len; ++i) { var mod = new CColorMod(); mod.name = r.GetString2(); mod.val = r.GetLong(); this.Mods.push(mod); } }; CColorModifiers.prototype.addMod = function (mod) { this.Mods.push(mod); }; CColorModifiers.prototype.removeMod = function (pos) { this.Mods.splice(pos, 1)[0]; }; CColorModifiers.prototype.IsIdentical = function (mods) { if (mods == null) { return false } if (mods.Mods == null || this.Mods.length !== mods.Mods.length) { return false; } for (var i = 0; i < this.Mods.length; ++i) { if (this.Mods[i].name !== mods.Mods[i].name || this.Mods[i].val !== mods.Mods[i].val) { return false; } } return true; }; CColorModifiers.prototype.createDuplicate = function () { var duplicate = new CColorModifiers(); for (var i = 0; i < this.Mods.length; ++i) { duplicate.Mods[i] = this.Mods[i].createDuplicate(); } return duplicate; }; CColorModifiers.prototype.RGB2HSL = function (R, G, B, HLS) { var iMin = (R < G ? R : G); iMin = iMin < B ? iMin : B;//Math.min(R, G, B); var iMax = (R > G ? R : G); iMax = iMax > B ? iMax : B;//Math.max(R, G, B); var iDelta = iMax - iMin; var dMax = (iMax + iMin) / 255.0; var dDelta = iDelta / 255.0; var H = 0; var S = 0; var L = dMax / 2.0; if (iDelta != 0) { if (L < 0.5) S = dDelta / dMax; else S = dDelta / (2.0 - dMax); dDelta = dDelta * 1530.0; var dR = (iMax - R) / dDelta; var dG = (iMax - G) / dDelta; var dB = (iMax - B) / dDelta; if (R == iMax) H = dB - dG; else if (G == iMax) H = cd13 + dR - dB; else if (B == iMax) H = cd23 + dG - dR; if (H < 0.0) H += 1.0; if (H > 1.0) H -= 1.0; } H = ((H * max_hls) >> 0) & 0xFF; if (H < 0) H = 0; if (H > 255) H = 255; S = ((S * max_hls) >> 0) & 0xFF; if (S < 0) S = 0; if (S > 255) S = 255; L = ((L * max_hls) >> 0) & 0xFF; if (L < 0) L = 0; if (L > 255) L = 255; HLS.H = H; HLS.S = S; HLS.L = L; }; CColorModifiers.prototype.HSL2RGB = function (HSL, RGB) { if (HSL.S == 0) { RGB.R = HSL.L; RGB.G = HSL.L; RGB.B = HSL.L; } else { var H = HSL.H / max_hls; var S = HSL.S / max_hls; var L = HSL.L / max_hls; var v2 = 0; if (L < 0.5) v2 = L * (1.0 + S); else v2 = L + S - S * L; var v1 = 2.0 * L - v2; var R = (255 * this.Hue_2_RGB(v1, v2, H + cd13)) >> 0; var G = (255 * this.Hue_2_RGB(v1, v2, H)) >> 0; var B = (255 * this.Hue_2_RGB(v1, v2, H - cd13)) >> 0; if (R < 0) R = 0; if (R > 255) R = 255; if (G < 0) G = 0; if (G > 255) G = 255; if (B < 0) B = 0; if (B > 255) B = 255; RGB.R = R; RGB.G = G; RGB.B = B; } }; CColorModifiers.prototype.Hue_2_RGB = function (v1, v2, vH) { if (vH < 0.0) vH += 1.0; if (vH > 1.0) vH -= 1.0; if (vH < cd16) return v1 + (v2 - v1) * 6.0 * vH; if (vH < 0.5) return v2; if (vH < cd23) return v1 + (v2 - v1) * (cd23 - vH) * 6.0; return v1; }; CColorModifiers.prototype.lclRgbCompToCrgbComp = function (value) { return (value * MAX_PERCENT / 255); }; CColorModifiers.prototype.lclCrgbCompToRgbComp = function (value) { return (value * 255 / MAX_PERCENT); }; CColorModifiers.prototype.lclGamma = function (nComp, fGamma) { return (Math.pow(nComp / MAX_PERCENT, fGamma) * MAX_PERCENT + 0.5) >> 0; }; CColorModifiers.prototype.RgbtoCrgb = function (RGBA) { //RGBA.R = this.lclGamma(this.lclRgbCompToCrgbComp(RGBA.R), DEC_GAMMA); //RGBA.G = this.lclGamma(this.lclRgbCompToCrgbComp(RGBA.G), DEC_//GAMMA); //RGBA.B = this.lclGamma(this.lclRgbCompToCrgbComp(RGBA.B), DEC_GAMMA); if (this.isUsePow) { RGBA.R = (Math.pow(RGBA.R / 255, DEC_GAMMA) * MAX_PERCENT + 0.5) >> 0; RGBA.G = (Math.pow(RGBA.G / 255, DEC_GAMMA) * MAX_PERCENT + 0.5) >> 0; RGBA.B = (Math.pow(RGBA.B / 255, DEC_GAMMA) * MAX_PERCENT + 0.5) >> 0; } }; CColorModifiers.prototype.CrgbtoRgb = function (RGBA) { //RGBA.R = (this.lclCrgbCompToRgbComp(this.lclGamma(RGBA.R, INC_GAMMA)) + 0.5) >> 0; //RGBA.G = (this.lclCrgbCompToRgbComp(this.lclGamma(RGBA.G, INC_GAMMA)) + 0.5) >> 0; //RGBA.B = (this.lclCrgbCompToRgbComp(this.lclGamma(RGBA.B, INC_GAMMA)) + 0.5) >> 0; if (this.isUsePow) { RGBA.R = (Math.pow(RGBA.R / 100000, INC_GAMMA) * 255 + 0.5) >> 0; RGBA.G = (Math.pow(RGBA.G / 100000, INC_GAMMA) * 255 + 0.5) >> 0; RGBA.B = (Math.pow(RGBA.B / 100000, INC_GAMMA) * 255 + 0.5) >> 0; } else { RGBA.R = AscFormat.ClampColor(RGBA.R); RGBA.G = AscFormat.ClampColor(RGBA.G); RGBA.B = AscFormat.ClampColor(RGBA.B); } }; CColorModifiers.prototype.Apply = function (RGBA) { if (null == this.Mods) return; var _len = this.Mods.length; for (var i = 0; i < _len; i++) { var colorMod = this.Mods[i]; var val = colorMod.val / 100000.0; if (colorMod.name === "alpha") { RGBA.A = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "blue") { RGBA.B = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "blueMod") { RGBA.B = AscFormat.ClampColor(RGBA.B * val); } else if (colorMod.name === "blueOff") { RGBA.B = AscFormat.ClampColor(RGBA.B + val * 255); } else if (colorMod.name === "green") { RGBA.G = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "greenMod") { RGBA.G = AscFormat.ClampColor(RGBA.G * val); } else if (colorMod.name === "greenOff") { RGBA.G = AscFormat.ClampColor(RGBA.G + val * 255); } else if (colorMod.name === "red") { RGBA.R = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "redMod") { RGBA.R = AscFormat.ClampColor(RGBA.R * val); } else if (colorMod.name === "redOff") { RGBA.R = AscFormat.ClampColor(RGBA.R + val * 255); } else if (colorMod.name === "hueOff") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var res = (HSL.H + (val * 10.0) / 9.0 + 0.5) >> 0; HSL.H = AscFormat.ClampColor2(res, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "inv") { RGBA.R ^= 0xFF; RGBA.G ^= 0xFF; RGBA.B ^= 0xFF; } else if (colorMod.name === "lumMod") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); HSL.L = AscFormat.ClampColor2(HSL.L * val, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "lumOff") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var res = (HSL.L + val * max_hls + 0.5) >> 0; HSL.L = AscFormat.ClampColor2(res, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "satMod") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); HSL.S = AscFormat.ClampColor2(HSL.S * val, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "satOff") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var res = (HSL.S + val * max_hls + 0.5) >> 0; HSL.S = AscFormat.ClampColor2(res, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "wordShade") { var val_ = colorMod.val / 255; //GBA.R = Math.max(0, (RGBA.R * (1 - val_)) >> 0); //GBA.G = Math.max(0, (RGBA.G * (1 - val_)) >> 0); //GBA.B = Math.max(0, (RGBA.B * (1 - val_)) >> 0); //RGBA.R = Math.max(0, ((1 - val_)*(- RGBA.R) + RGBA.R) >> 0); //RGBA.G = Math.max(0, ((1 - val_)*(- RGBA.G) + RGBA.G) >> 0); //RGBA.B = Math.max(0, ((1 - val_)*(- RGBA.B) + RGBA.B) >> 0); var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); HSL.L = AscFormat.ClampColor2(HSL.L * val_, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "wordTint") { var _val = colorMod.val / 255; //RGBA.R = Math.max(0, ((1 - _val)*(255 - RGBA.R) + RGBA.R) >> 0); //RGBA.G = Math.max(0, ((1 - _val)*(255 - RGBA.G) + RGBA.G) >> 0); //RGBA.B = Math.max(0, ((1 - _val)*(255 - RGBA.B) + RGBA.B) >> 0); var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var L_ = HSL.L * _val + (255 - colorMod.val); HSL.L = AscFormat.ClampColor2(L_, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "shade") { this.RgbtoCrgb(RGBA); if (val < 0) val = 0; if (val > 1) val = 1; RGBA.R = (RGBA.R * val); RGBA.G = (RGBA.G * val); RGBA.B = (RGBA.B * val); this.CrgbtoRgb(RGBA); } else if (colorMod.name === "tint") { this.RgbtoCrgb(RGBA); if (val < 0) val = 0; if (val > 1) val = 1; RGBA.R = (MAX_PERCENT - (MAX_PERCENT - RGBA.R) * val); RGBA.G = (MAX_PERCENT - (MAX_PERCENT - RGBA.G) * val); RGBA.B = (MAX_PERCENT - (MAX_PERCENT - RGBA.B) * val); this.CrgbtoRgb(RGBA); } else if (colorMod.name === "gamma") { this.RgbtoCrgb(RGBA); RGBA.R = this.lclGamma(RGBA.R, INC_GAMMA); RGBA.G = this.lclGamma(RGBA.G, INC_GAMMA); RGBA.B = this.lclGamma(RGBA.B, INC_GAMMA); this.CrgbtoRgb(RGBA); } else if (colorMod.name === "invGamma") { this.RgbtoCrgb(RGBA); RGBA.R = this.lclGamma(RGBA.R, DEC_GAMMA); RGBA.G = this.lclGamma(RGBA.G, DEC_GAMMA); RGBA.B = this.lclGamma(RGBA.B, DEC_GAMMA); this.CrgbtoRgb(RGBA); } } }; CColorModifiers.prototype.Merge = function (oOther) { if (!oOther) { return; } this.Mods = oOther.Mods.concat(this.Mods); }; CColorModifiers.prototype.toXml = function (writer) { for (let nMod = 0; nMod < this.Mods.length; ++nMod) { this.Mods[nMod].toXml(writer); } }; function getPercentageValue(sVal) { var _len = sVal.length; if (_len === 0) return null; var _ret = null; if ((_len - 1) === sVal.indexOf("%")) { sVal.substring(0, _len - 1); _ret = parseFloat(sVal); if (isNaN(_ret)) _ret = null; } else { _ret = parseFloat(sVal); if (isNaN(_ret)) _ret = null; else _ret /= 1000; } return _ret; // let nVal = 0; // if (sVal.indexOf("%") > -1) { // let nPct = parseInt(sVal.slice(0, sVal.length - 1)); // if (AscFormat.isRealNumber(nPct)) { // return ((100000 * nPct / 100 + 0.5 >> 0) - 1); // } // return 0; // } // let nValPct = parseInt(sVal); // if (AscFormat.isRealNumber(nValPct)) { // return nValPct; // } // return 0; } function getPercentageValueForWrite(dVal) { if (!AscFormat.isRealNumber(dVal)) { return null; } return (dVal * 1000 + 0.5 >> 0); } function CBaseColor() { CBaseNoIdObject.call(this); this.RGBA = { R: 0, G: 0, B: 0, A: 255, needRecalc: true }; this.Mods = null; //[]; } InitClass(CBaseColor, CBaseNoIdObject, 0); CBaseColor.prototype.type = c_oAscColor.COLOR_TYPE_NONE; CBaseColor.prototype.setR = function (pr) { this.RGBA.R = pr; }; CBaseColor.prototype.setG = function (pr) { this.RGBA.G = pr; }; CBaseColor.prototype.setB = function (pr) { this.RGBA.B = pr; }; CBaseColor.prototype.readModifier = function (name, reader) { if (MODS_MAP[name]) { var oMod = new CColorMod(); oMod.name = name; while (reader.MoveToNextAttribute()) { if (reader.GetNameNoNS() === "val") { oMod.val = reader.GetValueInt(); break; } } if (!Array.isArray(this.Mods)) { this.Mods = []; } this.Mods.push(oMod); } return false; }; CBaseColor.prototype.getChannelValue = function (sVal) { let nValPct = getPercentageValue(sVal); return (255 * nValPct / 100000 + 0.5 >> 0); }; CBaseColor.prototype.getTypeName = function () { return ""; }; CBaseColor.prototype.getNodeNS = function (writer) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.docType) { return ("w14:"); } else return ("a:"); }; CBaseColor.prototype.toXml = function (writer) { let sName = this.getNodeNS(writer) + this.getTypeName(); writer.WriteXmlNodeStart(sName); this.writeAttrXmlImpl(writer); writer.WriteXmlAttributesEnd(); this.writeChildrenXml(writer); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sName); }; CBaseColor.prototype.writeModifiers = function (writer) { if (Array.isArray(this.Mods)) { for (let nMod = 0; nMod < this.Mods.length; ++nMod) { this.Mods[nMod].toXml(writer); } } }; const COLOR_3DDKSHADOW = 21; const COLOR_3DFACE = 15; const COLOR_3DHIGHLIGHT = 20; const COLOR_3DHILIGHT = 20; const COLOR_3DLIGHT = 22; const COLOR_3DSHADOW = 16; const COLOR_ACTIVEBORDER = 10; const COLOR_ACTIVECAPTION = 2; const COLOR_APPWORKSPACE = 12; const COLOR_BACKGROUND = 1; const COLOR_BTNFACE = 15; const COLOR_BTNHIGHLIGHT = 20; const COLOR_BTNHILIGHT = 20; const COLOR_BTNSHADOW = 16; const COLOR_BTNTEXT = 18; const COLOR_CAPTIONTEXT = 9; const COLOR_DESKTOP = 1; const COLOR_GRAYTEXT = 17; const COLOR_HIGHLIGHT = 13; const COLOR_HIGHLIGHTTEXT = 14; const COLOR_HOTLIGHT = 26; const COLOR_INACTIVEBORDER = 11; const COLOR_INACTIVECAPTION = 3; const COLOR_INACTIVECAPTIONTEXT = 19; const COLOR_INFOBK = 24; const COLOR_INFOTEXT = 23; const COLOR_MENU = 4; const COLOR_GRADIENTACTIVECAPTION = 27; const COLOR_GRADIENTINACTIVECAPTION = 28; const COLOR_MENUHILIGHT = 29; const COLOR_MENUBAR = 30; const COLOR_MENUTEXT = 7; const COLOR_SCROLLBAR = 0; const COLOR_WINDOW = 5; const COLOR_WINDOWFRAME = 6; const COLOR_WINDOWTEXT = 8; function GetSysColor(nIndex) { // get color values from any windows theme // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724371(v=vs.85).aspx //***************** GetSysColor values begin (Win7 x64) ***************** let nValue = 0x0; //***************** GetSysColor values begin (Win7 x64) ***************** switch (nIndex) { case COLOR_3DDKSHADOW: nValue = 0x696969; break; case COLOR_3DFACE: nValue = 0xf0f0f0; break; case COLOR_3DHIGHLIGHT: nValue = 0xffffff; break; // case COLOR_3DHILIGHT: nValue = 0xffffff; break; // is COLOR_3DHIGHLIGHT case COLOR_3DLIGHT: nValue = 0xe3e3e3; break; case COLOR_3DSHADOW: nValue = 0xa0a0a0; break; case COLOR_ACTIVEBORDER: nValue = 0xb4b4b4; break; case COLOR_ACTIVECAPTION: nValue = 0xd1b499; break; case COLOR_APPWORKSPACE: nValue = 0xababab; break; case COLOR_BACKGROUND: nValue = 0x0; break; // case COLOR_BTNFACE: nValue = 0xf0f0f0; break; // is COLOR_3DFACE // case COLOR_BTNHIGHLIGHT: nValue = 0xffffff; break; // is COLOR_3DHIGHLIGHT // case COLOR_BTNHILIGHT: nValue = 0xffffff; break; // is COLOR_3DHIGHLIGHT // case COLOR_BTNSHADOW: nValue = 0xa0a0a0; break; // is COLOR_3DSHADOW case COLOR_BTNTEXT: nValue = 0x0; break; case COLOR_CAPTIONTEXT: nValue = 0x0; break; // case COLOR_DESKTOP: nValue = 0x0; break; // is COLOR_BACKGROUND case COLOR_GRADIENTACTIVECAPTION: nValue = 0xead1b9; break; case COLOR_GRADIENTINACTIVECAPTION: nValue = 0xf2e4d7; break; case COLOR_GRAYTEXT: nValue = 0x6d6d6d; break; case COLOR_HIGHLIGHT: nValue = 0xff9933; break; case COLOR_HIGHLIGHTTEXT: nValue = 0xffffff; break; case COLOR_HOTLIGHT: nValue = 0xcc6600; break; case COLOR_INACTIVEBORDER: nValue = 0xfcf7f4; break; case COLOR_INACTIVECAPTION: nValue = 0xdbcdbf; break; case COLOR_INACTIVECAPTIONTEXT: nValue = 0x544e43; break; case COLOR_INFOBK: nValue = 0xe1ffff; break; case COLOR_INFOTEXT: nValue = 0x0; break; case COLOR_MENU: nValue = 0xf0f0f0; break; case COLOR_MENUHILIGHT: nValue = 0xff9933; break; case COLOR_MENUBAR: nValue = 0xf0f0f0; break; case COLOR_MENUTEXT: nValue = 0x0; break; case COLOR_SCROLLBAR: nValue = 0xc8c8c8; break; case COLOR_WINDOW: nValue = 0xffffff; break; case COLOR_WINDOWFRAME: nValue = 0x646464; break; case COLOR_WINDOWTEXT: nValue = 0x0; break; default: nValue = 0x0; break; } // switch (nIndex) //***************** GetSysColor values end ***************** return nValue; } function CSysColor() { CBaseColor.call(this); this.id = ""; } InitClass(CSysColor, CBaseColor, 0); CSysColor.prototype.type = c_oAscColor.COLOR_TYPE_SYS; CSysColor.prototype.check = function () { var ret = this.RGBA.needRecalc; this.RGBA.needRecalc = false; return ret; }; CSysColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteString2(this.id); w.WriteLong(((this.RGBA.R << 16) & 0xFF0000) + ((this.RGBA.G << 8) & 0xFF00) + this.RGBA.B); }; CSysColor.prototype.Read_FromBinary = function (r) { this.id = r.GetString2(); var RGB = r.GetLong(); this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CSysColor.prototype.setId = function (id) { this.id = id; }; CSysColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.id === this.id; }; CSysColor.prototype.Calculate = function (obj) { }; CSysColor.prototype.createDuplicate = function () { var duplicate = new CSysColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CSysColor.prototype.FillRGBFromVal = function(str) { let RGB = 0; if (str && str !== "") { switch (str.charAt(0)) { case '3': if (str === ("3dDkShadow")) { RGB = GetSysColor(COLOR_3DDKSHADOW); break; } if (str === ("3dLight")) { RGB = GetSysColor(COLOR_3DLIGHT); break; } break; case 'a': if (str === ("activeBorder")) { RGB = GetSysColor(COLOR_ACTIVEBORDER); break; } if (str === ("activeCaption")) { RGB = GetSysColor(COLOR_ACTIVECAPTION); break; } if (str === ("appWorkspace")) { RGB = GetSysColor(COLOR_APPWORKSPACE); break; } break; case 'b': if (str === ("background")) { RGB = GetSysColor(COLOR_BACKGROUND); break; } if (str === ("btnFace")) { RGB = GetSysColor(COLOR_BTNFACE); break; } if (str === ("btnHighlight")) { RGB = GetSysColor(COLOR_BTNHIGHLIGHT); break; } if (str === ("btnShadow")) { RGB = GetSysColor(COLOR_BTNSHADOW); break; } if (str === ("btnText")) { RGB = GetSysColor(COLOR_BTNTEXT); break; } break; case 'c': if (str === ("captionText")) { RGB = GetSysColor(COLOR_CAPTIONTEXT); break; } break; case 'g': if (str === ("gradientActiveCaption")) { RGB = GetSysColor(COLOR_GRADIENTACTIVECAPTION); break; } if (str === ("gradientInactiveCaption")) { RGB = GetSysColor(COLOR_GRADIENTINACTIVECAPTION); break; } if (str === ("grayText")) { RGB = GetSysColor(COLOR_GRAYTEXT); break; } break; case 'h': if (str === ("highlight")) { RGB = GetSysColor(COLOR_HIGHLIGHT); break; } if (str === ("highlightText")) { RGB = GetSysColor(COLOR_HIGHLIGHTTEXT); break; } if (str === ("hotLight")) { RGB = GetSysColor(COLOR_HOTLIGHT); break; } break; case 'i': if (str === ("inactiveBorder")) { RGB = GetSysColor(COLOR_INACTIVEBORDER); break; } if (str === ("inactiveCaption")) { RGB = GetSysColor(COLOR_INACTIVECAPTION); break; } if (str === ("inactiveCaptionText")) { RGB = GetSysColor(COLOR_INACTIVECAPTIONTEXT); break; } if (str === ("infoBk")) { RGB = GetSysColor(COLOR_INFOBK); break; } if (str === ("infoText")) { RGB = GetSysColor(COLOR_INFOTEXT); break; } break; case 'm': if (str === ("menu")) { RGB = GetSysColor(COLOR_MENU); break; } if (str === ("menuBar")) { RGB = GetSysColor(COLOR_MENUBAR); break; } if (str === ("menuHighlight")) { RGB = GetSysColor(COLOR_MENUHILIGHT); break; } if (str === ("menuText")) { RGB = GetSysColor(COLOR_MENUTEXT); break; } break; case 's': if (str === ("scrollBar")) { RGB = GetSysColor(COLOR_SCROLLBAR); break; } break; case 'w': if (str === ("window")) { RGB = GetSysColor(COLOR_WINDOW); break; } if (str === ("windowFrame")) { RGB = GetSysColor(COLOR_WINDOWFRAME); break; } if (str === ("windowText")) { RGB = GetSysColor(COLOR_WINDOWTEXT); break; } break; } } this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; } CSysColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { this.id = reader.GetValue(); this.FillRGBFromVal(this.id); } else if (name === "lastClr") { // this.RGBA = AscCommon.RgbaHexToRGBA(reader.GetValue()); } }; CSysColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CSysColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("sysClr")); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), this.id); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("lastClr"), fRGBAToHexString(this.RGBA)); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("sysClr")); } else { writer.WriteXmlAttributesEnd(true); } }; function CPrstColor() { CBaseColor.call(this); this.id = ""; } InitClass(CPrstColor, CBaseColor, 0); CPrstColor.prototype.type = c_oAscColor.COLOR_TYPE_PRST; CPrstColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteString2(this.id); }; CPrstColor.prototype.Read_FromBinary = function (r) { this.id = r.GetString2(); }; CPrstColor.prototype.setId = function (id) { this.id = id; }; CPrstColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.id === this.id; }; CPrstColor.prototype.createDuplicate = function () { var duplicate = new CPrstColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CPrstColor.prototype.Calculate = function (obj) { var RGB = map_prst_color[this.id]; this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CPrstColor.prototype.check = function () { var r, g, b, rgb; rgb = map_prst_color[this.id]; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = rgb & 0xFF; var RGBA = this.RGBA; if (RGBA.needRecalc) { RGBA.R = r; RGBA.G = g; RGBA.B = b; RGBA.needRecalc = false; return true; } else { if (RGBA.R === r && RGBA.G === g && RGBA.B === b) return false; else { RGBA.R = r; RGBA.G = g; RGBA.B = b; return true; } } }; CPrstColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { this.id = reader.GetValue(); } }; CPrstColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CPrstColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("prstClr")); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), this.id); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("prstClr")); } else { writer.WriteXmlAttributesEnd(true); } }; var MODS_MAP = {}; MODS_MAP["alpha"] = true; MODS_MAP["alphaMod"] = true; MODS_MAP["alphaOff"] = true; MODS_MAP["blue"] = true; MODS_MAP["blueMod"] = true; MODS_MAP["blueOff"] = true; MODS_MAP["comp"] = true; MODS_MAP["gamma"] = true; MODS_MAP["gray"] = true; MODS_MAP["green"] = true; MODS_MAP["greenMod"] = true; MODS_MAP["greenOff"] = true; MODS_MAP["hue"] = true; MODS_MAP["hueMod"] = true; MODS_MAP["hueOff"] = true; MODS_MAP["inv"] = true; MODS_MAP["invGamma"] = true; MODS_MAP["lum"] = true; MODS_MAP["lumMod"] = true; MODS_MAP["lumOff"] = true; MODS_MAP["red"] = true; MODS_MAP["redMod"] = true; MODS_MAP["redOff"] = true; MODS_MAP["sat"] = true; MODS_MAP["satMod"] = true; MODS_MAP["satOff"] = true; MODS_MAP["shade"] = true; MODS_MAP["tint"] = true; function toHex(c) { var res = Number(c).toString(16).toUpperCase(); return res.length === 1 ? "0" + res : res; } function fRGBAToHexString(oRGBA) { return "" + toHex(oRGBA.R) + toHex(oRGBA.G) + toHex(oRGBA.B); } function CRGBColor() { CBaseColor.call(this); this.h = null; this.s = null; this.l = null; } InitClass(CRGBColor, CBaseColor, 0); CRGBColor.prototype.type = c_oAscColor.COLOR_TYPE_SRGB; CRGBColor.prototype.check = function () { var ret = this.RGBA.needRecalc; this.RGBA.needRecalc = false; return ret; }; CRGBColor.prototype.writeToBinaryLong = function (w) { w.WriteLong(((this.RGBA.R << 16) & 0xFF0000) + ((this.RGBA.G << 8) & 0xFF00) + this.RGBA.B); }; CRGBColor.prototype.readFromBinaryLong = function (r) { var RGB = r.GetLong(); this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CRGBColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteLong(((this.RGBA.R << 16) & 0xFF0000) + ((this.RGBA.G << 8) & 0xFF00) + this.RGBA.B); }; CRGBColor.prototype.Read_FromBinary = function (r) { var RGB = r.GetLong(); this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CRGBColor.prototype.setColor = function (r, g, b) { this.RGBA.R = r; this.RGBA.G = g; this.RGBA.B = b; }; CRGBColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.RGBA.R === this.RGBA.R && color.RGBA.G === this.RGBA.G && color.RGBA.B === this.RGBA.B && color.RGBA.A === this.RGBA.A; }; CRGBColor.prototype.createDuplicate = function () { var duplicate = new CRGBColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CRGBColor.prototype.Calculate = function (obj) { }; CRGBColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { this.RGBA = AscCommon.RgbaHexToRGBA(reader.GetValue()); } else if (name === "r") { this.RGBA.R = this.getChannelValue(reader.GetValue()); } else if (name === "g") { this.RGBA.G = this.getChannelValue(reader.GetValue()); } else if (name === "b") { this.RGBA.B = this.getChannelValue(reader.GetValue()); } else if (name === "h") { this.h = this.getChannelValue(reader.GetValue()); this.checkHSL(); } else if (name === "s") { this.s = this.getChannelValue(reader.GetValue()); this.checkHSL(); } else if (name === "l") { this.l = this.getChannelValue(reader.GetValue()); this.checkHSL(); } }; CRGBColor.prototype.checkHSL = function () { if (this.h !== null && this.s !== null && this.l !== null) { CColorModifiers.prototype.HSL2RGB.call(this, {H: this.h, S: this.s, L: this.l}, this.RGBA); this.h = null; this.s = null; this.l = null; } }; CRGBColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CRGBColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("srgbClr")); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), fRGBAToHexString(this.RGBA)); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("srgbClr")); } else { writer.WriteXmlAttributesEnd(true); } }; CRGBColor.prototype.fromScRgb = function() { this.RGBA.R = 255 * this.scRGB_to_sRGB(this.RGBA.R); this.RGBA.G = 255 * this.scRGB_to_sRGB(this.RGBA.G); this.RGBA.B = 255 * this.scRGB_to_sRGB(this.RGBA.B); }; CRGBColor.prototype.scRGB_to_sRGB = function(value) { if( value < 0) return 0; if(value <= 0.0031308) return value * 12.92; if(value < 1) return 1.055 * (Math.pow(value , (1 / 2.4))) - 0.055; return 1; }; function CSchemeColor() { CBaseColor.call(this); this.id = 0; } InitClass(CSchemeColor, CBaseColor, 0); CSchemeColor.prototype.type = c_oAscColor.COLOR_TYPE_SCHEME; CSchemeColor.prototype.check = function (theme, colorMap) { var RGBA, colors = theme.themeElements.clrScheme.colors; if (colorMap[this.id] != null && colors[colorMap[this.id]] != null) RGBA = colors[colorMap[this.id]].color.RGBA; else if (colors[this.id] != null) RGBA = colors[this.id].color.RGBA; if (!RGBA) { RGBA = {R: 0, G: 0, B: 0, A: 255}; } var _RGBA = this.RGBA; if (this.RGBA.needRecalc) { _RGBA.R = RGBA.R; _RGBA.G = RGBA.G; _RGBA.B = RGBA.B; _RGBA.A = RGBA.A; this.RGBA.needRecalc = false; return true; } else { if (_RGBA.R === RGBA.R && _RGBA.G === RGBA.G && _RGBA.B === RGBA.B && _RGBA.A === RGBA.A) { return false; } else { _RGBA.R = RGBA.R; _RGBA.G = RGBA.G; _RGBA.B = RGBA.B; _RGBA.A = RGBA.A; return true; } } }; CSchemeColor.prototype.getObjectType = function () { return AscDFH.historyitem_type_SchemeColor; }; CSchemeColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteLong(this.id); }; CSchemeColor.prototype.Read_FromBinary = function (r) { this.id = r.GetLong(); }; CSchemeColor.prototype.setId = function (id) { this.id = id; }; CSchemeColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.id === this.id; }; CSchemeColor.prototype.createDuplicate = function () { var duplicate = new CSchemeColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CSchemeColor.prototype.Calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { if (theme.themeElements.clrScheme) { if (this.id === phClr) { this.RGBA = RGBA; } else { var clrMap; if (colorMap && colorMap.color_map) { clrMap = colorMap.color_map; } else if (slide != null && slide.clrMap != null) { clrMap = slide.clrMap.color_map; } else if (layout != null && layout.clrMap != null) { clrMap = layout.clrMap.color_map; } else if (masterSlide != null && masterSlide.clrMap != null) { clrMap = masterSlide.clrMap.color_map; } else { clrMap = AscFormat.GetDefaultColorMap().color_map; } if (clrMap[this.id] != null && theme.themeElements.clrScheme.colors[clrMap[this.id]] != null && theme.themeElements.clrScheme.colors[clrMap[this.id]].color != null) this.RGBA = theme.themeElements.clrScheme.colors[clrMap[this.id]].color.RGBA; else if (theme.themeElements.clrScheme.colors[this.id] != null && theme.themeElements.clrScheme.colors[this.id].color != null) this.RGBA = theme.themeElements.clrScheme.colors[this.id].color.RGBA; } } }; CSchemeColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { var sVal = reader.GetValue(); if ("accent1" === sVal) this.id = 0; if ("accent2" === sVal) this.id = 1; if ("accent3" === sVal) this.id = 2; if ("accent4" === sVal) this.id = 3; if ("accent5" === sVal) this.id = 4; if ("accent6" === sVal) this.id = 5; if ("bg1" === sVal) this.id = 6; if ("bg2" === sVal) this.id = 7; if ("dk1" === sVal) this.id = 8; if ("dk2" === sVal) this.id = 9; if ("folHlink" === sVal) this.id = 10; if ("hlink" === sVal) this.id = 11; if ("lt1" === sVal) this.id = 12; if ("lt2" === sVal) this.id = 13; if ("phClr" === sVal) this.id = 14; if ("tx1" === sVal) this.id = 15; if ("tx2" === sVal) this.id = 16; } }; CSchemeColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CSchemeColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("schemeClr")); let sVal = ""; switch (this.id) { case 0: sVal = "accent1"; break; case 1: sVal = "accent2"; break; case 2: sVal = "accent3"; break; case 3: sVal = "accent4"; break; case 4: sVal = "accent5"; break; case 5: sVal = "accent6"; break; case 6: sVal = "bg1"; break; case 7: sVal = "bg2"; break; case 8: sVal = "dk1"; break; case 9: sVal = "dk2"; break; case 10: sVal = "folHlink"; break; case 11: sVal = "hlink"; break; case 12: sVal = "lt1"; break; case 13: sVal = "lt2"; break; case 14: sVal = "phClr"; break; case 15: sVal = "tx1"; break; case 16: sVal = "tx2"; break; } writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), sVal); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("schemeClr")); } else { writer.WriteXmlAttributesEnd(true); } }; function CStyleColor() { CBaseColor.call(this); this.bAuto = false; this.val = null; } InitClass(CStyleColor, CBaseColor, 0); CStyleColor.prototype.type = c_oAscColor.COLOR_TYPE_STYLE; CStyleColor.prototype.check = function (theme, colorMap) { }; CStyleColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); writeBool(w, this.bAuto); writeLong(w, this.val); }; CStyleColor.prototype.Read_FromBinary = function (r) { this.bAuto = readBool(r); this.val = readLong(r); }; CStyleColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.bAuto === this.bAuto && this.val === color.val; }; CStyleColor.prototype.createDuplicate = function () { var duplicate = new CStyleColor(); duplicate.bAuto = this.bAuto; duplicate.val = this.val; return duplicate; }; CStyleColor.prototype.Calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { }; CStyleColor.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (this.bAuto || this.val === null) { return aColors[nIdx % aColors.length]; } else { return aColors[this.val % aColors.length]; } }; CStyleColor.prototype.readAttrXml = function (name, reader) { //TODO:Implement in children }; CStyleColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CStyleColor.prototype.toXml = function (writer) { //TODO:Implement in children }; function CUniColor() { CBaseNoIdObject.call(this); this.color = null; this.Mods = null;//new CColorModifiers(); this.RGBA = { R: 0, G: 0, B: 0, A: 255 }; } InitClass(CUniColor, CBaseNoIdObject, 0); CUniColor.prototype.checkPhColor = function (unicolor, bMergeMods) { if (this.color && this.color.type === c_oAscColor.COLOR_TYPE_SCHEME && this.color.id === 14) { if (unicolor) { if (unicolor.color) { this.color = unicolor.color.createDuplicate(); } if (unicolor.Mods) { if (!this.Mods || this.Mods.Mods.length === 0) { this.Mods = unicolor.Mods.createDuplicate(); } else { if (bMergeMods) { this.Mods.Merge(unicolor.Mods); } } } } } }; CUniColor.prototype.saveSourceFormatting = function () { var _ret = new CUniColor(); _ret.color = new CRGBColor(); _ret.color.RGBA.R = this.RGBA.R; _ret.color.RGBA.G = this.RGBA.G; _ret.color.RGBA.B = this.RGBA.B; return _ret; }; CUniColor.prototype.addColorMod = function (mod) { if (!this.Mods) { this.Mods = new CColorModifiers(); } this.Mods.addMod(mod.createDuplicate()); }; CUniColor.prototype.check = function (theme, colorMap) { if (this.color && this.color.check(theme, colorMap.color_map)/*ะฒะพะทะฒั€ะฐั‰ะฐะตั‚ ะฑั‹ะป ะปะธ ะธะทะผะตะฝะตะฝ RGBA*/) { this.RGBA.R = this.color.RGBA.R; this.RGBA.G = this.color.RGBA.G; this.RGBA.B = this.color.RGBA.B; if (this.Mods) this.Mods.Apply(this.RGBA); } }; CUniColor.prototype.getModValue = function (sModName) { if (this.Mods && this.Mods.getModValue) { return this.Mods.getModValue(sModName); } return null; }; CUniColor.prototype.checkWordMods = function () { return this.Mods && this.Mods.Mods.length === 1 && (this.Mods.Mods[0].name === "wordTint" || this.Mods.Mods[0].name === "wordShade"); }; CUniColor.prototype.convertToPPTXMods = function () { if (this.checkWordMods()) { var val_, mod_; if (this.Mods.Mods[0].name === "wordShade") { mod_ = new CColorMod(); mod_.setName("lumMod"); mod_.setVal(((this.Mods.Mods[0].val / 255) * 100000) >> 0); this.Mods.Mods.splice(0, this.Mods.Mods.length); this.Mods.Mods.push(mod_); } else { val_ = ((this.Mods.Mods[0].val / 255) * 100000) >> 0; this.Mods.Mods.splice(0, this.Mods.Mods.length); mod_ = new CColorMod(); mod_.setName("lumMod"); mod_.setVal(val_); this.Mods.Mods.push(mod_); mod_ = new CColorMod(); mod_.setName("lumOff"); mod_.setVal(100000 - val_); this.Mods.Mods.push(mod_); } } }; CUniColor.prototype.canConvertPPTXModsToWord = function () { return this.Mods && ((this.Mods.Mods.length === 1 && this.Mods.Mods[0].name === "lumMod" && this.Mods.Mods[0].val > 0) || (this.Mods.Mods.length === 2 && this.Mods.Mods[0].name === "lumMod" && this.Mods.Mods[0].val > 0 && this.Mods.Mods[1].name === "lumOff" && this.Mods.Mods[1].val > 0)); }; CUniColor.prototype.convertToWordMods = function () { if (this.canConvertPPTXModsToWord()) { var mod_ = new CColorMod(); mod_.setName(this.Mods.Mods.length === 1 ? "wordShade" : "wordTint"); mod_.setVal(((this.Mods.Mods[0].val * 255) / 100000) >> 0); this.Mods.Mods.splice(0, this.Mods.Mods.length); this.Mods.Mods.push(mod_); } }; CUniColor.prototype.setColor = function (color) { this.color = color; }; CUniColor.prototype.setMods = function (mods) { this.Mods = mods; }; CUniColor.prototype.Write_ToBinary = function (w) { if (this.color) { w.WriteBool(true); this.color.Write_ToBinary(w); } else { w.WriteBool(false); } if (this.Mods) { w.WriteBool(true); this.Mods.Write_ToBinary(w); } else { w.WriteBool(false); } }; CUniColor.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { var type = r.GetLong(); switch (type) { case c_oAscColor.COLOR_TYPE_NONE: { break; } case c_oAscColor.COLOR_TYPE_SRGB: { this.color = new CRGBColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_PRST: { this.color = new CPrstColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_SCHEME: { this.color = new CSchemeColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_SYS: { this.color = new CSysColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_STYLE: { this.color = new CStyleColor(); this.color.Read_FromBinary(r); break; } } } if (r.GetBool()) { this.Mods = new CColorModifiers(); this.Mods.Read_FromBinary(r); } else { this.Mods = null; } }; CUniColor.prototype.createDuplicate = function () { var duplicate = new CUniColor(); if (this.color != null) { duplicate.color = this.color.createDuplicate(); } if (this.Mods) duplicate.Mods = this.Mods.createDuplicate(); duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CUniColor.prototype.IsIdentical = function (unicolor) { if (!isRealObject(unicolor)) { return false; } if (!isRealObject(unicolor.color) && isRealObject(this.color) || !isRealObject(this.color) && isRealObject(unicolor.color) || isRealObject(this.color) && !this.color.IsIdentical(unicolor.color)) { return false; } if (!isRealObject(unicolor.Mods) && isRealObject(this.Mods) && this.Mods.Mods.length > 0 || !isRealObject(this.Mods) && isRealObject(unicolor.Mods) && unicolor.Mods.Mods.length > 0 || isRealObject(this.Mods) && !this.Mods.IsIdentical(unicolor.Mods)) { return false; } return true; }; CUniColor.prototype.Calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { if (this.color == null) return this.RGBA; this.color.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); this.RGBA = {R: this.color.RGBA.R, G: this.color.RGBA.G, B: this.color.RGBA.B, A: this.color.RGBA.A}; if (this.Mods) this.Mods.Apply(this.RGBA); }; CUniColor.prototype.compare = function (unicolor) { if (unicolor == null) { return null; } var _ret = new CUniColor(); if (this.color == null || unicolor.color == null || this.color.type !== unicolor.color.type) { return _ret; } if (this.Mods && unicolor.Mods) { var aMods = this.Mods.Mods; var aMods2 = unicolor.Mods.Mods; if (aMods.length === aMods2.length) { for (var i = 0; i < aMods.length; ++i) { if (aMods2[i].name !== aMods[i].name || aMods2[i].val !== aMods[i].val) { break; } } if (i === aMods.length) { _ret.Mods = this.Mods.createDuplicate(); } } } switch (this.color.type) { case c_oAscColor.COLOR_TYPE_NONE: { break; } case c_oAscColor.COLOR_TYPE_PRST: { _ret.color = new CPrstColor(); if (unicolor.color.id == this.color.id) { _ret.color.id = this.color.id; _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.color.RGBA.A = this.color.RGBA.A; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; _ret.RGBA.A = this.RGBA.A; } break; } case c_oAscColor.COLOR_TYPE_SCHEME: { _ret.color = new CSchemeColor(); if (unicolor.color.id == this.color.id) { _ret.color.id = this.color.id; _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.color.RGBA.A = this.color.RGBA.A; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; _ret.RGBA.A = this.RGBA.A; } break; } case c_oAscColor.COLOR_TYPE_SRGB: { _ret.color = new CRGBColor(); var _RGBA1 = this.color.RGBA; var _RGBA2 = this.color.RGBA; if (_RGBA1.R === _RGBA2.R && _RGBA1.G === _RGBA2.G && _RGBA1.B === _RGBA2.B) { _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; } if (_RGBA1.A === _RGBA2.A) { _ret.color.RGBA.A = this.color.RGBA.A; } break; } case c_oAscColor.COLOR_TYPE_SYS: { _ret.color = new CSysColor(); if (unicolor.color.id == this.color.id) { _ret.color.id = this.color.id; _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.color.RGBA.A = this.color.RGBA.A; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; _ret.RGBA.A = this.RGBA.A; } break; } } return _ret; }; CUniColor.prototype.getCSSColor = function (transparent) { if (transparent != null) { var _css = "rgba(" + this.RGBA.R + "," + this.RGBA.G + "," + this.RGBA.B + ",1)"; return _css; } var _css = "rgba(" + this.RGBA.R + "," + this.RGBA.G + "," + this.RGBA.B + "," + (this.RGBA.A / 255) + ")"; return _css; }; CUniColor.prototype.isCorrect = function () { if (this.color !== null && this.color !== undefined) { return true; } return false; }; CUniColor.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (!this.color) { return null; } if (this.color.type !== c_oAscColor.COLOR_TYPE_STYLE) { return this; } return this.color.getNoStyleUnicolor(nIdx, aColors); }; CUniColor.prototype.fromXml = function (reader, name) { switch (name) { case "hslClr": case "scrgbClr": case "srgbClr": { this.color = new CRGBColor(); break; } case "prstClr": { this.color = new CPrstColor(); break; } case "schemeClr": { this.color = new CSchemeColor(); break; } case "sysClr": { this.color = new CSysColor(); break; } } if (this.color) { this.color.fromXml(reader); if(name === "scrgbClr") { this.color.fromScRgb(); } if (Array.isArray(this.color.Mods)) { this.Mods = new CColorModifiers(); this.Mods.Mods = this.color.Mods; this.color.Mods = undefined; } } }; CUniColor.prototype.toXml = function (writer) { if (this.color) { this.color.Mods = this.Mods && this.Mods.Mods; this.color.toXml(writer); this.color.Mods = undefined; } }; CUniColor.prototype.UNICOLOR_MAP = { "hslClr": true, "scrgbClr": true, "srgbClr": true, "prstClr": true, "schemeClr": true, "sysClr": true }; CUniColor.prototype.isUnicolor = function (sName) { return !!CUniColor.prototype.UNICOLOR_MAP[sName]; }; function CreateUniColorRGB(r, g, b) { var ret = new CUniColor(); ret.setColor(new CRGBColor()); ret.color.setColor(r, g, b); return ret; } function CreateUniColorRGB2(color) { var ret = new CUniColor(); ret.setColor(new CRGBColor()); ret.color.setColor(ret.RGBA.R = color.getR(), ret.RGBA.G = color.getG(), ret.RGBA.B = color.getB()); return ret; } function CreateSolidFillRGB(r, g, b) { return AscFormat.CreateUniFillByUniColor(CreateUniColorRGB(r, g, b)); } function CreateSolidFillRGBA(r, g, b, a) { var ret = new CUniFill(); ret.setFill(new CSolidFill()); ret.fill.setColor(new CUniColor()); var _uni_color = ret.fill.color; _uni_color.setColor(new CRGBColor()); _uni_color.color.setColor(r, g, b); _uni_color.RGBA.R = r; _uni_color.RGBA.G = g; _uni_color.RGBA.B = b; _uni_color.RGBA.A = a; return ret; } // ----------------------------- function CSrcRect() { CBaseNoIdObject.call(this); this.l = null; this.t = null; this.r = null; this.b = null; } InitClass(CSrcRect, CBaseNoIdObject, 0); CSrcRect.prototype.setLTRB = function (l, t, r, b) { this.l = l; this.t = t; this.r = r; this.b = b; }; CSrcRect.prototype.setValueForFitBlipFill = function (shapeWidth, shapeHeight, imageWidth, imageHeight) { if ((imageHeight / imageWidth) > (shapeHeight / shapeWidth)) { this.l = 0; this.r = 100; var widthAspectRatio = imageWidth / shapeWidth; var heightAspectRatio = shapeHeight / imageHeight; var stretchPercentage = ((1 - widthAspectRatio * heightAspectRatio) / 2) * 100; this.t = stretchPercentage; this.b = 100 - stretchPercentage; } else { this.t = 0; this.b = 100; heightAspectRatio = imageHeight / shapeHeight; widthAspectRatio = shapeWidth / imageWidth; stretchPercentage = ((1 - heightAspectRatio * widthAspectRatio) / 2) * 100; this.l = stretchPercentage; this.r = 100 - stretchPercentage; } }; CSrcRect.prototype.Write_ToBinary = function (w) { writeDouble(w, this.l); writeDouble(w, this.t); writeDouble(w, this.r); writeDouble(w, this.b); }; CSrcRect.prototype.Read_FromBinary = function (r) { this.l = readDouble(r); this.t = readDouble(r); this.r = readDouble(r); this.b = readDouble(r); }; CSrcRect.prototype.createDublicate = function () { var _ret = new CSrcRect(); _ret.l = this.l; _ret.t = this.t; _ret.r = this.r; _ret.b = this.b; return _ret; }; CSrcRect.prototype.fromXml = function (reader, bSkipFirstNode, bIsMain) { CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); let _ret = this; if (_ret.l == null) _ret.l = 0; if (_ret.t == null) _ret.t = 0; if (_ret.r == null) _ret.r = 0; if (_ret.b == null) _ret.b = 0; if (!bIsMain) { var _absW = Math.abs(_ret.l) + Math.abs(_ret.r) + 100; var _absH = Math.abs(_ret.t) + Math.abs(_ret.b) + 100; _ret.l = -100 * _ret.l / _absW; _ret.t = -100 * _ret.t / _absH; _ret.r = -100 * _ret.r / _absW; _ret.b = -100 * _ret.b / _absH; } _ret.r = 100 - _ret.r; _ret.b = 100 - _ret.b; if (_ret.l > _ret.r) { var tmp = _ret.l; _ret.l = _ret.r; _ret.r = tmp; } if (_ret.t > _ret.b) { var tmp = _ret.t; _ret.t = _ret.b; _ret.b = tmp; } this.setLTRB(_ret.l, _ret.t, _ret.r, _ret.b); }; CSrcRect.prototype.readAttrXml = function (name, reader) { var sVal = reader.GetValue(); switch (name) { case "l": { this.l = getPercentageValue(sVal); break; } case "t": { this.t = getPercentageValue(sVal); break; } case "r": { this.r = getPercentageValue(sVal); break; } case "b": { this.b = getPercentageValue(sVal); break; } } }; CSrcRect.prototype.toXml = function (writer, sName) { let sName_ = sName || "a:srcRect"; writer.WriteXmlNodeStart(sName_); writer.WriteXmlNullableAttributeUInt("l", getPercentageValueForWrite(this.l)); writer.WriteXmlNullableAttributeUInt("t", getPercentageValueForWrite(this.t)); if(AscFormat.isRealNumber(this.r)) { writer.WriteXmlAttributeUInt("r", getPercentageValueForWrite(100 - this.r)); } if(AscFormat.isRealNumber(this.b)) { writer.WriteXmlAttributeUInt("b", getPercentageValueForWrite(100 - this.b)); } writer.WriteXmlAttributesEnd(true); }; CSrcRect.prototype.isFullRect = function() { let r = this; let fAE = AscFormat.fApproxEqual; if(fAE(r.l, 0) && fAE(r.t, 0) && fAE(r.r, 100) && fAE(r.b, 100)) { return true; } return false; }; function CBlipFillTile() { CBaseNoIdObject.call(this) this.tx = null; this.ty = null; this.sx = null; this.sy = null; this.flip = null; this.algn = null; } InitClass(CBlipFillTile, CBaseNoIdObject, 0); CBlipFillTile.prototype.Write_ToBinary = function (w) { writeLong(w, this.tx); writeLong(w, this.ty); writeLong(w, this.sx); writeLong(w, this.sy); writeLong(w, this.flip); writeLong(w, this.algn); }; CBlipFillTile.prototype.Read_FromBinary = function (r) { this.tx = readLong(r); this.ty = readLong(r); this.sx = readLong(r); this.sy = readLong(r); this.flip = readLong(r); this.algn = readLong(r); }; CBlipFillTile.prototype.createDuplicate = function () { var ret = new CBlipFillTile(); ret.tx = this.tx; ret.ty = this.ty; ret.sx = this.sx; ret.sy = this.sy; ret.flip = this.flip; ret.algn = this.algn; return ret; }; CBlipFillTile.prototype.IsIdentical = function (o) { if (!o) { return false; } return (o.tx == this.tx && o.ty == this.ty && o.sx == this.sx && o.sy == this.sy && o.flip == this.flip && o.algn == this.algn) }; CBlipFillTile.prototype.readAttrXml = function (name, reader) { switch (name) { case "algn" : { this.algn = this.GetAlignBYTECode(reader.GetValue()); break; } case "flip" : { this.flip = reader.GetValue(); break; } case "sx" : { this.sx = reader.GetValueInt(); break; } case "sy" : { this.sy = reader.GetValueInt(); break; } case "tx" : { this.tx = reader.GetValueInt(); break; } case "ty" : { this.ty = reader.GetValueInt(); break; } } }; CBlipFillTile.prototype.GetAlignBYTECode = function (sVal) { if ("b" === sVal) return 0; if ("bl" === sVal) return 1; if ("br" === sVal) return 2; if ("ctr" === sVal) return 3; if ("l" === sVal) return 4; if ("r" === sVal) return 5; if ("t" === sVal) return 6; if ("tl" === sVal) return 7; if ("tr" === sVal) return 8; return 7; }; CBlipFillTile.prototype.SetAlignBYTECode = function (src) { switch (src) { case 0: return ("b"); break; case 1: return ("bl"); break; case 2: return ("br"); break; case 3: return ("ctr"); break; case 4: return ("l"); break; case 5: return ("r"); break; case 6: return ("t"); break; case 7: return ("tl"); break; case 8: return ("tr"); break; default: break; } return null; }; CBlipFillTile.prototype.GetFlipBYTECode = function (sVal) { if ("none" === sVal) return 0; if ("x" === sVal) return 1; if ("y" === sVal) return 2; if ("xy" === sVal) return 3; return 0; } CBlipFillTile.prototype.SetFlipBYTECode = function (src) { switch (src) { case 0: return ("none"); break; case 1: return ("x"); break; case 2: return ("y"); break; case 3: return ("xy"); break; default: break; } return null; } CBlipFillTile.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:tile"); writer.WriteXmlNullableAttributeString("algn", this.SetAlignBYTECode(this.algn)); writer.WriteXmlNullableAttributeString("flip", this.SetFlipBYTECode(this.flip)); writer.WriteXmlNullableAttributeInt("sx", this.sx); writer.WriteXmlNullableAttributeInt("sy", this.sy); writer.WriteXmlNullableAttributeInt("tx", this.tx); writer.WriteXmlNullableAttributeInt("ty", this.ty); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:tile"); }; function fReadEffectXML(name, reader) { var oEffect = null; switch (name) { case "alphaBiLevel": { oEffect = new CAlphaBiLevel(); break; } case "alphaCeiling": { oEffect = new CAlphaCeiling(); break; } case "alphaFloor": { oEffect = new CAlphaFloor(); break; } case "alphaInv": { oEffect = new CAlphaInv(); break; } case "alphaMod": { oEffect = new CAlphaMod(); break; } case "alphaModFix": { oEffect = new CAlphaModFix(); break; } case "alphaOutset": { oEffect = new CAlphaOutset(); break; } case "alphaRepl": { oEffect = new CAlphaRepl(); break; } case "biLevel": { oEffect = new CBiLevel(); break; } case "blend": { oEffect = new CBlend(); break; } case "blur": { oEffect = new CBlur(); break; } case "clrChange": { oEffect = new CClrChange(); break; } case "clrRepl": { oEffect = new CClrRepl(); break; } case "cont": { oEffect = new CEffectContainer(); break; } case "duotone": { oEffect = new CDuotone(); break; } case "effect": { //oEffect = new CEfect(); break; } case "fill": { oEffect = new CFillEffect(); break; } case "fillOverlay": { oEffect = new CFillOverlay(); break; } case "glow": { oEffect = new CGlow(); break; } case "grayscl": { oEffect = new CGrayscl(); break; } case "hsl": { oEffect = new CHslEffect(); break; } case "innerShdw": { oEffect = new CInnerShdw(); break; } case "lum": { oEffect = new CLumEffect(); break; } case "outerShdw": { oEffect = new COuterShdw(); break; } case "prstShdw": { oEffect = new CPrstShdw(); break; } case "reflection": { oEffect = new CReflection(); break; } case "relOff": { oEffect = new CRelOff(); break; } case "softEdge": { oEffect = new CSoftEdge(); break; } case "tint": { oEffect = new CTintEffect(); break; } case "xfrm": { oEffect = new CXfrmEffect(); break; } } return oEffect; } function CBaseFill() { CBaseNoIdObject.call(this); } InitClass(CBaseFill, CBaseNoIdObject, 0); CBaseFill.prototype.type = c_oAscFill.FILL_TYPE_NONE; function fReadXmlRasterImageId(reader, rId, blipFill) { var rel = reader.rels.getRelationship(rId); if (rel) { var context = reader.context; if ("Internal" === rel.targetMode) { var blipFills = context.imageMap[rel.targetFullName.substring(1)]; if (!blipFills) { context.imageMap[rel.targetFullName.substring(1)] = blipFills = []; } blipFills.push(blipFill); } } } function CBlip(oBlipFill) { CBaseNoIdObject.call(this); this.blipFill = oBlipFill; this.link = null; } InitClass(CBlip, CBaseNoIdObject, 0); CBlip.prototype.readAttrXml = function (name, reader) { switch (name) { case "embed" : { var rId = reader.GetValue(); fReadXmlRasterImageId(reader, rId, this.blipFill); break; } } }; CBlip.prototype.readChildXml = function (name, reader) { let oEffect = fReadEffectXML(name, reader); if (oEffect) { this.blipFill.Effects.push(oEffect); } }; CBlip.prototype.toXml = function (writer, sNamespace, sRasterImageId) { let sNamespace_ = sNamespace || "a"; let strName = ("" === sNamespace_) ? ("blip") : (sNamespace_ + (":blip")); let context = writer.context; //writer.WriteXmlNullable(blip); writer.WriteXmlNodeStart(strName); writer.WriteXmlString(' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'); writer.WriteXmlAttributeString("r:embed", context.getImageRId(sRasterImageId)); writer.WriteXmlAttributesEnd(); writer.WriteXmlString('<a:extLst><a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}"><a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/></a:ext></a:extLst>'); writer.WriteXmlNodeEnd(strName); }; function CBlipFill() { CBaseFill.call(this); this.RasterImageId = ""; this.srcRect = null; this.stretch = null; this.tile = null; this.rotWithShape = null; this.Effects = []; } InitClass(CBlipFill, CBaseFill, 0); CBlipFill.prototype.type = c_oAscFill.FILL_TYPE_BLIP; CBlipFill.prototype.saveSourceFormatting = function () { return this.createDuplicate(); }; CBlipFill.prototype.Write_ToBinary = function (w) { writeString(w, this.RasterImageId); if (this.srcRect) { writeBool(w, true); writeDouble(w, this.srcRect.l); writeDouble(w, this.srcRect.t); writeDouble(w, this.srcRect.r); writeDouble(w, this.srcRect.b); } else { writeBool(w, false); } writeBool(w, this.stretch); if (isRealObject(this.tile)) { w.WriteBool(true); this.tile.Write_ToBinary(w); } else { w.WriteBool(false); } writeBool(w, this.rotWithShape); w.WriteLong(this.Effects.length); for (var i = 0; i < this.Effects.length; ++i) { this.Effects[i].Write_ToBinary(w); } }; CBlipFill.prototype.Read_FromBinary = function (r) { this.RasterImageId = readString(r); var _correct_id = AscCommon.getImageFromChanges(this.RasterImageId); if (null != _correct_id) this.RasterImageId = _correct_id; //var srcUrl = readString(r); //if(srcUrl) { // AscCommon.g_oDocumentUrls.addImageUrl(this.RasterImageId, srcUrl); //} if (readBool(r)) { this.srcRect = new CSrcRect(); this.srcRect.l = readDouble(r); this.srcRect.t = readDouble(r); this.srcRect.r = readDouble(r); this.srcRect.b = readDouble(r); } else { this.srcRect = null; } this.stretch = readBool(r); if (r.GetBool()) { this.tile = new CBlipFillTile(); this.tile.Read_FromBinary(r); } else { this.tile = null; } this.rotWithShape = readBool(r); var count = r.GetLong(); for (var i = 0; i < count; ++i) { var effect = fReadEffect(r); if (!effect) { break; } this.Effects.push(effect); } }; CBlipFill.prototype.Refresh_RecalcData = function () { }; CBlipFill.prototype.check = function () { }; CBlipFill.prototype.checkWordMods = function () { return false; }; CBlipFill.prototype.convertToPPTXMods = function () { }; CBlipFill.prototype.canConvertPPTXModsToWord = function () { return false; }; CBlipFill.prototype.convertToWordMods = function () { }; CBlipFill.prototype.getObjectType = function () { return AscDFH.historyitem_type_BlipFill; }; CBlipFill.prototype.setRasterImageId = function (rasterImageId) { this.RasterImageId = checkRasterImageId(rasterImageId); }; CBlipFill.prototype.setSrcRect = function (srcRect) { this.srcRect = srcRect; }; CBlipFill.prototype.setStretch = function (stretch) { this.stretch = stretch; }; CBlipFill.prototype.setTile = function (tile) { this.tile = tile; }; CBlipFill.prototype.setRotWithShape = function (rotWithShape) { this.rotWithShape = rotWithShape; }; CBlipFill.prototype.createDuplicate = function () { var duplicate = new CBlipFill(); duplicate.RasterImageId = this.RasterImageId; duplicate.stretch = this.stretch; if (isRealObject(this.tile)) { duplicate.tile = this.tile.createDuplicate(); } if (null != this.srcRect) duplicate.srcRect = this.srcRect.createDublicate(); duplicate.rotWithShape = this.rotWithShape; if (Array.isArray(this.Effects)) { for (var i = 0; i < this.Effects.length; ++i) { if (this.Effects[i] && this.Effects[i].createDuplicate) { duplicate.Effects.push(this.Effects[i].createDuplicate()); } } } return duplicate; }; CBlipFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_BLIP) { return false; } if (fill.RasterImageId !== this.RasterImageId) { return false; } /*if(fill.VectorImageBin != this.VectorImageBin) { return false; } */ if (fill.stretch != this.stretch) { return false; } if (isRealObject(this.tile)) { if (!this.tile.IsIdentical(fill.tile)) { return false; } } else { if (fill.tile) { return false; } } /* if(fill.rotWithShape != this.rotWithShape) { return false; } */ return true; }; CBlipFill.prototype.compare = function (fill) { if (fill == null || fill.type !== c_oAscFill.FILL_TYPE_BLIP) { return null; } var _ret = new CBlipFill(); if (this.RasterImageId == fill.RasterImageId) { _ret.RasterImageId = this.RasterImageId; } if (fill.stretch == this.stretch) { _ret.stretch = this.stretch; } if (isRealObject(fill.tile)) { if (fill.tile.IsIdentical(this.tile)) { _ret.tile = this.tile.createDuplicate(); } else { _ret.tile = new CBlipFillTile(); } } if (fill.rotWithShape === this.rotWithShape) { _ret.rotWithShape = this.rotWithShape; } return _ret; }; CBlipFill.prototype.getBase64Data = function (bReduce, bReturnOrigIfCantDraw) { var sRasterImageId = this.RasterImageId; if (typeof sRasterImageId !== "string" || sRasterImageId.length === 0) { return null; } var oApi = Asc.editor || editor; var sDefaultResult = sRasterImageId; if(bReturnOrigIfCantDraw === false) { sDefaultResult = null; } if (!oApi) { return {img: sDefaultResult, w: null, h: null}; } var oImageLoader = oApi.ImageLoader; if (!oImageLoader) { return {img: sDefaultResult, w: null, h: null}; } var oImage = oImageLoader.map_image_index[AscCommon.getFullImageSrc2(sRasterImageId)]; if (!oImage || !oImage.Image || oImage.Status !== AscFonts.ImageLoadStatus.Complete) { return {img: sDefaultResult, w: null, h: null}; } if (sRasterImageId.indexOf("data:") === 0 && sRasterImageId.indexOf("base64") > 0) { return {img: sRasterImageId, w: oImage.Image.width, h: oImage.Image.height}; } var sResult = sDefaultResult; if (!window["NATIVE_EDITOR_ENJINE"]) { var oCanvas = document.createElement("canvas"); var nW = Math.max(oImage.Image.width, 1); var nH = Math.max(oImage.Image.height, 1); if (bReduce) { var nMaxSize = 640; var dWK = nW / nMaxSize; var dHK = nH / nMaxSize; var dK = Math.max(dWK, dHK); if (dK > 1) { nW = ((nW / dK) + 0.5 >> 0); nH = ((nH / dK) + 0.5 >> 0); } } oCanvas.width = nW; oCanvas.height = nH; var oCtx = oCanvas.getContext("2d"); oCtx.drawImage(oImage.Image, 0, 0, oCanvas.width, oCanvas.height); try { sResult = oCanvas.toDataURL("image/png"); } catch (err) { sResult = sDefaultResult; } return {img: sResult, w: oCanvas.width, h: oCanvas.height}; } return {img: sRasterImageId, w: null, h: null}; }; CBlipFill.prototype.getBase64RasterImageId = function (bReduce, bReturnOrigIfCantDraw) { return this.getBase64Data(bReduce, bReturnOrigIfCantDraw).img; }; CBlipFill.prototype.readAttrXml = function (name, reader) { if (name === "rotWithShape") { this.rotWithShape = reader.GetValueBool(); } else if (name === "dpi") { //todo } }; CBlipFill.prototype.fromXml = function (reader, bSkipFirstNode) { CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); if(this.srcRect && this.srcRect.isFullRect()) { this.srcRect = null; } } CBlipFill.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { let oBlip = new CBlip(this); oBlip.fromXml(reader); break; } case "srcRect": { this.srcRect = new CSrcRect(); this.srcRect.fromXml(reader, false, true); break; } case "stretch": { this.stretch = true; let oThis = this; let oPr = new CT_XmlNode(function (reader, name) { if (name === "fillRect") { let oSrcRect = new CSrcRect(); oSrcRect.fromXml(reader, false, false); if(!oSrcRect.isFullRect()) { oThis.srcRect = oSrcRect; } } return true; }); oPr.fromXml(reader); break; } case "tile": { this.tile = new CBlipFillTile(); this.tile.fromXml(reader); break; } } }; CBlipFill.prototype.writeBlip = function (writer) { CBlip.prototype.toXml.call(this, writer, "a", this.RasterImageId); }; CBlipFill.prototype.toXml = function (writer, sNamespace) { let sNamespace_ = sNamespace || "a"; let strName = ("" === sNamespace_) ? ("blipFill") : (sNamespace_ + (":blipFill")); writer.WriteXmlNodeStart(strName); //writer.WriteXmlNullableAttributeString("dpi", dpi); writer.WriteXmlNullableAttributeBool("rotWithShape", this.rotWithShape); writer.WriteXmlAttributesEnd(); this.writeBlip(writer); if (this.srcRect) { this.srcRect.toXml(writer) } //writer.WriteXmlNullable(tile); if (this.tile) { this.tile.toXml(writer); } //writer.WriteXmlNullable(stretch); if (this.stretch) { writer.WriteXmlNodeStart("a:stretch"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:fillRect"); writer.WriteXmlAttributesEnd(true); writer.WriteXmlNodeEnd("a:stretch"); } writer.WriteXmlNodeEnd(strName); }; //-----Effects----- var EFFECT_TYPE_NONE = 0; var EFFECT_TYPE_OUTERSHDW = 1; var EFFECT_TYPE_GLOW = 2; var EFFECT_TYPE_DUOTONE = 3; var EFFECT_TYPE_XFRM = 4; var EFFECT_TYPE_BLUR = 5; var EFFECT_TYPE_PRSTSHDW = 6; var EFFECT_TYPE_INNERSHDW = 7; var EFFECT_TYPE_REFLECTION = 8; var EFFECT_TYPE_SOFTEDGE = 9; var EFFECT_TYPE_FILLOVERLAY = 10; var EFFECT_TYPE_ALPHACEILING = 11; var EFFECT_TYPE_ALPHAFLOOR = 12; var EFFECT_TYPE_TINTEFFECT = 13; var EFFECT_TYPE_RELOFF = 14; var EFFECT_TYPE_LUM = 15; var EFFECT_TYPE_HSL = 16; var EFFECT_TYPE_GRAYSCL = 17; var EFFECT_TYPE_ELEMENT = 18; var EFFECT_TYPE_ALPHAREPL = 19; var EFFECT_TYPE_ALPHAOUTSET = 20; var EFFECT_TYPE_ALPHAMODFIX = 21; var EFFECT_TYPE_ALPHABILEVEL = 22; var EFFECT_TYPE_BILEVEL = 23; var EFFECT_TYPE_DAG = 24; var EFFECT_TYPE_FILL = 25; var EFFECT_TYPE_CLRREPL = 26; var EFFECT_TYPE_CLRCHANGE = 27; var EFFECT_TYPE_ALPHAINV = 28; var EFFECT_TYPE_ALPHAMOD = 29; var EFFECT_TYPE_BLEND = 30; function fCreateEffectByType(type) { var ret = null; switch (type) { case EFFECT_TYPE_NONE: { break; } case EFFECT_TYPE_OUTERSHDW: { ret = new COuterShdw(); break; } case EFFECT_TYPE_GLOW: { ret = new CGlow(); break; } case EFFECT_TYPE_DUOTONE: { ret = new CDuotone(); break; } case EFFECT_TYPE_XFRM: { ret = new CXfrmEffect(); break; } case EFFECT_TYPE_BLUR: { ret = new CBlur(); break; } case EFFECT_TYPE_PRSTSHDW: { ret = new CPrstShdw(); break; } case EFFECT_TYPE_INNERSHDW: { ret = new CInnerShdw(); break; } case EFFECT_TYPE_REFLECTION: { ret = new CReflection(); break; } case EFFECT_TYPE_SOFTEDGE: { ret = new CSoftEdge(); break; } case EFFECT_TYPE_FILLOVERLAY: { ret = new CFillOverlay(); break; } case EFFECT_TYPE_ALPHACEILING: { ret = new CAlphaCeiling(); break; } case EFFECT_TYPE_ALPHAFLOOR: { ret = new CAlphaFloor(); break; } case EFFECT_TYPE_TINTEFFECT: { ret = new CTintEffect(); break; } case EFFECT_TYPE_RELOFF: { ret = new CRelOff(); break; } case EFFECT_TYPE_LUM: { ret = new CLumEffect(); break; } case EFFECT_TYPE_HSL: { ret = new CHslEffect(); break; } case EFFECT_TYPE_GRAYSCL: { ret = new CGrayscl(); break; } case EFFECT_TYPE_ELEMENT: { ret = new CEffectElement(); break; } case EFFECT_TYPE_ALPHAREPL: { ret = new CAlphaRepl(); break; } case EFFECT_TYPE_ALPHAOUTSET: { ret = new CAlphaOutset(); break; } case EFFECT_TYPE_ALPHAMODFIX: { ret = new CAlphaModFix(); break; } case EFFECT_TYPE_ALPHABILEVEL: { ret = new CAlphaBiLevel(); break; } case EFFECT_TYPE_BILEVEL: { ret = new CBiLevel(); break; } case EFFECT_TYPE_DAG: { ret = new CEffectContainer(); break; } case EFFECT_TYPE_FILL: { ret = new CFillEffect(); break; } case EFFECT_TYPE_CLRREPL: { ret = new CClrRepl(); break; } case EFFECT_TYPE_CLRCHANGE: { ret = new CClrChange(); break; } case EFFECT_TYPE_ALPHAINV: { ret = new CAlphaInv(); break; } case EFFECT_TYPE_ALPHAMOD: { ret = new CAlphaMod(); break; } case EFFECT_TYPE_BLEND: { ret = new CBlend(); break; } } return ret; } function fReadEffect(r) { var type = r.GetLong(); var ret = fCreateEffectByType(type); ret.Read_FromBinary(r); return ret; } function CAlphaBiLevel() { CBaseNoIdObject.call(this); this.tresh = 0; } InitClass(CAlphaBiLevel, CBaseNoIdObject, 0); CAlphaBiLevel.prototype.Type = EFFECT_TYPE_ALPHABILEVEL; CAlphaBiLevel.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHABILEVEL); w.WriteLong(this.tresh); }; CAlphaBiLevel.prototype.Read_FromBinary = function (r) { this.tresh = r.GetLong(); }; CAlphaBiLevel.prototype.createDuplicate = function () { var oCopy = new CAlphaBiLevel(); oCopy.tresh = this.tresh; return oCopy; }; CAlphaBiLevel.prototype.readAttrXml = function (name, reader) { if (name === "tresh") { this.tresh = reader.GetValueInt(); } }; CAlphaBiLevel.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaBiLevel"); writer.WriteXmlNullableAttributeInt("thresh", this.tresh); writer.WriteXmlAttributesEnd(true); }; function CAlphaCeiling() { CBaseNoIdObject.call(this); } InitClass(CAlphaCeiling, CBaseNoIdObject, 0); CAlphaCeiling.prototype.Type = EFFECT_TYPE_ALPHACEILING; CAlphaCeiling.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHACEILING); }; CAlphaCeiling.prototype.Read_FromBinary = function (r) { }; CAlphaCeiling.prototype.createDuplicate = function () { var oCopy = new CAlphaCeiling(); return oCopy; }; CAlphaCeiling.prototype.toXml = function (writer) { writer.WriteXmlString("<a:alphaCeiling/>"); }; function CAlphaFloor() { CBaseNoIdObject.call(this); } InitClass(CBaseNoIdObject, CBaseNoIdObject, 0); CAlphaFloor.prototype.Type = EFFECT_TYPE_ALPHAFLOOR; CAlphaFloor.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAFLOOR); }; CAlphaFloor.prototype.Read_FromBinary = function (r) { }; CAlphaFloor.prototype.createDuplicate = function () { var oCopy = new CAlphaFloor(); return oCopy; }; CAlphaFloor.prototype.toXml = function (writer) { writer.WriteXmlString("<a:alphaFloor/>"); }; function CAlphaInv() { CBaseNoIdObject.call(this); this.unicolor = null; } InitClass(CAlphaInv, CBaseNoIdObject, 0); CAlphaInv.prototype.Type = EFFECT_TYPE_ALPHAINV; CAlphaInv.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAINV); if (this.unicolor) { w.WriteBool(true); this.unicolor.Write_ToBinary(w); } else { w.WriteBool(false); } }; CAlphaInv.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.unicolor = new CUniColor(); this.unicolor.Read_FromBinary(r); } }; CAlphaInv.prototype.createDuplicate = function () { var oCopy = new CAlphaInv(); if (this.unicolor) { oCopy.unicolor = this.unicolor.createDuplicate(); } return oCopy; }; CAlphaInv.prototype.readAttrXml = function (name, reader) { }; CAlphaInv.prototype.readChildXml = function (name, reader) { var oUniColor = new CUniColor(); oUniColor.fromXml(reader, name); if (oUniColor.color) { this.unicolor = oUniColor; } }; CAlphaInv.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaInv"); writer.WriteXmlAttributesEnd(); this.unicolor.toXml(writer); writer.WriteXmlNodeEnd("a:alphaInv"); }; var effectcontainertypeSib = 0; var effectcontainertypeTree = 1; function CEffectContainer() { CBaseNoIdObject.call(this); this.type = null; this.name = null; this.effectList = []; } InitClass(CEffectContainer, CBaseNoIdObject, 0); CEffectContainer.prototype.Type = EFFECT_TYPE_DAG; CEffectContainer.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_DAG); writeLong(w, this.type); writeString(w, this.name); w.WriteLong(this.effectList.length); for (var i = 0; i < this.effectList.length; ++i) { this.effectList[i].Write_ToBinary(w); } }; CEffectContainer.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.name = readString(r); var count = r.GetLong(); for (var i = 0; i < count; ++i) { var effect = fReadEffect(r); if (!effect) { //error break; } this.effectList.push(effect); } }; CEffectContainer.prototype.createDuplicate = function () { var oCopy = new CEffectContainer(); oCopy.type = this.type; oCopy.name = this.name; for (var i = 0; i < this.effectList.length; ++i) { oCopy.effectList.push(this.effectList[i].createDuplicate()); } return oCopy; }; CEffectContainer.prototype.readAttrXml = function (name, reader) { if (name === "name") { this.name = reader.GetValue() } else if (name === "type") { let sType = reader.GetValue(); if (sType === "sib") { this.type = effectcontainertypeSib; } else { this.type = effectcontainertypeTree; } } }; CEffectContainer.prototype.readChildXml = function (name, reader) { let oEffect = fReadEffectXML(name, reader); if (oEffect) { this.effectList.push(oEffect); } }; CEffectContainer.prototype.toXml = function (writer, sName) { let sName_ = (sName && sName.length > 0) ? sNname : "a:effectDag"; writer.WriteXmlNodeStart(sName_); writer.WriteXmlNullableAttributeString("name", name); writer.WriteXmlNullableAttributeString("type", type); writer.WriteXmlAttributesEnd(); for (let i = 0; i < this.effectList.length; i++) { this.effectList[i].toXml(writer); } writer.WriteXmlNodeEnd(sName_); }; function CAlphaMod() { CBaseNoIdObject.call(this); this.cont = new CEffectContainer(); } InitClass(CAlphaMod, CBaseNoIdObject, 0); CAlphaMod.prototype.Type = EFFECT_TYPE_ALPHAMOD; CAlphaMod.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAMOD); this.cont.Write_ToBinary(w); }; CAlphaMod.prototype.Read_FromBinary = function (r) { this.cont.Read_FromBinary(r); }; CAlphaMod.prototype.createDuplicate = function () { var oCopy = new CAlphaMod(); oCopy.cont = this.cont.createDuplicate(); return oCopy; }; CAlphaMod.prototype.readChildXml = function (name, reader) { if (name === "cont") { this.cont.fromXml(reader); } }; CAlphaMod.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaMod"); writer.WriteXmlAttributesEnd(); this.cont.toXml(writer, "a:cont"); writer.WriteXmlNodeEnd("a:alphaMod"); }; function CAlphaModFix() { CBaseNoIdObject.call(this); this.amt = null; } InitClass(CAlphaModFix, CBaseNoIdObject, 0); CAlphaModFix.prototype.Type = EFFECT_TYPE_ALPHAMODFIX; CAlphaModFix.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAMODFIX); writeLong(w, this.amt); }; CAlphaModFix.prototype.Read_FromBinary = function (r) { this.amt = readLong(r); }; CAlphaModFix.prototype.createDuplicate = function () { var oCopy = new CAlphaModFix(); oCopy.amt = this.amt; return oCopy; }; CAlphaModFix.prototype.readAttrXml = function (name, reader) { switch (name) { case "amt": { this.amt = reader.GetValueInt(); break; } } }; CAlphaModFix.prototype.readChildXml = function (name, reader) { }; CAlphaModFix.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaModFix"); writer.WriteXmlNullableAttributeInt("amt", this.amt); writer.WriteXmlAttributesEnd(true); }; function CAlphaOutset() { CBaseNoIdObject.call(this); this.rad = null; } InitClass(CAlphaOutset, CBaseNoIdObject, 0); CAlphaOutset.prototype.Type = EFFECT_TYPE_ALPHAOUTSET; CAlphaOutset.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAOUTSET); writeLong(w, this.rad); }; CAlphaOutset.prototype.Read_FromBinary = function (r) { this.rad = readLong(r); }; CAlphaOutset.prototype.createDuplicate = function () { var oCopy = new CAlphaOutset(); oCopy.rad = this.rad; return oCopy; }; CAlphaOutset.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } } }; CAlphaOutset.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaOutset"); writer.WriteXmlNullableAttributeInt("rad", this.rad); writer.WriteXmlAttributesEnd(true); }; function CAlphaRepl() { CBaseNoIdObject.call(this); this.a = null; } InitClass(CAlphaRepl, CBaseNoIdObject, 0); CAlphaRepl.prototype.Type = EFFECT_TYPE_ALPHAREPL; CAlphaRepl.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAREPL); writeLong(w, this.a); }; CAlphaRepl.prototype.Read_FromBinary = function (r) { this.a = readLong(r); }; CAlphaRepl.prototype.createDuplicate = function () { var oCopy = new CAlphaRepl(); oCopy.a = this.a; return oCopy; }; CAlphaRepl.prototype.readAttrXml = function (name, reader) { switch (name) { case "a": { this.a = reader.GetValueInt(); break; } } }; CAlphaRepl.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaRepl"); writer.WriteXmlNullableAttributeInt("a", this.a); writer.WriteXmlAttributesEnd(true); }; function CBiLevel() { CBaseNoIdObject.call(this); this.thresh = null; } InitClass(CBiLevel, CBaseNoIdObject, 0); CBiLevel.prototype.Type = EFFECT_TYPE_BILEVEL; CBiLevel.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_BILEVEL); writeLong(w, this.thresh); }; CBiLevel.prototype.Read_FromBinary = function (r) { this.thresh = readLong(r); }; CBiLevel.prototype.createDuplicate = function () { var oCopy = new CBiLevel(); oCopy.thresh = this.thresh; return oCopy; }; CBiLevel.prototype.readAttrXml = function (name, reader) { switch (name) { case "thresh": { this.thresh = reader.GetValueInt(); break; } } }; CBiLevel.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:biLevel"); writer.WriteXmlNullableAttributeInt("thresh", this.thresh); writer.WriteXmlAttributesEnd(true); }; var blendmodeDarken = 0; var blendmodeLighten = 1; var blendmodeMult = 2; var blendmodeOver = 3; var blendmodeScreen = 4; function CBlend() { CBaseNoIdObject.call(this); this.blend = null; this.cont = new CEffectContainer(); } InitClass(CBlend, CBaseNoIdObject, 0); CBlend.prototype.Type = EFFECT_TYPE_BLEND; CBlend.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_BLEND); writeLong(w, this.blend); this.cont.Write_ToBinary(w); }; CBlend.prototype.Read_FromBinary = function (r) { this.blend = readLong(r); this.cont.Read_FromBinary(r); }; CBlend.prototype.createDuplicate = function () { var oCopy = new CBlend(); oCopy.blend = this.blend; oCopy.cont = this.cont.createDuplicate(); return oCopy; }; CBlend.prototype.readAttrXml = function (name, reader) { switch (name) { case "blend": { this.blend = reader.GetValueInt(); break; } } }; CBlend.prototype.readChildXml = function (name, reader) { switch (name) { case "cont": { this.cont.fromXml(reader); break; } } }; CBlend.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:blend"); writer.WriteXmlNullableAttributeInt("blend", this.blend); writer.WriteXmlAttributesEnd(); this.cont.toXml(writer, "a:cont"); writer.WriteXmlNodeEnd("a:blend"); }; function CBlur() { CBaseNoIdObject.call(this); this.rad = null; this.grow = null; } InitClass(CBlur, CBaseNoIdObject, 0); CBlur.prototype.Type = EFFECT_TYPE_BLUR; CBlur.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_BLUR); writeLong(w, this.rad); writeBool(w, this.grow); }; CBlur.prototype.Read_FromBinary = function (r) { this.rad = readLong(r); this.grow = readBool(r); }; CBlur.prototype.createDuplicate = function () { var oCopy = new CBlur(); oCopy.rad = this.rad; oCopy.grow = this.grow; return oCopy; }; CBlur.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } case "grow": { this.grow = reader.GetValueBool(); break; } } }; CBlur.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:blur"); writer.WriteXmlNullableAttributeInt("rad", this.rad); writer.WriteXmlNullableAttributeBool("grow", this.grow); writer.WriteXmlAttributesEnd(true); }; function CClrChange() { CBaseNoIdObject.call(this); this.clrFrom = new CUniColor(); this.clrTo = new CUniColor(); this.useA = null; } InitClass(CClrChange, CBaseNoIdObject, 0); CClrChange.prototype.Type = EFFECT_TYPE_CLRCHANGE; CClrChange.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_CLRCHANGE); this.clrFrom.Write_ToBinary(w); this.clrTo.Write_ToBinary(w); writeBool(w, this.useA); }; CClrChange.prototype.Read_FromBinary = function (r) { this.clrFrom.Read_FromBinary(r); this.clrTo.Read_FromBinary(r); this.useA = readBool(r); }; CClrChange.prototype.createDuplicate = function () { var oCopy = new CClrChange(); oCopy.clrFrom = this.clrFrom.createDuplicate(); oCopy.clrTo = this.clrTo.createDuplicate(); oCopy.useA = this.useA; return oCopy; }; CClrChange.prototype.readAttrXml = function (name, reader) { switch (name) { case "useA": { this.useA = reader.GetValueBool(); break; } } }; CClrChange.prototype.readChildXml = function (name, reader) { if (name === "clrFrom" || name === "clrTo") { let oColor = null; let oPr = new CT_XmlNode(function (reader, name) { if (CUniColor.prototype.isUnicolor(name)) { oColor = new CUniColor(); oColor.fromXml(reader, name); } return true; }); oPr.fromXml(reader); if (name === "clrFrom") { this.clrFrom = oColor; } else { this.clrTo = oColor; } } }; CClrChange.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:clrChange"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:clrFrom"); writer.WriteXmlAttributesEnd(); this.clrFrom.toXml(writer); writer.WriteXmlNodeEnd("a:clrFrom"); writer.WriteXmlNodeStart("a:clrTo"); writer.WriteXmlAttributesEnd(); this.clrTo.toXml(writer); writer.WriteXmlNodeEnd("a:clrTo"); writer.WriteXmlNodeEnd("a:clrChange"); }; function CClrRepl() { CBaseNoIdObject.call(this); this.color = new CUniColor(); } InitClass(CClrRepl, CBaseNoIdObject, 0); CClrRepl.prototype.Type = EFFECT_TYPE_CLRREPL; CClrRepl.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_CLRREPL); this.color.Write_ToBinary(w); }; CClrRepl.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); }; CClrRepl.prototype.createDuplicate = function () { var oCopy = new CClrRepl(); oCopy.color = this.color.createDuplicate(); return oCopy; }; CClrRepl.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CClrRepl.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:clrRepl"); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:clrRepl"); }; function CDuotone() { CBaseNoIdObject.call(this); this.colors = []; } InitClass(CDuotone, CBaseNoIdObject, 0); CDuotone.prototype.Type = EFFECT_TYPE_DUOTONE; CDuotone.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_DUOTONE); w.WriteLong(this.colors.length); for (var i = 0; i < this.colors.length; ++i) { this.colors[i].Write_ToBinary(w); } }; CDuotone.prototype.Read_FromBinary = function (r) { var count = r.GetLong(); for (var i = 0; i < count; ++i) { this.colors[i] = new CUniColor(); this.colors[i].Read_FromBinary(r); } }; CDuotone.prototype.createDuplicate = function () { var oCopy = new CDuotone(); for (var i = 0; i < this.colors.length; ++i) { oCopy.colors[i] = this.colors[i].createDuplicate(); } return oCopy; }; CDuotone.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { let oColor = new CUniColor(); oColor.fromXml(reader, name); this.colors.push(oColor); } }; CDuotone.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:duotone"); writer.WriteXmlAttributesEnd(); for (let nClr = 0; nClr < this.colors.length; ++nClr) { this.colors[nClr].toXml(writer); } writer.WriteXmlNodeEnd("a:duotone"); }; function CEffectElement() { CBaseNoIdObject.call(this); this.ref = null; } InitClass(CEffectElement, CBaseNoIdObject, 0); CEffectElement.prototype.Type = EFFECT_TYPE_ELEMENT; CEffectElement.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ELEMENT); writeString(w, this.ref); }; CEffectElement.prototype.Read_FromBinary = function (r) { this.ref = readString(r); }; CEffectElement.prototype.createDuplicate = function () { var oCopy = new CEffectElement(); oCopy.ref = this.ref; return oCopy; }; CEffectElement.prototype.readAttrXml = function (name, reader) { switch (name) { case "ref": { this.ref = reader.GetValue(); break; } } }; CEffectElement.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:effect"); writer.WriteXmlNullableAttributeString("ref", this.ref); writer.WriteXmlAttributesEnd(true); }; function CFillEffect() { CBaseNoIdObject.call(this); this.fill = new CUniFill(); } InitClass(CFillEffect, CBaseNoIdObject, 0); CFillEffect.prototype.Type = EFFECT_TYPE_FILL; CFillEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_FILL); this.fill.Write_ToBinary(w); }; CFillEffect.prototype.Read_FromBinary = function (r) { this.fill.Read_FromBinary(r); }; CFillEffect.prototype.createDuplicate = function () { var oCopy = new CFillEffect(); oCopy.fill = this.fill.createDuplicate(); return oCopy; }; CFillEffect.prototype.readAttrXml = function (name, reader) { }; CFillEffect.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.fill.fromXml(reader, name); } }; CFillEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:fill"); writer.WriteXmlAttributesEnd(); this.fill.toXml(writer); writer.WriteXmlNodeEnd("a:fill"); }; function CFillOverlay() { CBaseNoIdObject.call(this); this.fill = new CUniFill(); this.blend = 0; } InitClass(CFillOverlay, CBaseNoIdObject, 0); CFillOverlay.prototype.Type = EFFECT_TYPE_FILLOVERLAY; CFillOverlay.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_FILLOVERLAY); this.fill.Write_ToBinary(w); w.WriteLong(this.blend); }; CFillOverlay.prototype.Read_FromBinary = function (r) { this.fill.Read_FromBinary(r); this.blend = r.GetLong(); }; CFillOverlay.prototype.createDuplicate = function () { var oCopy = new CFillOverlay(); oCopy.fill = this.fill.createDuplicate(); oCopy.blend = this.blend; return oCopy; }; CFillOverlay.prototype.readAttrXml = function (name, reader) { switch (name) { case "blend": { this.blend = reader.GetValueInt(); break; } } }; CFillOverlay.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.fill.fromXml(reader, name); } }; CFillOverlay.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:fillOverlay"); writer.WriteXmlNullableAttributeInt("blend", this.blend); writer.WriteXmlAttributesEnd(); this.fill.toXml(writer); writer.WriteXmlNodeEnd("a:fillOverlay"); }; function CGlow() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.rad = null; } InitClass(CGlow, CBaseNoIdObject, 0); CGlow.prototype.Type = EFFECT_TYPE_GLOW; CGlow.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_GLOW); this.color.Write_ToBinary(w); writeLong(w, this.rad); }; CGlow.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.rad = readLong(r); }; CGlow.prototype.createDuplicate = function () { var oCopy = new CGlow(); oCopy.color = this.color.createDuplicate(); oCopy.rad = this.rad; return oCopy; }; CGlow.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } } }; CGlow.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CGlow.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:glow"); writer.WriteXmlNullableAttributeInt("rad", this.rad); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:glow"); }; function CGrayscl() { CBaseNoIdObject.call(this); } InitClass(CGrayscl, CBaseNoIdObject, 0); CGrayscl.prototype.Type = EFFECT_TYPE_GRAYSCL; CGrayscl.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_GRAYSCL); }; CGrayscl.prototype.Read_FromBinary = function (r) { }; CGrayscl.prototype.createDuplicate = function () { var oCopy = new CGrayscl(); return oCopy; }; CGrayscl.prototype.toXml = function (writer) { writer.WriteXmlString("<a:grayscl/>"); }; function CHslEffect() { CBaseNoIdObject.call(this); this.h = null; this.s = null; this.l = null; } InitClass(CHslEffect, CBaseNoIdObject, 0); CHslEffect.prototype.Type = EFFECT_TYPE_HSL; CHslEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_HSL); writeLong(w, this.h); writeLong(w, this.s); writeLong(w, this.l); }; CHslEffect.prototype.Read_FromBinary = function (r) { this.h = readLong(r); this.s = readLong(r); this.l = readLong(r); }; CHslEffect.prototype.createDuplicate = function () { var oCopy = new CHslEffect(); oCopy.h = this.h; oCopy.s = this.s; oCopy.l = this.l; return oCopy; }; CHslEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "h": { this.h = reader.GetValueInt(); break; } case "s": { this.s = reader.GetValueInt(); break; } case "l": { this.l = reader.GetValueInt(); break; } } }; CHslEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:hsl"); writer.WriteXmlNullableAttributeInt("hue", this.hue); writer.WriteXmlNullableAttributeInt("sat", this.sat); writer.WriteXmlNullableAttributeInt("lum", this.lum); writer.WriteXmlAttributesEnd(true); }; function CInnerShdw() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.blurRad = null; this.dir = null; this.dist = null; } InitClass(CInnerShdw, CBaseNoIdObject, 0); CInnerShdw.prototype.Type = EFFECT_TYPE_INNERSHDW; CInnerShdw.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_INNERSHDW); this.color.Write_ToBinary(w); writeLong(w, this.blurRad); writeLong(w, this.dir); writeLong(w, this.dist); }; CInnerShdw.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.blurRad = readLong(r); this.dir = readLong(r); this.dist = readLong(r); }; CInnerShdw.prototype.createDuplicate = function () { var oCopy = new CInnerShdw(); oCopy.color = this.color.createDuplicate(); oCopy.blurRad = this.blurRad; oCopy.dir = this.dir; oCopy.dist = this.dist; return oCopy; }; CInnerShdw.prototype.readAttrXml = function (name, reader) { switch (name) { case "blurRad": { this.blurRad = reader.GetValueInt(); break; } case "dist": { this.dist = reader.GetValueInt(); break; } case "dir": { this.dir = reader.GetValueInt(); break; } } }; CInnerShdw.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CInnerShdw.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:innerShdw"); writer.WriteXmlNullableAttributeInt("blurRad", this.blurRad); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:innerShdw"); }; function CLumEffect() { CBaseNoIdObject.call(this); this.bright = null; this.contrast = null; } InitClass(CLumEffect, CBaseNoIdObject, 0); CLumEffect.prototype.Type = EFFECT_TYPE_LUM; CLumEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_LUM); writeLong(w, this.bright); writeLong(w, this.contrast); }; CLumEffect.prototype.Read_FromBinary = function (r) { this.bright = readLong(r); this.contrast = readLong(r); }; CLumEffect.prototype.createDuplicate = function () { var oCopy = new CLumEffect(); oCopy.bright = this.bright; oCopy.contrast = this.contrast; return oCopy; }; CLumEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "bright": { this.bright = reader.GetValueInt(); break; } case "contrast": { this.contrast = reader.GetValueInt(); break; } } }; CLumEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:lum"); writer.WriteXmlNullableAttributeInt("bright", this.bright); writer.WriteXmlNullableAttributeInt("contrast", this.contrast); writer.WriteXmlAttributesEnd(true); }; function COuterShdw() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.algn = null; this.blurRad = null; this.dir = null; this.dist = null; this.kx = null; this.ky = null; this.rotWithShape = null; this.sx = null; this.sy = null; } InitClass(COuterShdw, CBaseNoIdObject, 0); COuterShdw.prototype.Type = EFFECT_TYPE_OUTERSHDW; COuterShdw.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_OUTERSHDW); this.color.Write_ToBinary(w); writeLong(w, this.algn); writeLong(w, this.blurRad); writeLong(w, this.dir); writeLong(w, this.dist); writeLong(w, this.kx); writeLong(w, this.ky); writeBool(w, this.rotWithShape); writeLong(w, this.sx); writeLong(w, this.sy); }; COuterShdw.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.algn = readLong(r); this.blurRad = readLong(r); this.dir = readLong(r); this.dist = readLong(r); this.kx = readLong(r); this.ky = readLong(r); this.rotWithShape = readBool(r); this.sx = readLong(r); this.sy = readLong(r); }; COuterShdw.prototype.createDuplicate = function () { var oCopy = new COuterShdw(); oCopy.color = this.color.createDuplicate(); oCopy.algn = this.algn; oCopy.blurRad = this.blurRad; oCopy.dir = this.dir; oCopy.dist = this.dist; oCopy.kx = this.kx; oCopy.ky = this.ky; oCopy.rotWithShape = this.rotWithShape; oCopy.sx = this.sx; oCopy.sy = this.sy; return oCopy; }; COuterShdw.prototype.IsIdentical = function (other) { if (!other) { return false; } if (!this.color && other.color || this.color && !other.color || !this.color.IsIdentical(other.color)) { return false; } if (other.algn !== this.algn || other.blurRad !== this.blurRad || other.dir !== this.dir || other.dist !== this.dist || other.kx !== this.kx || other.ky !== this.ky || other.rotWithShape !== this.rotWithShape || other.sx !== this.sx || other.sy !== this.sy) { return false; } return true; }; COuterShdw.prototype.readAttrXml = function (name, reader) { switch (name) { case "algn": { this.algn = reader.GetValueInt(); break; } case "blurRad": { this.blurRad = reader.GetValueInt(); break; } case "dir": { this.dir = reader.GetValueInt(); break; } case "dist": { this.dist = reader.GetValueInt(); break; } case "kx": { this.kx = reader.GetValueInt(); break; } case "ky": { this.ky = reader.GetValueInt(); break; } case "rotWithShape": { this.rotWithShape = reader.GetValueBool(); break; } case "sx": { this.sx = reader.GetValueInt(); break; } case "sy": { this.sy = reader.GetValueInt(); break; } } }; COuterShdw.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; COuterShdw.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:outerShdw"); writer.WriteXmlNullableAttributeInt("blurRad", this.blurRad); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlNullableAttributeInt("kx", this.kx); writer.WriteXmlNullableAttributeInt("ky", this.ky); writer.WriteXmlNullableAttributeInt("sx", this.sx); writer.WriteXmlNullableAttributeInt("sy", this.sy); writer.WriteXmlNullableAttributeBool("rotWithShape", this.rotWithShape); writer.WriteXmlNullableAttributeInt("algn", this.algn); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:outerShdw"); }; function asc_CShadowProperty() { COuterShdw.call(this); this.algn = 7; this.blurRad = 50800; this.color = new CUniColor(); this.color.color = new CPrstColor(); this.color.color.id = "black"; this.color.Mods = new CColorModifiers(); var oMod = new CColorMod(); oMod.name = "alpha"; oMod.val = 40000; this.color.Mods.Mods.push(oMod); this.dir = 2700000; this.dist = 38100; this.rotWithShape = false; } asc_CShadowProperty.prototype = Object.create(COuterShdw.prototype); asc_CShadowProperty.prototype.constructor = asc_CShadowProperty; window['Asc'] = window['Asc'] || {}; window['Asc']['asc_CShadowProperty'] = window['Asc'].asc_CShadowProperty = asc_CShadowProperty; function CPrstShdw() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.prst = null; this.dir = null; this.dist = null; } InitClass(CPrstShdw, CBaseNoIdObject, 0); CPrstShdw.prototype.Type = EFFECT_TYPE_PRSTSHDW; CPrstShdw.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_PRSTSHDW); this.color.Write_ToBinary(w); writeLong(w, this.prst); writeLong(w, this.dir); writeLong(w, this.dist); }; CPrstShdw.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.prst = readLong(r); this.dir = readLong(r); this.dist = readLong(r); }; CPrstShdw.prototype.createDuplicate = function () { var oCopy = new CPrstShdw(); oCopy.color = this.color.createDuplicate(); oCopy.prst = this.prst; oCopy.dir = this.dir; oCopy.dist = this.dist; return oCopy; }; CPrstShdw.prototype.readAttrXml = function (name, reader) { switch (name) { case "prst": { let sVal = reader.GetValue(); this.prst = this.GetBYTECode(sVal); break; } case "dir": { this.dir = reader.GetValueInt(); break; } case "dist": { this.dist = reader.GetValueInt(); break; } } }; CPrstShdw.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CPrstShdw.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:prstShdw"); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlNullableAttributeString("prst", this.SetBYTECode(prst)); writer.WriteXmlAttributesEnd(); if (this.color) { this.color.toXml(writer); } else { writer.WriteXmlNodeStart("a:scrgbClr"); writer.WriteXmlNullableAttributeInt("r", 0); writer.WriteXmlNullableAttributeInt("g", 0); writer.WriteXmlNullableAttributeInt("b", 0); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd("a:prstShdw"); }; CPrstShdw.prototype.GetBYTECode = function (sValue) { if ("shdw1" === sValue) return 0; if ("shdw2" === sValue) return 1; if ("shdw3" === sValue) return 2; if ("shdw4" === sValue) return 3; if ("shdw5" === sValue) return 4; if ("shdw6" === sValue) return 5; if ("shdw7" === sValue) return 6; if ("shdw8" === sValue) return 7; if ("shdw9" === sValue) return 8; if ("shdw10" === sValue) return 9; if ("shdw11" === sValue) return 10; if ("shdw12" === sValue) return 11; if ("shdw13" === sValue) return 12; if ("shdw14" === sValue) return 13; if ("shdw15" === sValue) return 14; if ("shdw16" === sValue) return 15; if ("shdw17" === sValue) return 16; if ("shdw18" === sValue) return 17; if ("shdw19" === sValue) return 18; if ("shdw20" === sValue) return 19; return 0; }; CPrstShdw.prototype.SetBYTECode = function (src) { switch (src) { case 0: return "shdw1"; break; case 1: return "shdw2"; break; case 2: return "shdw3"; break; case 3: return "shdw4"; break; case 4: return "shdw5"; break; case 5: return "shdw6"; break; case 6: return "shdw7"; break; case 7: return "shdw8"; break; case 8: return "shdw9"; break; case 9: return "shdw10"; break; case 10: return "shdw11"; break; case 11: return "shdw12"; break; case 12: return "shdw13"; break; case 13: return "shdw14"; break; case 14: return "shdw15"; break; case 15: return "shdw16"; break; case 16: return "shdw17"; break; case 17: return "shdw18"; break; case 18: return "shdw19"; break; case 19: return "shdw20"; break; } }; function CReflection() { CBaseNoIdObject.call(this); this.algn = null; this.blurRad = null; this.stA = null; this.endA = null; this.stPos = null; this.endPos = null; this.dir = null; this.fadeDir = null; this.dist = null; this.kx = null; this.ky = null; this.rotWithShape = null; this.sx = null; this.sy = null; } InitClass(CReflection, CBaseNoIdObject, 0); CReflection.prototype.Type = EFFECT_TYPE_REFLECTION; CReflection.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_REFLECTION); writeLong(w, this.algn); writeLong(w, this.blurRad); writeLong(w, this.stA); writeLong(w, this.endA); writeLong(w, this.stPos); writeLong(w, this.endPos); writeLong(w, this.dir); writeLong(w, this.fadeDir); writeLong(w, this.dist); writeLong(w, this.kx); writeLong(w, this.ky); writeBool(w, this.rotWithShape); writeLong(w, this.sx); writeLong(w, this.sy); }; CReflection.prototype.Read_FromBinary = function (r) { this.algn = readLong(r); this.blurRad = readLong(r); this.stA = readLong(r); this.endA = readLong(r); this.stPos = readLong(r); this.endPos = readLong(r); this.dir = readLong(r); this.fadeDir = readLong(r); this.dist = readLong(r); this.kx = readLong(r); this.ky = readLong(r); this.rotWithShape = readBool(r); this.sx = readLong(r); this.sy = readLong(r); }; CReflection.prototype.createDuplicate = function () { var oCopy = new CReflection(); oCopy.algn = this.algn; oCopy.blurRad = this.blurRad; oCopy.stA = this.stA; oCopy.endA = this.endA; oCopy.stPos = this.stPos; oCopy.endPos = this.endPos; oCopy.dir = this.dir; oCopy.fadeDir = this.fadeDir; oCopy.dist = this.dist; oCopy.kx = this.kx; oCopy.ky = this.ky; oCopy.rotWithShape = this.rotWithShape; oCopy.sx = this.sx; oCopy.sy = this.sy; return oCopy; }; CReflection.prototype.readAttrXml = function (name, reader) { switch (name) { case "blurRad": this.blurRad = reader.GetValueInt(); break; case "dist": this.dist = reader.GetValueInt(); break; case "dir": this.dir = reader.GetValueInt(); break; case "kx": this.kx = reader.GetValueInt(); break; case "ky": this.ky = reader.GetValueInt(); break; case "sx": this.sx = reader.GetValueInt(); break; case "sy": this.sy = reader.GetValueInt(); break; case "rotWithShape": this.rotWithShape = reader.GetValueBool(); break; case "fadeDir": this.fadeDir = reader.GetValueInt(); break; case "algn": this.algn = reader.GetValueInt(); break; case "stA": this.stA = reader.GetValueInt(); break; case "stPos": this.stPos = reader.GetValueInt(); break; case "endA": this.endA = reader.GetValueInt(); break; case "endPos": this.endPos = reader.GetValueInt(); break; } }; CReflection.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:reflection"); writer.WriteXmlNullableAttributeInt("blurRad", this.blurRad); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlNullableAttributeInt("kx", this.kx); writer.WriteXmlNullableAttributeInt("ky", this.ky); writer.WriteXmlNullableAttributeInt("sx", this.sx); writer.WriteXmlNullableAttributeInt("sy", this.sy); writer.WriteXmlNullableAttributeBool("rotWithShape", this.rotWithShape); writer.WriteXmlNullableAttributeInt("fadeDir", this.fadeDir); writer.WriteXmlNullableAttributeInt("algn", this.algn); writer.WriteXmlNullableAttributeInt("stA", this.stA); writer.WriteXmlNullableAttributeInt("stPos", this.stPos); writer.WriteXmlNullableAttributeInt("endA", this.endA); writer.WriteXmlNullableAttributeInt("endPos", this.endPos); writer.WriteXmlAttributesEnd(true); }; function CRelOff() { CBaseNoIdObject.call(this); this.tx = null; this.ty = null; } InitClass(CRelOff, CBaseNoIdObject, 0); CRelOff.prototype.Type = EFFECT_TYPE_RELOFF; CRelOff.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_RELOFF); writeLong(w, this.tx); writeLong(w, this.ty); }; CRelOff.prototype.Read_FromBinary = function (r) { this.tx = readLong(r); this.ty = readLong(r); }; CRelOff.prototype.createDuplicate = function () { var oCopy = new CRelOff(); oCopy.tx = this.tx; oCopy.ty = this.ty; return oCopy; }; CRelOff.prototype.readAttrXml = function (name, reader) { switch (name) { case "tx": { this.tx = reader.GetValueInt(); break; } case "ty": { this.ty = reader.GetValueInt(); break; } } }; CRelOff.prototype.readChildXml = function (name, reader) { switch (name) { case "tx": { this.tx = reader.GetValueInt() break; } case "ty": { this.ty = reader.GetValueInt() break; } } }; CRelOff.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:relOff"); writer.WriteXmlNullableAttributeInt("tx", this.tx); writer.WriteXmlNullableAttributeInt("ty", this.ty); writer.WriteXmlAttributesEnd(true); }; function CSoftEdge() { CBaseNoIdObject.call(this); this.rad = null; } InitClass(CSoftEdge, CBaseNoIdObject, 0); CSoftEdge.prototype.Type = EFFECT_TYPE_SOFTEDGE; CSoftEdge.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_SOFTEDGE); writeLong(w, this.rad); }; CSoftEdge.prototype.Read_FromBinary = function (r) { this.rad = readLong(r); }; CSoftEdge.prototype.createDuplicate = function () { var oCopy = new CSoftEdge(); oCopy.rad = this.rad; return oCopy; }; CSoftEdge.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } } }; CSoftEdge.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:softEdge"); writer.WriteXmlNullableAttributeString("rad", this.rad); writer.WriteXmlAttributesEnd(true); }; function CTintEffect() { CBaseNoIdObject.call(this); this.amt = null; this.hue = null; } InitClass(CTintEffect, CBaseNoIdObject, 0); CTintEffect.prototype.Type = EFFECT_TYPE_TINTEFFECT; CTintEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_TINTEFFECT); writeLong(w, this.amt); writeLong(w, this.hue); }; CTintEffect.prototype.Read_FromBinary = function (r) { this.amt = readLong(r); this.hue = readLong(r); }; CTintEffect.prototype.createDuplicate = function () { var oCopy = new CTintEffect(); oCopy.amt = this.amt; oCopy.hue = this.hue; return oCopy; }; CTintEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "amt": { this.amt = reader.GetValueInt(); break; } case "hue": { this.hue = reader.GetValueInt(); break; } } }; CTintEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:tint"); writer.WriteXmlNullableAttributeString("hue", this.hue); writer.WriteXmlNullableAttributeString("amt", this.amt); writer.WriteXmlAttributesEnd(true); }; function CXfrmEffect() { CBaseNoIdObject.call(this); this.kx = null; this.ky = null; this.sx = null; this.sy = null; this.tx = null; this.ty = null; } InitClass(CXfrmEffect, CBaseNoIdObject, 0); CXfrmEffect.prototype.Type = EFFECT_TYPE_XFRM; CXfrmEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_XFRM); writeLong(w, this.kx); writeLong(w, this.ky); writeLong(w, this.sx); writeLong(w, this.sy); writeLong(w, this.tx); writeLong(w, this.ty); }; CXfrmEffect.prototype.Read_FromBinary = function (r) { this.kx = readLong(r); this.ky = readLong(r); this.sx = readLong(r); this.sy = readLong(r); this.tx = readLong(r); this.ty = readLong(r); }; CXfrmEffect.prototype.createDuplicate = function () { var oCopy = new CXfrmEffect(); oCopy.kx = this.kx; oCopy.ky = this.ky; oCopy.sx = this.sx; oCopy.sy = this.sy; oCopy.tx = this.tx; oCopy.ty = this.ty; return oCopy; }; CXfrmEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "kx": { this.kx = reader.GetValueInt(); break; } case "ky": { this.ky = reader.GetValueInt(); break; } case "sx": { this.sx = reader.GetValueInt(); break; } case "sy": { this.sy = reader.GetValueInt(); break; } case "tx": { this.tx = reader.GetValueInt(); break; } case "ty": { this.kx = reader.GetValueInt(); break; } } }; CXfrmEffect.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNodeStart("a:xfrm"); writer.WriteXmlNullableAttributeString("kx", kx); writer.WriteXmlNullableAttributeString("ky", ky); writer.WriteXmlNullableAttributeString("sx", sx); writer.WriteXmlNullableAttributeString("sy", sy); writer.WriteXmlNullableAttributeString("tx", tx); writer.WriteXmlNullableAttributeString("ty", ty); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:xfrm"); }; //----------------- function CSolidFill() { CBaseNoIdObject.call(this); this.type = c_oAscFill.FILL_TYPE_SOLID; this.color = null; } InitClass(CSolidFill, CBaseNoIdObject, 0); CSolidFill.prototype.check = function (theme, colorMap) { if (this.color) { this.color.check(theme, colorMap); } }; CSolidFill.prototype.saveSourceFormatting = function () { var _ret = new CSolidFill(); if (this.color) { _ret.color = this.color.saveSourceFormatting(); } return _ret; }; CSolidFill.prototype.setColor = function (color) { this.color = color; }; CSolidFill.prototype.Write_ToBinary = function (w) { if (this.color) { w.WriteBool(true); this.color.Write_ToBinary(w); } else { w.WriteBool(false); } }; CSolidFill.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.color = new CUniColor(); this.color.Read_FromBinary(r); } }; CSolidFill.prototype.checkWordMods = function () { return this.color && this.color.checkWordMods(); }; CSolidFill.prototype.convertToPPTXMods = function () { this.color && this.color.convertToPPTXMods(); }; CSolidFill.prototype.canConvertPPTXModsToWord = function () { return this.color && this.color.canConvertPPTXModsToWord(); }; CSolidFill.prototype.convertToWordMods = function () { this.color && this.color.convertToWordMods(); }; CSolidFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_SOLID) { return false; } if (this.color) { return this.color.IsIdentical(fill.color); } return (fill.color === null); }; CSolidFill.prototype.createDuplicate = function () { var duplicate = new CSolidFill(); if (this.color) { duplicate.color = this.color.createDuplicate(); } return duplicate; }; CSolidFill.prototype.compare = function (fill) { if (fill == null || fill.type !== c_oAscFill.FILL_TYPE_SOLID) { return null; } if (this.color && fill.color) { var _ret = new CSolidFill(); _ret.color = this.color.compare(fill.color); return _ret; } return null; }; CSolidFill.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color = new CUniColor(); this.color.fromXml(reader, name); } }; CSolidFill.prototype.toXml = function (writer, sNamespace) { let strName; let sNamespace_ = sNamespace || "a" if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) strName = ("w14:solidFill"); else strName = ("" === sNamespace_) ? ("solidFill") : (sNamespace_ + (":solidFill")); writer.WriteXmlNodeStart(strName); writer.WriteXmlAttributesEnd(); if (this.color) this.color.toXml(writer); writer.WriteXmlNodeEnd(strName); }; function CGs() { CBaseNoIdObject.call(this); this.color = null; this.pos = 0; } InitClass(CGs, CBaseNoIdObject, 0); CGs.prototype.setColor = function (color) { this.color = color; }; CGs.prototype.setPos = function (pos) { this.pos = pos; }; CGs.prototype.saveSourceFormatting = function () { var _ret = new CGs(); _ret.pos = this.pos; if (this.color) { _ret.color = this.color.saveSourceFormatting(); } return _ret; }; CGs.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.color)); if (isRealObject(this.color)) { this.color.Write_ToBinary(w); } writeLong(w, this.pos); }; CGs.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.color = new CUniColor(); this.color.Read_FromBinary(r); } else { this.color = null; } this.pos = readLong(r); }; CGs.prototype.IsIdentical = function (fill) { if (!fill) return false; if (this.pos !== fill.pos) return false; if (!this.color && fill.color || this.color && !fill.color || (this.color && fill.color && !this.color.IsIdentical(fill.color))) return false; return true; }; CGs.prototype.createDuplicate = function () { var duplicate = new CGs(); duplicate.pos = this.pos; if (this.color) { duplicate.color = this.color.createDuplicate(); } return duplicate; }; CGs.prototype.compare = function (gs) { if (gs.pos !== this.pos) { return null; } var compare_unicolor = this.color.compare(gs.color); if (!isRealObject(compare_unicolor)) { return null; } var ret = new CGs(); ret.color = compare_unicolor; ret.pos = gs.pos === this.pos ? this.pos : 0; return ret; }; CGs.prototype.readAttrXml = function (name, reader) { switch (name) { case "pos": { this.pos = getPercentageValue(reader.GetValue()) * 1000; break; } } }; CGs.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color = new CUniColor(); this.color.fromXml(reader, name); } }; CGs.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("gs")); writer.WriteXmlNullableAttributeInt(sAttrNamespace + ("pos"), this.pos); writer.WriteXmlAttributesEnd(); if (this.color) { this.color.toXml(writer); } writer.WriteXmlNodeEnd(sNodeNamespace + ("gs")); }; function GradLin() { CBaseNoIdObject.call(this); this.angle = 5400000; this.scale = true; } InitClass(GradLin, CBaseNoIdObject, 0); GradLin.prototype.setAngle = function (angle) { this.angle = angle; }; GradLin.prototype.setScale = function (scale) { this.scale = scale; }; GradLin.prototype.Write_ToBinary = function (w) { writeLong(w, this.angle); writeBool(w, this.scale); }; GradLin.prototype.Read_FromBinary = function (r) { this.angle = readLong(r); this.scale = readBool(r); }; GradLin.prototype.IsIdentical = function (lin) { if (this.angle != lin.angle) return false; if (this.scale != lin.scale) return false; return true; }; GradLin.prototype.createDuplicate = function () { var duplicate = new GradLin(); duplicate.angle = this.angle; duplicate.scale = this.scale; return duplicate; }; GradLin.prototype.compare = function (lin) { return null; }; GradLin.prototype.readAttrXml = function (name, reader) { switch (name) { case "ang": { this.angle = reader.GetValueInt(); break; } case "scaled": { this.scale = reader.GetValueBool(); break; } } }; GradLin.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + "lin"); writer.WriteXmlNullableAttributeInt(sAttrNamespace + "ang", this.angle); writer.WriteXmlNullableAttributeBool(sAttrNamespace + "scaled", this.scale); writer.WriteXmlAttributesEnd(true); }; function GradPath() { CBaseNoIdObject.call(this); this.path = 0; this.rect = null; } InitClass(GradPath, CBaseNoIdObject, 0); GradPath.prototype.setPath = function (path) { this.path = path; }; GradPath.prototype.setRect = function (rect) { this.rect = rect; }; GradPath.prototype.Write_ToBinary = function (w) { writeLong(w, this.path); w.WriteBool(isRealObject(this.rect)); if (isRealObject(this.rect)) { this.rect.Write_ToBinary(w); } }; GradPath.prototype.Read_FromBinary = function (r) { this.path = readLong(r); if (r.GetBool()) { this.rect = new CSrcRect(); this.rect.Read_FromBinary(r); } }; GradPath.prototype.IsIdentical = function (path) { if (this.path !== path.path) return false; return true; }; GradPath.prototype.createDuplicate = function () { var duplicate = new GradPath(); duplicate.path = this.path; return duplicate; }; GradPath.prototype.compare = function (path) { return null; }; GradPath.prototype.readAttrXml = function (name, reader) { switch (name) { case "path": { break; } } }; GradPath.prototype.readChildXml = function (name, reader) { switch (name) { case "fillToRect": { this.rect = new CSrcRect(); this.rect.fromXml(reader); break; } } }; GradPath.prototype.toXml = function (writer) { let sNodeNamespace; let sAttrNamespace; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = "a:"; writer.WriteXmlNodeStart(sNodeNamespace + "path"); writer.WriteXmlNullableAttributeString("path", "circle"); writer.WriteXmlAttributesEnd(); //writer.WriteXmlNullable(rect); if (this.rect) { this.rect.toXml(writer, "a:fillToRect"); } writer.WriteXmlNodeEnd(sNodeNamespace + ("path")); }; function CGradFill() { CBaseFill.call(this); // ะฟะพะบะฐ ะฟั€ะพัั‚ะพ front color this.colors = []; this.lin = null; this.path = null; this.rotateWithShape = null; } InitClass(CGradFill, CBaseFill, 0); CGradFill.prototype.type = c_oAscFill.FILL_TYPE_GRAD; CGradFill.prototype.saveSourceFormatting = function () { var _ret = new CGradFill(); if (this.lin) { _ret.lin = this.lin.createDuplicate(); } if (this.path) { _ret.path = this.path.createDuplicate(); } for (var i = 0; i < this.colors.length; ++i) { _ret.colors.push(this.colors[i].saveSourceFormatting()); } return _ret; }; CGradFill.prototype.check = function (theme, colorMap) { for (var i = 0; i < this.colors.length; ++i) { if (this.colors[i].color) { this.colors[i].color.check(theme, colorMap); } } }; CGradFill.prototype.checkWordMods = function () { for (var i = 0; i < this.colors.length; ++i) { if (this.colors[i] && this.colors[i].color && this.colors[i].color.checkWordMods()) { return true; } } return false; }; CGradFill.prototype.convertToPPTXMods = function () { for (var i = 0; i < this.colors.length; ++i) { this.colors[i] && this.colors[i].color && this.colors[i].color.convertToPPTXMods(); } }; CGradFill.prototype.canConvertPPTXModsToWord = function () { for (var i = 0; i < this.colors.length; ++i) { if (this.colors[i] && this.colors[i].color && this.colors[i].color.canConvertPPTXModsToWord()) { return true; } } return false; }; CGradFill.prototype.convertToWordMods = function () { for (var i = 0; i < this.colors.length; ++i) { this.colors[i] && this.colors[i].color && this.colors[i].color.convertToWordMods(); } }; CGradFill.prototype.addColor = function (color) { this.colors.push(color); }; CGradFill.prototype.setLin = function (lin) { this.lin = lin; }; CGradFill.prototype.setPath = function (path) { this.path = path; }; CGradFill.prototype.Write_ToBinary = function (w) { w.WriteLong(this.colors.length); for (var i = 0; i < this.colors.length; ++i) { this.colors[i].Write_ToBinary(w); } w.WriteBool(isRealObject(this.lin)); if (isRealObject(this.lin)) { this.lin.Write_ToBinary(w); } w.WriteBool(isRealObject(this.path)); if (isRealObject(this.path)) { this.path.Write_ToBinary(w); } writeBool(w, this.rotateWithShape); }; CGradFill.prototype.Read_FromBinary = function (r) { var len = r.GetLong(); for (var i = 0; i < len; ++i) { this.colors[i] = new CGs(); this.colors[i].Read_FromBinary(r); } if (r.GetBool()) { this.lin = new GradLin(); this.lin.Read_FromBinary(r); } else { this.lin = null; } if (r.GetBool()) { this.path = new GradPath(); this.path.Read_FromBinary(r); } else { this.path = null; } this.rotateWithShape = readBool(r); }; CGradFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_GRAD) { return false; } if (fill.colors.length !== this.colors.length) { return false; } for (var i = 0; i < this.colors.length; ++i) { if (!this.colors[i].IsIdentical(fill.colors[i])) { return false; } } if (!this.path && fill.path || this.path && !fill.path || (this.path && fill.path && !this.path.IsIdentical(fill.path))) return false; if (!this.lin && fill.lin || !fill.lin && this.lin || (this.lin && fill.lin && !this.lin.IsIdentical(fill.lin))) return false; if(this.rotateWithShape !== fill.rotateWithShape) { return false; } return true; }; CGradFill.prototype.createDuplicate = function () { var duplicate = new CGradFill(); for (var i = 0; i < this.colors.length; ++i) { duplicate.colors[i] = this.colors[i].createDuplicate(); } if (this.lin) duplicate.lin = this.lin.createDuplicate(); if (this.path) duplicate.path = this.path.createDuplicate(); if (this.rotateWithShape != null) duplicate.rotateWithShape = this.rotateWithShape; return duplicate; }; CGradFill.prototype.compare = function (fill) { if (fill == null || fill.type !== c_oAscFill.FILL_TYPE_GRAD) { return null; } var _ret = new CGradFill(); if (this.lin == null || fill.lin == null) _ret.lin = null; else { _ret.lin = new GradLin(); _ret.lin.angle = this.lin && this.lin.angle === fill.lin.angle ? fill.lin.angle : 5400000; _ret.lin.scale = this.lin && this.lin.scale === fill.lin.scale ? fill.lin.scale : true; } if (this.path == null || fill.path == null) { _ret.path = null; } else { _ret.path = new GradPath(); } if (this.colors.length === fill.colors.length) { for (var i = 0; i < this.colors.length; ++i) { var compare_unicolor = this.colors[i].compare(fill.colors[i]); if (!isRealObject(compare_unicolor)) { return null; } _ret.colors[i] = compare_unicolor; } } if(this.rotateWithShape === fill.rotateWithShape) { _ret.rotateWithShape = this.rotateWithShape; } return _ret; }; CGradFill.prototype.readAttrXml = function (name, reader) { switch (name) { case "flip": { break; } case "rotWithShape": { this.rotateWithShape = reader.GetValueBool(); break; } } }; CGradFill.prototype.readChildXml = function (name, reader) { let oGradFill = this; switch (name) { case "gsLst": { let oPr = new CT_XmlNode(function (reader, name) { if (name === "gs") { let oGs = new CGs(); oGs.fromXml(reader); oGradFill.colors.push(oGs); return oGs; } }); oPr.fromXml(reader); break; } case "lin": { let oLin = new GradLin(); oLin.fromXml(reader); this.lin = oLin; break; } case "path": { this.path = new GradPath(); this.path.fromXml(reader); break; } case "tileRect": { break; } } }; CGradFill.prototype.fromXml = function (reader, bSkipFirstNode) { CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); this.colors.sort(function(a,b){return a.pos- b.pos;}); } CGradFill.prototype.toXml = function (writer, sNamespace) { let sAttrNamespace = ""; let strName = ""; let sNamespace_ = sNamespace || "a"; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sAttrNamespace = ("w14:"); strName = ("w14:gradFill"); } else { strName = sNamespace_.length === 0 ? ("gradFill") : (sNamespace_ + (":gradFill")); } writer.WriteXmlNodeStart(strName); // writer.WriteXmlNullableAttributeString(sAttrNamespace + ("flip"), this.flip); writer.WriteXmlNullableAttributeBool(sAttrNamespace + ("rotWithShape"), this.rotWithShape); writer.WriteXmlAttributesEnd(); let sListName; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) sListName = "w14:gsLst"; else sListName = "a:gsLst"; writer.WriteXmlNodeStart(sListName); writer.WriteXmlAttributesEnd(); for (let nGs = 0; nGs < this.colors.length; ++nGs) { this.colors[nGs].toXml(writer); } writer.WriteXmlNodeEnd(sListName); if (this.path) { this.path.toXml(writer); } if (this.lin) { this.lin.toXml(writer); } //writer.WriteXmlNullable(tileRect); writer.WriteXmlNodeEnd(strName); }; CGradFill.prototype.getColorsCount = function() { return this.colors.length; }; function CPattFill() { CBaseFill.call(this); this.ftype = 0; this.fgClr = null;//new CUniColor(); this.bgClr = null;//new CUniColor(); } InitClass(CPattFill, CBaseFill, 0); CPattFill.prototype.type = c_oAscFill.FILL_TYPE_PATT; CPattFill.prototype.check = function (theme, colorMap) { if (this.fgClr) this.fgClr.check(theme, colorMap); if (this.bgClr) this.bgClr.check(theme, colorMap); }; CPattFill.prototype.checkWordMods = function () { if (this.fgClr && this.fgClr.checkWordMods()) { return true; } return this.bgClr && this.bgClr.checkWordMods(); }; CPattFill.prototype.saveSourceFormatting = function () { var _ret = new CPattFill(); if (this.fgClr) { _ret.fgClr = this.fgClr.saveSourceFormatting(); } if (this.bgClr) { _ret.bgClr = this.bgClr.saveSourceFormatting(); } _ret.ftype = this.ftype; return _ret; }; CPattFill.prototype.convertToPPTXMods = function () { this.fgClr && this.fgClr.convertToPPTXMods(); this.bgClr && this.bgClr.convertToPPTXMods(); }; CPattFill.prototype.canConvertPPTXModsToWord = function () { if (this.fgClr && this.fgClr.canConvertPPTXModsToWord()) { return true; } return this.bgClr && this.bgClr.canConvertPPTXModsToWord(); }; CPattFill.prototype.convertToWordMods = function () { this.fgClr && this.fgClr.convertToWordMods(); this.bgClr && this.bgClr.convertToWordMods(); }; CPattFill.prototype.setFType = function (fType) { this.ftype = fType; }; CPattFill.prototype.setFgColor = function (fgClr) { this.fgClr = fgClr; }; CPattFill.prototype.setBgColor = function (bgClr) { this.bgClr = bgClr; }; CPattFill.prototype.Write_ToBinary = function (w) { writeLong(w, this.ftype); w.WriteBool(isRealObject(this.fgClr)); if (isRealObject(this.fgClr)) { this.fgClr.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bgClr)); if (isRealObject(this.bgClr)) { this.bgClr.Write_ToBinary(w); } }; CPattFill.prototype.Read_FromBinary = function (r) { this.ftype = readLong(r); if (r.GetBool()) { this.fgClr = new CUniColor(); this.fgClr.Read_FromBinary(r); } if (r.GetBool()) { this.bgClr = new CUniColor(); this.bgClr.Read_FromBinary(r); } }; CPattFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_PATT && this.ftype !== fill.ftype) { return false; } return this.fgClr.IsIdentical(fill.fgClr) && this.bgClr.IsIdentical(fill.bgClr) && this.ftype === fill.ftype; }; CPattFill.prototype.createDuplicate = function () { var duplicate = new CPattFill(); duplicate.ftype = this.ftype; if (this.fgClr) { duplicate.fgClr = this.fgClr.createDuplicate(); } if (this.bgClr) { duplicate.bgClr = this.bgClr.createDuplicate(); } return duplicate; }; CPattFill.prototype.compare = function (fill) { if (fill == null) { return null; } if (fill.type !== c_oAscFill.FILL_TYPE_PATT) { return null; } var _ret = new CPattFill(); if (fill.ftype == this.ftype) { _ret.ftype = this.ftype; } if (this.fgClr) { _ret.fgClr = this.fgClr.compare(fill.fgClr); } else { _ret.fgClr = null; } if (this.bgClr) { _ret.bgClr = this.bgClr.compare(fill.bgClr); } else { _ret.bgClr = null; } if (!_ret.bgClr && !_ret.fgClr) { return null; } return _ret; }; CPattFill.prototype.readAttrXml = function (name, reader) { switch (name) { case "prst": { let sVal = reader.GetValue(); switch (sVal) { case "cross": this.ftype = AscCommon.global_hatch_offsets.cross; break; case "dashDnDiag": this.ftype = AscCommon.global_hatch_offsets.dashDnDiag; break; case "dashHorz": this.ftype = AscCommon.global_hatch_offsets.dashHorz; break; case "dashUpDiag": this.ftype = AscCommon.global_hatch_offsets.dashUpDiag; break; case "dashVert": this.ftype = AscCommon.global_hatch_offsets.dashVert; break; case "diagBrick": this.ftype = AscCommon.global_hatch_offsets.diagBrick; break; case "diagCross": this.ftype = AscCommon.global_hatch_offsets.diagCross; break; case "divot": this.ftype = AscCommon.global_hatch_offsets.divot; break; case "dkDnDiag": this.ftype = AscCommon.global_hatch_offsets.dkDnDiag; break; case "dkHorz": this.ftype = AscCommon.global_hatch_offsets.dkHorz; break; case "dkUpDiag": this.ftype = AscCommon.global_hatch_offsets.dkUpDiag; break; case "dkVert": this.ftype = AscCommon.global_hatch_offsets.dkVert; break; case "dnDiag": this.ftype = AscCommon.global_hatch_offsets.dnDiag; break; case "dotDmnd": this.ftype = AscCommon.global_hatch_offsets.dotDmnd; break; case "dotGrid": this.ftype = AscCommon.global_hatch_offsets.dotGrid; break; case "horz": this.ftype = AscCommon.global_hatch_offsets.horz; break; case "horzBrick": this.ftype = AscCommon.global_hatch_offsets.horzBrick; break; case "lgCheck": this.ftype = AscCommon.global_hatch_offsets.lgCheck; break; case "lgConfetti": this.ftype = AscCommon.global_hatch_offsets.lgConfetti; break; case "lgGrid": this.ftype = AscCommon.global_hatch_offsets.lgGrid; break; case "ltDnDiag": this.ftype = AscCommon.global_hatch_offsets.ltDnDiag; break; case "ltHorz": this.ftype = AscCommon.global_hatch_offsets.ltHorz; break; case "ltUpDiag": this.ftype = AscCommon.global_hatch_offsets.ltUpDiag; break; case "ltVert": this.ftype = AscCommon.global_hatch_offsets.ltVert; break; case "narHorz": this.ftype = AscCommon.global_hatch_offsets.narHorz; break; case "narVert": this.ftype = AscCommon.global_hatch_offsets.narVert; break; case "openDmnd": this.ftype = AscCommon.global_hatch_offsets.openDmnd; break; case "pct10": this.ftype = AscCommon.global_hatch_offsets.pct10; break; case "pct20": this.ftype = AscCommon.global_hatch_offsets.pct20; break; case "pct25": this.ftype = AscCommon.global_hatch_offsets.pct25; break; case "pct30": this.ftype = AscCommon.global_hatch_offsets.pct30; break; case "pct40": this.ftype = AscCommon.global_hatch_offsets.pct40; break; case "pct5": this.ftype = AscCommon.global_hatch_offsets.pct5; break; case "pct50": this.ftype = AscCommon.global_hatch_offsets.pct50; break; case "pct60": this.ftype = AscCommon.global_hatch_offsets.pct60; break; case "pct70": this.ftype = AscCommon.global_hatch_offsets.pct70; break; case "pct75": this.ftype = AscCommon.global_hatch_offsets.pct75; break; case "pct80": this.ftype = AscCommon.global_hatch_offsets.pct80; break; case "pct90": this.ftype = AscCommon.global_hatch_offsets.pct90; break; case "plaid": this.ftype = AscCommon.global_hatch_offsets.plaid; break; case "shingle": this.ftype = AscCommon.global_hatch_offsets.shingle; break; case "smCheck": this.ftype = AscCommon.global_hatch_offsets.smCheck; break; case "smConfetti": this.ftype = AscCommon.global_hatch_offsets.smConfetti; break; case "smGrid": this.ftype = AscCommon.global_hatch_offsets.smGrid; break; case "solidDmnd": this.ftype = AscCommon.global_hatch_offsets.solidDmnd; break; case "sphere": this.ftype = AscCommon.global_hatch_offsets.sphere; break; case "trellis": this.ftype = AscCommon.global_hatch_offsets.trellis; break; case "upDiag": this.ftype = AscCommon.global_hatch_offsets.upDiag; break; case "vert": this.ftype = AscCommon.global_hatch_offsets.vert; break; case "wave": this.ftype = AscCommon.global_hatch_offsets.wave; break; case "wdDnDiag": this.ftype = AscCommon.global_hatch_offsets.wdDnDiag; break; case "wdUpDiag": this.ftype = AscCommon.global_hatch_offsets.wdUpDiag; break; case "weave": this.ftype = AscCommon.global_hatch_offsets.weave; break; case "zigZag": this.ftype = AscCommon.global_hatch_offsets.zigZag; break; } break; } } }; CPattFill.prototype.readChildXml = function (name, reader) { let oPatt = this; switch (name) { case "bgClr": { let oClr = new CT_XmlNode(function (reader, name) { if (CUniColor.prototype.isUnicolor(name)) { oPatt.bgClr = new CUniColor(); oPatt.bgClr.fromXml(reader, name); return oPatt.bgClr; } }); oClr.fromXml(reader); break; } case "fgClr": { let oClr = new CT_XmlNode(function (reader, name) { if (CUniColor.prototype.isUnicolor(name)) { oPatt.fgClr = new CUniColor(); oPatt.fgClr.fromXml(reader, name); return oPatt.fgClr; } }); oClr.fromXml(reader); break; } } }; CPattFill.prototype.toXml = function (writer, sNamespace) { let sNamespace_ = sNamespace || "a"; let strName = ("" === sNamespace_) ? "pattFill" : (sNamespace_ + ":pattFill"); writer.WriteXmlNodeStart(strName); writer.WriteXmlNullableAttributeString("prst", this.prst); writer.WriteXmlAttributesEnd(); if (this.fgClr) { writer.WriteXmlNodeStart("a:fgClr"); writer.WriteXmlAttributesEnd(); this.fgClr.toXml(writer); writer.WriteXmlNodeEnd("a:fgClr"); } if (this.bgClr) { writer.WriteXmlNodeStart("a:bgClr"); writer.WriteXmlAttributesEnd(); this.bgClr.toXml(writer); writer.WriteXmlNodeEnd("a:bgClr"); } writer.WriteXmlNodeEnd(strName); }; function CNoFill() { CBaseFill.call(this); } InitClass(CNoFill, CBaseFill, 0); CNoFill.prototype.type = c_oAscFill.FILL_TYPE_NOFILL; CNoFill.prototype.check = function () { }; CNoFill.prototype.saveSourceFormatting = function () { return this.createDuplicate(); }; CNoFill.prototype.Write_ToBinary = function (w) { }; CNoFill.prototype.Read_FromBinary = function (r) { }; CNoFill.prototype.checkWordMods = function () { return false; }; CNoFill.prototype.convertToPPTXMods = function () { }; CNoFill.prototype.canConvertPPTXModsToWord = function () { return false; }; CNoFill.prototype.convertToWordMods = function () { }; CNoFill.prototype.createDuplicate = function () { return new CNoFill(); }; CNoFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } return fill.type === c_oAscFill.FILL_TYPE_NOFILL; }; CNoFill.prototype.compare = function (nofill) { if (nofill == null) { return null; } if (nofill.type === this.type) { return new CNoFill(); } return null; }; CNoFill.prototype.readAttrXml = function (name, reader) { }; CNoFill.prototype.readChildXml = function (name, reader) { }; CNoFill.prototype.toXml = function (writer) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) writer.WriteXmlString("<w14:noFill/>"); else writer.WriteXmlString("<a:noFill/>"); }; function CGrpFill() { CBaseFill.call(this); } InitClass(CGrpFill, CBaseFill, 0); CGrpFill.prototype.type = c_oAscFill.FILL_TYPE_GRP; CGrpFill.prototype.check = function () { }; CGrpFill.prototype.getObjectType = function () { return AscDFH.historyitem_type_GrpFill; }; CGrpFill.prototype.Write_ToBinary = function (w) { }; CGrpFill.prototype.Read_FromBinary = function (r) { }; CGrpFill.prototype.checkWordMods = function () { return false; }; CGrpFill.prototype.convertToPPTXMods = function () { }; CGrpFill.prototype.canConvertPPTXModsToWord = function () { return false; }; CGrpFill.prototype.convertToWordMods = function () { }; CGrpFill.prototype.createDuplicate = function () { return new CGrpFill(); }; CGrpFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } return fill.type === c_oAscFill.FILL_TYPE_GRP; }; CGrpFill.prototype.compare = function (grpfill) { if (grpfill == null) { return null; } if (grpfill.type === this.type) { return new CGrpFill(); } return null; }; CGrpFill.prototype.toXml = function (writer) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) writer.WriteXmlString("<w14:grpFill/>"); else writer.WriteXmlString("<a:grpFill/>"); }; function FormatRGBAColor() { this.R = 0; this.G = 0; this.B = 0; this.A = 255; } function CUniFill() { CBaseNoIdObject.call(this); this.fill = null; this.transparent = null; } InitClass(CUniFill, CBaseNoIdObject, 0); CUniFill.prototype.check = function (theme, colorMap) { if (this.fill) { this.fill.check(theme, colorMap); } }; CUniFill.prototype.addColorMod = function (mod) { if (this.fill) { switch (this.fill.type) { case c_oAscFill.FILL_TYPE_BLIP: case c_oAscFill.FILL_TYPE_NOFILL: case c_oAscFill.FILL_TYPE_GRP: { break; } case c_oAscFill.FILL_TYPE_SOLID: { if (this.fill.color && this.fill.color) { this.fill.color.addColorMod(mod); } break; } case c_oAscFill.FILL_TYPE_GRAD: { for (var i = 0; i < this.fill.colors.length; ++i) { if (this.fill.colors[i] && this.fill.colors[i].color) { this.fill.colors[i].color.addColorMod(mod); } } break; } case c_oAscFill.FILL_TYPE_PATT: { if (this.fill.bgClr) { this.fill.bgClr.addColorMod(mod); } if (this.fill.fgClr) { this.fill.fgClr.addColorMod(mod); } break; } } } }; CUniFill.prototype.checkPhColor = function (unicolor, bMergeMods) { if (this.fill) { switch (this.fill.type) { case c_oAscFill.FILL_TYPE_BLIP: case c_oAscFill.FILL_TYPE_NOFILL: case c_oAscFill.FILL_TYPE_GRP: { break; } case c_oAscFill.FILL_TYPE_SOLID: { if (this.fill.color && this.fill.color) { this.fill.color.checkPhColor(unicolor, bMergeMods); } break; } case c_oAscFill.FILL_TYPE_GRAD: { for (var i = 0; i < this.fill.colors.length; ++i) { if (this.fill.colors[i] && this.fill.colors[i].color) { this.fill.colors[i].color.checkPhColor(unicolor, bMergeMods); } } break; } case c_oAscFill.FILL_TYPE_PATT: { if (this.fill.bgClr) { this.fill.bgClr.checkPhColor(unicolor, bMergeMods); } if (this.fill.fgClr) { this.fill.fgClr.checkPhColor(unicolor, bMergeMods); } break; } } } }; CUniFill.prototype.checkPatternType = function (nType) { if (this.fill) { if (this.fill.type === c_oAscFill.FILL_TYPE_PATT) { this.fill.ftype = nType; } } }; CUniFill.prototype.Get_TextBackGroundColor = function () { if (!this.fill) { return undefined; } var oColor = undefined, RGBA; switch (this.fill.type) { case c_oAscFill.FILL_TYPE_SOLID: { if (this.fill.color) { RGBA = this.fill.color.RGBA; if (RGBA) { oColor = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false); } } break; } case c_oAscFill.FILL_TYPE_PATT: { var oClr; if (this.fill.ftype === 38) { oClr = this.fill.fgClr; } else { oClr = this.fill.bgClr; } if (oClr) { RGBA = oClr.RGBA; if (RGBA) { oColor = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false); } } break; } } return oColor; }; CUniFill.prototype.checkWordMods = function () { return this.fill && this.fill.checkWordMods(); }; CUniFill.prototype.convertToPPTXMods = function () { this.fill && this.fill.convertToPPTXMods(); }; CUniFill.prototype.canConvertPPTXModsToWord = function () { return this.fill && this.fill.canConvertPPTXModsToWord(); }; CUniFill.prototype.convertToWordMods = function () { this.fill && this.fill.convertToWordMods(); }; CUniFill.prototype.setFill = function (fill) { this.fill = fill; }; CUniFill.prototype.setTransparent = function (transparent) { this.transparent = transparent; }; CUniFill.prototype.Set_FromObject = function (o) { //TODO: }; CUniFill.prototype.Write_ToBinary = function (w) { writeDouble(w, this.transparent); w.WriteBool(isRealObject(this.fill)); if (isRealObject(this.fill)) { w.WriteLong(this.fill.type); this.fill.Write_ToBinary(w); } }; CUniFill.prototype.Read_FromBinary = function (r) { this.transparent = readDouble(r); if (r.GetBool()) { var type = r.GetLong(); switch (type) { case c_oAscFill.FILL_TYPE_BLIP: { this.fill = new CBlipFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_NOFILL: { this.fill = new CNoFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_SOLID: { this.fill = new CSolidFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_GRAD: { this.fill = new CGradFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_PATT: { this.fill = new CPattFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_GRP: { this.fill = new CGrpFill(); this.fill.Read_FromBinary(r); break; } } } }; CUniFill.prototype.calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { if (this.fill) { if (this.fill.color) { this.fill.color.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); } if (this.fill.colors) { for (var i = 0; i < this.fill.colors.length; ++i) { this.fill.colors[i].color.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); } } if (this.fill.fgClr) this.fill.fgClr.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); if (this.fill.bgClr) this.fill.bgClr.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); } }; CUniFill.prototype.getRGBAColor = function () { if (this.fill) { if (this.fill.type === c_oAscFill.FILL_TYPE_SOLID) { if (this.fill.color) { return this.fill.color.RGBA; } else { return new FormatRGBAColor(); } } if (this.fill.type === c_oAscFill.FILL_TYPE_GRAD) { var RGBA = new FormatRGBAColor(); var _colors = this.fill.colors; var _len = _colors.length; if (0 === _len) return RGBA; for (var i = 0; i < _len; i++) { RGBA.R += _colors[i].color.RGBA.R; RGBA.G += _colors[i].color.RGBA.G; RGBA.B += _colors[i].color.RGBA.B; } RGBA.R = (RGBA.R / _len) >> 0; RGBA.G = (RGBA.G / _len) >> 0; RGBA.B = (RGBA.B / _len) >> 0; return RGBA; } if (this.fill.type === c_oAscFill.FILL_TYPE_PATT) { return this.fill.fgClr.RGBA; } if (this.fill.type === c_oAscFill.FILL_TYPE_NOFILL) { return {R: 0, G: 0, B: 0}; } } return new FormatRGBAColor(); }; CUniFill.prototype.createDuplicate = function () { var duplicate = new CUniFill(); if (this.fill != null) { duplicate.fill = this.fill.createDuplicate(); } duplicate.transparent = this.transparent; return duplicate; }; CUniFill.prototype.saveSourceFormatting = function () { var duplicate = new CUniFill(); if (this.fill) { if (this.fill.saveSourceFormatting) { duplicate.fill = this.fill.saveSourceFormatting(); } else { duplicate.fill = this.fill.createDuplicate(); } } duplicate.transparent = this.transparent; return duplicate; }; CUniFill.prototype.merge = function (unifill) { if (unifill) { if (unifill.fill != null) { this.fill = unifill.fill.createDuplicate(); if (this.fill.type === c_oAscFill.FILL_TYPE_PATT) { var _patt_fill = this.fill; if (!_patt_fill.fgClr) { _patt_fill.setFgColor(CreateUniColorRGB(0, 0, 0)); } if (!_patt_fill.bgClr) { _patt_fill.bgClr = CreateUniColorRGB(255, 255, 255); } } } if (unifill.transparent != null) { this.transparent = unifill.transparent; } } }; CUniFill.prototype.IsIdentical = function (unifill) { if (unifill == null) { return false; } if (isRealNumber(this.transparent) !== isRealNumber(unifill.transparent) || isRealNumber(this.transparent) && this.transparent !== unifill.transparent) { return false; } if (this.fill == null && unifill.fill == null) { return true; } if (this.fill != null) { return this.fill.IsIdentical(unifill.fill); } else { return false; } }; CUniFill.prototype.Is_Equal = function (unfill) { return this.IsIdentical(unfill); }; CUniFill.prototype.isEqual = function (unfill) { return this.IsIdentical(unfill); }; CUniFill.prototype.compare = function (unifill) { if (unifill == null) { return null; } var _ret = new CUniFill(); if (!(this.fill == null || unifill.fill == null)) { if (this.fill.compare) { _ret.fill = this.fill.compare(unifill.fill); } } return _ret.fill; }; CUniFill.prototype.isSolidFillRGB = function () { return (this.fill && this.fill.color && this.fill.color.color && this.fill.color.color.type === window['Asc'].c_oAscColor.COLOR_TYPE_SRGB) }; CUniFill.prototype.isSolidFillScheme = function () { return (this.fill && this.fill.color && this.fill.color.color && this.fill.color.color.type === window['Asc'].c_oAscColor.COLOR_TYPE_SCHEME) }; CUniFill.prototype.isNoFill = function () { return this.fill && this.fill.type === window['Asc'].c_oAscFill.FILL_TYPE_NOFILL; }; CUniFill.prototype.isVisible = function () { return this.fill && this.fill.type !== window['Asc'].c_oAscFill.FILL_TYPE_NOFILL; }; CUniFill.prototype.fromXml = function (reader, name) { switch (name) { case "blipFill": { this.fill = new CBlipFill(); break; } case "gradFill": { this.fill = new CGradFill(); break; } case "grpFill": { this.fill = new CGrpFill(); break; } case "noFill": { this.fill = new CNoFill(); break; } case "pattFill": { this.fill = new CPattFill(); break; } case "solidFill": { this.fill = new CSolidFill(); break; } } if (this.fill) { this.fill.fromXml(reader); if(this.checkTransparent) { this.checkTransparent(); } } }; CUniFill.prototype.FILL_NAMES = { "blipFill": true, "gradFill": true, "grpFill": true, "noFill": true, "pattFill": true, "solidFill": true }; CUniFill.prototype.isFillName = function (sName) { return !!CUniFill.prototype.FILL_NAMES[sName]; }; CUniFill.prototype.toXml = function (writer, ns) { var fill = this.fill; if (!fill) return; fill.toXml(writer, ns); }; CUniFill.prototype.addAlpha = function(dValue) { this.setTransparent(Math.max(0, Math.min(255, (dValue * 255 + 0.5) >> 0))); // let oMod = new CColorMod(); // oMod.name = "alpha"; // oMod.val = nPctValue; // this.addColorMod(oMod); }; CUniFill.prototype.isBlipFill = function() { if(this.fill && this.fill.type === c_oAscFill.FILL_TYPE_BLIP) { return true; } }; CUniFill.prototype.checkTransparent = function() { let oFill = this.fill; if(oFill) { switch (oFill.type) { case c_oAscFill.FILL_TYPE_BLIP: { let aEffects = oFill.Effects; for(let nEffect = 0; nEffect < aEffects.length; ++nEffect) { let oEffect = aEffects[nEffect]; if(oEffect instanceof AscFormat.CAlphaModFix && AscFormat.isRealNumber(oEffect.amt)) { this.setTransparent(255 * oEffect.amt / 100000); } } break; } case c_oAscFill.FILL_TYPE_SOLID: { let oColor = oFill.color; if(oColor) { let fAlphaVal = oColor.getModValue("alpha"); if(fAlphaVal !== null) { this.setTransparent(255 * fAlphaVal / 100000); let aMods = oColor.Mods && oColor.Mods.Mods; if(Array.isArray(aMods)) { for(let nMod = aMods.length -1; nMod > -1; nMod--) { let oMod = aMods[nMod]; if(oMod && oMod.name === "alpha") { aMods.splice(nMod); } } } } } break; } case c_oAscFill.FILL_TYPE_PATT: { if(oFill.fgClr && oFill.bgClr) { let fAlphaVal = oFill.fgClr.getModValue("alpha"); if(fAlphaVal !== null) { if(fAlphaVal === oFill.bgClr.getModValue("alpha")) { this.setTransparent(255 * fAlphaVal / 100000) } } } break; } } } }; function CBuBlip() { CBaseNoIdObject.call(this); this.blip = null; } InitClass(CBuBlip, CBaseNoIdObject, 0); CBuBlip.prototype.setBlip = function (oPr) { this.blip = oPr; }; CBuBlip.prototype.fillObject = function (oCopy, oIdMap) { if (this.blip) { oCopy.setBlip(this.blip.createDuplicate(oIdMap)); } }; CBuBlip.prototype.createDuplicate = function () { var oCopy = new CBuBlip(); this.fillObject(oCopy, {}); return oCopy; }; CBuBlip.prototype.getChildren = function () { return [this.blip]; }; CBuBlip.prototype.isEqual = function (oBlip) { return this.blip.isEqual(oBlip.blip); }; CBuBlip.prototype.toPPTY = function (pWriter) { var _src = this.blip.fill.RasterImageId; var imageLocal = AscCommon.g_oDocumentUrls.getImageLocal(_src); if (imageLocal) _src = imageLocal; pWriter.image_map[_src] = true; _src = pWriter.prepareRasterImageIdForWrite(_src); pWriter.WriteBlip(this.blip.fill, _src); }; CBuBlip.prototype.fromPPTY = function (pReader, oParagraph, oBullet) { this.setBlip(new AscFormat.CUniFill()); this.blip.setFill(new AscFormat.CBlipFill()); pReader.ReadBlip(this.blip, undefined, undefined, undefined, oParagraph, oBullet); }; CBuBlip.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.blip = new CUniFill(); this.blip.Read_FromBinary(r); } }; CBuBlip.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.blip)); if (isRealObject(this.blip)) { this.blip.Write_ToBinary(w); } }; CBuBlip.prototype.compare = function (compareObj) { var ret = null; if (compareObj instanceof CBuBlip) { ret = new CBuBlip(); if (this.blip) { ret.blip = CompareUniFill(this.blip, compareObj.blip); } } return ret; }; CBuBlip.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { this.blip = new CUniFill(); this.blip.fill = new CBlipFill(); this.blip.fill.readChildXml("blip", reader); break; } } }; CBuBlip.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:buBlip"); writer.WriteXmlAttributesEnd(); this.blip.fill.writeBlip(writer); writer.WriteXmlNodeEnd("a:buBlip"); }; function CompareUniFill(unifill_1, unifill_2) { if (unifill_1 == null || unifill_2 == null) { return null; } var _ret = new CUniFill(); if (!(unifill_1.transparent === null || unifill_2.transparent === null || unifill_1.transparent !== unifill_2.transparent)) { _ret.transparent = unifill_1.transparent; } if (unifill_1.fill == null || unifill_2.fill == null || unifill_1.fill.type != unifill_2.fill.type) { return _ret; } _ret.fill = unifill_1.compare(unifill_2); return _ret; } function CompareBlipTiles(tile1, tile2) { if (isRealObject(tile1)) { return tile1.IsIdentical(tile2); } return tile1 === tile2; } function CompareUnifillBool(u1, u2) { if (!u1 && !u2) return true; if (!u1 && u2 || u1 && !u2) return false; if (isRealNumber(u1.transparent) !== isRealNumber(u2.transparent) || isRealNumber(u1.transparent) && u1.transparent !== u2.transparent) { return false; } if (!u1.fill && !u2.fill) return true; if (!u1.fill && u2.fill || u1.fill && !u2.fill) return false; if (u1.fill.type !== u2.fill.type) return false; switch (u1.fill.type) { case c_oAscFill.FILL_TYPE_BLIP: { if (u1.fill.RasterImageId && !u2.fill.RasterImageId || u2.fill.RasterImageId && !u1.fill.RasterImageId) return false; if (typeof u1.fill.RasterImageId === "string" && typeof u2.fill.RasterImageId === "string" && AscCommon.getFullImageSrc2(u1.fill.RasterImageId) !== AscCommon.getFullImageSrc2(u2.fill.RasterImageId)) return false; if (u1.fill.srcRect && !u2.fill.srcRect || !u1.fill.srcRect && u2.fill.srcRect) return false; if (u1.fill.srcRect && u2.fill.srcRect) { if (u1.fill.srcRect.l !== u2.fill.srcRect.l || u1.fill.srcRect.t !== u2.fill.srcRect.t || u1.fill.srcRect.r !== u2.fill.srcRect.r || u1.fill.srcRect.b !== u2.fill.srcRect.b) return false; } if (u1.fill.stretch !== u2.fill.stretch || !CompareBlipTiles(u1.fill.tile, u2.fill.tile) || u1.fill.rotWithShape !== u2.fill.rotWithShape) return false; break; } case c_oAscFill.FILL_TYPE_SOLID: { if (u1.fill.color && u2.fill.color) { return CompareUniColor(u1.fill.color, u2.fill.color) } break; } case c_oAscFill.FILL_TYPE_GRAD: { if (u1.fill.colors.length !== u2.fill.colors.length) return false; if (isRealObject(u1.fill.path) !== isRealObject(u2.fill.path)) return false; if (u1.fill.path && !u1.fill.path.IsIdentical(u2.fill.path)) return false; if (isRealObject(u1.fill.lin) !== isRealObject(u2.fill.lin)) return false; if (u1.fill.lin && !u1.fill.lin.IsIdentical(u2.fill.lin)) return false; for (var i = 0; i < u1.fill.colors.length; ++i) { if (u1.fill.colors[i].pos !== u2.fill.colors[i].pos || !CompareUniColor(u1.fill.colors[i].color, u2.fill.colors[i].color)) return false; } break; } case c_oAscFill.FILL_TYPE_PATT: { if (u1.fill.ftype !== u2.fill.ftype || !CompareUniColor(u1.fill.fgClr, u2.fill.fgClr) || !CompareUniColor(u1.fill.bgClr, u2.fill.bgClr)) return false; break; } } return true; } function CompareUniColor(u1, u2) { if (!u1 && !u2) return true; if (!u1 && u2 || u1 && !u2) return false; if (!u1.color && u2.color || u1.color && !u2.color) return false; if (u1.color && u2.color) { if (u1.color.type !== u2.color.type) return false; switch (u1.color.type) { case c_oAscColor.COLOR_TYPE_NONE: { break; } case c_oAscColor.COLOR_TYPE_SRGB: { if (u1.color.RGBA.R !== u2.color.RGBA.R || u1.color.RGBA.G !== u2.color.RGBA.G || u1.color.RGBA.B !== u2.color.RGBA.B || u1.color.RGBA.A !== u2.color.RGBA.A) { return false; } break; } case c_oAscColor.COLOR_TYPE_PRST: case c_oAscColor.COLOR_TYPE_SCHEME: { if (u1.color.id !== u2.color.id) return false; break; } case c_oAscColor.COLOR_TYPE_SYS: { if (u1.color.RGBA.R !== u2.color.RGBA.R || u1.color.RGBA.G !== u2.color.RGBA.G || u1.color.RGBA.B !== u2.color.RGBA.B || u1.color.RGBA.A !== u2.color.RGBA.A || u1.color.id !== u2.color.id) { return false; } break; } case c_oAscColor.COLOR_TYPE_STYLE: { if (u1.bAuto !== u2.bAuto || u1.val !== u2.val) { return false; } break; } } } if (!u1.Mods && u2.Mods || !u2.Mods && u1.Mods) return false; if (u1.Mods && u2.Mods) { if (u1.Mods.Mods.length !== u2.Mods.Mods.length) return false; for (var i = 0; i < u1.Mods.Mods.length; ++i) { if (u1.Mods.Mods[i].name !== u2.Mods.Mods[i].name || u1.Mods.Mods[i].val !== u2.Mods.Mods[i].val) return false; } } return true; } // ----------------------------- function CompareShapeProperties(shapeProp1, shapeProp2) { var _result_shape_prop = {}; if (shapeProp1.type === shapeProp2.type) { _result_shape_prop.type = shapeProp1.type; } else { _result_shape_prop.type = null; } if (shapeProp1.h === shapeProp2.h) { _result_shape_prop.h = shapeProp1.h; } else { _result_shape_prop.h = null; } if (shapeProp1.w === shapeProp2.w) { _result_shape_prop.w = shapeProp1.w; } else { _result_shape_prop.w = null; } if (shapeProp1.x === shapeProp2.x) { _result_shape_prop.x = shapeProp1.x; } else { _result_shape_prop.x = null; } if (shapeProp1.y === shapeProp2.y) { _result_shape_prop.y = shapeProp1.y; } else { _result_shape_prop.y = null; } if (shapeProp1.rot === shapeProp2.rot) { _result_shape_prop.rot = shapeProp1.rot; } else { _result_shape_prop.rot = null; } if (shapeProp1.flipH === shapeProp2.flipH) { _result_shape_prop.flipH = shapeProp1.flipH; } else { _result_shape_prop.flipH = null; } if (shapeProp1.flipV === shapeProp2.flipV) { _result_shape_prop.flipV = shapeProp1.flipV; } else { _result_shape_prop.flipV = null; } if (shapeProp1.anchor === shapeProp2.anchor) { _result_shape_prop.anchor = shapeProp1.anchor; } else { _result_shape_prop.anchor = null; } if (shapeProp1.stroke == null || shapeProp2.stroke == null) { _result_shape_prop.stroke = null; } else { _result_shape_prop.stroke = shapeProp1.stroke.compare(shapeProp2.stroke) } /* if(shapeProp1.verticalTextAlign === shapeProp2.verticalTextAlign) { _result_shape_prop.verticalTextAlign = shapeProp1.verticalTextAlign; } else */ { _result_shape_prop.verticalTextAlign = null; _result_shape_prop.vert = null; } if (shapeProp1.canChangeArrows !== true || shapeProp2.canChangeArrows !== true) _result_shape_prop.canChangeArrows = false; else _result_shape_prop.canChangeArrows = true; _result_shape_prop.fill = CompareUniFill(shapeProp1.fill, shapeProp2.fill); _result_shape_prop.IsLocked = shapeProp1.IsLocked === true || shapeProp2.IsLocked === true; if (isRealObject(shapeProp1.paddings) && isRealObject(shapeProp2.paddings)) { _result_shape_prop.paddings = new Asc.asc_CPaddings(); _result_shape_prop.paddings.Left = isRealNumber(shapeProp1.paddings.Left) ? (shapeProp1.paddings.Left === shapeProp2.paddings.Left ? shapeProp1.paddings.Left : undefined) : undefined; _result_shape_prop.paddings.Top = isRealNumber(shapeProp1.paddings.Top) ? (shapeProp1.paddings.Top === shapeProp2.paddings.Top ? shapeProp1.paddings.Top : undefined) : undefined; _result_shape_prop.paddings.Right = isRealNumber(shapeProp1.paddings.Right) ? (shapeProp1.paddings.Right === shapeProp2.paddings.Right ? shapeProp1.paddings.Right : undefined) : undefined; _result_shape_prop.paddings.Bottom = isRealNumber(shapeProp1.paddings.Bottom) ? (shapeProp1.paddings.Bottom === shapeProp2.paddings.Bottom ? shapeProp1.paddings.Bottom : undefined) : undefined; } _result_shape_prop.canFill = shapeProp1.canFill === true || shapeProp2.canFill === true; if (shapeProp1.bFromChart || shapeProp2.bFromChart) { _result_shape_prop.bFromChart = true; } else { _result_shape_prop.bFromChart = false; } if (shapeProp1.bFromSmartArt || shapeProp2.bFromSmartArt) { _result_shape_prop.bFromSmartArt = true; } else { _result_shape_prop.bFromSmartArt = false; } if (shapeProp1.bFromSmartArtInternal || shapeProp2.bFromSmartArtInternal) { _result_shape_prop.bFromSmartArtInternal = true; } else { _result_shape_prop.bFromSmartArtInternal = false; } if (shapeProp1.bFromGroup || shapeProp2.bFromGroup) { _result_shape_prop.bFromGroup = true; } else { _result_shape_prop.bFromGroup = false; } if (!shapeProp1.bFromImage || !shapeProp2.bFromImage) { _result_shape_prop.bFromImage = false; } else { _result_shape_prop.bFromImage = true; } if (shapeProp1.locked || shapeProp2.locked) { _result_shape_prop.locked = true; } _result_shape_prop.lockAspect = !!(shapeProp1.lockAspect && shapeProp2.lockAspect); _result_shape_prop.textArtProperties = CompareTextArtProperties(shapeProp1.textArtProperties, shapeProp2.textArtProperties); if (shapeProp1.bFromSmartArtInternal && !shapeProp2.bFromSmartArtInternal || !shapeProp1.bFromSmartArtInternal && shapeProp2.bFromSmartArtInternal) { _result_shape_prop.textArtProperties = null; } if (shapeProp1.title === shapeProp2.title) { _result_shape_prop.title = shapeProp1.title; } if (shapeProp1.description === shapeProp2.description) { _result_shape_prop.description = shapeProp1.description; } if (shapeProp1.columnNumber === shapeProp2.columnNumber) { _result_shape_prop.columnNumber = shapeProp1.columnNumber; } if (shapeProp1.columnSpace === shapeProp2.columnSpace) { _result_shape_prop.columnSpace = shapeProp1.columnSpace; } if (shapeProp1.textFitType === shapeProp2.textFitType) { _result_shape_prop.textFitType = shapeProp1.textFitType; } if (shapeProp1.vertOverflowType === shapeProp2.vertOverflowType) { _result_shape_prop.vertOverflowType = shapeProp1.vertOverflowType; } if (!shapeProp1.shadow && !shapeProp2.shadow) { _result_shape_prop.shadow = null; } else if (shapeProp1.shadow && !shapeProp2.shadow) { _result_shape_prop.shadow = null; } else if (!shapeProp1.shadow && shapeProp2.shadow) { _result_shape_prop.shadow = null; } else if (shapeProp1.shadow.IsIdentical(shapeProp2.shadow)) { _result_shape_prop.shadow = shapeProp1.shadow.createDuplicate(); } else { _result_shape_prop.shadow = null; } _result_shape_prop.protectionLockText = CompareProtectionFlags(shapeProp1.protectionLockText, shapeProp2.protectionLockText); _result_shape_prop.protectionLocked = CompareProtectionFlags(shapeProp1.protectionLocked, shapeProp2.protectionLocked); _result_shape_prop.protectionPrint = CompareProtectionFlags(shapeProp1.protectionPrint, shapeProp2.protectionPrint); return _result_shape_prop; } function CompareProtectionFlags(bFlag1, bFlag2) { if (bFlag1 === null || bFlag2 === null) { return null; } else if (bFlag1 === bFlag2) { return bFlag1; } return undefined; } function CompareTextArtProperties(oProps1, oProps2) { if (!oProps1 || !oProps2) return null; var oRet = {Fill: undefined, Line: undefined, Form: undefined}; if (oProps1.Form === oProps2.Form) { oRet.From = oProps1.Form; } if (oProps1.Fill && oProps2.Fill) { oRet.Fill = CompareUniFill(oProps1.Fill, oProps2.Fill); } if (oProps1.Line && oProps2.Line) { oRet.Line = oProps1.Line.compare(oProps2.Line); } return oRet; } // LN -------------------------- // ั€ะฐะทะผะตั€ั‹ ัั‚ั€ะตะปะพะบ; var lg = 500, mid = 300, sm = 200; //ั‚ะธะฟั‹ ัั‚ั€ะตะปะพะบ var ar_arrow = 0, ar_diamond = 1, ar_none = 2, ar_oval = 3, ar_stealth = 4, ar_triangle = 5; var LineEndType = { None: 0, Arrow: 1, Diamond: 2, Oval: 3, Stealth: 4, Triangle: 5 }; var LineEndSize = { Large: 0, Mid: 1, Small: 2 }; var LineJoinType = { Empty: 0, Round: 1, Bevel: 2, Miter: 3 }; function EndArrow() { CBaseNoIdObject.call(this); this.type = null; this.len = null; this.w = null; } InitClass(EndArrow, CBaseNoIdObject, 0); EndArrow.prototype.compare = function (end_arrow) { if (end_arrow == null) { return null; } var _ret = new EndArrow(); if (this.type === end_arrow.type) { _ret.type = this.type; } if (this.len === end_arrow.len) { _ret.len = this.len; } if (this.w === end_arrow) { _ret.w = this.w; } return _ret; }; EndArrow.prototype.createDuplicate = function () { var duplicate = new EndArrow(); duplicate.type = this.type; duplicate.len = this.len; duplicate.w = this.w; return duplicate; }; EndArrow.prototype.IsIdentical = function (arrow) { return arrow && arrow.type === this.type && arrow.len === this.len && arrow.w === this.w; }; EndArrow.prototype.GetWidth = function (_size, _max) { var size = Math.max(_size, _max ? _max : 2); var _ret = 3 * size; if (null != this.w) { switch (this.w) { case LineEndSize.Large: _ret = 5 * size; break; case LineEndSize.Small: _ret = 2 * size; break; default: break; } } return _ret; }; EndArrow.prototype.GetLen = function (_size, _max) { var size = Math.max(_size, _max ? _max : 2); var _ret = 3 * size; if (null != this.len) { switch (this.len) { case LineEndSize.Large: _ret = 5 * size; break; case LineEndSize.Small: _ret = 2 * size; break; default: break; } } return _ret; }; EndArrow.prototype.setType = function (type) { this.type = type; }; EndArrow.prototype.setLen = function (len) { this.len = len; }; EndArrow.prototype.setW = function (w) { this.w = w; }; EndArrow.prototype.Write_ToBinary = function (w) { writeLong(w, this.type); writeLong(w, this.len); writeLong(w, this.w); }; EndArrow.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.len = readLong(r); this.w = readLong(r); }; EndArrow.prototype.GetSizeCode = function (sVal) { switch (sVal) { case "lg": { return LineEndSize.Large; } case "med": { return LineEndSize.Mid; } case "sm": { return LineEndSize.Small; } } return LineEndSize.Mid; }; EndArrow.prototype.GetSizeByCode = function (nCode) { switch (nCode) { case LineEndSize.Large: { return "lg"; } case LineEndSize.Mid: { return "med"; } case LineEndSize.Small: { return "sm"; } } return "med"; }; EndArrow.prototype.GetTypeCode = function (sVal) { switch (sVal) { case "arrow": { return LineEndType.Arrow; } case "diamond": { return LineEndType.Diamond; } case "none": { return LineEndType.None; } case "oval": { return LineEndType.Oval; } case "stealth": { return LineEndType.Stealth; } case "triangle": { return LineEndType.Triangle; } } return LineEndType.Arrow; }; EndArrow.prototype.GetTypeByCode = function (nCode) { switch (nCode) { case LineEndType.Arrow : { return "arrow"; } case LineEndType.Diamond: { return "diamond"; } case LineEndType.None: { return "none"; } case LineEndType.Oval: { return "oval"; } case LineEndType.Stealth: { return "stealth"; } case LineEndType.Triangle: { return "triangle"; } } return "arrow"; }; EndArrow.prototype.readAttrXml = function (name, reader) { switch (name) { case "len": { let sVal = reader.GetValue(); this.len = this.GetSizeCode(sVal); break; } case "type": { let sVal = reader.GetValue(); this.type = this.GetTypeCode(sVal); break; } case "w": { let sVal = reader.GetValue(); this.w = this.GetSizeCode(sVal); break; } } }; EndArrow.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlNullableAttributeString("type", this.GetTypeByCode(this.type)); writer.WriteXmlNullableAttributeString("w", this.GetSizeByCode(this.w)); writer.WriteXmlNullableAttributeString("len", this.GetSizeByCode(this.len)); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd(sName); }; function ConvertJoinAggType(_type) { switch (_type) { case LineJoinType.Round: return 2; case LineJoinType.Bevel: return 1; case LineJoinType.Miter: return 0; default: break; } return 2; } function LineJoin(type) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(type) ? type : null; this.limit = null; } InitClass(LineJoin, CBaseNoIdObject, 0); LineJoin.prototype.IsIdentical = function (oJoin) { if (!oJoin) return false; if (this.type !== oJoin.type) { return false; } if (this.limit !== oJoin.limit) return false; return true; }; LineJoin.prototype.createDuplicate = function () { var duplicate = new LineJoin(); duplicate.type = this.type; duplicate.limit = this.limit; return duplicate; }; LineJoin.prototype.setType = function (type) { this.type = type; }; LineJoin.prototype.setLimit = function (limit) { this.limit = limit; }; LineJoin.prototype.Write_ToBinary = function (w) { writeLong(w, this.type); writeLong(w, this.limit); }; LineJoin.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.limit = readLong(r); }; LineJoin.prototype.readAttrXml = function (name, reader) { switch (name) { case "lim": { this.limit = reader.GetValueInt(); break; } } }; LineJoin.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = "w14:"; sAttrNamespace = sNodeNamespace; } else sNodeNamespace = "a:"; if (this.type === LineJoinType.Round) { writer.WriteXmlString("<" + sNodeNamespace + "round/>"); } else if (this.type === LineJoinType.Bevel) { writer.WriteXmlString("<" + sNodeNamespace + "bevel/>"); } else if (this.type === LineJoinType.Miter) { writer.WriteXmlNodeStart(sNodeNamespace + "miter"); writer.WriteXmlNullableAttributeInt(sAttrNamespace + "lim", this.limit); writer.WriteXmlAttributesEnd(true); } }; function CLn() { CBaseNoIdObject.call(this); this.Fill = null;//new CUniFill(); this.prstDash = null; this.Join = null; this.headEnd = null; this.tailEnd = null; this.algn = null; this.cap = null; this.cmpd = null; this.w = null; } InitClass(CLn, CBaseNoIdObject, 0); CLn.prototype.compare = function (line) { if (line == null) { return null; } var _ret = new CLn(); if (this.Fill != null) { _ret.Fill = CompareUniFill(this.Fill, line.Fill); } if (this.prstDash === line.prstDash) { _ret.prstDash = this.prstDash; } else { _ret.prstDash = undefined; } if (this.Join === line.Join) { _ret.Join = this.Join; } if (this.tailEnd != null) { _ret.tailEnd = this.tailEnd.compare(line.tailEnd); } if (this.headEnd != null) { _ret.headEnd = this.headEnd.compare(line.headEnd); } if (this.algn === line.algn) { _ret.algn = this.algn; } if (this.cap === line.cap) { _ret.cap = this.cap; } if (this.cmpd === line.cmpd) { _ret.cmpd = this.cmpd; } if (this.w === line.w) { _ret.w = this.w; } return _ret; }; CLn.prototype.merge = function (ln) { if (ln == null) { return; } if (ln.Fill != null && ln.Fill.fill != null) { this.Fill = ln.Fill.createDuplicate(); } if (ln.prstDash != null) { this.prstDash = ln.prstDash; } if (ln.Join != null) { this.Join = ln.Join.createDuplicate(); } if (ln.headEnd != null) { this.headEnd = ln.headEnd.createDuplicate(); } if (ln.tailEnd != null) { this.tailEnd = ln.tailEnd.createDuplicate(); } if (ln.algn != null) { this.algn = ln.algn; } if (ln.cap != null) { this.cap = ln.cap; } if (ln.cmpd != null) { this.cmpd = ln.cmpd; } if (ln.w != null) { this.w = ln.w; } }; CLn.prototype.calculate = function (theme, slide, layout, master, RGBA, colorMap) { if (isRealObject(this.Fill)) { this.Fill.calculate(theme, slide, layout, master, RGBA, colorMap); } }; CLn.prototype.createDuplicate = function (bSaveFormatting) { var duplicate = new CLn(); if (null != this.Fill) { if (bSaveFormatting === true) { duplicate.Fill = this.Fill.saveSourceFormatting(); } else { duplicate.Fill = this.Fill.createDuplicate(); } } duplicate.prstDash = this.prstDash; duplicate.Join = this.Join; if (this.headEnd != null) { duplicate.headEnd = this.headEnd.createDuplicate(); } if (this.tailEnd != null) { duplicate.tailEnd = this.tailEnd.createDuplicate(); } duplicate.algn = this.algn; duplicate.cap = this.cap; duplicate.cmpd = this.cmpd; duplicate.w = this.w; return duplicate; }; CLn.prototype.IsIdentical = function (ln) { return ln && (this.Fill == null ? ln.Fill == null : this.Fill.IsIdentical(ln.Fill)) && (this.Join == null ? ln.Join == null : this.Join.IsIdentical(ln.Join)) && (this.headEnd == null ? ln.headEnd == null : this.headEnd.IsIdentical(ln.headEnd)) && (this.tailEnd == null ? ln.tailEnd == null : this.tailEnd.IsIdentical(ln.headEnd)) && this.algn == ln.algn && this.cap == ln.cap && this.cmpd == ln.cmpd && this.w == ln.w && this.prstDash === ln.prstDash; }; CLn.prototype.setFill = function (fill) { this.Fill = fill; }; CLn.prototype.setPrstDash = function (prstDash) { this.prstDash = prstDash; }; CLn.prototype.setJoin = function (join) { this.Join = join; }; CLn.prototype.setHeadEnd = function (headEnd) { this.headEnd = headEnd; }; CLn.prototype.setTailEnd = function (tailEnd) { this.tailEnd = tailEnd; }; CLn.prototype.setAlgn = function (algn) { this.algn = algn; }; CLn.prototype.setCap = function (cap) { this.cap = cap; }; CLn.prototype.setCmpd = function (cmpd) { this.cmpd = cmpd; }; CLn.prototype.setW = function (w) { this.w = w; }; CLn.prototype.isVisible = function () { return this.Fill && this.Fill.isVisible(); }; CLn.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.Fill)); if (isRealObject(this.Fill)) { this.Fill.Write_ToBinary(w); } writeLong(w, this.prstDash); w.WriteBool(isRealObject(this.Join)); if (isRealObject(this.Join)) { this.Join.Write_ToBinary(w); } w.WriteBool(isRealObject(this.headEnd)); if (isRealObject(this.headEnd)) { this.headEnd.Write_ToBinary(w); } w.WriteBool(isRealObject(this.tailEnd)); if (isRealObject(this.tailEnd)) { this.tailEnd.Write_ToBinary(w); } writeLong(w, this.algn); writeLong(w, this.cap); writeLong(w, this.cmpd); writeLong(w, this.w); }; CLn.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.Fill = new CUniFill(); this.Fill.Read_FromBinary(r); } else { this.Fill = null; } this.prstDash = readLong(r); if (r.GetBool()) { this.Join = new LineJoin(); this.Join.Read_FromBinary(r); } if (r.GetBool()) { this.headEnd = new EndArrow(); this.headEnd.Read_FromBinary(r); } if (r.GetBool()) { this.tailEnd = new EndArrow(); this.tailEnd.Read_FromBinary(r); } this.algn = readLong(r); this.cap = readLong(r); this.cmpd = readLong(r); this.w = readLong(r); }; CLn.prototype.isNoFillLine = function () { if (this.Fill) { return this.Fill.isNoFill(); } return false; }; CLn.prototype.GetCapCode = function (sVal) { switch (sVal) { case "flat": { return 0; } case "rnd": { return 1; } case "sq": { return 2; } } return 0; }; CLn.prototype.GetCapByCode = function (nCode) { switch (nCode) { case 0: { return "flat"; } case 1: { return "rnd"; } case 2: { return "sq"; } } return null; }; CLn.prototype.GetAlgnCode = function (sVal) { switch (sVal) { case "ctr": { return 0; } case "in": { return 1; } } return 0; }; CLn.prototype.GetAlgnByCode = function (sVal) { switch (sVal) { case 0: { return "ctr"; } case 1: { return "in"; } } return null; }; CLn.prototype.GetCmpdCode = function (sVal) { switch (sVal) { case "dbl": { return 0; } case "sng": { return 1; } case "thickThin": { return 2; } case "thinThick": { return 3; } case "tri": { return 4; } } return 1; }; CLn.prototype.GetCmpdByCode = function (sVal) { switch (sVal) { case 0: { return "dbl"; } case 1: { return "sng"; } case 2: { return "thickThin"; } case 3: { return "thinThick"; } case 4: { return "tri"; } } return null; }; CLn.prototype.GetDashCode = function (sVal) { switch (sVal) { case "dash": { return 0; } case "dashDot": { return 1; } case "dot": { return 2; } case "lgDash": { return 3; } case "lgDashDot": { return 4; } case "lgDashDotDot": { return 5; } case "solid": { return 6; } case "sysDash": { return 7; } case "sysDashDot": { return 8; } case "sysDashDotDot": { return 9; } case "sysDot": { return 10; } } return 6; }; CLn.prototype.GetDashByCode = function (sVal) { switch (sVal) { case 0: { return "dash"; } case 1 : { return "dashDot"; } case 2 : { return "dot"; } case 3 : { return "lgDash"; } case 4 : { return "lgDashDot"; } case 5 : { return "lgDashDotDot"; } case 6 : { return "solid"; } case 7 : { return "sysDash"; } case 8: { return "sysDashDot"; } case 9 : { return "sysDashDotDot"; } case 10 : { return "sysDot"; } } return null; }; CLn.prototype.readAttrXml = function (name, reader) { switch (name) { case "algn": { let sVal = reader.GetValue(); this.algn = this.GetAlgnCode(sVal); break; } case "cap": { let sVal = reader.GetValue(); this.cap = this.GetCapCode(sVal); break; } case "cmpd": { let sVal = reader.GetValue(); this.cmpd = this.GetCmpdCode(sVal); break; } case "w": { this.w = reader.GetValueInt(); break; } } }; CLn.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.Fill = new CUniFill(); this.Fill.fromXml(reader, name); } else if (name === "headEnd") { this.headEnd = new EndArrow(); this.headEnd.fromXml(reader); } else if (name === "tailEnd") { this.tailEnd = new EndArrow(); this.tailEnd.fromXml(reader); } else if (name === "prstDash") { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); let sVal = oNode.attributes["val"]; this.prstDash = this.GetDashCode(sVal); } else if (name === "bevel") { this.Join = new LineJoin(LineJoinType.Bevel); this.Join.fromXml(reader); } else if (name === "miter") { this.Join = new LineJoin(LineJoinType.Miter); this.Join.fromXml(reader); } else if (name === "round") { this.Join = new LineJoin(LineJoinType.Round); this.Join.fromXml(reader); } }; CLn.prototype.toXml = function (writer, sName) { let _name = sName; if (!_name || _name.length === 0) _name = ("a:ln"); let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { _name = ("w14:textOutline"); sAttrNamespace = ("w14:"); } writer.WriteXmlNodeStart(_name); writer.WriteXmlNullableAttributeUInt(sAttrNamespace + "w", this.w); writer.WriteXmlNullableAttributeString(sAttrNamespace + "cap", this.GetCapByCode(this.cap)); writer.WriteXmlNullableAttributeString(sAttrNamespace + "cmpd", this.GetCmpdByCode(this.cmpd)); writer.WriteXmlNullableAttributeString(sAttrNamespace + "algn", this.GetAlgnByCode(this.algn)); writer.WriteXmlAttributesEnd(); if(this.Fill) { this.Fill.toXml(writer); } let nDashCode = this.GetDashByCode(this.prstDash); if(nDashCode !== null) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { writer.WriteXmlNodeStart("w14:prstDash"); writer.WriteXmlNullableAttributeString("w14:val", this.GetDashByCode(this.prstDash)); writer.WriteXmlAttributesEnd(true); } else { writer.WriteXmlNodeStart("a:prstDash"); writer.WriteXmlNullableAttributeString("val", this.GetDashByCode(this.prstDash)); writer.WriteXmlAttributesEnd(true); } } if (this.Join) { this.Join.toXml(writer); } if (this.headEnd) { this.headEnd.toXml(writer, "a:headEnd"); } if (this.tailEnd) { this.tailEnd.toXml(writer, "a:tailEnd"); } writer.WriteXmlNodeEnd(_name); }; CLn.prototype.fillDocumentBorder = function(oBorder) { if(this.Fill) { oBorder.Unifill = this.Fill; } oBorder.Size = (this.w === null) ? 12700 : ((this.w) >> 0); oBorder.Size /= 36000; oBorder.Value = AscCommonWord.border_Single; }; CLn.prototype.fromDocumentBorder = function(oBorder) { this.Fill = oBorder.Unifill; this.w = null; if(AscFormat.isRealNumber(oBorder.Size)) { this.w = oBorder.Size * 36000 >> 0; } this.cmpd = 1; }; // ----------------------------- // SHAPE ---------------------------- function DefaultShapeDefinition() { CBaseFormatObject.call(this); this.spPr = new CSpPr(); this.bodyPr = new CBodyPr(); this.lstStyle = new TextListStyle(); this.style = null; } InitClass(DefaultShapeDefinition, CBaseFormatObject, AscDFH.historyitem_type_DefaultShapeDefinition); DefaultShapeDefinition.prototype.setSpPr = function (spPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_DefaultShapeDefinition_SetSpPr, this.spPr, spPr)); this.spPr = spPr; }; DefaultShapeDefinition.prototype.setBodyPr = function (bodyPr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr, this.bodyPr, bodyPr)); this.bodyPr = bodyPr; }; DefaultShapeDefinition.prototype.setLstStyle = function (lstStyle) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle, this.lstStyle, lstStyle)); this.lstStyle = lstStyle; }; DefaultShapeDefinition.prototype.setStyle = function (style) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_DefaultShapeDefinition_SetStyle, this.style, style)); this.style = style; }; DefaultShapeDefinition.prototype.createDuplicate = function () { var ret = new DefaultShapeDefinition(); if (this.spPr) { ret.setSpPr(this.spPr.createDuplicate()); } if (this.bodyPr) { ret.setBodyPr(this.bodyPr.createDuplicate()); } if (this.lstStyle) { ret.setLstStyle(this.lstStyle.createDuplicate()); } if (this.style) { ret.setStyle(this.style.createDuplicate()); } return ret; }; DefaultShapeDefinition.prototype.readChildXml = function (name, reader) { switch (name) { case "bodyPr": { let oBodyPr = new AscFormat.CBodyPr(); oBodyPr.fromXml(reader); this.setBodyPr(oBodyPr); break; } case "lstStyle": { let oPr = new AscFormat.TextListStyle(); oPr.fromXml(reader); this.setLstStyle(oPr); break; } case "spPr": { let oPr = new AscFormat.CSpPr(); oPr.fromXml(reader); this.setSpPr(oPr); break; } case "style": { let oPr = new AscFormat.CShapeStyle(); oPr.fromXml(reader); this.setStyle(oPr); break; } case "extLst": { break; } } }; DefaultShapeDefinition.prototype.toXml = function (writer, sName) { let oContext = writer.context; let nOldDocType = oContext.docType; oContext.docType = AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS; writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); if (this.spPr) { writer.context.flag = 0x04; this.spPr.toXml(writer); writer.context.flag = 0; } if (this.bodyPr) this.bodyPr.toXml(writer); if (this.lstStyle) { this.lstStyle.toXml(writer, "a:lstStyle"); } if (this.style) { this.style.toXml(writer); } writer.WriteXmlNodeEnd(sName); oContext.docType = nOldDocType; }; function CNvPr() { CBaseFormatObject.call(this); this.id = 0; this.name = ""; this.isHidden = null; this.descr = null; this.title = null; this.hlinkClick = null; this.hlinkHover = null; this.form = null; this.setId(AscCommon.CreateDurableId()); } InitClass(CNvPr, CBaseFormatObject, AscDFH.historyitem_type_CNvPr); CNvPr.prototype.createDuplicate = function () { var duplicate = new CNvPr(); duplicate.setName(this.name); duplicate.setIsHidden(this.isHidden); duplicate.setDescr(this.descr); duplicate.setTitle(this.title); if (this.hlinkClick) { duplicate.setHlinkClick(this.hlinkClick.createDuplicate()); } if (this.hlinkHover) { duplicate.setHlinkHover(this.hlinkHover.createDuplicate()); } return duplicate; }; CNvPr.prototype.setId = function (id) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_CNvPr_SetId, this.id, id)); this.id = id; }; CNvPr.prototype.setName = function (name) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_CNvPr_SetName, this.name, name)); this.name = name; }; CNvPr.prototype.setIsHidden = function (isHidden) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_CNvPr_SetIsHidden, this.isHidden, isHidden)); this.isHidden = isHidden; }; CNvPr.prototype.setDescr = function (descr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_CNvPr_SetDescr, this.descr, descr)); this.descr = descr; }; CNvPr.prototype.setHlinkClick = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_CNvPr_SetHlinkClick, this.hlinkClick, pr)); this.hlinkClick = pr; }; CNvPr.prototype.setHlinkHover = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_CNvPr_SetHlinkHover, this.hlinkHover, pr)); this.hlinkHover = pr; }; CNvPr.prototype.setTitle = function (title) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_CNvPr_SetTitle, this.title, title)); this.title = title; }; CNvPr.prototype.setFromOther = function (oOther) { if (!oOther) { return; } if (oOther.name) { this.setName(oOther.name); } if (oOther.descr) { this.setDescr(oOther.descr); } if (oOther.title) { this.setTitle(oOther.title); } }; CNvPr.prototype.hasSameNameAndId = function (oPr) { if (!oPr) { return false; } return this.id === oPr.id && this.name === oPr.name; }; CNvPr.prototype.toXml = function (writer, name) { writer.WriteXmlNodeStart(name); writer.WriteXmlNullableAttributeUInt("id", this.id); writer.WriteXmlNullableAttributeStringEncode("name", this.name); writer.WriteXmlNullableAttributeStringEncode("descr", this.descr); writer.WriteXmlNullableAttributeBool("hidden", this.isHidden); writer.WriteXmlNullableAttributeBool("form", this.form); writer.WriteXmlNullableAttributeStringEncode("title", this.title); //writer.WriteXmlNullableAttributeBool("title", this.form); if(this.hlinkClick || this.hlinkHover) { let sNS = AscCommon.StaxParser.prototype.GetNSFromNodeName(name); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.hlinkClick, sNS + ":hlinkClick"); writer.WriteXmlNullable(this.hlinkHover, sNS + ":hlinkHover"); //writer.WriteXmlNullable(this.ExtLst, "w:extLst"); writer.WriteXmlNodeEnd(name); } else { writer.WriteXmlAttributesEnd(true); } }; CNvPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "id": { this.setId(reader.GetValueUInt()); break; } case "name": { this.setName(reader.GetValueDecodeXml()); break; } case "descr": { this.setDescr(reader.GetValueDecodeXml()); break; } case "hidden": { this.setIsHidden(reader.GetValueBool()); break; } case "title": { this.setTitle(reader.GetValueDecodeXml()); break; } case "form": { this.form = reader.GetValueBool(); break; } } }; CNvPr.prototype.readChildXml = function (name, reader) { switch (name) { case "hlinkClick": { let oPr = new CT_Hyperlink(); oPr.fromXml(reader); this.setHlinkClick(oPr); break; } case "hlinkHover": { let oPr = new CT_Hyperlink(); oPr.fromXml(reader); this.setHlinkHover(oPr); break; } } }; CNvPr.prototype.toXml = function (writer, sName) { if (sName) { this.toXml3(sName, writer); return; } let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; this.toXml2(namespace_, writer); }; CNvPr.prototype.toXml2 = function (namespace_, writer) { this.toXml3(namespace_ + (":cNvPr"), writer); }; CNvPr.prototype.toXml3 = function (sName, writer) { writer.WriteXmlNodeStart(sName); let _id = this.id; if (_id < 0) { _id = writer.context.objectId; ++writer.context.objectId; } else { if (writer.context.objectId <= _id) { writer.context.objectId = _id + 1; } } writer.WriteXmlNullableAttributeString("id", _id); writer.WriteXmlNullableAttributeStringEncode("name", this.name); if (this.descr) { let d = this.descr; d = d.replace(new RegExp("\n", 'g'), "&#xA;"); writer.WriteXmlNullableAttributeString("descr", d); } writer.WriteXmlNullableAttributeBool("hidden", this.isHidden); writer.WriteXmlNullableAttributeBool("form", this.form); if (this.title) writer.WriteXmlNullableAttributeStringEncode("title", this.title); if(this.hlinkClick || this.hlinkHover) { writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.hlinkClick, "a:hlinkClick"); writer.WriteXmlNullable(this.hlinkHover, "a:hlinkHover"); writer.WriteXmlNodeEnd(sName); } else { writer.WriteXmlAttributesEnd(true); } }; var AUDIO_CD = 0; var WAV_AUDIO_FILE = 1; var AUDIO_FILE = 2; var VIDEO_FILE = 3; var QUICK_TIME_FILE = 4; function UniMedia() { CBaseNoIdObject.call(this); this.type = null; this.media = null; } InitClass(UniMedia, CBaseNoIdObject, 0); UniMedia.prototype.Write_ToBinary = function (w) { var bType = this.type !== null && this.type !== undefined; var bMedia = typeof this.media === 'string'; var nFlags = 0; bType && (nFlags |= 1); bMedia && (nFlags |= 2); w.WriteLong(nFlags); bType && w.WriteLong(this.type); bMedia && w.WriteString2(this.media); }; UniMedia.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.type = r.GetLong(); } if (nFlags & 2) { this.media = r.GetString2(); } }; UniMedia.prototype.createDuplicate = function () { var _ret = new UniMedia(); _ret.type = this.type; _ret.media = this.media; return _ret; }; UniMedia.prototype.fromXml = function (reader, name) { //TODO:Implement in children // if (name === ("audioCd")) // // this.type = null; // else if (name === ("wavAudioFile")) // Media.reset(new Logic::WavAudioFile(oReader)); // else if (name === ("audioFile")) // Media.reset(new Logic::MediaFile(oReader)); // else if (name === ("videoFile")) // Media.reset(new Logic::MediaFile(oReader)); // else if (name === ("quickTimeFile")) // Media.reset(new Logic::MediaFile(oReader)); // else Media.reset(); }; UniMedia.prototype.toXml = function (writer) { //TODO:Implement in children }; drawingConstructorsMap[AscDFH.historyitem_NvPr_SetUniMedia] = UniMedia; function NvPr() { CBaseFormatObject.call(this); this.isPhoto = null; this.userDrawn = null; this.ph = null; this.unimedia = null; } InitClass(NvPr, CBaseFormatObject, AscDFH.historyitem_type_NvPr); NvPr.prototype.setIsPhoto = function (isPhoto) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_NvPr_SetIsPhoto, this.isPhoto, isPhoto)); this.isPhoto = isPhoto; }; NvPr.prototype.setUserDrawn = function (userDrawn) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_NvPr_SetUserDrawn, this.userDrawn, userDrawn)); this.userDrawn = userDrawn; }; NvPr.prototype.setPh = function (ph) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_NvPr_SetPh, this.ph, ph)); this.ph = ph; }; NvPr.prototype.setUniMedia = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_NvPr_SetUniMedia, this.unimedia, pr)); this.unimedia = pr; }; NvPr.prototype.createDuplicate = function () { var duplicate = new NvPr(); duplicate.setIsPhoto(this.isPhoto); duplicate.setUserDrawn(this.userDrawn); if (this.ph != null) { duplicate.setPh(this.ph.createDuplicate()); } if (this.unimedia != null) { duplicate.setUniMedia(this.unimedia.createDuplicate()); } return duplicate; }; NvPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "isPhoto": { this.isPhoto = reader.GetValueBool(); break; } case "userDrawn": { this.userDrawn = reader.GetValueBool(); break; } } }; NvPr.prototype.readChildXml = function (name, reader) { switch (name) { case "ph": { let oPr = new Ph(); oPr.fromXml(reader); this.setPh(oPr); break; } } }; NvPr.prototype.toXml = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; this.toXml2(namespace_, writer); }; NvPr.prototype.toXml2 = function (strNS, writer) { writer.WriteXmlNodeStart(strNS + ":nvPr"); writer.WriteXmlNullableAttributeBool("isPhoto", this.isPhoto); writer.WriteXmlNullableAttributeBool("userDrawn", this.userDrawn); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.ph); //media.toXml(writer); // let namespace_extLst = "a"; // if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_extLst = "p"; // // writer.WriteArray(namespace_extLst + ":extLst", extLst); writer.WriteXmlNodeEnd(strNS + ":nvPr"); }; var szPh_full = 0, szPh_half = 1, szPh_quarter = 2; var orientPh_horz = 0, orientPh_vert = 1; function Ph() { CBaseFormatObject.call(this); this.hasCustomPrompt = null; this.idx = null; this.orient = null; this.sz = null; this.type = null; } InitClass(Ph, CBaseFormatObject, AscDFH.historyitem_type_Ph); Ph.prototype.createDuplicate = function () { var duplicate = new Ph(); duplicate.setHasCustomPrompt(this.hasCustomPrompt); duplicate.setIdx(this.idx); duplicate.setOrient(this.orient); duplicate.setSz(this.sz); duplicate.setType(this.type); return duplicate; }; Ph.prototype.setHasCustomPrompt = function (hasCustomPrompt) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Ph_SetHasCustomPrompt, this.hasCustomPrompt, hasCustomPrompt)); this.hasCustomPrompt = hasCustomPrompt; }; Ph.prototype.setIdx = function (idx) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_Ph_SetIdx, this.idx, idx)); this.idx = idx; }; Ph.prototype.setOrient = function (orient) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_Ph_SetOrient, this.orient, orient)); this.orient = orient; }; Ph.prototype.setSz = function (sz) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_Ph_SetSz, this.sz, sz)); this.sz = sz; }; Ph.prototype.setType = function (type) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_Ph_SetType, this.type, type)); this.type = type; }; Ph.prototype.GetOrientCode = function(sVal) { switch (sVal) { case "horz": { return orientPh_horz; } case "vert": { return orientPh_vert; } } return null; }; Ph.prototype.GetOrientByCode = function(nVal) { switch (nVal) { case orientPh_horz: { return "horz"; } case orientPh_vert: { return "vert"; } } return null; }; Ph.prototype.GetSzCode = function(sVal) { switch (sVal) { case "full": { return szPh_full; } case "half": { return szPh_half; } case "quarter": { return szPh_quarter; } } return null; }; Ph.prototype.GetSzByCode = function(nVal) { switch (nVal) { case szPh_full: { return "full"; } case szPh_half: { return "half"; } case szPh_quarter: { return "quarter"; } } return null; }; Ph.prototype.GetTypeCode = function(sVal) { switch (sVal) { case "body": { return AscFormat.phType_body; } case "chart": { return AscFormat.phType_chart; } case "clipArt": { return AscFormat.phType_clipArt; } case "ctrTitle": { return AscFormat.phType_ctrTitle; } case "dgm": { return AscFormat.phType_dgm; } case "dt": { return AscFormat.phType_dt; } case "ftr": { return AscFormat.phType_ftr; } case "hdr": { return AscFormat.phType_hdr; } case "media": { return AscFormat.phType_media; } case "obj": { return AscFormat.phType_obj; } case "pic": { return AscFormat.phType_pic; } case "sldImg": { return AscFormat.phType_sldImg; } case "sldNum": { return AscFormat.phType_sldNum; } case "subTitle": { return AscFormat.phType_subTitle; } case "tbl": { return AscFormat.phType_tbl; } case "title": { return AscFormat.phType_title; } } return null; }; Ph.prototype.GetTypeByCode = function(nVal) { switch (nVal) { case AscFormat.phType_body: { return "body"; } case AscFormat.phType_chart: { return "chart"; } case AscFormat.phType_clipArt: { return "clipArt"; } case AscFormat.phType_ctrTitle: { return "ctrTitle"; } case AscFormat.phType_dgm: { return "dgm"; } case AscFormat.phType_dt: { return "dt"; } case AscFormat.phType_ftr: { return "ftr"; } case AscFormat.phType_hdr: { return "hdr"; } case AscFormat.phType_media: { return "media"; } case AscFormat.phType_obj: { return "obj"; } case AscFormat.phType_pic: { return "pic"; } case AscFormat.phType_sldImg: { return "sldImg"; } case AscFormat.phType_sldNum: { return "sldNum"; } case AscFormat.phType_subTitle: { return "subTitle"; } case AscFormat.phType_tbl: { return "tbl"; } case AscFormat.phType_title: { return "title"; } } return null; }; Ph.prototype.readAttrXml = function (name, reader) { switch (name) { case "hasCustomPrompt": { this.setHasCustomPrompt(reader.GetValueBool()); break; } case "idx": { this.setIdx(reader.GetValue()); break; } case "orient": { let sVal = reader.GetValue(); let nVal = this.GetOrientCode(sVal); if(nVal !== null) { this.setOrient(nVal); } break; } case "sz": { let sVal = reader.GetValue(); let nVal = this.GetSzCode(sVal); if(nVal !== null) { this.setSz(nVal); } break; } case "type": { let sVal = reader.GetValue(); let nVal = this.GetTypeCode(sVal); if(nVal !== null) { this.setType(nVal); } break; } } }; Ph.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:ph"); writer.WriteXmlNullableAttributeString("type", this.GetTypeByCode(this.type)); writer.WriteXmlNullableAttributeString("orient", this.GetOrientByCode(this.orient)); writer.WriteXmlNullableAttributeString("sz", this.GetSzByCode(this.sz)); writer.WriteXmlNullableAttributeString("idx", this.idx); writer.WriteXmlNullableAttributeBool("hasCustomPrompt", this.hasCustomPrompt); writer.WriteXmlAttributesEnd(true); }; function fUpdateLocksValue(nLocks, nMask, bValue) { nLocks |= nMask; if (bValue) { nLocks |= (nMask << 1) } else { nLocks &= ~(nMask << 1) } return nLocks; } function fGetLockValue(nLocks, nMask) { if (nLocks & nMask) { return !!(nLocks & (nMask << 1)); } return undefined; } window['AscFormat'] = window['AscFormat'] || {}; window['AscFormat'].fUpdateLocksValue = fUpdateLocksValue; window['AscFormat'].fGetLockValue = fGetLockValue; function CNvUniSpPr() { CBaseNoIdObject.call(this); this.locks = null; this.stCnxIdx = null; this.stCnxId = null; this.endCnxIdx = null; this.endCnxId = null; } InitClass(CNvUniSpPr, CBaseNoIdObject, 0); CNvUniSpPr.prototype.Write_ToBinary = function (w) { if (AscFormat.isRealNumber(this.locks)) { w.WriteBool(true); w.WriteLong(this.locks); } else { w.WriteBool(false); } if (AscFormat.isRealNumber(this.stCnxIdx) && typeof (this.stCnxId) === "string" && this.stCnxId.length > 0) { w.WriteBool(true); w.WriteLong(this.stCnxIdx); w.WriteString2(this.stCnxId); } else { w.WriteBool(false); } if (AscFormat.isRealNumber(this.endCnxIdx) && typeof (this.endCnxId) === "string" && this.endCnxId.length > 0) { w.WriteBool(true); w.WriteLong(this.endCnxIdx); w.WriteString2(this.endCnxId); } else { w.WriteBool(false); } }; CNvUniSpPr.prototype.Read_FromBinary = function (r) { var bCnx = r.GetBool(); if (bCnx) { this.locks = r.GetLong(); } else { this.locks = null; } bCnx = r.GetBool(); if (bCnx) { this.stCnxIdx = r.GetLong(); this.stCnxId = r.GetString2(); } else { this.stCnxIdx = null; this.stCnxId = null; } bCnx = r.GetBool(); if (bCnx) { this.endCnxIdx = r.GetLong(); this.endCnxId = r.GetString2(); } else { this.endCnxIdx = null; this.endCnxId = null; } }; CNvUniSpPr.prototype.assignConnectors = function(aSpTree) { let bNeedSetStart = AscFormat.isRealNumber(this.stCnxIdFormat); let bNeedSetEnd = AscFormat.isRealNumber(this.endCnxIdFormat); if(bNeedSetStart || bNeedSetEnd) { for(let nSp = 0; nSp < aSpTree.length && (bNeedSetEnd || bNeedSetStart); ++nSp) { let oSp = aSpTree[nSp]; if(bNeedSetStart && oSp.getFormatId() === this.stCnxIdFormat) { this.stCnxId = oSp.Get_Id(); this.stCnxIdFormat = undefined; bNeedSetStart = false; } if(bNeedSetEnd && oSp.getFormatId() === this.endCnxIdFormat) { this.endCnxId = oSp.Get_Id(); this.endCnxIdFormat = undefined; bNeedSetEnd = false; } } } }; CNvUniSpPr.prototype.copy = function () { var _ret = new CNvUniSpPr(); _ret.locks = this.locks; _ret.stCnxId = this.stCnxId; _ret.stCnxIdx = this.stCnxIdx; _ret.endCnxId = this.endCnxId; _ret.endCnxIdx = this.endCnxIdx; return _ret; }; CNvUniSpPr.prototype.readChildXml = function (name, reader) { if (name.toLowerCase().indexOf("locks") > -1) { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); this.locks = 0; let oAttr = oNode.attributes; for (let sAttr in oAttr) { if (oAttr.hasOwnProperty(sAttr)) { let sVal = oAttr[sAttr]; if (sVal) { let bBoolVal = reader.GetBool(sVal); switch (sAttr) { case "txBox": { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.txBox, bBoolVal); break; } case "noAdjustHandles" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles, bBoolVal); break; } case "noChangeArrowheads" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads, bBoolVal); break; } case "noChangeAspect" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect, bBoolVal); break; } case "noChangeShapeType" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType, bBoolVal); break; } case "noEditPoints" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints, bBoolVal); break; } case "noGrp" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noGrp, bBoolVal); break; } case "noMove" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noMove, bBoolVal); break; } case "noResize" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noResize, bBoolVal); break; } case "noRot" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noRot, bBoolVal); break; } case "noSelect": { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noSelect, bBoolVal); break; } case "noTextEdit": { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit, bBoolVal); break; } } } } } } else if (name === "stCxn" || name === "endCxn") { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); if(name === "stCxn") { this.stCnxIdx = parseInt(oNode.attributes["idx"]); this.stCnxIdFormat = parseInt(oNode.attributes["id"]); } if(name === "endCxn") { this.endCnxIdx = parseInt(oNode.attributes["idx"]); this.endCnxIdFormat = parseInt(oNode.attributes["id"]); } reader.context.addConnectorsPr(this); //TODO: connections } }; CNvUniSpPr.prototype.toXmlCxn = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvCxnSpPr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:cxnSpLocks"); writer.WriteXmlNullableAttributeBool("txBox", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.txBox)); writer.WriteXmlNullableAttributeBool("noAdjustHandles", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles)); writer.WriteXmlNullableAttributeBool("noChangeArrowheads", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads)); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noChangeShapeType", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType)); writer.WriteXmlNullableAttributeBool("noEditPoints", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noTextEdit", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit)); writer.WriteXmlAttributesEnd(true); if (AscFormat.isRealNumber(this.stCnxIdx) && this.stCnxId) { let nId = null; let oSp = AscCommon.g_oTableId.Get_ById(this.stCnxId); if(oSp) { nId = oSp.getFormatId && oSp.getFormatId(); } if(AscFormat.isRealNumber(nId)) { writer.WriteXmlNodeStart("a:stCxn"); writer.WriteXmlAttributeUInt("id", nId); writer.WriteXmlAttributeUInt("idx", this.stCnxIdx); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:stCxn"); } } if (AscFormat.isRealNumber(this.endCnxIdx) && this.endCnxId) { let nId = null; let oSp = AscCommon.g_oTableId.Get_ById(this.endCnxId); if(oSp) { nId = oSp.getFormatId && oSp.getFormatId(); } if(AscFormat.isRealNumber(nId)) { writer.WriteXmlNodeStart("a:endCxn"); writer.WriteXmlAttributeUInt("id", nId); writer.WriteXmlAttributeUInt("idx", this.endCnxIdx); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:endCxn"); } } writer.WriteXmlNodeEnd(namespace_ + ":cNvCxnSpPr"); }; CNvUniSpPr.prototype.toXmlGrFrame = function (writer) { let namespace_ = "a"; let namespaceLock_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { namespaceLock_ = "a"; namespace_ = "wp"; } else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvGraphicFramePr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart(namespaceLock_ + ":graphicFrameLocks"); writer.WriteXmlAttributeString("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noDrilldown", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noDrilldown)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlAttributesEnd(true); writer.WriteXmlNodeEnd(namespace_ + ":cNvGraphicFramePr"); }; CNvUniSpPr.prototype.toXmlGrSp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; if (!fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp) === undefined) { writer.WriteXmlString("<" + namespace_ + ":cNvGrpSpPr/>"); return; } writer.WriteXmlString("<" + namespace_ + ":cNvGrpSpPr>"); writer.WriteXmlNodeStart("a:grpSpLocks"); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noUngrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp)); writer.WriteXmlAttributesEnd(true); writer.WriteXmlString("</" + namespace_ + ":cNvGrpSpPr>"); }; CNvUniSpPr.prototype.toXmlGrSp2 = function (writer, strNS) { if (fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp) === undefined) { writer.WriteXmlString("<" + strNS + ":cNvGrpSpPr/>"); return; } writer.WriteXmlNodeStart(strNS + ":cNvGrpSpPr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:grpSpLocks"); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noUngrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp)); writer.WriteXmlAttributesEnd(true); writer.WriteXmlNodeEnd(strNS + ":cNvGrpSpPr"); }; CNvUniSpPr.prototype.toXmlPic = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvPicPr"); //writer.WriteXmlNullableAttributeString("preferRelativeResize", preferRelativeResize); writer.WriteXmlAttributesEnd(); if (fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noCrop) !== undefined) { writer.WriteXmlNodeStart("a:picLocks"); writer.WriteXmlNullableAttributeBool("noAdjustHandles", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles)); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noChangeArrowheads", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads)); writer.WriteXmlNullableAttributeBool("noChangeShapeType", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType)); writer.WriteXmlNullableAttributeBool("noEditPoints", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noCrop", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noCrop)); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(namespace_ + ":cNvPicPr"); }; CNvUniSpPr.prototype.toXmlSp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvSpPr"); //writer.WriteXmlAttributeBool("txBox", this.txBox); writer.WriteXmlAttributesEnd(); if (fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit) !== undefined) { writer.WriteXmlNodeStart("a:spLocks"); writer.WriteXmlNullableAttributeBool("noAdjustHandles", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles)); writer.WriteXmlNullableAttributeBool("noChangeArrowheads", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads)); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noChangeShapeType", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType)); writer.WriteXmlNullableAttributeBool("noEditPoints", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noTextEdit", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit)); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(namespace_ + ":cNvSpPr"); }; CNvUniSpPr.prototype.getLocks = function() { if(!AscFormat.isRealNumber(this.locks)) { return 0; } return this.locks; }; function UniNvPr() { CBaseFormatObject.call(this); this.cNvPr = null; this.UniPr = null; this.nvPr = null; this.nvUniSpPr = null; this.setCNvPr(new CNvPr()); this.setNvPr(new NvPr()); this.setUniSpPr(new CNvUniSpPr()); } InitClass(UniNvPr, CBaseFormatObject, AscDFH.historyitem_type_UniNvPr); UniNvPr.prototype.setCNvPr = function (cNvPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_UniNvPr_SetCNvPr, this.cNvPr, cNvPr)); this.cNvPr = cNvPr; }; UniNvPr.prototype.setUniSpPr = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_UniNvPr_SetUniSpPr, this.nvUniSpPr, pr)); this.nvUniSpPr = pr; }; UniNvPr.prototype.setUniPr = function (uniPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_UniNvPr_SetUniPr, this.UniPr, uniPr)); this.UniPr = uniPr; }; UniNvPr.prototype.setNvPr = function (nvPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_UniNvPr_SetNvPr, this.nvPr, nvPr)); this.nvPr = nvPr; }; UniNvPr.prototype.createDuplicate = function () { var duplicate = new UniNvPr(); this.cNvPr && duplicate.setCNvPr(this.cNvPr.createDuplicate()); this.nvPr && duplicate.setNvPr(this.nvPr.createDuplicate()); this.nvUniSpPr && duplicate.setUniSpPr(this.nvUniSpPr.copy()); return duplicate; }; UniNvPr.prototype.Write_ToBinary2 = function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); writeObject(w, this.cNvPr); writeObject(w, this.nvPr); }; UniNvPr.prototype.Read_FromBinary2 = function (r) { this.Id = r.GetString2(); this.cNvPr = readObject(r); this.nvPr = readObject(r); }; UniNvPr.prototype.readChildXml = function (name, reader) { switch (name) { case "cNvPr": { this.cNvPr.fromXml(reader); break; } case "cNvCxnSpPr": case "cNvGraphicFramePr": case "cNvGrpSpPr": case "cNvPicPr": case "cNvSpPr": { this.nvUniSpPr.fromXml(reader); break; } case "nvPr": { this.nvPr.fromXml(reader); break; } } }; UniNvPr.prototype.getLocks = function() { if(this.nvUniSpPr) { return this.nvUniSpPr.getLocks(); } return 0; }; UniNvPr.prototype.toXmlGrFrame = function (writer) { let namespace_ = "a"; if ((writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) && writer.context.groupIndex >= 0) { this.cNvPr.toXml2("wpg", writer); writer.WriteXmlString("<wpg:cNvFrPr/>"); return; } else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX && writer.context.groupIndex >= 0) { writer.WriteXmlNodeStart("xdr:nvGraphicFramePr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, "xdr:cNvPr"); this.nvUniSpPr.toXmlGrFrame(writer); writer.WriteXmlNodeEnd("xdr:nvGraphicFramePr"); return; } if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvGraphicFramePr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); this.nvUniSpPr.toXmlGrFrame(writer); this.nvPr.toXml(writer); writer.WriteXmlNodeEnd(namespace_ + ":nvGraphicFramePr"); }; UniNvPr.prototype.toXmlCxn = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvCxnSpPr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml2(namespace_, writer); this.nvUniSpPr.toXmlCxn(writer); if (writer.context.docType !== AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS && writer.context.docType !== AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) { this.nvPr.toXml2(namespace_, writer); } writer.WriteXmlNodeEnd(namespace_ + ":nvCxnSpPr"); }; UniNvPr.prototype.toXmlSp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvSpPr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); this.nvUniSpPr.toXmlSp(writer); if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) this.nvPr.toXml(writer); writer.WriteXmlNodeEnd(namespace_ + ":nvSpPr"); }; UniNvPr.prototype.toXmlPic = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvPicPr"); writer.WriteXmlAttributesEnd(); if (this.cNvPr) { this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); } if (this.nvUniSpPr) { this.nvUniSpPr.toXmlPic(writer); } if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) { if (this.nvPr) { this.nvPr.toXml(writer); } } writer.WriteXmlNodeEnd(namespace_ + ":nvPicPr"); }; UniNvPr.prototype.toXmlGrp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wpg"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvGrpSpPr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); this.nvUniSpPr.toXmlGrSp(writer); if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) { this.nvPr.toXml(writer); } writer.WriteXmlNodeEnd(namespace_ + ":nvGrpSpPr"); }; function StyleRef() { CBaseNoIdObject.call(this); this.idx = 0; this.Color = new CUniColor(); } InitClass(StyleRef, CBaseNoIdObject, 0); StyleRef.prototype.isIdentical = function (styleRef) { if (styleRef == null) { return false; } if (this.idx !== styleRef.idx) { return false; } if(this.Color && !styleRef.Color || !this.Color && styleRef.Color) { return false; } if (!this.Color.IsIdentical(styleRef.Color)) { return false; } return true; }; StyleRef.prototype.getObjectType = function () { return AscDFH.historyitem_type_StyleRef; }; StyleRef.prototype.setIdx = function (idx) { this.idx = idx; }; StyleRef.prototype.setColor = function (color) { this.Color = color; }; StyleRef.prototype.createDuplicate = function () { var duplicate = new StyleRef(); duplicate.setIdx(this.idx); if (this.Color) duplicate.setColor(this.Color.createDuplicate()); return duplicate; }; StyleRef.prototype.Refresh_RecalcData = function () { }; StyleRef.prototype.Write_ToBinary = function (w) { writeLong(w, this.idx); w.WriteBool(isRealObject(this.Color)); if (isRealObject(this.Color)) { this.Color.Write_ToBinary(w); } }; StyleRef.prototype.Read_FromBinary = function (r) { this.idx = readLong(r); if (r.GetBool()) { this.Color = new CUniColor(); this.Color.Read_FromBinary(r); } }; StyleRef.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (this.Color && this.Color.isCorrect()) { return this.Color.getNoStyleUnicolor(nIdx, aColors); } return null; }; StyleRef.prototype.readAttrXml = function (name, reader) { switch (name) { case "idx": { this.idx = reader.GetValueInt(); break; } } }; StyleRef.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.Color.fromXml(reader, name); } }; StyleRef.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlNullableAttributeUInt("idx", this.idx); writer.WriteXmlAttributesEnd(); if (this.Color) { this.Color.toXml(writer); } writer.WriteXmlNodeEnd(sName); }; function FontRef() { CBaseNoIdObject.call(this); this.idx = AscFormat.fntStyleInd_none; this.Color = null; } InitClass(FontRef, CBaseNoIdObject, 0); FontRef.prototype.setIdx = function (idx) { this.idx = idx; }; FontRef.prototype.setColor = function (color) { this.Color = color; }; FontRef.prototype.createDuplicate = function () { var duplicate = new FontRef(); duplicate.setIdx(this.idx); if (this.Color) duplicate.setColor(this.Color.createDuplicate()); return duplicate; }; FontRef.prototype.Write_ToBinary = function (w) { writeLong(w, this.idx); w.WriteBool(isRealObject(this.Color)); if (isRealObject(this.Color)) { this.Color.Write_ToBinary(w); } }; FontRef.prototype.Read_FromBinary = function (r) { this.idx = readLong(r); if (r.GetBool()) { this.Color = new CUniColor(); this.Color.Read_FromBinary(r); } }; FontRef.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (this.Color && this.Color.isCorrect()) { return this.Color.getNoStyleUnicolor(nIdx, aColors); } return null; }; FontRef.prototype.getFirstPartThemeName = function () { if (this.idx === AscFormat.fntStyleInd_major) { return "+mj-"; } return "+mn-"; }; FontRef.prototype.readAttrXml = function (name, reader) { switch (name) { case "idx": { let sVal = reader.GetValue(); if (sVal === "major") { this.idx = AscFormat.fntStyleInd_major; } else if (sVal === "minor") { this.idx = AscFormat.fntStyleInd_minor; } else if (sVal === "none") { this.idx = AscFormat.fntStyleInd_none; } break; } } }; FontRef.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { let oColor = new CUniColor(); oColor.fromXml(reader, name); this.Color = oColor; } }; FontRef.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); let sVal; switch (this.idx) { case AscFormat.fntStyleInd_major: { sVal = "major"; break; } case AscFormat.fntStyleInd_minor: { sVal = "minor"; break; } case AscFormat.fntStyleInd_none: { sVal = "none"; break; } } writer.WriteXmlAttributeString("idx", sVal); writer.WriteXmlAttributesEnd(); if (this.Color) { this.Color.toXml(writer); } writer.WriteXmlNodeEnd(sName); }; function CShapeStyle() { CBaseFormatObject.call(this); this.lnRef = null; this.fillRef = null; this.effectRef = null; this.fontRef = null; } InitClass(CShapeStyle, CBaseFormatObject, AscDFH.historyitem_type_ShapeStyle); CShapeStyle.prototype.merge = function (style) { if (style != null) { if (style.lnRef != null) { this.lnRef = style.lnRef.createDuplicate(); } if (style.fillRef != null) { this.fillRef = style.fillRef.createDuplicate(); } if (style.effectRef != null) { this.effectRef = style.effectRef.createDuplicate(); } if (style.fontRef != null) { this.fontRef = style.fontRef.createDuplicate(); } } }; CShapeStyle.prototype.createDuplicate = function () { var duplicate = new CShapeStyle(); if (this.lnRef != null) { duplicate.setLnRef(this.lnRef.createDuplicate()); } if (this.fillRef != null) { duplicate.setFillRef(this.fillRef.createDuplicate()); } if (this.effectRef != null) { duplicate.setEffectRef(this.effectRef.createDuplicate()); } if (this.fontRef != null) { duplicate.setFontRef(this.fontRef.createDuplicate()); } return duplicate; }; CShapeStyle.prototype.setLnRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetLnRef, this.lnRef, pr)); this.lnRef = pr; }; CShapeStyle.prototype.setFillRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetFillRef, this.fillRef, pr)); this.fillRef = pr; }; CShapeStyle.prototype.setFontRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetFontRef, this.fontRef, pr)); this.fontRef = pr; }; CShapeStyle.prototype.setEffectRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetEffectRef, this.effectRef, pr)); this.effectRef = pr; }; CShapeStyle.prototype.readChildXml = function (name, reader) { switch (name) { case "effectRef": { let oStyleRef = new StyleRef(); oStyleRef.fromXml(reader); this.setEffectRef(oStyleRef); break; } case "fillRef": { let oStyleRef = new StyleRef(); oStyleRef.fromXml(reader); this.setFillRef(oStyleRef); break; } case "fontRef": { let oStyleRef = new FontRef(); oStyleRef.fromXml(reader); this.setFontRef(oStyleRef); break; } case "lnRef": { let oStyleRef = new StyleRef(); oStyleRef.fromXml(reader); this.setLnRef(oStyleRef); break; } } }; CShapeStyle.prototype.toXml = function (writer) { let sNS = "a"; let oContext = writer.context; if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) sNS = "wps"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) sNS = "xdr"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) sNS = "a"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) sNS = "cdr"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) sNS = "dgm"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) sNS = "p"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) sNS = "dsp"; let sName = sNS + ":style"; writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); this.lnRef.toXml(writer, "a:lnRef"); this.fillRef.toXml(writer, "a:fillRef"); this.effectRef.toXml(writer, "a:effectRef"); this.fontRef.toXml(writer, "a:fontRef"); writer.WriteXmlNodeEnd(sName); }; var LINE_PRESETS_MAP = {}; LINE_PRESETS_MAP["line"] = true; LINE_PRESETS_MAP["bracePair"] = true; LINE_PRESETS_MAP["leftBrace"] = true; LINE_PRESETS_MAP["rightBrace"] = true; LINE_PRESETS_MAP["bracketPair"] = true; LINE_PRESETS_MAP["leftBracket"] = true; LINE_PRESETS_MAP["rightBracket"] = true; LINE_PRESETS_MAP["bentConnector2"] = true; LINE_PRESETS_MAP["bentConnector3"] = true; LINE_PRESETS_MAP["bentConnector4"] = true; LINE_PRESETS_MAP["bentConnector5"] = true; LINE_PRESETS_MAP["curvedConnector2"] = true; LINE_PRESETS_MAP["curvedConnector3"] = true; LINE_PRESETS_MAP["curvedConnector4"] = true; LINE_PRESETS_MAP["curvedConnector5"] = true; LINE_PRESETS_MAP["straightConnector1"] = true; LINE_PRESETS_MAP["arc"] = true; function CreateDefaultShapeStyle(preset) { var b_line = typeof preset === "string" && LINE_PRESETS_MAP[preset]; var tx_color = b_line; var unicolor; var style = new CShapeStyle(); var lnRef = new StyleRef(); lnRef.setIdx(b_line ? 1 : 2); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); var mod = new CColorMod(); mod.setName("shade"); mod.setVal(50000); unicolor.setMods(new CColorModifiers()); unicolor.Mods.addMod(mod); lnRef.setColor(unicolor); style.setLnRef(lnRef); var fillRef = new StyleRef(); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); fillRef.setIdx(b_line ? 0 : 1); fillRef.setColor(unicolor); style.setFillRef(fillRef); var effectRef = new StyleRef(); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); effectRef.setIdx(0); effectRef.setColor(unicolor); style.setEffectRef(effectRef); var fontRef = new FontRef(); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(tx_color ? 15 : 12); fontRef.setIdx(AscFormat.fntStyleInd_minor); fontRef.setColor(unicolor); style.setFontRef(fontRef); return style; } function CXfrm() { CBaseFormatObject.call(this); this.offX = null; this.offY = null; this.extX = null; this.extY = null; this.chOffX = null; this.chOffY = null; this.chExtX = null; this.chExtY = null; this.flipH = null; this.flipV = null; this.rot = null; } InitClass(CXfrm, CBaseFormatObject, AscDFH.historyitem_type_Xfrm); CXfrm.prototype.isNotNull = function () { return isRealNumber(this.offX) && isRealNumber(this.offY) && isRealNumber(this.extX) && isRealNumber(this.extY); }; CXfrm.prototype.isNotNullForGroup = function () { return isRealNumber(this.offX) && isRealNumber(this.offY) && isRealNumber(this.chOffX) && isRealNumber(this.chOffY) && isRealNumber(this.extX) && isRealNumber(this.extY) && isRealNumber(this.chExtX) && isRealNumber(this.chExtY); }; CXfrm.prototype.isZero = function () { return ( this.offX === 0 && this.offY === 0 && this.extX === 0 && this.extY === 0 ); }; CXfrm.prototype.isZeroCh = function () { return ( this.chOffX === 0 && this.chOffY === 0 && this.chExtX === 0 && this.chExtY === 0 ); }; CXfrm.prototype.isZeroInGroup = function () { return this.isZero() && this.isZeroCh(); }; CXfrm.prototype.isEqual = function (xfrm) { return xfrm && this.offX === xfrm.offX && this.offY === xfrm.offY && this.extX === xfrm.extX && this.extY === xfrm.extY && this.chOffX === xfrm.chOffX && this.chOffY === xfrm.chOffY && this.chExtX === xfrm.chExtX && this.chExtY === xfrm.chExtY; }; CXfrm.prototype.merge = function (xfrm) { if (xfrm.offX != null) { this.offX = xfrm.offX; } if (xfrm.offY != null) { this.offY = xfrm.offY; } if (xfrm.extX != null) { this.extX = xfrm.extX; } if (xfrm.extY != null) { this.extY = xfrm.extY; } if (xfrm.chOffX != null) { this.chOffX = xfrm.chOffX; } if (xfrm.chOffY != null) { this.chOffY = xfrm.chOffY; } if (xfrm.chExtX != null) { this.chExtX = xfrm.chExtX; } if (xfrm.chExtY != null) { this.chExtY = xfrm.chExtY; } if (xfrm.flipH != null) { this.flipH = xfrm.flipH; } if (xfrm.flipV != null) { this.flipV = xfrm.flipV; } if (xfrm.rot != null) { this.rot = xfrm.rot; } }; CXfrm.prototype.createDuplicate = function () { var duplicate = new CXfrm(); duplicate.setOffX(this.offX); duplicate.setOffY(this.offY); duplicate.setExtX(this.extX); duplicate.setExtY(this.extY); duplicate.setChOffX(this.chOffX); duplicate.setChOffY(this.chOffY); duplicate.setChExtX(this.chExtX); duplicate.setChExtY(this.chExtY); duplicate.setFlipH(this.flipH); duplicate.setFlipV(this.flipV); duplicate.setRot(this.rot); return duplicate; }; CXfrm.prototype.setParent = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_Xfrm_SetParent, this.parent, pr)); this.parent = pr; }; CXfrm.prototype.setOffX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetOffX, this.offX, pr)); this.offX = pr; this.handleUpdatePosition(); }; CXfrm.prototype.setOffY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetOffY, this.offY, pr)); this.offY = pr; this.handleUpdatePosition(); }; CXfrm.prototype.setExtX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetExtX, this.extX, pr)); this.extX = pr; this.handleUpdateExtents(true); }; CXfrm.prototype.setExtY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetExtY, this.extY, pr)); this.extY = pr; this.handleUpdateExtents(false); }; CXfrm.prototype.setChOffX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChOffX, this.chOffX, pr)); this.chOffX = pr; this.handleUpdateChildOffset(); }; CXfrm.prototype.setChOffY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChOffY, this.chOffY, pr)); this.chOffY = pr; this.handleUpdateChildOffset(); }; CXfrm.prototype.setChExtX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChExtX, this.chExtX, pr)); this.chExtX = pr; this.handleUpdateChildExtents(); }; CXfrm.prototype.setChExtY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChExtY, this.chExtY, pr)); this.chExtY = pr; this.handleUpdateChildExtents(); }; CXfrm.prototype.setFlipH = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Xfrm_SetFlipH, this.flipH, pr)); this.flipH = pr; this.handleUpdateFlip(); }; CXfrm.prototype.setFlipV = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Xfrm_SetFlipV, this.flipV, pr)); this.flipV = pr; this.handleUpdateFlip(); }; CXfrm.prototype.setRot = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetRot, this.rot, pr)); this.rot = pr; this.handleUpdateRot(); }; CXfrm.prototype.handleUpdatePosition = function () { if (this.parent && this.parent.handleUpdatePosition) { this.parent.handleUpdatePosition(); } }; CXfrm.prototype.handleUpdateExtents = function (bExtX) { if (this.parent && this.parent.handleUpdateExtents) { this.parent.handleUpdateExtents(bExtX); } }; CXfrm.prototype.handleUpdateChildOffset = function () { if (this.parent && this.parent.handleUpdateChildOffset) { this.parent.handleUpdateChildOffset(); } }; CXfrm.prototype.handleUpdateChildExtents = function () { if (this.parent && this.parent.handleUpdateChildExtents) { this.parent.handleUpdateChildExtents(); } }; CXfrm.prototype.handleUpdateFlip = function () { if (this.parent && this.parent.handleUpdateFlip) { this.parent.handleUpdateFlip(); } }; CXfrm.prototype.handleUpdateRot = function () { if (this.parent && this.parent.handleUpdateRot) { this.parent.handleUpdateRot(); } }; CXfrm.prototype.Refresh_RecalcData = function (data) { switch (data.Type) { case AscDFH.historyitem_Xfrm_SetOffX: { this.handleUpdatePosition(); break; } case AscDFH.historyitem_Xfrm_SetOffY: { this.handleUpdatePosition(); break; } case AscDFH.historyitem_Xfrm_SetExtX: { this.handleUpdateExtents(); break; } case AscDFH.historyitem_Xfrm_SetExtY: { this.handleUpdateExtents(); break; } case AscDFH.historyitem_Xfrm_SetChOffX: { this.handleUpdateChildOffset(); break; } case AscDFH.historyitem_Xfrm_SetChOffY: { this.handleUpdateChildOffset(); break; } case AscDFH.historyitem_Xfrm_SetChExtX: { this.handleUpdateChildExtents(); break; } case AscDFH.historyitem_Xfrm_SetChExtY: { this.handleUpdateChildExtents(); break; } case AscDFH.historyitem_Xfrm_SetFlipH: { this.handleUpdateFlip(); break; } case AscDFH.historyitem_Xfrm_SetFlipV: { this.handleUpdateFlip(); break; } case AscDFH.historyitem_Xfrm_SetRot: { this.handleUpdateRot(); break; } } }; CXfrm.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { break; } } //TODO:Implement in children }; CXfrm.prototype.fromXml = function (reader) { this.readAttr(reader); var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { if ("off" === reader.GetNameNoNS()) { this.readAttrOff(reader, this.setOffX, this.setOffY); } else if ("ext" === reader.GetNameNoNS()) { this.readAttrExt(reader, this.setExtX, this.setExtY); } else if ("chOff" === reader.GetNameNoNS()) { this.readAttrOff(reader, this.setChOffX, this.setChOffY); } else if ("chExt" === reader.GetNameNoNS()) { this.readAttrExt(reader, this.setChExtX, this.setChExtY); } } }; CXfrm.prototype.toXml = function (writer, name) { writer.WriteXmlNodeStart(name); if (null !== this.rot) { writer.WriteXmlAttributeNumber("rot", Math.round(this.rot * 180 * 60000 / Math.PI)); } writer.WriteXmlNullableAttributeBool("flipH", this.flipH); writer.WriteXmlNullableAttributeBool("flipV", this.flipV); writer.WriteXmlAttributesEnd(); if (null !== this.offX || null !== this.offY) { writer.WriteXmlNodeStart("a:off"); if (null !== this.offX) { writer.WriteXmlAttributeNumber("x", Math.round(this.offX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.offY) { writer.WriteXmlAttributeNumber("y", Math.round(this.offY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } if (null !== this.extX || null !== this.extY) { writer.WriteXmlNodeStart("a:ext"); if (null !== this.extX) { writer.WriteXmlAttributeNumber("cx", Math.round(this.extX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.extY) { writer.WriteXmlAttributeNumber("cy", Math.round(this.extY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } if (null !== this.chOffX || null !== this.chOffY) { writer.WriteXmlNodeStart("a:chOff"); if (null !== this.chOffX) { writer.WriteXmlAttributeNumber("x", Math.round(this.chOffX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.chOffY) { writer.WriteXmlAttributeNumber("y", Math.round(this.chOffY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } if (null !== this.chExtX || null !== this.chExtY) { writer.WriteXmlNodeStart("a:chExt"); if (null !== this.chExtX) { writer.WriteXmlAttributeNumber("cx", Math.round(this.chExtX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.chExtY) { writer.WriteXmlAttributeNumber("cy", Math.round(this.chExtY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(name); }; CXfrm.prototype.readAttr = function (reader) { while (reader.MoveToNextAttribute()) { if ("flipH" === reader.GetName()) { this.setFlipH(reader.GetValueBool()); } else if ("flipV" === reader.GetName()) { this.setFlipV(reader.GetValueBool()); } else if ("rot" === reader.GetName()) { this.setRot((reader.GetValueInt() / 60000) * Math.PI / 180); } } }; CXfrm.prototype.readAttrOff = function (reader, fSetX, fSetY) { while (reader.MoveToNextAttribute()) { if ("x" === reader.GetName()) { fSetX.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } else if ("y" === reader.GetName()) { fSetY.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } } }; CXfrm.prototype.readAttrExt = function (reader, fSetCX, fSetCY) { while (reader.MoveToNextAttribute()) { if ("cx" === reader.GetName()) { fSetCX.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } else if ("cy" === reader.GetName()) { fSetCY.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } } }; function CEffectProperties() { CBaseNoIdObject.call(this); this.EffectDag = null; this.EffectLst = null; } InitClass(CEffectProperties, CBaseNoIdObject, 0); CEffectProperties.prototype.createDuplicate = function () { var oCopy = new CEffectProperties(); if (this.EffectDag) { oCopy.EffectDag = this.EffectDag.createDuplicate(); } if (this.EffectLst) { oCopy.EffectLst = this.EffectLst.createDuplicate(); } return oCopy; }; CEffectProperties.prototype.Write_ToBinary = function (w) { var nFlags = 0; if (this.EffectDag) { nFlags |= 1; } if (this.EffectLst) { nFlags |= 2; } w.WriteLong(nFlags); if (this.EffectDag) { this.EffectDag.Write_ToBinary(w); } if (this.EffectLst) { this.EffectLst.Write_ToBinary(w); } }; CEffectProperties.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.EffectDag = new CEffectContainer(); this.EffectDag.Read_FromBinary(r); } if (nFlags & 2) { this.EffectLst = new CEffectLst(); this.EffectLst.Read_FromBinary(r); } }; CEffectProperties.prototype.fromXml = function (reader, name) { if (name === "effectLst") { this.EffectLst = new CEffectLst(); this.EffectLst.fromXml(reader); } else if (name === "effectDag") { this.EffectDag = new CEffectContainer(); this.EffectDag.fromXml(reader); } }; CEffectProperties.prototype.toXml = function (writer) { if (this.EffectLst) { this.EffectLst.toXml(writer, "effectLst"); } else if (this.EffectDag) { this.EffectDag.toXml(writer, "effectDag"); } }; function CEffectLst() { CBaseNoIdObject.call(this); this.blur = null; this.fillOverlay = null; this.glow = null; this.innerShdw = null; this.outerShdw = null; this.prstShdw = null; this.reflection = null; this.softEdge = null; } InitClass(CEffectLst, CBaseNoIdObject, 0); CEffectLst.prototype.createDuplicate = function () { var oCopy = new CEffectLst(); if (this.blur) { oCopy.blur = this.blur.createDuplicate(); } if (this.fillOverlay) { oCopy.fillOverlay = this.fillOverlay.createDuplicate(); } if (this.glow) { oCopy.glow = this.glow.createDuplicate(); } if (this.innerShdw) { oCopy.innerShdw = this.innerShdw.createDuplicate(); } if (this.outerShdw) { oCopy.outerShdw = this.outerShdw.createDuplicate(); } if (this.prstShdw) { oCopy.prstShdw = this.prstShdw.createDuplicate(); } if (this.reflection) { oCopy.reflection = this.reflection.createDuplicate(); } if (this.softEdge) { oCopy.softEdge = this.softEdge.createDuplicate(); } return oCopy; }; CEffectLst.prototype.Write_ToBinary = function (w) { var nFlags = 0; if (this.blur) { nFlags |= 1; } if (this.fillOverlay) { nFlags |= 2; } if (this.glow) { nFlags |= 4; } if (this.innerShdw) { nFlags |= 8; } if (this.outerShdw) { nFlags |= 16; } if (this.prstShdw) { nFlags |= 32; } if (this.reflection) { nFlags |= 64; } if (this.softEdge) { nFlags |= 128; } w.WriteLong(nFlags); if (this.blur) { this.blur.Write_ToBinary(w); } if (this.fillOverlay) { this.fillOverlay.Write_ToBinary(w); } if (this.glow) { this.glow.Write_ToBinary(w); } if (this.innerShdw) { this.innerShdw.Write_ToBinary(w); } if (this.outerShdw) { this.outerShdw.Write_ToBinary(w); } if (this.prstShdw) { this.prstShdw.Write_ToBinary(w); } if (this.reflection) { this.reflection.Write_ToBinary(w); } if (this.softEdge) { this.softEdge.Write_ToBinary(w); } }; CEffectLst.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.blur = new CBlur(); r.GetLong(); this.blur.Read_FromBinary(r); } if (nFlags & 2) { this.fillOverlay = new CFillOverlay(); r.GetLong(); this.fillOverlay.Read_FromBinary(r); } if (nFlags & 4) { this.glow = new CGlow(); r.GetLong(); this.glow.Read_FromBinary(r); } if (nFlags & 8) { this.innerShdw = new CInnerShdw(); r.GetLong(); this.innerShdw.Read_FromBinary(r); } if (nFlags & 16) { this.outerShdw = new COuterShdw(); r.GetLong(); this.outerShdw.Read_FromBinary(r); } if (nFlags & 32) { this.prstShdw = new CPrstShdw(); r.GetLong(); this.prstShdw.Read_FromBinary(r); } if (nFlags & 64) { this.reflection = new CReflection(); r.GetLong(); this.reflection.Read_FromBinary(r); } if (nFlags & 128) { this.softEdge = new CSoftEdge(); r.GetLong(); this.softEdge.Read_FromBinary(r); } }; CEffectLst.prototype.readChildXml = function (name, reader) { if (name === "blur") { this.blur = new CBlur(); this.blur.fromXml(reader); } else if (name === "fillOverlay") { this.fillOverlay = new CFillOverlay(); this.fillOverlay.fromXml(reader); } else if (name === "glow") { this.glow = new CGlow(); this.glow.fromXml(reader); } else if (name === "innerShdw") { this.innerShdw = new CInnerShdw(); this.innerShdw.fromXml(reader); } else if (name === "outerShdw") { this.outerShdw = new COuterShdw(); this.outerShdw.fromXml(reader); } else if (name === "prstShdw") { this.prstShdw = new CPrstShdw(); this.prstShdw.fromXml(reader); } else if (name === "reflection") { this.reflection = new CReflection(); this.reflection.fromXml(reader); } else if (name === "softEdge") { this.softEdge = new CSoftEdge(); this.softEdge.fromXml(reader); } }; CEffectLst.prototype.toXml = function (writer) { if (!this.blur && !this.fillOverlay && !this.glow && !this.innerShdw && !this.outerShdw && !this.prstShdw && !this.reflection && !this.softEdge) { writer.WriteXmlString("<a:effectLst/>"); return; } writer.WriteXmlNodeStart("a:effectLst"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.blur); writer.WriteXmlNullable(this.fillOverlay); writer.WriteXmlNullable(this.glow); writer.WriteXmlNullable(this.innerShdw); writer.WriteXmlNullable(this.outerShdw); writer.WriteXmlNullable(this.prstShdw); writer.WriteXmlNullable(this.reflection); writer.WriteXmlNullable(this.softEdge); writer.WriteXmlNodeEnd("a:effectLst"); }; function CSpPr() { CBaseFormatObject.call(this); this.bwMode = 0; this.xfrm = null; this.geometry = null; this.Fill = null; this.ln = null; this.parent = null; this.effectProps = null; } InitClass(CSpPr, CBaseFormatObject, AscDFH.historyitem_type_SpPr); CSpPr.prototype.Refresh_RecalcData = function (data) { switch (data.Type) { case AscDFH.historyitem_SpPr_SetParent: { break; } case AscDFH.historyitem_SpPr_SetBwMode: { break; } case AscDFH.historyitem_SpPr_SetXfrm: { this.handleUpdateExtents(); break; } case AscDFH.historyitem_SpPr_SetGeometry: case AscDFH.historyitem_SpPr_SetEffectPr: { this.handleUpdateGeometry(); break; } case AscDFH.historyitem_SpPr_SetFill: { this.handleUpdateFill(); break; } case AscDFH.historyitem_SpPr_SetLn: { this.handleUpdateLn(); break; } } }; CSpPr.prototype.Refresh_RecalcData2 = function (data) { }; CSpPr.prototype.createDuplicate = function () { var duplicate = new CSpPr(); duplicate.setBwMode(this.bwMode); if (this.xfrm) { duplicate.setXfrm(this.xfrm.createDuplicate()); duplicate.xfrm.setParent(duplicate); } if (this.geometry != null) { duplicate.setGeometry(this.geometry.createDuplicate()); } if (this.Fill != null) { duplicate.setFill(this.Fill.createDuplicate()); } if (this.ln != null) { duplicate.setLn(this.ln.createDuplicate()); } if (this.effectProps) { duplicate.setEffectPr(this.effectProps.createDuplicate()); } return duplicate; }; CSpPr.prototype.createDuplicateForSmartArt = function () { var duplicate = new CSpPr(); if (this.Fill != null) { duplicate.setFill(this.Fill.createDuplicate()); } return duplicate; }; CSpPr.prototype.hasRGBFill = function () { return this.Fill && this.Fill.fill && this.Fill.fill.color && this.Fill.fill.color.color && this.Fill.fill.color.color.type === c_oAscColor.COLOR_TYPE_SRGB; }; CSpPr.prototype.hasNoFill = function () { if (this.Fill) { return this.Fill.isNoFill(); } return false; }; CSpPr.prototype.hasNoFillLine = function () { if (this.ln) { return this.ln.isNoFillLine(); } return false; }; CSpPr.prototype.checkUniFillRasterImageId = function (unifill) { if (unifill && unifill.fill && typeof unifill.fill.RasterImageId === "string" && unifill.fill.RasterImageId.length > 0) return unifill.fill.RasterImageId; return null; }; CSpPr.prototype.checkBlipFillRasterImage = function (images) { var fill_image_id = this.checkUniFillRasterImageId(this.Fill); if (fill_image_id !== null) images.push(fill_image_id); if (this.ln) { var line_image_id = this.checkUniFillRasterImageId(this.ln.Fill); if (line_image_id) images.push(line_image_id); } }; CSpPr.prototype.changeShadow = function (oShadow) { if (oShadow) { var oEffectProps = this.effectProps ? this.effectProps.createDuplicate() : new AscFormat.CEffectProperties(); if (!oEffectProps.EffectLst) { oEffectProps.EffectLst = new CEffectLst(); } oEffectProps.EffectLst.outerShdw = oShadow.createDuplicate(); this.setEffectPr(oEffectProps); } else { if (this.effectProps) { if (this.effectProps.EffectLst) { if (this.effectProps.EffectLst.outerShdw) { var oEffectProps = this.effectProps.createDuplicate(); oEffectProps.EffectLst.outerShdw = null; this.setEffectPr(oEffectProps); } } } } }; CSpPr.prototype.merge = function (spPr) { /*if(spPr.xfrm != null) { this.xfrm.merge(spPr.xfrm); } */ if (spPr.geometry != null) { this.geometry = spPr.geometry.createDuplicate(); } if (spPr.Fill != null && spPr.Fill.fill != null) { //this.Fill = spPr.Fill.createDuplicate(); } /*if(spPr.ln!=null) { if(this.ln == null) this.ln = new CLn(); this.ln.merge(spPr.ln); } */ }; CSpPr.prototype.setParent = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_SpPr_SetParent, this.parent, pr)); this.parent = pr; }; CSpPr.prototype.setBwMode = function (pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_SpPr_SetBwMode, this.bwMode, pr)); this.bwMode = pr; }; CSpPr.prototype.setXfrm = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_SpPr_SetXfrm, this.xfrm, pr)); this.xfrm = pr; if(pr) { pr.setParent(this); } }; CSpPr.prototype.setGeometry = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_SpPr_SetGeometry, this.geometry, pr)); this.geometry = pr; if (this.geometry) { this.geometry.setParent(this); } this.handleUpdateGeometry(); }; CSpPr.prototype.setFill = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_SpPr_SetFill, this.Fill, pr)); this.Fill = pr; if (this.parent && this.parent.handleUpdateFill) { this.parent.handleUpdateFill(); } }; CSpPr.prototype.setLn = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_SpPr_SetLn, this.ln, pr)); this.ln = pr; if (this.parent && this.parent.handleUpdateLn) { this.parent.handleUpdateLn(); } }; CSpPr.prototype.setEffectPr = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_SpPr_SetEffectPr, this.effectProps, pr)); this.effectProps = pr; }; CSpPr.prototype.handleUpdatePosition = function () { if (this.parent && this.parent.handleUpdatePosition) { this.parent.handleUpdatePosition(); } }; CSpPr.prototype.handleUpdateExtents = function (bExtX) { if (this.parent && this.parent.handleUpdateExtents) { this.parent.handleUpdateExtents(bExtX); } }; CSpPr.prototype.handleUpdateChildOffset = function () { if (this.parent && this.parent.handleUpdateChildOffset) { this.parent.handleUpdateChildOffset(); } }; CSpPr.prototype.handleUpdateChildExtents = function () { if (this.parent && this.parent.handleUpdateChildExtents) { this.parent.handleUpdateChildExtents(); } }; CSpPr.prototype.handleUpdateFlip = function () { if (this.parent && this.parent.handleUpdateFlip) { this.parent.handleUpdateFlip(); } }; CSpPr.prototype.handleUpdateRot = function () { if (this.parent && this.parent.handleUpdateRot) { this.parent.handleUpdateRot(); } }; CSpPr.prototype.handleUpdateGeometry = function () { if (this.parent && this.parent.handleUpdateGeometry) { this.parent.handleUpdateGeometry(); } }; CSpPr.prototype.handleUpdateFill = function () { if (this.parent && this.parent.handleUpdateFill) { this.parent.handleUpdateFill(); } }; CSpPr.prototype.handleUpdateLn = function () { if (this.parent && this.parent.handleUpdateLn) { this.parent.handleUpdateLn(); } }; CSpPr.prototype.setLineFill = function () { if (this.ln && this.ln.Fill) { this.setFill(this.ln.Fill.createDuplicate()); } }; CSpPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "bwMode": { break; } } }; CSpPr.prototype.readChildXml = function (name, reader) { let oPr; if (name === "xfrm") { oPr = new AscFormat.CXfrm(); oPr.fromXml(reader); this.setXfrm(oPr); } else if (name === "prstGeom" || name === "custGeom") { let oPr = new AscFormat.Geometry(); oPr.fromXml(reader); this.setGeometry(oPr); } else if (CUniFill.prototype.isFillName(name)) { let oFill = new CUniFill(); oFill.fromXml(reader, name); this.setFill(oFill); } else if (name === "ln") { let oLn = new CLn(); oLn.fromXml(reader); this.setLn(oLn); } else if (name === "effectDag" || name === "effectLst") { let oEffectProps = new CEffectProperties(); oEffectProps.fromXml(reader, name); this.setEffectPr(oEffectProps); } }; CSpPr.prototype.toXml = function (writer, name) { let name_ = "a:spPr"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { if (0 === (writer.context.flag & 0x01)) name_ = "wps:spPr"; else name_ = "pic:spPr"; } else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) name_ = "xdr:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) name_ = "cdr:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) name_ = "dgm:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) name_ = "dsp:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART) name_ = "c:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) name_ = "a:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_STYLE) name_ = "cs:spPr"; else {//theme if (0 !== (writer.context.flag & 0x04)) name_ = "a:spPr"; else name_ = "p:spPr"; } writer.WriteXmlNodeStart(name_); writer.WriteXmlAttributeString("bwMode", "auto"); if(this.xfrm || this.geometry || ((writer.context.flag & 0x02) !== 0 && !this.Fill) || this.Fill || this.ln || this.effectProps) { writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.xfrm, "a:xfrm"); writer.WriteXmlNullable(this.geometry); if ((writer.context.flag & 0x02) !== 0 && !this.Fill) { writer.WriteXmlString("<a:grpFill/>"); } writer.WriteXmlNullable(this.Fill); writer.WriteXmlNullable(this.ln); writer.WriteXmlNullable(this.effectProps); //writer.WriteXmlNullable(scene3d); //writer.WriteXmlNullable(sp3d); writer.WriteXmlNodeEnd(name_); } else { writer.WriteXmlAttributesEnd(true); } }; CSpPr.prototype.toXmlGroup = function(writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wpg"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":grpSpPr"); writer.WriteXmlAttributeString("bwMode", "auto"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.xfrm, "a:xfrm"); writer.WriteXmlNullable(this.Fill); writer.WriteXmlNullable(this.effectProps); //writer.Write(scene3d); writer.WriteXmlNodeEnd(namespace_ + ":grpSpPr"); }; // ---------------------------------- // THEME ---------------------------- var g_clr_MIN = 0; var g_clr_accent1 = 0; var g_clr_accent2 = 1; var g_clr_accent3 = 2; var g_clr_accent4 = 3; var g_clr_accent5 = 4; var g_clr_accent6 = 5; var g_clr_dk1 = 6; var g_clr_dk2 = 7; var g_clr_folHlink = 8; var g_clr_hlink = 9; var g_clr_lt1 = 10; var g_clr_lt2 = 11; var g_clr_MAX = 11; var g_clr_bg1 = g_clr_lt1; var g_clr_bg2 = g_clr_lt2; var g_clr_tx1 = g_clr_dk1; var g_clr_tx2 = g_clr_dk2; var phClr = 14; var tx1 = 15; var tx2 = 16; let CLR_IDX_MAP = {}; CLR_IDX_MAP["dk1"] = 8; CLR_IDX_MAP["lt1"] = 12; CLR_IDX_MAP["dk2"] = 9; CLR_IDX_MAP["lt2"] = 13; CLR_IDX_MAP["accent1"] = 0; CLR_IDX_MAP["accent2"] = 1; CLR_IDX_MAP["accent3"] = 2; CLR_IDX_MAP["accent4"] = 3; CLR_IDX_MAP["accent5"] = 4; CLR_IDX_MAP["accent6"] = 5; CLR_IDX_MAP["hlink"] = 11; CLR_IDX_MAP["folHlink"] = 10; let CLR_NAME_MAP = {}; CLR_NAME_MAP[8] = "dk1"; CLR_NAME_MAP[12] = "lt1"; CLR_NAME_MAP[9] = "dk2"; CLR_NAME_MAP[13] = "lt2"; CLR_NAME_MAP[0] = "accent1"; CLR_NAME_MAP[1] = "accent2"; CLR_NAME_MAP[2] = "accent3"; CLR_NAME_MAP[3] = "accent4"; CLR_NAME_MAP[4] = "accent5"; CLR_NAME_MAP[5] = "accent6"; CLR_NAME_MAP[11] = "hlink"; CLR_NAME_MAP[10] = "folHlink"; function ClrScheme() { CBaseNoIdObject.call(this); this.name = ""; this.colors = []; for (var i = g_clr_MIN; i <= g_clr_MAX; i++) this.colors[i] = null; } InitClass(ClrScheme, CBaseNoIdObject, 0); ClrScheme.prototype.isIdentical = function (clrScheme) { if (!(clrScheme instanceof ClrScheme)) { return false; } if (clrScheme.name !== this.name) { return false; } for (var _clr_index = g_clr_MIN; _clr_index <= g_clr_MAX; ++_clr_index) { if (this.colors[_clr_index]) { if (!this.colors[_clr_index].IsIdentical(clrScheme.colors[_clr_index])) { return false; } } else { if (clrScheme.colors[_clr_index]) { return false; } } } return true; }; ClrScheme.prototype.createDuplicate = function () { var _duplicate = new ClrScheme(); _duplicate.name = this.name; for (var _clr_index = 0; _clr_index <= this.colors.length; ++_clr_index) { if (this.colors[_clr_index]) { _duplicate.colors[_clr_index] = this.colors[_clr_index].createDuplicate(); } } return _duplicate; }; ClrScheme.prototype.Write_ToBinary = function (w) { w.WriteLong(this.colors.length); w.WriteString2(this.name); for (var i = 0; i < this.colors.length; ++i) { w.WriteBool(isRealObject(this.colors[i])); if (isRealObject(this.colors[i])) { this.colors[i].Write_ToBinary(w); } } }; ClrScheme.prototype.Read_FromBinary = function (r) { var len = r.GetLong(); this.name = r.GetString2(); for (var i = 0; i < len; ++i) { if (r.GetBool()) { this.colors[i] = new CUniColor(); this.colors[i].Read_FromBinary(r); } else { this.colors[i] = null; } } }; ClrScheme.prototype.setName = function (name) { this.name = name; }; ClrScheme.prototype.addColor = function (index, color) { this.colors[index] = color; }; ClrScheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.name = reader.GetValue(); break; } } }; ClrScheme.prototype.readChildXml = function (name, reader) { let nClrIdx = CLR_IDX_MAP[name]; if (AscFormat.isRealNumber(nClrIdx)) { this.colors[nClrIdx] = new CUniColor(); var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { var sClrName = reader.GetNameNoNS(); if (CUniColor.prototype.isUnicolor(sClrName)) { this.colors[nClrIdx].fromXml(reader, sClrName); } } } }; ClrScheme.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNullableAttributeStringEncode("name", this.name); }; ClrScheme.prototype.writeChildrenXml = function (writer) { let aIdx = [8, 12, 9, 13, 0, 1, 2, 3, 4, 5, 11, 10]; for (let nIdx = 0; nIdx < aIdx.length; ++nIdx) { let oColor = this.colors[aIdx[nIdx]]; if (oColor) { let sName = CLR_NAME_MAP[aIdx[nIdx]]; if (sName) { let sNodeName = "a:" + sName; writer.WriteXmlNodeStart(sNodeName); writer.WriteXmlAttributesEnd(); oColor.toXml(writer); writer.WriteXmlNodeEnd(sNodeName); } } } }; function ClrMap() { CBaseFormatObject.call(this); this.color_map = []; for (var i = g_clr_MIN; i <= g_clr_MAX; i++) this.color_map[i] = null; } InitClass(ClrMap, CBaseFormatObject, AscDFH.historyitem_type_ClrMap); ClrMap.prototype.Refresh_RecalcData = function () { }; ClrMap.prototype.notAllowedWithoutId = function () { return false; }; ClrMap.prototype.createDuplicate = function () { var _copy = new ClrMap(); for (var _color_index = g_clr_MIN; _color_index <= this.color_map.length; ++_color_index) { _copy.setClr(_color_index, this.color_map[_color_index]); } return _copy; }; ClrMap.prototype.compare = function (other) { if (!other) return false; for (var i = g_clr_MIN; i < this.color_map.length; ++i) { if (this.color_map[i] !== other.color_map[i]) { return false; } } return true; }; ClrMap.prototype.setClr = function (index, clr) { History.Add(new CChangesDrawingsContentLongMap(this, AscDFH.historyitem_ClrMap_SetClr, index, [clr], true)); this.color_map[index] = clr; }; ClrMap.prototype.SchemeClr_GetBYTECode = function (sValue) { if ("accent1" === sValue) return 0; if ("accent2" === sValue) return 1; if ("accent3" === sValue) return 2; if ("accent4" === sValue) return 3; if ("accent5" === sValue) return 4; if ("accent6" === sValue) return 5; if ("bg1" === sValue) return 6; if ("bg2" === sValue) return 7; if ("dk1" === sValue) return 8; if ("dk2" === sValue) return 9; if ("folHlink" === sValue) return 10; if ("hlink" === sValue) return 11; if ("lt1" === sValue) return 12; if ("lt2" === sValue) return 13; if ("phClr" === sValue) return 14; if ("tx1" === sValue) return 15; if ("tx2" === sValue) return 16; return 0; }; ClrMap.prototype.SchemeClr_GetStringCode = function (val) { switch (val) { case 0: return ("accent1"); case 1: return ("accent2"); case 2: return ("accent3"); case 3: return ("accent4"); case 4: return ("accent5"); case 5: return ("accent6"); case 6: return ("bg1"); case 7: return ("bg2"); case 8: return ("dk1"); case 9: return ("dk2"); case 10: return ("folHlink"); case 11: return ("hlink"); case 12: return ("lt1"); case 13: return ("lt2"); case 14: return ("phClr"); case 15: return ("tx1"); case 16: return ("tx2"); } return ("accent1"); } ClrMap.prototype.getColorIdx = function (name) { if ("accent1" === name) return 0; if ("accent2" === name) return 1; if ("accent3" === name) return 2; if ("accent4" === name) return 3; if ("accent5" === name) return 4; if ("accent6" === name) return 5; if ("bg1" === name) return 6; if ("bg2" === name) return 7; if ("dk1" === name) return 8; if ("dk2" === name) return 9; if ("folHlink" === name) return 10; if ("hlink" === name) return 11; if ("lt1" === name) return 12; if ("lt2" === name) return 13; if ("phClr" === name) return 14; if ("tx1" === name) return 15; if ("tx2" === name) return 16; return null; }; ClrMap.prototype.getColorName = function (nIdx) { if (0 === nIdx) return "accent1"; if (1 === nIdx) return "accent2"; if (2 === nIdx) return "accent3"; if (3 === nIdx) return "accent4"; if (4 === nIdx) return "accent5"; if (5 === nIdx) return "accent6"; if (6 === nIdx) return "bg1"; if (7 === nIdx) return "bg2"; if (8 === nIdx) return "dk1"; if (9 === nIdx) return "dk2"; if (10 === nIdx) return "folHlink"; if (11 === nIdx) return "hlink"; if (12 === nIdx) return "lt1"; if (13 === nIdx) return "lt2"; if (14 === nIdx) return "phClr"; if (15 === nIdx) return "tx1"; if (16 === nIdx) return "tx2"; return null; }; ClrMap.prototype.readAttrXml = function (name, reader) { let nIdx = this.SchemeClr_GetBYTECode(name); let sVal = reader.GetValue(); let nVal = this.getColorIdx(sVal); if (nVal !== null) { this.color_map[nIdx] = nVal } }; ClrMap.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); let aIdx = [6, 15, 7, 16, 0, 1, 2, 3, 4, 5, 11, 10]; for (let i = 0; i < aIdx.length; ++i) { if (AscFormat.isRealNumber(this.color_map[aIdx[i]])) { writer.WriteXmlNullableAttributeString(this.SchemeClr_GetStringCode(aIdx[i]), this.getColorName(this.color_map[aIdx[i]])); } } writer.WriteXmlAttributesEnd(true); }; ClrMap.prototype.SchemeClr_GetBYTECodeWord = function (sValue) { if ("accent1" === sValue) return 0; if ("accent2" === sValue) return 1; if ("accent3" === sValue) return 2; if ("accent4" === sValue) return 3; if ("accent5" === sValue) return 4; if ("accent6" === sValue) return 5; if ("bg1" === sValue) return 6; if ("bg2" === sValue) return 7; if ("followedHyperlink" === sValue) return 10; if ("hyperlink" === sValue) return 11; if ("t1" === sValue) return 15; if ("t2" === sValue) return 16; return null; }; ClrMap.prototype.SchemeClr_GetStringCodeWord = function (val) { switch (val) { case 0: return ("accent1"); case 1: return ("accent2"); case 2: return ("accent3"); case 3: return ("accent4"); case 4: return ("accent5"); case 5: return ("accent6"); case 6: return ("bg1"); case 7: return ("bg2"); case 10: return ("followedHyperlink"); case 11: return ("hyperlink"); case 15: return ("t1"); case 16: return ("t2"); } return (""); } ClrMap.prototype.getColorIdxWord = function (name) { if ("accent1" === name) return 0; if ("accent2" === name) return 1; if ("accent3" === name) return 2; if ("accent4" === name) return 3; if ("accent5" === name) return 4; if ("accent6" === name) return 5; if ("dark1" === name) return 8; if ("dark2" === name) return 9; if ("followedHyperlink" === name) return 10; if ("hyperlink" === name) return 11; if ("light1" === name) return 12; if ("light2" === name) return 13; return null; }; ClrMap.prototype.getColorNameWord = function (val) { switch (val) { case 0: return ("accent1"); case 1: return ("accent2"); case 2: return ("accent3"); case 3: return ("accent4"); case 4: return ("accent5"); case 5: return ("accent6"); case 8: return ("dark1"); case 9: return ("dark2"); case 10: return ("followedHyperlink"); case 11: return ("hyperlink"); case 12: return ("light1"); case 13: return ("light2"); } return (""); }; ClrMap.prototype.fromXmlWord = function (reader) { while (reader.MoveToNextAttribute()) { let nIdx = this.SchemeClr_GetBYTECodeWord(reader.GetNameNoNS()); let sVal = reader.GetValue(); let nVal = this.getColorIdxWord(sVal); if (nIdx !== null && nVal !== null) { this.color_map[nIdx] = nVal } } reader.ReadTillEnd(); }; ClrMap.prototype.toXmlWord = function (writer, name) { writer.WriteXmlNodeStart(name); let ns = AscCommon.StaxParser.prototype.GetNSFromNodeName(name); for (let i in this.color_map) { if (this.color_map.hasOwnProperty(i)) { let name = this.SchemeClr_GetStringCodeWord(parseInt(i)); let val = this.getColorNameWord(this.color_map[i]); if (name && val) { writer.WriteXmlNullableAttributeString(ns + name, val); } } } writer.WriteXmlAttributesEnd(true); }; function ExtraClrScheme() { CBaseFormatObject.call(this); this.clrScheme = null; this.clrMap = null; } InitClass(ExtraClrScheme, CBaseFormatObject, AscDFH.historyitem_type_ExtraClrScheme); ExtraClrScheme.prototype.Refresh_RecalcData = function () { }; ExtraClrScheme.prototype.setClrScheme = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ExtraClrScheme_SetClrScheme, this.clrScheme, pr)); this.clrScheme = pr; }; ExtraClrScheme.prototype.setClrMap = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ExtraClrScheme_SetClrMap, this.clrMap, pr)); this.clrMap = pr; }; ExtraClrScheme.prototype.createDuplicate = function () { var ret = new ExtraClrScheme(); if (this.clrScheme) { ret.setClrScheme(this.clrScheme.createDuplicate()) } if (this.clrMap) { ret.setClrMap(this.clrMap.createDuplicate()); } return ret; }; ExtraClrScheme.prototype.readChildXml = function (name, reader) { switch (name) { case "clrMap": { let oPr = new ClrMap(); oPr.fromXml(reader); this.setClrMap(oPr); break; } case "clrScheme": { let oPr = new ClrScheme(); oPr.fromXml(reader); this.setClrScheme(oPr); break; } } }; ExtraClrScheme.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:extraClrScheme"); writer.WriteXmlAttributesEnd(); if (this.clrScheme) { this.clrScheme.toXml(writer, "a:clrScheme"); } if (this.clrMap) { this.clrMap.toXml(writer, "a:clrMap") } writer.WriteXmlNodeEnd("a:extraClrScheme"); }; drawingConstructorsMap[AscDFH.historyitem_ExtraClrScheme_SetClrScheme] = ClrScheme; function FontCollection(fontScheme) { CBaseNoIdObject.call(this); this.latin = null; this.ea = null; this.cs = null; if (fontScheme) { this.setFontScheme(fontScheme); } } InitClass(FontCollection, CBaseNoIdObject, 0); FontCollection.prototype.Refresh_RecalcData = function () { }; FontCollection.prototype.setFontScheme = function (fontScheme) { this.fontScheme = fontScheme; }; FontCollection.prototype.setLatin = function (pr) { this.latin = pr; if (this.fontScheme) this.fontScheme.checkFromFontCollection(pr, this, FONT_REGION_LT); }; FontCollection.prototype.setEA = function (pr) { this.ea = pr; if (this.fontScheme) this.fontScheme.checkFromFontCollection(pr, this, FONT_REGION_EA); }; FontCollection.prototype.setCS = function (pr) { this.cs = pr; if (this.fontScheme) this.fontScheme.checkFromFontCollection(pr, this, FONT_REGION_CS); }; FontCollection.prototype.Write_ToBinary = function (w) { writeString(w, this.latin); writeString(w, this.ea); writeString(w, this.cs); }; FontCollection.prototype.Read_FromBinary = function (r) { this.latin = readString(r); this.ea = readString(r); this.cs = readString(r); if (this.fontScheme) { this.fontScheme.checkFromFontCollection(this.latin, this, FONT_REGION_LT); this.fontScheme.checkFromFontCollection(this.ea, this, FONT_REGION_EA); this.fontScheme.checkFromFontCollection(this.cs, this, FONT_REGION_CS); } }; FontCollection.prototype.readFont = function (reader) { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); return oNode.attributes["typeface"]; }; FontCollection.prototype.writeFont = function (writer, sNodeName, sFont) { writer.WriteXmlNodeStart(sNodeName); writer.WriteXmlAttributeString("typeface", sFont || ""); writer.WriteXmlAttributesEnd(true); }; FontCollection.prototype.readChildXml = function (name, reader) { switch (name) { case "cs": { this.setCS(this.readFont(reader)); break; } case "ea": { this.setEA(this.readFont(reader)); break; } case "latin": { this.setLatin(this.readFont(reader)); break; } } }; FontCollection.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); this.writeFont(writer, "a:latin", this.latin); this.writeFont(writer, "a:ea", this.ea); this.writeFont(writer, "a:cs", this.cs); // let nCount = Fonts.length; // for (let i = 0; // i < nCount; // ++i // ) // Fonts[i].toXml(writer); writer.WriteXmlNodeEnd(sName); }; var FONT_REGION_LT = 0x00; var FONT_REGION_EA = 0x01; var FONT_REGION_CS = 0x02; function FontScheme() { CBaseNoIdObject.call(this) this.name = ""; this.majorFont = new FontCollection(this); this.minorFont = new FontCollection(this); this.fontMap = { "+mj-lt": undefined, "+mj-ea": undefined, "+mj-cs": undefined, "+mn-lt": undefined, "+mn-ea": undefined, "+mn-cs": undefined, "majorAscii": undefined, "majorBidi": undefined, "majorEastAsia": undefined, "majorHAnsi": undefined, "minorAscii": undefined, "minorBidi": undefined, "minorEastAsia": undefined, "minorHAnsi": undefined }; } InitClass(FontScheme, CBaseNoIdObject, 0); FontScheme.prototype.createDuplicate = function () { var oCopy = new FontScheme(); oCopy.majorFont.setLatin(this.majorFont.latin); oCopy.majorFont.setEA(this.majorFont.ea); oCopy.majorFont.setCS(this.majorFont.cs); oCopy.minorFont.setLatin(this.minorFont.latin); oCopy.minorFont.setEA(this.minorFont.ea); oCopy.minorFont.setCS(this.minorFont.cs); return oCopy; }; FontScheme.prototype.Refresh_RecalcData = function () { }; FontScheme.prototype.Write_ToBinary = function (w) { this.majorFont.Write_ToBinary(w); this.minorFont.Write_ToBinary(w); writeString(w, this.name); }; FontScheme.prototype.Read_FromBinary = function (r) { this.majorFont.Read_FromBinary(r); this.minorFont.Read_FromBinary(r); this.name = readString(r); }; FontScheme.prototype.checkFromFontCollection = function (font, fontCollection, region) { if (fontCollection === this.majorFont) { switch (region) { case FONT_REGION_LT: { this.fontMap["+mj-lt"] = font; this.fontMap["majorAscii"] = font; this.fontMap["majorHAnsi"] = font; break; } case FONT_REGION_EA: { this.fontMap["+mj-ea"] = font; this.fontMap["majorEastAsia"] = font; break; } case FONT_REGION_CS: { this.fontMap["+mj-cs"] = font; this.fontMap["majorBidi"] = font; break; } } } else if (fontCollection === this.minorFont) { switch (region) { case FONT_REGION_LT: { this.fontMap["+mn-lt"] = font; this.fontMap["minorAscii"] = font; this.fontMap["minorHAnsi"] = font; break; } case FONT_REGION_EA: { this.fontMap["+mn-ea"] = font; this.fontMap["minorEastAsia"] = font; break; } case FONT_REGION_CS: { this.fontMap["+mn-cs"] = font; this.fontMap["minorBidi"] = font; break; } } } }; FontScheme.prototype.checkFont = function (font) { if (g_oThemeFontsName[font]) { if (this.fontMap[font]) { return this.fontMap[font]; } else if (this.fontMap["+mn-lt"]) { return this.fontMap["+mn-lt"]; } else { return "Arial"; } } return font; }; FontScheme.prototype.getObjectType = function () { return AscDFH.historyitem_type_FontScheme; }; FontScheme.prototype.setName = function (pr) { this.name = pr; }; FontScheme.prototype.setMajorFont = function (pr) { this.majorFont = pr; }; FontScheme.prototype.setMinorFont = function (pr) { this.minorFont = pr; }; FontScheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.name = reader.GetValue(); break; } } }; FontScheme.prototype.readChildXml = function (name, reader) { switch (name) { case "majorFont": { this.majorFont.fromXml(reader); break; } case "minorFont": { this.minorFont.fromXml(reader); break; } } }; FontScheme.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNullableAttributeStringEncode("name", this.name); }; FontScheme.prototype.writeChildrenXml = function (writer) { this.majorFont.toXml(writer, "a:majorFont"); this.minorFont.toXml(writer, "a:minorFont"); }; function FmtScheme() { CBaseNoIdObject.call(this); this.name = ""; this.fillStyleLst = []; this.lnStyleLst = []; this.effectStyleLst = null; this.bgFillStyleLst = []; } InitClass(FmtScheme, CBaseNoIdObject, 0); FmtScheme.prototype.GetFillStyle = function (number, unicolor) { if (number >= 1 && number <= 999) { var ret = this.fillStyleLst[number - 1]; if (!ret) return null; var ret2 = ret.createDuplicate(); ret2.checkPhColor(unicolor, false); return ret2; } else if (number >= 1001) { var ret = this.bgFillStyleLst[number - 1001]; if (!ret) return null; var ret2 = ret.createDuplicate(); ret2.checkPhColor(unicolor, false); return ret2; } return null; }; FmtScheme.prototype.Write_ToBinary = function (w) { writeString(w, this.name); var i; w.WriteLong(this.fillStyleLst.length); for (i = 0; i < this.fillStyleLst.length; ++i) { this.fillStyleLst[i].Write_ToBinary(w); } w.WriteLong(this.lnStyleLst.length); for (i = 0; i < this.lnStyleLst.length; ++i) { this.lnStyleLst[i].Write_ToBinary(w); } w.WriteLong(this.bgFillStyleLst.length); for (i = 0; i < this.bgFillStyleLst.length; ++i) { this.bgFillStyleLst[i].Write_ToBinary(w); } }; FmtScheme.prototype.Read_FromBinary = function (r) { this.name = readString(r); var _len = r.GetLong(), i; for (i = 0; i < _len; ++i) { this.fillStyleLst[i] = new CUniFill(); this.fillStyleLst[i].Read_FromBinary(r); } _len = r.GetLong(); for (i = 0; i < _len; ++i) { this.lnStyleLst[i] = new CLn(); this.lnStyleLst[i].Read_FromBinary(r); } _len = r.GetLong(); for (i = 0; i < _len; ++i) { this.bgFillStyleLst[i] = new CUniFill(); this.bgFillStyleLst[i].Read_FromBinary(r); } }; FmtScheme.prototype.createDuplicate = function () { var oCopy = new FmtScheme(); oCopy.name = this.name; var i; for (i = 0; i < this.fillStyleLst.length; ++i) { oCopy.fillStyleLst[i] = this.fillStyleLst[i].createDuplicate(); } for (i = 0; i < this.lnStyleLst.length; ++i) { oCopy.lnStyleLst[i] = this.lnStyleLst[i].createDuplicate(); } for (i = 0; i < this.bgFillStyleLst.length; ++i) { oCopy.bgFillStyleLst[i] = this.bgFillStyleLst[i].createDuplicate(); } return oCopy; }; FmtScheme.prototype.setName = function (pr) { this.name = pr; }; FmtScheme.prototype.addFillToStyleLst = function (pr) { this.fillStyleLst.push(pr); }; FmtScheme.prototype.addLnToStyleLst = function (pr) { this.lnStyleLst.push(pr); }; FmtScheme.prototype.addEffectToStyleLst = function (pr) { this.effectStyleLst.push(pr); }; FmtScheme.prototype.addBgFillToStyleLst = function (pr) { this.bgFillStyleLst.push(pr); }; FmtScheme.prototype.getImageFromBulletsMap = function(oImages) {}; FmtScheme.prototype.getDocContentsWithImageBullets = function (arrContents) {}; FmtScheme.prototype.getAllRasterImages = function(aImages) { for(let nIdx = 0; nIdx < this.fillStyleLst.length; ++nIdx) { let oUnifill = this.fillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId) { aImages.push(sRasterImageId); } } for(let nIdx = 0; nIdx < this.bgFillStyleLst.length; ++nIdx) { let oUnifill = this.bgFillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId) { aImages.push(sRasterImageId); } } }; FmtScheme.prototype.Reassign_ImageUrls = function(oImageMap) { for(let nIdx = 0; nIdx < this.fillStyleLst.length; ++nIdx) { let oUnifill = this.fillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId && oImageMap[sRasterImageId]) { oUnifill.fill.RasterImageId = oImageMap[sRasterImageId] } } for(let nIdx = 0; nIdx < this.bgFillStyleLst.length; ++nIdx) { let oUnifill = this.bgFillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId && oImageMap[sRasterImageId]) { oUnifill.fill.RasterImageId = oImageMap[sRasterImageId] } } }; FmtScheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.name = reader.GetValue(); break; } } }; FmtScheme.prototype.readList = function (reader, aArray, fConstructor) { var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { let name = reader.GetNameNoNS(); let oObj = new fConstructor(); oObj.fromXml(reader, name === "ln" ? undefined : name); aArray.push(oObj); } }; FmtScheme.prototype.writeList = function (writer, aArray, sName, sChildName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); for (let nIdx = 0; nIdx < aArray.length; ++nIdx) { aArray[nIdx].toXml(writer, sChildName) } writer.WriteXmlNodeEnd(sName); }; FmtScheme.prototype.readChildXml = function (name, reader) { switch (name) { case "bgFillStyleLst": { this.readList(reader, this.bgFillStyleLst, CUniFill); break; } case "effectStyleLst": { break; } case "fillStyleLst": { this.readList(reader, this.fillStyleLst, CUniFill); break; } case "lnStyleLst": { this.readList(reader, this.lnStyleLst, CLn); break; } } }; FmtScheme.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNullableAttributeStringEncode("name", this.name); }; FmtScheme.prototype.writeChildrenXml = function (writer) { this.writeList(writer, this.fillStyleLst, "a:fillStyleLst"); this.writeList(writer, this.lnStyleLst, "a:lnStyleLst", "a:ln"); writer.WriteXmlString("<a:effectStyleLst><a:effectStyle><a:effectLst>\ <a:outerShdw blurRad=\"40000\" dist=\"20000\" dir=\"5400000\" rotWithShape=\"0\"><a:srgbClr val=\"000000\"><a:alpha val=\"38000\"/></a:srgbClr></a:outerShdw>\ </a:effectLst></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=\"40000\" dist=\"23000\" dir=\"5400000\" rotWithShape=\"0\">\ <a:srgbClr val=\"000000\"><a:alpha val=\"35000\"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle><a:effectStyle><a:effectLst>\ <a:outerShdw blurRad=\"40000\" dist=\"23000\" dir=\"5400000\" rotWithShape=\"0\"><a:srgbClr val=\"000000\"><a:alpha val=\"35000\"/></a:srgbClr>\ </a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst>"); this.writeList(writer, this.bgFillStyleLst, "a:bgFillStyleLst"); }; function ThemeElements(oTheme) { CBaseNoIdObject.call(this); this.theme = oTheme; this.clrScheme = new ClrScheme(); this.fontScheme = new FontScheme(); this.fmtScheme = new FmtScheme(); } InitClass(ThemeElements, CBaseNoIdObject, 0); ThemeElements.prototype.readAttrXml = function (name, reader) { }; ThemeElements.prototype.readChildXml = function (name, reader) { switch (name) { case "clrScheme": { let oClrScheme = new ClrScheme(); oClrScheme.fromXml(reader); this.theme.setColorScheme(oClrScheme); break; } case "extLst": { break; } case "fmtScheme": { let oFmtScheme = new FmtScheme(); oFmtScheme.fromXml(reader); this.theme.setFormatScheme(oFmtScheme); break; } case "fontScheme": { let oFontScheme = new FontScheme(); oFontScheme.fromXml(reader); this.theme.setFontScheme(oFontScheme); break; } } }; ThemeElements.prototype.writeAttrXmlImpl = function (writer) { }; ThemeElements.prototype.writeChildrenXml = function (writer) { writer.WriteXmlNullable(this.clrScheme, "a:clrScheme"); writer.WriteXmlNullable(this.fontScheme, "a:fontScheme"); writer.WriteXmlNullable(this.fmtScheme, "a:fmtScheme"); }; function CTheme() { CBaseFormatObject.call(this); this.name = ""; this.themeElements = new ThemeElements(this); this.spDef = null; this.lnDef = null; this.txDef = null; this.extraClrSchemeLst = []; this.isThemeOverride = false; // pointers this.presentation = null; this.clrMap = null; } InitClass(CTheme, CBaseFormatObject, 0); CTheme.prototype.notAllowedWithoutId = function () { return false; }; CTheme.prototype.createDuplicate = function () { var oTheme = new CTheme(); oTheme.setName(this.name); oTheme.setColorScheme(this.themeElements.clrScheme.createDuplicate()); oTheme.setFontScheme(this.themeElements.fontScheme.createDuplicate()); oTheme.setFormatScheme(this.themeElements.fmtScheme.createDuplicate()); if (this.spDef) { oTheme.setSpDef(this.spDef.createDuplicate()); } if (this.lnDef) { oTheme.setLnDef(this.lnDef.createDuplicate()); } if (this.txDef) { oTheme.setTxDef(this.txDef.createDuplicate()); } for (var i = 0; i < this.extraClrSchemeLst.length; ++i) { oTheme.addExtraClrSceme(this.extraClrSchemeLst[i].createDuplicate()); } return oTheme; }; CTheme.prototype.Document_Get_AllFontNames = function (AllFonts) { var font_scheme = this.themeElements.fontScheme; var major_font = font_scheme.majorFont; typeof major_font.latin === "string" && major_font.latin.length > 0 && (AllFonts[major_font.latin] = 1); typeof major_font.ea === "string" && major_font.ea.length > 0 && (AllFonts[major_font.ea] = 1); typeof major_font.cs === "string" && major_font.latin.length > 0 && (AllFonts[major_font.cs] = 1); var minor_font = font_scheme.minorFont; typeof minor_font.latin === "string" && minor_font.latin.length > 0 && (AllFonts[minor_font.latin] = 1); typeof minor_font.ea === "string" && minor_font.ea.length > 0 && (AllFonts[minor_font.ea] = 1); typeof minor_font.cs === "string" && minor_font.latin.length > 0 && (AllFonts[minor_font.cs] = 1); }; CTheme.prototype.getFillStyle = function (idx, unicolor) { if (idx === 0 || idx === 1000) { return AscFormat.CreateNoFillUniFill(); } var ret; if (idx >= 1 && idx <= 999) { if (this.themeElements.fmtScheme.fillStyleLst[idx - 1]) { ret = this.themeElements.fmtScheme.fillStyleLst[idx - 1].createDuplicate(); if (ret) { ret.checkPhColor(unicolor, false); return ret; } } } else if (idx >= 1001) { if (this.themeElements.fmtScheme.bgFillStyleLst[idx - 1001]) { ret = this.themeElements.fmtScheme.bgFillStyleLst[idx - 1001].createDuplicate(); if (ret) { ret.checkPhColor(unicolor, false); return ret; } } } return CreateSolidFillRGBA(0, 0, 0, 255); }; CTheme.prototype.getLnStyle = function (idx, unicolor) { if (idx === 0) { return AscFormat.CreateNoFillLine(); } if (this.themeElements.fmtScheme.lnStyleLst[idx - 1]) { var ret = this.themeElements.fmtScheme.lnStyleLst[idx - 1].createDuplicate(); if (ret.Fill) { ret.Fill.checkPhColor(unicolor, false); } return ret; } return new CLn(); }; CTheme.prototype.getExtraClrScheme = function (sName) { for (var i = 0; i < this.extraClrSchemeLst.length; ++i) { if (this.extraClrSchemeLst[i].clrScheme && this.extraClrSchemeLst[i].clrScheme.name === sName) { return this.extraClrSchemeLst[i].clrScheme.createDuplicate(); } } return null; }; CTheme.prototype.changeColorScheme = function (clrScheme) { var oCurClrScheme = this.themeElements.clrScheme; this.setColorScheme(clrScheme); var oOldAscColorScheme = AscCommon.getAscColorScheme(oCurClrScheme, this), aExtraAscClrSchemes = this.getExtraAscColorSchemes(); var oNewAscColorScheme = AscCommon.getAscColorScheme(clrScheme, this); if (AscCommon.getIndexColorSchemeInArray(AscCommon.g_oUserColorScheme, oOldAscColorScheme) === -1) { if (AscCommon.getIndexColorSchemeInArray(aExtraAscClrSchemes, oOldAscColorScheme) === -1) { var oExtraClrScheme = new ExtraClrScheme(); if (this.clrMap) { oExtraClrScheme.setClrMap(this.clrMap.createDuplicate()); } oExtraClrScheme.setClrScheme(oCurClrScheme.createDuplicate()); this.addExtraClrSceme(oExtraClrScheme, 0); aExtraAscClrSchemes = this.getExtraAscColorSchemes(); } } var nIndex = AscCommon.getIndexColorSchemeInArray(aExtraAscClrSchemes, oNewAscColorScheme); if (nIndex > -1) { this.removeExtraClrScheme(nIndex); } }; CTheme.prototype.getExtraAscColorSchemes = function () { var asc_color_scheme; var aCustomSchemes = []; var _extra = this.extraClrSchemeLst; var _count = _extra.length; for (var i = 0; i < _count; ++i) { var _scheme = _extra[i].clrScheme; asc_color_scheme = AscCommon.getAscColorScheme(_scheme, this); aCustomSchemes.push(asc_color_scheme); } return aCustomSchemes; }; CTheme.prototype.setColorScheme = function (clrScheme) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ThemeSetColorScheme, this.themeElements.clrScheme, clrScheme)); this.themeElements.clrScheme = clrScheme; }; CTheme.prototype.setFontScheme = function (fontScheme) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ThemeSetFontScheme, this.themeElements.fontScheme, fontScheme)); this.themeElements.fontScheme = fontScheme; }; CTheme.prototype.changeFontScheme = function (fontScheme) { this.setFontScheme(fontScheme); let aIndexes = this.GetAllSlideIndexes(); let aSlides = this.GetPresentationSlides(); if(aIndexes && aSlides) { for (let i = 0; i < aIndexes.length; ++i) { aSlides[aIndexes[i]] && aSlides[aIndexes[i]].checkSlideTheme(); } } }; CTheme.prototype.setFormatScheme = function (fmtScheme) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ThemeSetFmtScheme, this.themeElements.fmtScheme, fmtScheme)); this.themeElements.fmtScheme = fmtScheme; }; CTheme.prototype.setName = function (pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ThemeSetName, this.name, pr)); this.name = pr; }; CTheme.prototype.setIsThemeOverride = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ThemeSetIsThemeOverride, this.isThemeOverride, pr)); this.isThemeOverride = pr; }; CTheme.prototype.setSpDef = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ThemeSetSpDef, this.spDef, pr)); this.spDef = pr; }; CTheme.prototype.setLnDef = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ThemeSetLnDef, this.lnDef, pr)); this.lnDef = pr; }; CTheme.prototype.setTxDef = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ThemeSetTxDef, this.txDef, pr)); this.txDef = pr; }; CTheme.prototype.addExtraClrSceme = function (pr, idx) { var pos; if (AscFormat.isRealNumber(idx)) pos = idx; else pos = this.extraClrSchemeLst.length; History.Add(new CChangesDrawingsContent(this, AscDFH.historyitem_ThemeAddExtraClrScheme, pos, [pr], true)); this.extraClrSchemeLst.splice(pos, 0, pr); }; CTheme.prototype.removeExtraClrScheme = function (idx) { if (idx > -1 && idx < this.extraClrSchemeLst.length) { History.Add(new CChangesDrawingsContent(this, AscDFH.historyitem_ThemeRemoveExtraClrScheme, idx, this.extraClrSchemeLst.splice(idx, 1), false)); } }; CTheme.prototype.GetLogicDocument = function() { let oRet = typeof editor !== "undefined" && editor.WordControl && editor.WordControl.m_oLogicDocument; return AscCommon.isRealObject(oRet) ? oRet : null; }; CTheme.prototype.GetWordDrawingObjects = function () { let oLogicDocument = this.GetLogicDocument(); let oRet = oLogicDocument && oLogicDocument.DrawingObjects; return AscCommon.isRealObject(oRet) ? oRet : null; }; CTheme.prototype.GetPresentationSlides = function () { let oLogicDocument = this.GetLogicDocument(); if(oLogicDocument && Array.isArray(oLogicDocument.Slides)) { return oLogicDocument.Slides; } return null; }; CTheme.prototype.GetAllSlideIndexes = function () { let oPresentation = this.GetLogicDocument(); let aSlides = this.GetPresentationSlides(); if(oPresentation && aSlides) { let aIndexes = []; for(let nSlide = 0; nSlide < aSlides.length; ++nSlide) { let oSlide = aSlides[nSlide]; let oTheme = oSlide.getTheme(); if(oTheme === this) { aIndexes.push(nSlide); } } return aIndexes; } return null; }; CTheme.prototype.Refresh_RecalcData = function (oData) { if (oData) { if (oData.Type === AscDFH.historyitem_ThemeSetColorScheme) { let oWordGraphicObject = this.GetWordDrawingObjects(); if (oWordGraphicObject) { History.RecalcData_Add({All: true}); let aDrawings = oWordGraphicObject.drawingObjects; for (let nDrawing = 0; nDrawing < aDrawings.length; ++nDrawing) { let oGrObject = aDrawings[nDrawing].GraphicObj; if (oGrObject) { oGrObject.handleUpdateFill(); oGrObject.handleUpdateLn(); } } let oApi = oWordGraphicObject.document.Api; oApi.chartPreviewManager.clearPreviews(); oApi.textArtPreviewManager.clear(); } } else if(oData.Type === AscDFH.historyitem_ThemeSetFontScheme) { let oPresentation = this.GetLogicDocument(); let aSlideIndexes = this.GetAllSlideIndexes(); if(oPresentation) { oPresentation.Refresh_RecalcData({Type: AscDFH.historyitem_Presentation_ChangeTheme, aIndexes: aSlideIndexes}); } } } }; CTheme.prototype.getAllRasterImages = function(aImages) { if(this.themeElements && this.themeElements.fmtScheme) { this.themeElements.fmtScheme.getAllRasterImages(aImages); } }; CTheme.prototype.getImageFromBulletsMap = function(oImages) {}; CTheme.prototype.getDocContentsWithImageBullets = function (arrContents) {}; CTheme.prototype.Reassign_ImageUrls = function(images_rename) { if(this.themeElements && this.themeElements.fmtScheme) { let aImages = []; this.themeElements.fmtScheme.getAllRasterImages(aImages); let bReassign = false; for(let nImage = 0; nImage < aImages.length; ++nImage) { if(images_rename[aImages[nImage]]) { bReassign = true; break; } } if(bReassign) { let oNewFmtScheme = this.themeElements.fmtScheme.createDuplicate(); oNewFmtScheme.Reassign_ImageUrls(images_rename); this.setFormatScheme(oNewFmtScheme); } } }; CTheme.prototype.getObjectType = function () { return AscDFH.historyitem_type_Theme; }; CTheme.prototype.Write_ToBinary2 = function (w) { w.WriteLong(AscDFH.historyitem_type_Theme); w.WriteString2(this.Id); }; CTheme.prototype.Read_FromBinary2 = function (r) { this.Id = r.GetString2(); }; CTheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.setName(reader.GetValue()); break; } } }; CTheme.prototype.readChildXml = function (name, reader) { switch (name) { case "custClrLst": { break; } case "extLst": { break; } case "extraClrSchemeLst": { let oTheme = this; let oNode = new CT_XmlNode(function (reader, name) { if (name === "extraClrScheme") { let oExtraClrScheme = new ExtraClrScheme(); oExtraClrScheme.fromXml(reader); return oTheme.addExtraClrSceme(oExtraClrScheme, oTheme.extraClrSchemeLst.length); } return true; }); oNode.fromXml(reader); break; } case "objectDefaults": { let oTheme = this; let oNode = new CT_XmlNode(function (reader, name) { if (name === "lnDef") { oTheme.setLnDef(new DefaultShapeDefinition()); oTheme.lnDef.fromXml(reader); return oTheme.lnDef; } if (name === "spDef") { oTheme.setSpDef(new DefaultShapeDefinition()); oTheme.spDef.fromXml(reader); return oTheme.spDef; } if (name === "txDef") { oTheme.setTxDef(new DefaultShapeDefinition()); oTheme.txDef.fromXml(reader); return oTheme.txDef; } }); oNode.fromXml(reader); break; } case "themeElements": { this.themeElements.fromXml(reader); break; } } }; CTheme.prototype.toXml = function (writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); let sName = "a:theme"; writer.WriteXmlNodeStart(sName); writer.WriteXmlString(" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\""); writer.WriteXmlNullableAttributeStringEncode("name", this.name); writer.WriteXmlAttributesEnd(); this.themeElements.toXml(writer, "a:themeElements"); if(this.lnDef || this.spDef || this.txDef) { let oNode = new CT_XmlNode(); if (this.lnDef) oNode.members["a:lnDef"] = this.lnDef; if (this.spDef) oNode.members["a:spDef"] = this.spDef; if (this.txDef) oNode.members["a:txDef"] = this.txDef; oNode.toXml(writer, "a:objectDefaults"); } else { writer.WriteXmlNodeStart("a:objectDefaults"); writer.WriteXmlAttributesEnd(true); } if(this.extraClrSchemeLst.length > 0) { let oNode = new CT_XmlNode(); oNode.members["a:extraClrScheme"] = this.extraClrSchemeLst; writer.WriteXmlNullable(oNode, "a:extraClrSchemeLst"); } else { writer.WriteXmlNodeStart("a:extraClrSchemeLst"); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(sName); } // ---------------------------------- // CSLD ----------------------------- function HF() { CBaseFormatObject.call(this); this.dt = null; this.ftr = null; this.hdr = null; this.sldNum = null; } InitClass(HF, CBaseFormatObject, AscDFH.historyitem_type_HF); HF.prototype.Refresh_RecalcData = function () { }; HF.prototype.createDuplicate = function () { var ret = new HF(); if (ret.dt !== this.dt) { ret.setDt(this.dt); } if (ret.ftr !== this.ftr) { ret.setFtr(this.ftr); } if (ret.hdr !== this.hdr) { ret.setHdr(this.hdr); } if (ret.sldNum !== this.sldNum) { ret.setSldNum(this.sldNum); } return ret; }; HF.prototype.setDt = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetDt, this.dt, pr)); this.dt = pr; }; HF.prototype.setFtr = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetFtr, this.ftr, pr)); this.ftr = pr; }; HF.prototype.setHdr = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetHdr, this.hdr, pr)); this.hdr = pr; }; HF.prototype.setSldNum = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetSldNum, this.sldNum, pr)); this.sldNum = pr; }; HF.prototype.readAttrXml = function (name, reader) { switch (name) { case "dt": { this.setDt(reader.GetValueBool()); break; } case "ftr": { this.setFtr(reader.GetValueBool()); break; } case "hdr": { this.setHdr(reader.GetValueBool()); break; } case "sldNum": { this.setSldNum(reader.GetValueBool()); break; } } }; HF.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:hf"); writer.WriteXmlNullableAttributeString("dt", this.dt); writer.WriteXmlNullableAttributeString("ftr", this.ftr); writer.WriteXmlNullableAttributeString("hdr", this.hdr); writer.WriteXmlNullableAttributeString("sldNum", this.sldNum); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("p:hf"); }; function CBgPr() { CBaseNoIdObject.call(this) this.Fill = null; this.shadeToTitle = false; this.EffectProperties = null; } InitClass(CBgPr, CBaseNoIdObject, 0); CBgPr.prototype.merge = function (bgPr) { if (this.Fill == null) { this.Fill = new CUniFill(); if (bgPr.Fill != null) { this.Fill.merge(bgPr.Fill) } } }; CBgPr.prototype.createFullCopy = function () { var _copy = new CBgPr(); if (this.Fill != null) { _copy.Fill = this.Fill.createDuplicate(); } _copy.shadeToTitle = this.shadeToTitle; return _copy; }; CBgPr.prototype.setFill = function (pr) { this.Fill = pr; }; CBgPr.prototype.setShadeToTitle = function (pr) { this.shadeToTitle = pr; }; CBgPr.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.Fill)); if (isRealObject(this.Fill)) { this.Fill.Write_ToBinary(w); } w.WriteBool(this.shadeToTitle); }; CBgPr.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.Fill = new CUniFill(); this.Fill.Read_FromBinary(r); } this.shadeToTitle = r.GetBool(); }; CBgPr.prototype.readAttrXml = function (name, reader) { if (name === "shadeToTitle") { this.shadeToTitle = reader.GetValueBool(); } }; CBgPr.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.Fill = new CUniFill(); this.Fill.fromXml(reader, name); } else if (name === "effectDag" || name === "effectLst") { this.EffectProperties = new CEffectProperties(); this.EffectProperties.fromXml(reader); } }; CBgPr.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:bgPr"); writer.WriteXmlNullableAttributeBool("shadeToTitle", this.shadeToTitle); writer.WriteXmlAttributesEnd(); if (this.Fill) { this.Fill.toXml(writer); } if (this.EffectProperties) { this.EffectProperties.toXml(writer); } writer.WriteXmlNodeEnd("p:bgPr"); }; function CBg() { CBaseNoIdObject.call(this); this.bwMode = null; this.bgPr = null; this.bgRef = null; } InitClass(CBg, CBaseNoIdObject, 0); CBg.prototype.setBwMode = function (pr) { this.bwMode = pr; }; CBg.prototype.setBgPr = function (pr) { this.bgPr = pr; }; CBg.prototype.setBgRef = function (pr) { this.bgRef = pr; }; CBg.prototype.merge = function (bg) { if (this.bgPr == null) { this.bgPr = new CBgPr(); if (bg.bgPr != null) { this.bgPr.merge(bg.bgPr); } } }; CBg.prototype.createFullCopy = function () { var _copy = new CBg(); _copy.bwMode = this.bwMode; if (this.bgPr != null) { _copy.bgPr = this.bgPr.createFullCopy(); } if (this.bgRef != null) { _copy.bgRef = this.bgRef.createDuplicate(); } return _copy; }; CBg.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.bgPr)); if (isRealObject(this.bgPr)) { this.bgPr.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bgRef)); if (isRealObject(this.bgRef)) { this.bgRef.Write_ToBinary(w); } }; CBg.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.bgPr = new CBgPr(); this.bgPr.Read_FromBinary(r); } if (r.GetBool()) { this.bgRef = new StyleRef(); this.bgRef.Read_FromBinary(r); } }; CBg.prototype.readAttrXml = function (name, reader) { if (name === "bwMode") { this.bwMode = reader.GetValue(); } }; CBg.prototype.readChildXml = function (name, reader) { switch (name) { case "bgPr": { var oBgPr = new CBgPr(); oBgPr.fromXml(reader); this.bgPr = oBgPr; break; } case "bgRef": { var oBgRef = new StyleRef(); oBgRef.fromXml(reader); this.bgRef = oBgRef; break; } } }; CBg.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:bg"); writer.WriteXmlNullableAttributeString("bwMode", this.bwMode); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.bgPr); writer.WriteXmlNullable(this.bgRef, "p:bgRef"); writer.WriteXmlNodeEnd("p:bg"); }; function CSld(parent) { CBaseNoIdObject.call(this); this.name = ""; this.Bg = null; this.spTree = [];//new GroupShape(); this.parent = parent; } InitClass(CSld, CBaseNoIdObject, 0); CSld.prototype.getObjectsNamesPairs = function () { var aPairs = []; var aSpTree = this.spTree; for (var nSp = 0; nSp < aSpTree.length; ++nSp) { var oSp = aSpTree[nSp]; if (!oSp.isEmptyPlaceholder()) { aPairs.push({object: oSp, name: oSp.getObjectName()}); } } return aPairs; }; CSld.prototype.getObjectsNames = function () { var aPairs = this.getObjectsNamesPairs(); var aNames = []; for (var nPair = 0; nPair < aPairs.length; ++nPair) { var oPair = aPairs[nPair]; aNames.push(oPair.name); } return aNames; }; CSld.prototype.getObjectByName = function (sName) { var aSpTree = this.spTree; for (var nSp = 0; nSp < aSpTree.length; ++nSp) { var oSp = aSpTree[nSp]; if (oSp.getObjectName() === sName) { return oSp; } } return null; }; CSld.prototype.readAttrXml = function (name, reader) { if (name === "name") { this.name = reader.GetValue(); } }; CSld.prototype.readChildXml = function (name, reader) { switch (name) { case "bg": { var oBg = new AscFormat.CBg(); oBg.fromXml(reader); this.Bg = oBg; break; } case "controls": { break; } case "custDataLst": { break; } case "extLst": { break; } case "spTree": { var oSpTree = new CSpTree(this.parent); oSpTree.fromXml(reader); this.spTree = oSpTree.spTree; break; } } }; CSld.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:cSld"); if(typeof this.name === "string" && this.name.length > 0) { writer.WriteXmlNullableAttributeString("name", this.name); } writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.Bg); let oSpTree = new CSpTree(null); oSpTree.spTree = this.spTree; oSpTree.toXml(writer); // this.spTree.toXml(writer); writer.WriteXmlNodeEnd("p:cSld"); }; function CSpTree(oSlideObject) { CBaseNoIdObject.call(this); this.spTree = []; this.slideObject = oSlideObject; } InitClass(CSpTree, CBaseNoIdObject, 0); CSpTree.prototype.fromXml = function(reader) { CBaseNoIdObject.prototype.fromXml.call(this, reader); if(!(this instanceof AscFormat.CGroupShape)) { reader.context.assignConnectors(this.spTree); } }; CSpTree.prototype.readSpTreeElement = function(name, reader) { let oSp = null; switch (name) { case "contentPart": { break; } case "cxnSp": { oSp = new AscFormat.CConnectionShape(); oSp.fromXml(reader); break; } case "extLst": { break; } case "graphicFrame": { oSp = new AscFormat.CGraphicFrame(); oSp.fromXml(reader); break; } case "grpSp": { oSp = new AscFormat.CGroupShape(); oSp.fromXml(reader); break; } case "grpSpPr": { break; } case "nvGrpSpPr": { break; } case "pic": { oSp = new AscFormat.CImageShape(); oSp.fromXml(reader); break; } case "sp": { oSp = new AscFormat.CShape(); oSp.fromXml(reader); break; } case "AlternateContent": { let oThis = this; let oNode = new CT_XmlNode(function (reader, name) { if(!oSp) { if(name === "Choice") { let oChoiceNode = new CT_XmlNode(function(reader, name) { oSp = CSpTree.prototype.readSpTreeElement.call(oThis, name, reader); return true; }); oChoiceNode.fromXml(reader); } else if(name === "Fallback") { let oFallbackNode = new CT_XmlNode(function(reader, name) { oSp = CSpTree.prototype.readSpTreeElement.call(oThis, name, reader); return true; }); oFallbackNode.fromXml(reader); } } return true; }); oNode.fromXml(reader); break; } } if (oSp) { if (name === "graphicFrame" && !(oSp.graphicObject instanceof AscCommonWord.CTable)) { let _xfrm = oSp.spPr && oSp.spPr.xfrm; let _nvGraphicFramePr = oSp.nvGraphicFramePr; oSp = oSp.graphicObject; if (oSp) { if (!oSp.spPr) { oSp.setSpPr(new AscFormat.CSpPr()); oSp.spPr.setParent(oSp); } if (!_xfrm) { _xfrm = new AscFormat.CXfrm(); _xfrm.setOffX(0); _xfrm.setOffY(0); _xfrm.setExtX(0); _xfrm.setExtY(0); } if (AscCommon.isRealObject(_nvGraphicFramePr)) { oSp.setNvSpPr(_nvGraphicFramePr); if (AscFormat.isRealNumber(_nvGraphicFramePr.locks)) { oSp.setLocks(_nvGraphicFramePr.locks); } if (oSp.cNvPr) {//TODO: connect objects //this.map_shapes_by_id[_nvGraphicFramePr.cNvPr.id] = oSp; } } oSp.spPr.setXfrm(_xfrm); _xfrm.setParent(oSp.spPr); } } } return oSp; }; CSpTree.prototype.readChildXml = function (name, reader) { let oSp = CSpTree.prototype.readSpTreeElement.call(this, name, reader); if (oSp) { oSp.setBDeleted(false); if(this.slideObject) { oSp.setParent(this.slideObject); } this.spTree.push(oSp); } return oSp; }; CSpTree.prototype.toXml = function (writer, bGroup) { let name_; let nDocType = writer.context.docType; if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || nDocType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { if (writer.context.groupIndex === 0) name_ = "wpg:wgp"; else name_ = "wpg:grpSp"; } else if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) name_ = "xdr:grpSp"; else if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) name_ = "cdr:grpSp"; else if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) name_ = "a:grpSp"; else if(nDocType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) name_ = "dsp:spTree"; else { if (writer.context.groupIndex === 0) name_ = "p:spTree"; else name_ = "p:grpSp"; } writer.WriteXmlNodeStart(name_); writer.WriteXmlAttributesEnd(); if (this.nvGrpSpPr) { if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { if (this.nvGrpSpPr.cNvGrpSpPr) { this.nvGrpSpPr.cNvGrpSpPr.toXmlGrSp2(writer, "wpg"); } } else this.nvGrpSpPr.toXmlGrp(writer); } else { if(writer.context.groupIndex === 0) { writer.WriteXmlString("<p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr /></p:nvGrpSpPr><p:grpSpPr bwMode=\"auto\"><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"0\" cy=\"0\"/></a:xfrm></p:grpSpPr>") } } if (this.spPr) { if(bGroup) { this.spPr.toXmlGroup(writer); } else { this.spPr.toXml(writer); } } writer.context.groupIndex++; for (let i = 0; i < this.spTree.length; ++i) { let oSp = this.spTree[i]; let nType = oSp.getObjectType(); let oElement = oSp; if(nType === AscDFH.historyitem_type_ChartSpace || nType === AscDFH.historyitem_type_SmartArt) { oElement = AscFormat.CGraphicFrame.prototype.static_CreateGraphicFrameFromDrawing(oSp); } oElement.toXml(writer); } writer.context.groupIndex--; writer.WriteXmlNodeEnd(name_); }; // ---------------------------------- // MASTERSLIDE ---------------------- function CTextStyles() { CBaseNoIdObject.call(this); this.titleStyle = null; this.bodyStyle = null; this.otherStyle = null; } InitClass(CTextStyles, CBaseNoIdObject, 0); CTextStyles.prototype.getStyleByPhType = function (phType) { switch (phType) { case AscFormat.phType_ctrTitle: case AscFormat.phType_title: { return this.titleStyle; } case AscFormat.phType_body: case AscFormat.phType_subTitle: case AscFormat.phType_obj: case null: { return this.bodyStyle; } default: { break; } } return this.otherStyle; }; CTextStyles.prototype.createDuplicate = function () { var ret = new CTextStyles(); if (isRealObject(this.titleStyle)) { ret.titleStyle = this.titleStyle.createDuplicate(); } if (isRealObject(this.bodyStyle)) { ret.bodyStyle = this.bodyStyle.createDuplicate(); } if (isRealObject(this.otherStyle)) { ret.otherStyle = this.otherStyle.createDuplicate(); } return ret; }; CTextStyles.prototype.Refresh_RecalcData = function () { }; CTextStyles.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.titleStyle)); if (isRealObject(this.titleStyle)) { this.titleStyle.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bodyStyle)); if (isRealObject(this.bodyStyle)) { this.bodyStyle.Write_ToBinary(w); } w.WriteBool(isRealObject(this.otherStyle)); if (isRealObject(this.otherStyle)) { this.otherStyle.Write_ToBinary(w); } }; CTextStyles.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.titleStyle = new TextListStyle(); this.titleStyle.Read_FromBinary(r); } else { this.titleStyle = null; } if (r.GetBool()) { this.bodyStyle = new TextListStyle(); this.bodyStyle.Read_FromBinary(r); } else { this.bodyStyle = null; } if (r.GetBool()) { this.otherStyle = new TextListStyle(); this.otherStyle.Read_FromBinary(r); } else { this.otherStyle = null; } }; CTextStyles.prototype.Document_Get_AllFontNames = function (AllFonts) { if (this.titleStyle) { this.titleStyle.Document_Get_AllFontNames(AllFonts); } if (this.bodyStyle) { this.bodyStyle.Document_Get_AllFontNames(AllFonts); } if (this.otherStyle) { this.otherStyle.Document_Get_AllFontNames(AllFonts); } }; CTextStyles.prototype.readChildXml = function (name, reader) { switch (name) { case "bodyStyle": { this.bodyStyle = new TextListStyle(); this.bodyStyle.fromXml(reader); break; } case "otherStyle": { this.otherStyle = new TextListStyle(); this.otherStyle.fromXml(reader); break; } case "titleStyle": { this.titleStyle = new TextListStyle(); this.titleStyle.fromXml(reader); break; } } }; CTextStyles.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart("p:txStyles"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.titleStyle, "p:titleStyle"); writer.WriteXmlNullable(this.bodyStyle, "p:bodyStyle"); writer.WriteXmlNullable(this.otherStyle, "p:otherStyle"); writer.WriteXmlNodeEnd("p:txStyles"); }; //--------------------------- // SLIDELAYOUT ---------------------- //Layout types var nSldLtTBlank = 0; // Blank )) var nSldLtTChart = 1; //Chart) var nSldLtTChartAndTx = 2; //( Chart and Text )) var nSldLtTClipArtAndTx = 3; //Clip Art and Text) var nSldLtTClipArtAndVertTx = 4; //Clip Art and Vertical Text) var nSldLtTCust = 5; // Custom )) var nSldLtTDgm = 6; //Diagram )) var nSldLtTFourObj = 7; //Four Objects) var nSldLtTMediaAndTx = 8; // ( Media and Text )) var nSldLtTObj = 9; //Title and Object) var nSldLtTObjAndTwoObj = 10; //Object and Two Object) var nSldLtTObjAndTx = 11; // ( Object and Text )) var nSldLtTObjOnly = 12; //Object) var nSldLtTObjOverTx = 13; // ( Object over Text)) var nSldLtTObjTx = 14; //Title, Object, and Caption) var nSldLtTPicTx = 15; //Picture and Caption) var nSldLtTSecHead = 16; //Section Header) var nSldLtTTbl = 17; // ( Table )) var nSldLtTTitle = 18; // ( Title )) var nSldLtTTitleOnly = 19; // ( Title Only )) var nSldLtTTwoColTx = 20; // ( Two Column Text )) var nSldLtTTwoObj = 21; //Two Objects) var nSldLtTTwoObjAndObj = 22; //Two Objects and Object) var nSldLtTTwoObjAndTx = 23; //Two Objects and Text) var nSldLtTTwoObjOverTx = 24; //Two Objects over Text) var nSldLtTTwoTxTwoObj = 25; //Two Text and Two Objects) var nSldLtTTx = 26; // ( Text )) var nSldLtTTxAndChart = 27; // ( Text and Chart )) var nSldLtTTxAndClipArt = 28; //Text and Clip Art) var nSldLtTTxAndMedia = 29; // ( Text and Media )) var nSldLtTTxAndObj = 30; // ( Text and Object )) var nSldLtTTxAndTwoObj = 31; //Text and Two Objects) var nSldLtTTxOverObj = 32; // ( Text over Object)) var nSldLtTVertTitleAndTx = 33; //Vertical Title and Text) var nSldLtTVertTitleAndTxOverChart = 34; //Vertical Title and Text Over Chart) var nSldLtTVertTx = 35; //Vertical Text) AscFormat.nSldLtTBlank = nSldLtTBlank; // Blank )) AscFormat.nSldLtTChart = nSldLtTChart; //Chart) AscFormat.nSldLtTChartAndTx = nSldLtTChartAndTx; //( Chart and Text )) AscFormat.nSldLtTClipArtAndTx = nSldLtTClipArtAndTx; //Clip Art and Text) AscFormat.nSldLtTClipArtAndVertTx = nSldLtTClipArtAndVertTx; //Clip Art and Vertical Text) AscFormat.nSldLtTCust = nSldLtTCust; // Custom )) AscFormat.nSldLtTDgm = nSldLtTDgm; //Diagram )) AscFormat.nSldLtTFourObj = nSldLtTFourObj; //Four Objects) AscFormat.nSldLtTMediaAndTx = nSldLtTMediaAndTx; // ( Media and Text )) AscFormat.nSldLtTObj = nSldLtTObj; //Title and Object) AscFormat.nSldLtTObjAndTwoObj = nSldLtTObjAndTwoObj; //Object and Two Object) AscFormat.nSldLtTObjAndTx = nSldLtTObjAndTx; // ( Object and Text )) AscFormat.nSldLtTObjOnly = nSldLtTObjOnly; //Object) AscFormat.nSldLtTObjOverTx = nSldLtTObjOverTx; // ( Object over Text)) AscFormat.nSldLtTObjTx = nSldLtTObjTx; //Title, Object, and Caption) AscFormat.nSldLtTPicTx = nSldLtTPicTx; //Picture and Caption) AscFormat.nSldLtTSecHead = nSldLtTSecHead; //Section Header) AscFormat.nSldLtTTbl = nSldLtTTbl; // ( Table )) AscFormat.nSldLtTTitle = nSldLtTTitle; // ( Title )) AscFormat.nSldLtTTitleOnly = nSldLtTTitleOnly; // ( Title Only )) AscFormat.nSldLtTTwoColTx = nSldLtTTwoColTx; // ( Two Column Text )) AscFormat.nSldLtTTwoObj = nSldLtTTwoObj; //Two Objects) AscFormat.nSldLtTTwoObjAndObj = nSldLtTTwoObjAndObj; //Two Objects and Object) AscFormat.nSldLtTTwoObjAndTx = nSldLtTTwoObjAndTx; //Two Objects and Text) AscFormat.nSldLtTTwoObjOverTx = nSldLtTTwoObjOverTx; //Two Objects over Text) AscFormat.nSldLtTTwoTxTwoObj = nSldLtTTwoTxTwoObj; //Two Text and Two Objects) AscFormat.nSldLtTTx = nSldLtTTx; // ( Text )) AscFormat.nSldLtTTxAndChart = nSldLtTTxAndChart; // ( Text and Chart )) AscFormat.nSldLtTTxAndClipArt = nSldLtTTxAndClipArt; //Text and Clip Art) AscFormat.nSldLtTTxAndMedia = nSldLtTTxAndMedia; // ( Text and Media )) AscFormat.nSldLtTTxAndObj = nSldLtTTxAndObj; // ( Text and Object )) AscFormat.nSldLtTTxAndTwoObj = nSldLtTTxAndTwoObj; //Text and Two Objects) AscFormat.nSldLtTTxOverObj = nSldLtTTxOverObj; // ( Text over Object)) AscFormat.nSldLtTVertTitleAndTx = nSldLtTVertTitleAndTx; //Vertical Title and Text) AscFormat.nSldLtTVertTitleAndTxOverChart = nSldLtTVertTitleAndTxOverChart; //Vertical Title and Text Over Chart) AscFormat.nSldLtTVertTx = nSldLtTVertTx; //Vertical Text) var _ph_multiplier = 4; var _weight_body = 9; var _weight_chart = 5; var _weight_clipArt = 2; var _weight_ctrTitle = 11; var _weight_dgm = 4; var _weight_media = 3; var _weight_obj = 8; var _weight_pic = 7; var _weight_subTitle = 10; var _weight_tbl = 6; var _weight_title = 11; var _ph_summ_blank = 0; var _ph_summ_chart = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_chart); var _ph_summ_chart_and_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_chart) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ_dgm = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_dgm); var _ph_summ_four_obj = Math.pow(_ph_multiplier, _weight_title) + 4 * Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__media_and_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_media) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__obj = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__obj_and_two_obj = Math.pow(_ph_multiplier, _weight_title) + 3 * Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__obj_and_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_obj) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__obj_only = Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__pic_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_pic) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__sec_head = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_subTitle); var _ph_summ__tbl = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_tbl); var _ph_summ__title_only = Math.pow(_ph_multiplier, _weight_title); var _ph_summ__two_col_tx = Math.pow(_ph_multiplier, _weight_title) + 2 * Math.pow(_ph_multiplier, _weight_body); var _ph_summ__two_obj_and_tx = Math.pow(_ph_multiplier, _weight_title) + 2 * Math.pow(_ph_multiplier, _weight_obj) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__two_obj_and_two_tx = Math.pow(_ph_multiplier, _weight_title) + 2 * Math.pow(_ph_multiplier, _weight_obj) + 2 * Math.pow(_ph_multiplier, _weight_body); var _ph_summ__tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__tx_and_clip_art = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_body) + +Math.pow(_ph_multiplier, _weight_clipArt); var _arr_lt_types_weight = []; _arr_lt_types_weight[0] = _ph_summ_blank; _arr_lt_types_weight[1] = _ph_summ_chart; _arr_lt_types_weight[2] = _ph_summ_chart_and_tx; _arr_lt_types_weight[3] = _ph_summ_dgm; _arr_lt_types_weight[4] = _ph_summ_four_obj; _arr_lt_types_weight[5] = _ph_summ__media_and_tx; _arr_lt_types_weight[6] = _ph_summ__obj; _arr_lt_types_weight[7] = _ph_summ__obj_and_two_obj; _arr_lt_types_weight[8] = _ph_summ__obj_and_tx; _arr_lt_types_weight[9] = _ph_summ__obj_only; _arr_lt_types_weight[10] = _ph_summ__pic_tx; _arr_lt_types_weight[11] = _ph_summ__sec_head; _arr_lt_types_weight[12] = _ph_summ__tbl; _arr_lt_types_weight[13] = _ph_summ__title_only; _arr_lt_types_weight[14] = _ph_summ__two_col_tx; _arr_lt_types_weight[15] = _ph_summ__two_obj_and_tx; _arr_lt_types_weight[16] = _ph_summ__two_obj_and_two_tx; _arr_lt_types_weight[17] = _ph_summ__tx; _arr_lt_types_weight[18] = _ph_summ__tx_and_clip_art; _arr_lt_types_weight.sort(AscCommon.fSortAscending); var _global_layout_summs_array = {}; _global_layout_summs_array["_" + _ph_summ_blank] = nSldLtTBlank; _global_layout_summs_array["_" + _ph_summ_chart] = nSldLtTChart; _global_layout_summs_array["_" + _ph_summ_chart_and_tx] = nSldLtTChartAndTx; _global_layout_summs_array["_" + _ph_summ_dgm] = nSldLtTDgm; _global_layout_summs_array["_" + _ph_summ_four_obj] = nSldLtTFourObj; _global_layout_summs_array["_" + _ph_summ__media_and_tx] = nSldLtTMediaAndTx; _global_layout_summs_array["_" + _ph_summ__obj] = nSldLtTObj; _global_layout_summs_array["_" + _ph_summ__obj_and_two_obj] = nSldLtTObjAndTwoObj; _global_layout_summs_array["_" + _ph_summ__obj_and_tx] = nSldLtTObjAndTx; _global_layout_summs_array["_" + _ph_summ__obj_only] = nSldLtTObjOnly; _global_layout_summs_array["_" + _ph_summ__pic_tx] = nSldLtTPicTx; _global_layout_summs_array["_" + _ph_summ__sec_head] = nSldLtTSecHead; _global_layout_summs_array["_" + _ph_summ__tbl] = nSldLtTTbl; _global_layout_summs_array["_" + _ph_summ__title_only] = nSldLtTTitleOnly; _global_layout_summs_array["_" + _ph_summ__two_col_tx] = nSldLtTTwoColTx; _global_layout_summs_array["_" + _ph_summ__two_obj_and_tx] = nSldLtTTwoObjAndTx; _global_layout_summs_array["_" + _ph_summ__two_obj_and_two_tx] = nSldLtTTwoTxTwoObj; _global_layout_summs_array["_" + _ph_summ__tx] = nSldLtTTx; _global_layout_summs_array["_" + _ph_summ__tx_and_clip_art] = nSldLtTTxAndClipArt; // SLIDE ---------------------------- function redrawSlide(slide, presentation, arrInd, pos, direction, arr_slides) { if (slide) { slide.recalculate(); presentation.DrawingDocument.OnRecalculatePage(slide.num, slide); } if (direction === 0) { if (pos > 0) { presentation.backChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos - 1]], presentation, arrInd, pos - 1, -1, arr_slides) }, recalcSlideInterval); } else { presentation.backChangeThemeTimeOutId = null; } if (pos < arrInd.length - 1) { presentation.forwardChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos + 1]], presentation, arrInd, pos + 1, +1, arr_slides) }, recalcSlideInterval); } else { presentation.forwardChangeThemeTimeOutId = null; } presentation.startChangeThemeTimeOutId = null; } if (direction > 0) { if (pos < arrInd.length - 1) { presentation.forwardChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos + 1]], presentation, arrInd, pos + 1, +1, arr_slides) }, recalcSlideInterval); } else { presentation.forwardChangeThemeTimeOutId = null; } } if (direction < 0) { if (pos > 0) { presentation.backChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos - 1]], presentation, arrInd, pos - 1, -1, arr_slides) }, recalcSlideInterval); } else { presentation.backChangeThemeTimeOutId = null; } } } function CTextFit(nType) { CBaseNoIdObject.call(this); this.type = nType !== undefined && nType !== null ? nType : 0; this.fontScale = null; this.lnSpcReduction = null; } InitClass(CTextFit, CBaseNoIdObject, 0); CTextFit.prototype.CreateDublicate = function () { var d = new CTextFit(); d.type = this.type; d.fontScale = this.fontScale; d.lnSpcReduction = this.lnSpcReduction; return d; }; CTextFit.prototype.Write_ToBinary = function (w) { writeLong(w, this.type); writeLong(w, this.fontScale); writeLong(w, this.lnSpcReduction); }; CTextFit.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.fontScale = readLong(r); this.lnSpcReduction = readLong(r); }; CTextFit.prototype.Get_Id = function () { return this.Id; }; CTextFit.prototype.Refresh_RecalcData = function () { }; CTextFit.prototype.readAttrXml = function (name, reader) { switch (name) { case "fontScale": { this.fontScale = reader.GetValueInt(); break; } case "lnSpcReduction": { this.lnSpcReduction = reader.GetValueInt(); break; } } }; CTextFit.prototype.toXml = function (writer) { if (this.type === AscFormat.text_fit_No) { writer.WriteXmlString("<a:noAutofit/>"); return; } if (this.type === AscFormat.text_fit_Auto) { writer.WriteXmlString("<a:spAutoFit/>"); return; } if (this.type === AscFormat.text_fit_NormAuto) { writer.WriteXmlNodeStart("a:normAutofit"); writer.WriteXmlNullableAttributeString("fontScale", this.fontScale); writer.WriteXmlNullableAttributeString("lnSpcReduction", this.lnSpcReduction); writer.WriteXmlAttributesEnd(true); } }; //----------------------------- //Text Anchoring Types var nTextATB = 0;// (Text Anchor Enum ( Bottom )) var nTextATCtr = 1;// (Text Anchor Enum ( Center )) var nTextATDist = 2;// (Text Anchor Enum ( Distributed )) var nTextATJust = 3;// (Text Anchor Enum ( Justified )) var nTextATT = 4;// Top function CBodyPr() { CBaseNoIdObject.call(this); this.flatTx = null; this.anchor = null; this.anchorCtr = null; this.bIns = null; this.compatLnSpc = null; this.forceAA = null; this.fromWordArt = null; this.horzOverflow = null; this.lIns = null; this.numCol = null; this.rIns = null; this.rot = null; this.rtlCol = null; this.spcCol = null; this.spcFirstLastPara = null; this.tIns = null; this.upright = null; this.vert = null; this.vertOverflow = null; this.wrap = null; this.textFit = null; this.prstTxWarp = null; this.parent = null; } InitClass(CBodyPr, CBaseNoIdObject, 0); CBodyPr.prototype.Get_Id = function () { return this.Id; }; CBodyPr.prototype.Refresh_RecalcData = function () { }; CBodyPr.prototype.setVertOpen = function (nVert) { let nVert_ = nVert; if(nVert === AscFormat.nVertTTwordArtVert) { nVert_ = AscFormat.nVertTTvert; } this.vert = nVert_; }; CBodyPr.prototype.getLnSpcReduction = function () { if (this.textFit && this.textFit.type === AscFormat.text_fit_NormAuto && AscFormat.isRealNumber(this.textFit.lnSpcReduction)) { return this.textFit.lnSpcReduction / 100000.0; } return undefined; }; CBodyPr.prototype.getFontScale = function () { if (this.textFit && this.textFit.type === AscFormat.text_fit_NormAuto && AscFormat.isRealNumber(this.textFit.fontScale)) { return this.textFit.fontScale / 100000.0; } return undefined; }; CBodyPr.prototype.isNotNull = function () { return this.flatTx !== null || this.anchor !== null || this.anchorCtr !== null || this.bIns !== null || this.compatLnSpc !== null || this.forceAA !== null || this.fromWordArt !== null || this.horzOverflow !== null || this.lIns !== null || this.numCol !== null || this.rIns !== null || this.rot !== null || this.rtlCol !== null || this.spcCol !== null || this.spcFirstLastPara !== null || this.tIns !== null || this.upright !== null || this.vert !== null || this.vertOverflow !== null || this.wrap !== null || this.textFit !== null || this.prstTxWarp !== null; }; CBodyPr.prototype.setAnchor = function (val) { this.anchor = val; }; CBodyPr.prototype.setVert = function (val) { this.vert = val; }; CBodyPr.prototype.setRot = function (val) { this.rot = val; }; CBodyPr.prototype.reset = function () { this.flatTx = null; this.anchor = null; this.anchorCtr = null; this.bIns = null; this.compatLnSpc = null; this.forceAA = null; this.fromWordArt = null; this.horzOverflow = null; this.lIns = null; this.numCol = null; this.rIns = null; this.rot = null; this.rtlCol = null; this.spcCol = null; this.spcFirstLastPara = null; this.tIns = null; this.upright = null; this.vert = null; this.vertOverflow = null; this.wrap = null; this.textFit = null; this.prstTxWarp = null; }; CBodyPr.prototype.WritePrstTxWarp = function (w) { w.WriteBool(isRealObject(this.prstTxWarp)); if (isRealObject(this.prstTxWarp)) { writeString(w, this.prstTxWarp.preset); var startPos = w.GetCurPosition(), countAv = 0; w.Skip(4); for (var key in this.prstTxWarp.avLst) { if (this.prstTxWarp.avLst.hasOwnProperty(key)) { ++countAv; w.WriteString2(key); w.WriteLong(this.prstTxWarp.gdLst[key]); } } var endPos = w.GetCurPosition(); w.Seek(startPos); w.WriteLong(countAv); w.Seek(endPos); } }; CBodyPr.prototype.ReadPrstTxWarp = function (r) { ExecuteNoHistory(function () { if (r.GetBool()) { this.prstTxWarp = AscFormat.CreatePrstTxWarpGeometry(readString(r)); var count = r.GetLong(); for (var i = 0; i < count; ++i) { var sAdj = r.GetString2(); var nVal = r.GetLong(); this.prstTxWarp.AddAdj(sAdj, 15, nVal + "", undefined, undefined); } } }, this, []); }; CBodyPr.prototype.Write_ToBinary2 = function (w) { var flag = this.flatTx != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.flatTx); } flag = this.anchor != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.anchor); } flag = this.anchorCtr != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.anchorCtr); } flag = this.bIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.bIns); } flag = this.compatLnSpc != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.compatLnSpc); } flag = this.forceAA != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.forceAA); } flag = this.fromWordArt != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.fromWordArt); } flag = this.horzOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.horzOverflow); } flag = this.lIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.lIns); } flag = this.numCol != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.numCol); } flag = this.rIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.rIns); } flag = this.rot != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.rot); } flag = this.rtlCol != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.rtlCol); } flag = this.spcCol != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.spcCol); } flag = this.spcFirstLastPara != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.spcFirstLastPara); } flag = this.tIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.tIns); } flag = this.upright != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.upright); } flag = this.vert != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vert); } flag = this.vertOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vertOverflow); } flag = this.wrap != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.wrap); } this.WritePrstTxWarp(w); w.WriteBool(isRealObject(this.textFit)); if (this.textFit) { this.textFit.Write_ToBinary(w); } }; CBodyPr.prototype.Read_FromBinary2 = function (r) { var flag = r.GetBool(); if (flag) { this.flatTx = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchor = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchorCtr = r.GetBool(); } flag = r.GetBool(); if (flag) { this.bIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.compatLnSpc = r.GetBool(); } flag = r.GetBool(); if (flag) { this.forceAA = r.GetBool(); } flag = r.GetBool(); if (flag) { this.fromWordArt = r.GetBool(); } flag = r.GetBool(); if (flag) { this.horzOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.lIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.numCol = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.rot = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rtlCol = r.GetBool(); } flag = r.GetBool(); if (flag) { this.spcCol = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.spcFirstLastPara = r.GetBool(); } flag = r.GetBool(); if (flag) { this.tIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.upright = r.GetBool(); } flag = r.GetBool(); if (flag) { this.vert = r.GetLong(); } flag = r.GetBool(); if (flag) { this.vertOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.wrap = r.GetLong(); } this.ReadPrstTxWarp(r); if (r.GetBool()) { this.textFit = new CTextFit(); this.textFit.Read_FromBinary(r); } }; CBodyPr.prototype.setDefault = function () { this.flatTx = null; this.anchor = 4; this.anchorCtr = false; this.bIns = 45720 / 36000; this.compatLnSpc = false; this.forceAA = false; this.fromWordArt = false; this.horzOverflow = AscFormat.nHOTOverflow; this.lIns = 91440 / 36000; this.numCol = 1; this.rIns = 91440 / 36000; this.rot = null; this.rtlCol = false; this.spcCol = false; this.spcFirstLastPara = null; this.tIns = 45720 / 36000; this.upright = false; this.vert = AscFormat.nVertTThorz; this.vertOverflow = AscFormat.nVOTOverflow; this.wrap = AscFormat.nTWTSquare; this.prstTxWarp = null; this.textFit = null; }; CBodyPr.prototype.createDuplicate = function () { var duplicate = new CBodyPr(); duplicate.flatTx = this.flatTx; duplicate.anchor = this.anchor; duplicate.anchorCtr = this.anchorCtr; duplicate.bIns = this.bIns; duplicate.compatLnSpc = this.compatLnSpc; duplicate.forceAA = this.forceAA; duplicate.fromWordArt = this.fromWordArt; duplicate.horzOverflow = this.horzOverflow; duplicate.lIns = this.lIns; duplicate.numCol = this.numCol; duplicate.rIns = this.rIns; duplicate.rot = this.rot; duplicate.rtlCol = this.rtlCol; duplicate.spcCol = this.spcCol; duplicate.spcFirstLastPara = this.spcFirstLastPara; duplicate.tIns = this.tIns; duplicate.upright = this.upright; duplicate.vert = this.vert; duplicate.vertOverflow = this.vertOverflow; duplicate.wrap = this.wrap; if (this.prstTxWarp) { duplicate.prstTxWarp = ExecuteNoHistory(function () { return this.prstTxWarp.createDuplicate(); }, this, []); } if (this.textFit) { duplicate.textFit = this.textFit.CreateDublicate(); } return duplicate; }; CBodyPr.prototype.createDuplicateForSmartArt = function (oPr) { var duplicate = new CBodyPr(); duplicate.anchor = this.anchor; duplicate.vert = this.vert; duplicate.rot = this.rot; duplicate.vertOverflow = this.vertOverflow; duplicate.horzOverflow = this.horzOverflow; duplicate.upright = this.upright; duplicate.rtlCol = this.rtlCol; duplicate.fromWordArt = this.fromWordArt; duplicate.compatLnSpc = this.compatLnSpc; duplicate.forceAA = this.forceAA; if (oPr.lIns) { duplicate.lIns = this.lIns; } if (oPr.rIns) { duplicate.rIns = this.rIns; } if (oPr.tIns) { duplicate.tIns = this.tIns; } if (oPr.bIns) { duplicate.bIns = this.bIns; } return duplicate; }; CBodyPr.prototype.merge = function (bodyPr) { if (!bodyPr) return; if (bodyPr.flatTx != null) { this.flatTx = bodyPr.flatTx; } if (bodyPr.anchor != null) { this.anchor = bodyPr.anchor; } if (bodyPr.anchorCtr != null) { this.anchorCtr = bodyPr.anchorCtr; } if (bodyPr.bIns != null) { this.bIns = bodyPr.bIns; } if (bodyPr.compatLnSpc != null) { this.compatLnSpc = bodyPr.compatLnSpc; } if (bodyPr.forceAA != null) { this.forceAA = bodyPr.forceAA; } if (bodyPr.fromWordArt != null) { this.fromWordArt = bodyPr.fromWordArt; } if (bodyPr.horzOverflow != null) { this.horzOverflow = bodyPr.horzOverflow; } if (bodyPr.lIns != null) { this.lIns = bodyPr.lIns; } if (bodyPr.numCol != null) { this.numCol = bodyPr.numCol; } if (bodyPr.rIns != null) { this.rIns = bodyPr.rIns; } if (bodyPr.rot != null) { this.rot = bodyPr.rot; } if (bodyPr.rtlCol != null) { this.rtlCol = bodyPr.rtlCol; } if (bodyPr.spcCol != null) { this.spcCol = bodyPr.spcCol; } if (bodyPr.spcFirstLastPara != null) { this.spcFirstLastPara = bodyPr.spcFirstLastPara; } if (bodyPr.tIns != null) { this.tIns = bodyPr.tIns; } if (bodyPr.upright != null) { this.upright = bodyPr.upright; } if (bodyPr.vert != null) { this.vert = bodyPr.vert; } if (bodyPr.vertOverflow != null) { this.vertOverflow = bodyPr.vertOverflow; } if (bodyPr.wrap != null) { this.wrap = bodyPr.wrap; } if (bodyPr.prstTxWarp) { this.prstTxWarp = ExecuteNoHistory(function () { return bodyPr.prstTxWarp.createDuplicate(); }, this, []); } if (bodyPr.textFit) { this.textFit = bodyPr.textFit.CreateDublicate(); } if (bodyPr.numCol != null) { this.numCol = bodyPr.numCol; } return this; }; CBodyPr.prototype.Write_ToBinary = function (w) { var flag = this.flatTx != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.flatTx); } flag = this.anchor != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.anchor); } flag = this.anchorCtr != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.anchorCtr); } flag = this.bIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.bIns); } flag = this.compatLnSpc != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.compatLnSpc); } flag = this.forceAA != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.forceAA); } flag = this.fromWordArt != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.fromWordArt); } flag = this.horzOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.horzOverflow); } flag = this.lIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.lIns); } flag = this.numCol != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.numCol); } flag = this.rIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.rIns); } flag = this.rot != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.rot); } flag = this.rtlCol != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.rtlCol); } flag = this.spcCol != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.spcCol); } flag = this.spcFirstLastPara != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.spcFirstLastPara); } flag = this.tIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.tIns); } flag = this.upright != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.upright); } flag = this.vert != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vert); } flag = this.vertOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vertOverflow); } flag = this.wrap != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.wrap); } this.WritePrstTxWarp(w); w.WriteBool(isRealObject(this.textFit)); if (this.textFit) { this.textFit.Write_ToBinary(w); } }; CBodyPr.prototype.Read_FromBinary = function (r) { var flag = r.GetBool(); if (flag) { this.flatTx = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchor = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchorCtr = r.GetBool(); } flag = r.GetBool(); if (flag) { this.bIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.compatLnSpc = r.GetBool(); } flag = r.GetBool(); if (flag) { this.forceAA = r.GetBool(); } flag = r.GetBool(); if (flag) { this.fromWordArt = r.GetBool(); } flag = r.GetBool(); if (flag) { this.horzOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.lIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.numCol = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.rot = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rtlCol = r.GetBool(); } flag = r.GetBool(); if (flag) { this.spcCol = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.spcFirstLastPara = r.GetBool(); } flag = r.GetBool(); if (flag) { this.tIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.upright = r.GetBool(); } flag = r.GetBool(); if (flag) { this.vert = r.GetLong(); } flag = r.GetBool(); if (flag) { this.vertOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.wrap = r.GetLong(); } this.ReadPrstTxWarp(r); if (r.GetBool()) { this.textFit = new CTextFit(); this.textFit.Read_FromBinary(r) } }; CBodyPr.prototype.readXmlInset = function (reader) { return reader.GetValueInt() / 36000; }; CBodyPr.prototype.getXmlInset = function (dVal) { if (!AscFormat.isRealNumber(dVal)) { return null; } return dVal * 36000 + 0.5 >> 0; }; CBodyPr.prototype.GetAnchorCode = function (sVal) { switch (sVal) { case "b": { return AscFormat.VERTICAL_ANCHOR_TYPE_BOTTOM; } case "ctr": { return AscFormat.VERTICAL_ANCHOR_TYPE_CENTER; } case "dist": { return AscFormat.VERTICAL_ANCHOR_TYPE_DISTRIBUTED; } case "just": { return AscFormat.VERTICAL_ANCHOR_TYPE_JUSTIFIED; } case "t": { return AscFormat.VERTICAL_ANCHOR_TYPE_TOP; } } }; CBodyPr.prototype.GetAnchorByCode = function (nCode) { switch (nCode) { case AscFormat.VERTICAL_ANCHOR_TYPE_BOTTOM: { return "b"; } case AscFormat.VERTICAL_ANCHOR_TYPE_CENTER: { return "ctr"; } case AscFormat.VERTICAL_ANCHOR_TYPE_DISTRIBUTED: { return "dist"; } case AscFormat.VERTICAL_ANCHOR_TYPE_JUSTIFIED: { return "just"; } case AscFormat.VERTICAL_ANCHOR_TYPE_TOP: { return "t" } } return null; }; CBodyPr.prototype.GetVertOverFlowCode = function (sVal) { switch (sVal) { case "clip": { return AscFormat.nVOTClip; } case "ellipsis": { return AscFormat.nVOTEllipsis; } case "overflow": { return AscFormat.nVOTOverflow; } } }; CBodyPr.prototype.GetHorOverFlowCode = function (sVal) { switch (sVal) { case "clip": { return AscFormat.nHOTClip; } case "overflow": { return AscFormat.nHOTOverflow; } } }; CBodyPr.prototype.GetVertOverFlowByCode = function (nCode) { switch (nCode) { case AscFormat.nVOTClip: { return "clip"; } case AscFormat.nVOTEllipsis : { return "ellipsis"; } case AscFormat.nVOTOverflow: { return "overflow"; } } }; CBodyPr.prototype.GetHorOverFlowByCode = function (nCode) { switch (nCode) { case AscFormat.nHOTClip: { return "clip"; } case AscFormat.nHOTOverflow: { return "overflow"; } } }; CBodyPr.prototype.GetVertCode = function (sVal) { switch (sVal) { case "eaVert": { return AscFormat.nVertTTeaVert; } case "horz": { return AscFormat.nVertTThorz; } case "mongolianVert": { return AscFormat.nVertTTmongolianVert; } case "vert": { return AscFormat.nVertTTvert; } case "vert270": { return AscFormat.nVertTTvert270; } case "wordArtVert": { return AscFormat.nVertTTwordArtVert; } case "wordArtVertRtl": { return AscFormat.nVertTTwordArtVertRtl; } } }; CBodyPr.prototype.GetVertByCode = function (nCode) { switch (nCode) { case AscFormat.nVertTTeaVert: { return "eaVert"; } case AscFormat.nVertTThorz: { return "horz"; } case AscFormat.nVertTTmongolianVert: { return "mongolianVert"; } case AscFormat.nVertTTvert: { return "vert"; } case AscFormat.nVertTTvert270: { return "vert270"; } case AscFormat.nVertTTwordArtVert: { return "wordArtVert"; } case AscFormat.nVertTTwordArtVertRtl: { return "wordArtVertRtl"; } } }; CBodyPr.prototype.GetWrapCode = function (sVal) { switch (sVal) { case "none": { return AscFormat.nTWTNone; } case "square": { return AscFormat.nTWTSquare; } } }; CBodyPr.prototype.GetWrapByCode = function (nCode) { switch (nCode) { case AscFormat.nTWTNone: { return "none"; } case AscFormat.nTWTSquare: { return "square"; } } }; CBodyPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "anchor": { let sVal = reader.GetValue(); this.anchor = this.GetAnchorCode(sVal); break; } case "anchorCtr": { this.anchorCtr = reader.GetValueBool(); break; } case "bIns": { this.bIns = this.readXmlInset(reader); break; } case "compatLnSpc": { this.compatLnSpc = reader.GetValueBool(); break; } case "forceAA": { this.forceAA = reader.GetValueBool(); break; } case "fromWordArt": { this.fromWordArt = reader.GetValueBool(); break; } case "horzOverflow": { let sVal = reader.GetValue(); this.horzOverflow = this.GetHorOverFlowCode(sVal); break; } case "lIns": { this.lIns = this.readXmlInset(reader); break; } case "numCol": { this.numCol = reader.GetValueInt(); break; } case "rIns": { this.rIns = this.readXmlInset(reader); break; } case "rot": { this.rot = reader.GetValueInt(); break; } case "rtlCol": { this.rtlCol = reader.GetValueBool(); break; } case "spcCol": { this.spcCol = this.readXmlInset(reader); break; } case "spcFirstLastPara": { this.spcFirstLastPara = reader.GetValueBool(); break; } case "tIns": { this.tIns = this.readXmlInset(reader); break; } case "upright": { this.upright = reader.GetValueBool(); break; } case "vert": { let sVal = reader.GetValue(); this.setVertOpen(this.GetVertCode(sVal)); break; } case "vertOverflow": { let sVal = reader.GetValue(); this.vertOverflow = this.GetVertOverFlowCode(sVal); break; } case "wrap": { let sVal = reader.GetValue(); this.wrap = this.GetWrapCode(sVal); break; } } }; CBodyPr.prototype.readChildXml = function (name, reader) { switch (name) { case "flatTx": { this.flatTx = AscCommon.CT_Int.prototype.toVal(reader, null); break; } case "noAutofit": { this.textFit = new CTextFit(AscFormat.text_fit_No); break; } case "normAutofit": { this.textFit = new CTextFit(AscFormat.text_fit_NormAuto); this.textFit.fromXml(reader); break; } case "prstTxWarp": { this.prstTxWarp = AscFormat.ExecuteNoHistory(function () { let oGeometry = new AscFormat.Geometry(); oGeometry.bWrap = true; oGeometry.fromXml(reader); return oGeometry; }, this, []); break; } case "scene3d": { //TODO: break; } case "sp3d": { //TODO break; } case "spAutoFit": { this.textFit = new CTextFit(AscFormat.text_fit_Auto); break; } } }; CBodyPr.prototype.toXml = function (writer, sNamespace) { let sNamespace_ = sNamespace || "a"; writer.WriteXmlNodeStart(sNamespace_ + ":bodyPr"); writer.WriteXmlNullableAttributeString("rot", this.rot); writer.WriteXmlNullableAttributeBool("spcFirstLastPara", this.spcFirstLastPara); writer.WriteXmlNullableAttributeString("vertOverflow", this.GetVertOverFlowByCode(this.vertOverflow)); writer.WriteXmlNullableAttributeString("horzOverflow", this.GetHorOverFlowByCode(this.horzOverflow)); writer.WriteXmlNullableAttributeString("vert", this.GetVertByCode(this.vert)); writer.WriteXmlNullableAttributeString("wrap", this.GetWrapByCode(this.wrap)); writer.WriteXmlNullableAttributeInt("lIns", this.getXmlInset(this.lIns)); writer.WriteXmlNullableAttributeInt("tIns", this.getXmlInset(this.tIns)); writer.WriteXmlNullableAttributeInt("rIns", this.getXmlInset(this.rIns)); writer.WriteXmlNullableAttributeInt("bIns", this.getXmlInset(this.bIns)); writer.WriteXmlNullableAttributeUInt("numCol", this.numCol); writer.WriteXmlNullableAttributeInt("spcCol", this.getXmlInset(this.spcCol)); writer.WriteXmlNullableAttributeBool("rtlCol", this.rtlCol); writer.WriteXmlNullableAttributeBool("fromWordArt", this.fromWordArt); writer.WriteXmlNullableAttributeString("anchor", this.GetAnchorByCode(this.anchor)); writer.WriteXmlNullableAttributeBool("anchorCtr", this.anchorCtr); writer.WriteXmlNullableAttributeBool("forceAA", this.forceAA); writer.WriteXmlNullableAttributeBool("upright", this.upright); writer.WriteXmlNullableAttributeBool("compatLnSpc", this.compatLnSpc); if(this.prstTxWarp || this.textFit || AscFormat.isRealNumber(this.flatTx)) { writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.prstTxWarp, "a:prstTxWarp"); writer.WriteXmlNullable(this.textFit); //writer.WriteXmlNullable(this.scene3d); //writer.WriteXmlNullable(this.sp3d); if (AscFormat.isRealNumber(this.flatTx)) { writer.WriteXmlNodeStart(sNamespace_ + ":flatTx"); writer.WriteXmlNullableAttributeString("z", this.flatTx); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd(sNamespace_ + ":flatTx"); } writer.WriteXmlNodeEnd(sNamespace_ + ":bodyPr"); } else { writer.WriteXmlAttributesEnd(true); } }; function CTextParagraphPr() { this.bullet = new CBullet(); this.lvl = null; this.pPr = new CParaPr(); this.rPr = new CTextPr(); } function CreateNoneBullet() { var ret = new CBullet(); ret.bulletType = new CBulletType(); ret.bulletType.type = AscFormat.BULLET_TYPE_BULLET_NONE; return ret; } function CompareBullets(bullet1, bullet2) { //TODO: ะฟะพะบะฐ ะฑัƒะดะตะผ ัั€ะฐะฒะฝะธะฒะฐั‚ัŒ ั‚ะพะปัŒะบะพ bulletType, ั‚. ะบ. ัั‚ะฐ ั„ัƒะฝะบั†ะธั ะธัะฟะพะปัŒะทัƒะตั‚ัั ะดะปั ะผะตั€ะถะฐ ัะฒะพะนัั‚ะฒ ะฟั€ะธ ะพั‚ะดะฐั‡ะต ะฒ ะธะฝั‚ะตั€ั„ะตะนั, ะฐ ะดะปั ะธะฝั‚ะตั€ั„ะตะนัะฐ bulletTyp'a ะดะพัั‚ะฐั‚ะพั‡ะฝะพ. ะ•ัะปะธ ะฟะพะฝะฐะดะพะฑะธั‚ัั ะฝัƒะถะฝะพ ัะดะตะปะฐั‚ัŒ ะฟะพะปะฝะพะต ัั€ะฐะฒะฝะตะฝะธะต. // if (bullet1.bulletType && bullet2.bulletType && bullet1.bulletType.type === bullet2.bulletType.type) { var ret = new CBullet(); ret.bulletType = new CBulletType(); switch (bullet1.bulletType.type) { case AscFormat.BULLET_TYPE_BULLET_CHAR: { ret.bulletType.type = AscFormat.BULLET_TYPE_BULLET_CHAR; if (bullet1.bulletType.Char === bullet2.bulletType.Char) { ret.bulletType.Char = bullet1.bulletType.Char; } break; } case AscFormat.BULLET_TYPE_BULLET_BLIP: { ret.bulletType.type = AscFormat.BULLET_TYPE_BULLET_BLIP; var compareBlip = bullet1.bulletType.Blip && bullet2.bulletType.Blip && bullet1.bulletType.Blip.compare(bullet2.bulletType.Blip); ret.bulletType.Blip = compareBlip; break; } case AscFormat.BULLET_TYPE_BULLET_AUTONUM: { if (bullet1.bulletType.AutoNumType === bullet2.bulletType.AutoNumType) { ret.bulletType.AutoNumType = bullet1.bulletType.AutoNumType; } if (bullet1.bulletType.startAt === bullet2.bulletType.startAt) { ret.bulletType.startAt = bullet1.bulletType.startAt; } else { ret.bulletType.startAt = undefined; } if (bullet1.bulletType.type === bullet2.bulletType.type) { ret.bulletType.type = bullet1.bulletType.type; } break; } } if (bullet1.bulletSize && bullet2.bulletSize && bullet1.bulletSize.val === bullet2.bulletSize.val && bullet1.bulletSize.type === bullet2.bulletSize.type) { ret.bulletSize = bullet1.bulletSize; } if (bullet1.bulletColor && bullet2.bulletColor && bullet1.bulletColor.type === bullet2.bulletColor.type) { ret.bulletColor = new CBulletColor(); ret.bulletColor.type = bullet2.bulletColor.type; if (bullet1.bulletColor.UniColor) { ret.bulletColor.UniColor = bullet1.bulletColor.UniColor.compare(bullet2.bulletColor.UniColor); } if (!ret.bulletColor.UniColor || !ret.bulletColor.UniColor.color) { ret.bulletColor = null; } } return ret; } else { return undefined; } } function CBullet() { CBaseNoIdObject.call(this) this.bulletColor = null; this.bulletSize = null; this.bulletTypeface = null; this.bulletType = null; this.Bullet = null; //used to get properties for interface this.FirstTextPr = null; } InitClass(CBullet, CBaseNoIdObject, 0); CBullet.prototype.Set_FromObject = function (obj) { if (obj) { if (obj.bulletColor) { this.bulletColor = new CBulletColor(); this.bulletColor.Set_FromObject(obj.bulletColor); } else this.bulletColor = null; if (obj.bulletSize) { this.bulletSize = new CBulletSize(); this.bulletSize.Set_FromObject(obj.bulletSize); } else this.bulletSize = null; if (obj.bulletTypeface) { this.bulletTypeface = new CBulletTypeface(); this.bulletTypeface.Set_FromObject(obj.bulletTypeface); } else this.bulletTypeface = null; } }; CBullet.prototype.merge = function (oBullet) { if (!oBullet) { return; } if (oBullet.bulletColor) { if (!this.bulletColor) { this.bulletColor = oBullet.bulletColor.createDuplicate(); } else { this.bulletColor.merge(oBullet.bulletColor); } } if (oBullet.bulletSize) { if (!this.bulletSize) { this.bulletSize = oBullet.bulletSize.createDuplicate(); } else { this.bulletSize.merge(oBullet.bulletSize); } } if (oBullet.bulletTypeface) { if (!this.bulletTypeface) { this.bulletTypeface = oBullet.bulletTypeface.createDuplicate(); } else { this.bulletTypeface.merge(oBullet.bulletTypeface); } } if (oBullet.bulletType) { if (!this.bulletType) { this.bulletType = oBullet.bulletType.createDuplicate(); } else { this.bulletType.merge(oBullet.bulletType); } } }; CBullet.prototype.createDuplicate = function () { var duplicate = new CBullet(); if (this.bulletColor) { duplicate.bulletColor = this.bulletColor.createDuplicate(); } if (this.bulletSize) { duplicate.bulletSize = this.bulletSize.createDuplicate(); } if (this.bulletTypeface) { duplicate.bulletTypeface = this.bulletTypeface.createDuplicate(); } if (this.bulletType) { duplicate.bulletType = this.bulletType.createDuplicate(); } duplicate.Bullet = this.Bullet; return duplicate; }; CBullet.prototype.isBullet = function () { return this.bulletType != null && this.bulletType.type != null; }; CBullet.prototype.getPresentationBullet = function (theme, color) { var para_pr = new CParaPr(); para_pr.Bullet = this; return para_pr.Get_PresentationBullet(theme, color); }; CBullet.prototype.getBulletType = function (theme, color) { return this.getPresentationBullet(theme, color).m_nType; }; CBullet.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.bulletColor)); if (isRealObject(this.bulletColor)) { this.bulletColor.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bulletSize)); if (isRealObject(this.bulletSize)) { this.bulletSize.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bulletTypeface)); if (isRealObject(this.bulletTypeface)) { this.bulletTypeface.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bulletType)); if (isRealObject(this.bulletType)) { this.bulletType.Write_ToBinary(w); } }; CBullet.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.bulletColor = new CBulletColor(); this.bulletColor.Read_FromBinary(r); } if (r.GetBool()) { this.bulletSize = new CBulletSize(); this.bulletSize.Read_FromBinary(r); } if (r.GetBool()) { this.bulletTypeface = new CBulletTypeface(); this.bulletTypeface.Read_FromBinary(r); } if (r.GetBool()) { this.bulletType = new CBulletType(); this.bulletType.Read_FromBinary(r); } }; CBullet.prototype.Get_AllFontNames = function (AllFonts) { if (this.bulletTypeface && typeof this.bulletTypeface.typeface === "string" && this.bulletTypeface.typeface.length > 0) { AllFonts[this.bulletTypeface.typeface] = true; } }; CBullet.prototype.putNumStartAt = function (NumStartAt) { if (!this.bulletType) { this.bulletType = new CBulletType(); } this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_AUTONUM; this.bulletType.startAt = NumStartAt; }; CBullet.prototype.getNumStartAt = function () { if (this.bulletType) { if (AscFormat.isRealNumber(this.bulletType.startAt)) { return Math.max(1, this.bulletType.startAt); } } return undefined; }; CBullet.prototype.isEqual = function (oBullet) { if (!oBullet) { return false; } if (!this.bulletColor && oBullet.bulletColor || !oBullet.bulletColor && this.bulletColor) { return false; } if (this.bulletColor && oBullet.bulletColor) { if (!this.bulletColor.IsIdentical(oBullet.bulletColor)) { return false; } } if (!this.bulletSize && oBullet.bulletSize || this.bulletSize && !oBullet.bulletSize) { return false; } if (this.bulletSize && oBullet.bulletSize) { if (!this.bulletSize.IsIdentical(oBullet.bulletSize)) { return false; } } if (!this.bulletTypeface && oBullet.bulletTypeface || this.bulletTypeface && !oBullet.bulletTypeface) { return false; } if (this.bulletTypeface && oBullet.bulletTypeface) { if (!this.bulletTypeface.IsIdentical(oBullet.bulletTypeface)) { return false; } } if (!this.bulletType && oBullet.bulletType || this.bulletType && !oBullet.bulletType) { return false; } if (this.bulletType && oBullet.bulletType) { if (!this.bulletType.IsIdentical(oBullet.bulletType)) { return false; } } return true; }; CBullet.prototype.fillBulletImage = function (url) { this.bulletType = new CBulletType(); this.bulletType.Blip = new AscFormat.CBuBlip(); this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_BLIP; this.bulletType.Blip.setBlip(AscFormat.CreateBlipFillUniFillFromUrl(url)); }; CBullet.prototype.fillBulletFromCharAndFont = function (char, font) { this.bulletType = new AscFormat.CBulletType(); this.bulletTypeface = new AscFormat.CBulletTypeface(); this.bulletTypeface.type = AscFormat.BULLET_TYPE_TYPEFACE_BUFONT; this.bulletTypeface.typeface = font || AscFonts.FontPickerByCharacter.getFontBySymbol(char.getUnicodeIterator().value()); this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_CHAR; this.bulletType.Char = char; }; CBullet.prototype.getImageBulletURL = function () { var res = (this.bulletType && this.bulletType.Blip && this.bulletType.Blip.blip && this.bulletType.Blip.blip.fill && this.bulletType.Blip.blip.fill.RasterImageId); return res ? res : null; }; CBullet.prototype.setImageBulletURL = function (url) { var blipFill = (this.bulletType && this.bulletType.Blip && this.bulletType.Blip.blip && this.bulletType.Blip.blip.fill); if (blipFill) { blipFill.setRasterImageId(url); } }; CBullet.prototype.drawSquareImage = function (sDivId, nRelativeIndent) { nRelativeIndent = nRelativeIndent || 0; const sImageUrl = this.getImageBulletURL(); const oApi = editor || Asc.editor; if (!sImageUrl || !oApi) { return; } const oDiv = document.getElementById(sDivId); if (!oDiv) { return; } const nWidth = oDiv.clientWidth; const nHeight = oDiv.clientHeight; const nRPR = AscCommon.AscBrowser.retinaPixelRatio; const nCanvasSide = Math.min(nWidth, nHeight) * nRPR; let oCanvas = oDiv.firstChild; if (!oCanvas) { oCanvas = document.createElement('canvas'); oCanvas.style.cssText = "padding:0;margin:0;user-select:none;"; oCanvas.style.width = oDiv.clientWidth + 'px'; oCanvas.style.height = oDiv.clientHeight + 'px'; oCanvas.width = nCanvasSide; oCanvas.height = nCanvasSide; oDiv.appendChild(oCanvas); } const oContext = oCanvas.getContext('2d'); oContext.fillStyle = "white"; oContext.fillRect(0, 0, oCanvas.width, oCanvas.height); const oImage = oApi.ImageLoader.map_image_index[AscCommon.getFullImageSrc2(sImageUrl)]; if (oImage && oImage.Image && oImage.Status !== AscFonts.ImageLoadStatus.Loading) { const nImageWidth = oImage.Image.width; const nImageHeight = oImage.Image.height; const absoluteIndent = nCanvasSide * nRelativeIndent; const nSideSizeWithoutIndent = nCanvasSide - 2 * absoluteIndent; const nAdaptCoefficient = Math.max(nImageWidth / nSideSizeWithoutIndent, nImageHeight / nSideSizeWithoutIndent); const nImageAdaptWidth = nImageWidth / nAdaptCoefficient; const nImageAdaptHeight = nImageHeight / nAdaptCoefficient; const nX = (nCanvasSide - nImageAdaptWidth) / 2; const nY = (nCanvasSide - nImageAdaptHeight) / 2; oContext.drawImage(oImage.Image, nX, nY, nImageAdaptWidth, nImageAdaptHeight); } }; CBullet.prototype.readChildXml = function (name, reader) { switch (name) { case "buAutoNum": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_AUTONUM); this.bulletType.fromXml(reader); break; } case "buBlip": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_BLIP); this.bulletType.fromXml(reader); break; } case "buChar": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_CHAR); this.bulletType.fromXml(reader); break; } case "buClr": { this.bulletColor = new CBulletColor(AscFormat.BULLET_TYPE_COLOR_CLR); this.bulletColor.fromXml(reader); break; } case "buClrTx": { this.bulletColor = new CBulletColor(AscFormat.BULLET_TYPE_COLOR_CLRTX); this.bulletColor.fromXml(reader); break; } case "buFont": { this.bulletTypeface = new CBulletTypeface(AscFormat.BULLET_TYPE_TYPEFACE_BUFONT); this.bulletTypeface.fromXml(reader); break; } case "buFontTx": { this.bulletTypeface = new CBulletTypeface(AscFormat.BULLET_TYPE_TYPEFACE_TX); this.bulletTypeface.fromXml(reader); break; } case "buNone": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_NONE); this.bulletType.fromXml(reader); break; } case "buSzPct": { this.bulletSize = new CBulletSize(AscFormat.BULLET_TYPE_SIZE_PCT); this.bulletSize.fromXml(reader); break; } case "buSzPts": { this.bulletSize = new CBulletSize(AscFormat.BULLET_TYPE_SIZE_PTS); this.bulletSize.fromXml(reader); break; } case "buSzTx": { this.bulletSize = new CBulletSize(AscFormat.BULLET_TYPE_SIZE_TX); this.bulletSize.fromXml(reader); break; } } }; CBullet.prototype.toXml = function (writer) { if (this.bulletColor) { this.bulletColor.toXml(writer); } if (this.bulletSize) { this.bulletSize.toXml(writer); } if (this.bulletTypeface) { this.bulletTypeface.toXml(writer); } if (this.bulletType) { this.bulletType.toXml(writer); } }; //interface methods var prot = CBullet.prototype; prot["fillBulletImage"] = prot["asc_fillBulletImage"] = CBullet.prototype.fillBulletImage; prot["fillBulletFromCharAndFont"] = prot["asc_fillBulletFromCharAndFont"] = CBullet.prototype.fillBulletFromCharAndFont; prot["drawSquareImage"] = prot["asc_drawSquareImage"] = CBullet.prototype.drawSquareImage; prot.getImageId = function () { return this.getImageBulletURL(); } prot["getImageId"] = prot["asc_getImageId"] = CBullet.prototype.getImageId; prot.put_ImageUrl = function (sUrl, token) { var _this = this; var Api = editor || Asc.editor; if (!Api) { return; } AscCommon.sendImgUrls(Api, [sUrl], function (data) { if (data && data[0] && data[0].url !== "error") { var url = AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path); Api.ImageLoader.LoadImagesWithCallback([AscCommon.getFullImageSrc2(url)], function () { _this.fillBulletImage(url); //_this.drawSquareImage(); Api.sendEvent("asc_onBulletImageLoaded", _this); }); } }, false, false, token); }; prot["put_ImageUrl"] = prot["asc_putImageUrl"] = CBullet.prototype.put_ImageUrl; prot.showFileDialog = function () { var Api = editor || Asc.editor; if (!Api) { return; } var _this = this; AscCommon.ShowImageFileDialog(Api.documentId, Api.documentUserId, Api.CoAuthoringApi.get_jwt(), function (error, files) { if (Asc.c_oAscError.ID.No !== error) { Api.sendEvent("asc_onError", error, Asc.c_oAscError.Level.NoCritical); } else { Api.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); AscCommon.UploadImageFiles(files, Api.documentId, Api.documentUserId, Api.CoAuthoringApi.get_jwt(), function (error, urls) { if (Asc.c_oAscError.ID.No !== error) { Api.sendEvent("asc_onError", error, Asc.c_oAscError.Level.NoCritical); Api.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); } else { Api.ImageLoader.LoadImagesWithCallback(urls, function () { if (urls.length > 0) { _this.fillBulletImage(urls[0]); //_this.drawSquareImage(); Api.sendEvent("asc_onBulletImageLoaded", _this); } Api.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); }); } }); } }, function (error) { if (Asc.c_oAscError.ID.No !== error) { Api.sendEvent("asc_onError", error, Asc.c_oAscError.Level.NoCritical); } Api.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); }); }; prot["showFileDialog"] = prot["asc_showFileDialog"] = CBullet.prototype.showFileDialog; prot.asc_getSize = function () { var nRet = 100; if (this.bulletSize) { switch (this.bulletSize.type) { case AscFormat.BULLET_TYPE_SIZE_NONE: { break; } case AscFormat.BULLET_TYPE_SIZE_TX: { break; } case AscFormat.BULLET_TYPE_SIZE_PCT: { nRet = this.bulletSize.val / 1000.0; break; } case AscFormat.BULLET_TYPE_SIZE_PTS: { break; } } } return nRet; }; prot["get_Size"] = prot["asc_getSize"] = CBullet.prototype.asc_getSize; prot.asc_putSize = function (Size) { if (AscFormat.isRealNumber(Size)) { this.bulletSize = new AscFormat.CBulletSize(); this.bulletSize.type = AscFormat.BULLET_TYPE_SIZE_PCT; this.bulletSize.val = (Size * 1000) >> 0; } }; prot["put_Size"] = prot["asc_putSize"] = CBullet.prototype.asc_putSize; prot.asc_getColor = function () { if (this.bulletColor) { if (this.bulletColor.UniColor) { return AscCommon.CreateAscColor(this.bulletColor.UniColor); } } else { var FirstTextPr = this.FirstTextPr; if (FirstTextPr && FirstTextPr.Unifill) { if (FirstTextPr.Unifill.fill instanceof AscFormat.CSolidFill && FirstTextPr.Unifill.fill.color) { return AscCommon.CreateAscColor(FirstTextPr.Unifill.fill.color); } else { var RGBA = FirstTextPr.Unifill.getRGBAColor(); return AscCommon.CreateAscColorCustom(RGBA.R, RGBA.G, RGBA.B); } } } return AscCommon.CreateAscColorCustom(0, 0, 0); }; prot["get_Color"] = prot["asc_getColor"] = prot.asc_getColor; prot.asc_putColor = function (color) { this.bulletColor = new AscFormat.CBulletColor(); this.bulletColor.type = AscFormat.BULLET_TYPE_COLOR_CLR; this.bulletColor.UniColor = AscFormat.CorrectUniColor(color, this.bulletColor.UniColor, 0); }; prot["put_Color"] = prot["asc_putColor"] = prot.asc_putColor; prot.asc_getFont = function () { var sRet = ""; if (this.bulletTypeface && this.bulletTypeface.type === AscFormat.BULLET_TYPE_TYPEFACE_BUFONT && typeof this.bulletTypeface.typeface === "string" && this.bulletTypeface.typeface.length > 0) { sRet = this.bulletTypeface.typeface; } else { var FirstTextPr = this.FirstTextPr; if (FirstTextPr && FirstTextPr.FontFamily && typeof FirstTextPr.FontFamily.Name === "string" && FirstTextPr.FontFamily.Name.length > 0) { sRet = FirstTextPr.FontFamily.Name; } } return sRet; }; prot["get_Font"] = prot["asc_getFont"] = prot.asc_getFont; prot.asc_putFont = function (val) { if (typeof val === "string" && val.length > 0) { this.bulletTypeface = new AscFormat.CBulletTypeface(); this.bulletTypeface.type = AscFormat.BULLET_TYPE_TYPEFACE_BUFONT; this.bulletTypeface.typeface = val; } }; prot["put_Font"] = prot["asc_putFont"] = prot.asc_putFont; prot.asc_putNumStartAt = function (NumStartAt) { this.putNumStartAt(NumStartAt); }; prot["put_NumStartAt"] = prot["asc_putNumStartAt"] = prot.asc_putNumStartAt; prot.asc_getNumStartAt = function () { return this.getNumStartAt(); }; prot["get_NumStartAt"] = prot["asc_getNumStartAt"] = prot.asc_getNumStartAt; prot.asc_getSymbol = function () { if (this.bulletType && this.bulletType.type === AscFormat.BULLET_TYPE_BULLET_CHAR) { return this.bulletType.Char; } return undefined; }; prot["get_Symbol"] = prot["asc_getSymbol"] = prot.asc_getSymbol; prot.asc_putSymbol = function (v) { if (!this.bulletType) { this.bulletType = new CBulletType(); } this.bulletType.AutoNumType = 0; this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_CHAR; this.bulletType.Char = v; }; prot["put_Symbol"] = prot["asc_putSymbol"] = prot.asc_putSymbol; prot.asc_putAutoNumType = function (val) { if (!this.bulletType) { this.bulletType = new CBulletType(); } this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_AUTONUM; this.bulletType.AutoNumType = AscFormat.getNumberingType(val); }; prot["put_AutoNumType"] = prot["asc_putAutoNumType"] = prot.asc_putAutoNumType; prot.asc_getAutoNumType = function () { if (this.bulletType && this.bulletType.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { return AscFormat.fGetListTypeFromBullet(this).SubType; } return -1; }; prot["get_AutoNumType"] = prot["asc_getAutoNumType"] = prot.asc_getAutoNumType; prot.asc_putListType = function (type, subtype, custom) { var NumberInfo = { Type: type, SubType: subtype, Custom: custom }; AscFormat.fFillBullet(NumberInfo, this); }; prot["put_ListType"] = prot["asc_putListType"] = prot.asc_putListType; prot.asc_getListType = function () { return new AscCommon.asc_CListType(AscFormat.fGetListTypeFromBullet(this)); }; prot.asc_getType = function () { return this.bulletType && this.bulletType.type; }; prot["get_Type"] = prot["asc_getType"] = prot.asc_getType; window["Asc"]["asc_CBullet"] = window["Asc"].asc_CBullet = CBullet; function CBulletColor(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : AscFormat.BULLET_TYPE_COLOR_CLRTX; this.UniColor = null; } InitClass(CBulletColor, CBaseNoIdObject, 0); CBulletColor.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletColor.prototype.merge = function (oBulletColor) { if (!oBulletColor) { return; } if (oBulletColor.UniColor) { this.type = oBulletColor.type; this.UniColor = oBulletColor.UniColor.createDuplicate(); } }; CBulletColor.prototype.IsIdentical = function (oBulletColor) { if (!oBulletColor) { return false; } if (this.type !== oBulletColor.type) { return false; } if (this.UniColor && !oBulletColor.UniColor || oBulletColor.UniColor && !this.UniColor) { return false; } if (this.UniColor) { if (!this.UniColor.IsIdentical(oBulletColor.UniColor)) { return false; } } return true; }; CBulletColor.prototype.createDuplicate = function () { var duplicate = new CBulletColor(); duplicate.type = this.type; if (this.UniColor != null) { duplicate.UniColor = this.UniColor.createDuplicate(); } return duplicate; }; CBulletColor.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(isRealObject(this.UniColor)); if (isRealObject(this.UniColor)) { this.UniColor.Write_ToBinary(w); } }; CBulletColor.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { this.UniColor = new CUniColor(); this.UniColor.Read_FromBinary(r); } }; CBulletColor.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { if (this.type === AscFormat.BULLET_TYPE_COLOR_CLR) { this.UniColor = new CUniColor(); this.UniColor.fromXml(reader, name); } } }; CBulletColor.prototype.toXml = function (writer) { if (this.type === AscFormat.BULLET_TYPE_COLOR_CLR) { writer.WriteXmlNodeStart("a:buClr"); writer.WriteXmlAttributesEnd(); if (this.UniColor) { this.UniColor.toXml(writer); } writer.WriteXmlNodeEnd("a:buClr"); } else { writer.WriteXmlString("<a:buClrTx/>"); } }; function CBulletSize(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : AscFormat.BULLET_TYPE_SIZE_NONE; this.val = 0; } InitClass(CBulletSize, CBaseNoIdObject, 0); CBulletSize.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletSize.prototype.merge = function (oBulletSize) { if (!oBulletSize) { return; } this.type = oBulletSize.type; this.val = oBulletSize.val; }; CBulletSize.prototype.createDuplicate = function () { var d = new CBulletSize(); d.type = this.type; d.val = this.val; return d; }; CBulletSize.prototype.IsIdentical = function (oBulletSize) { if (!oBulletSize) { return false; } return this.type === oBulletSize.type && this.val === oBulletSize.val; }; CBulletSize.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(isRealNumber(this.val)); if (isRealNumber(this.val)) { w.WriteLong(this.val); } }; CBulletSize.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { (this.val) = r.GetLong(); } }; CBulletSize.prototype.readAttrXml = function (name, reader) { switch (name) { case "val": { if (this.type === AscFormat.BULLET_TYPE_SIZE_PCT) { this.val = reader.GetValueInt(); } else if (this.type === AscFormat.BULLET_TYPE_SIZE_PTS) { this.val = reader.GetValueInt(); } break; } } }; CBulletSize.prototype.toXml = function (writer) { if (this.type === AscFormat.BULLET_TYPE_SIZE_PCT) { writer.WriteXmlNodeStart("a:buSzPct"); writer.WriteXmlNullableAttributeInt("val", this.val); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:buSzPct"); } else if (this.type === AscFormat.BULLET_TYPE_SIZE_PTS) { writer.WriteXmlNodeStart("a:buSzPts"); writer.WriteXmlNullableAttributeString("val", this.val); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:buSzPts"); } else { writer.WriteXmlString("<a:buSzTx/>"); } }; function CBulletTypeface(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : AscFormat.BULLET_TYPE_TYPEFACE_NONE; this.typeface = ""; } InitClass(CBulletTypeface, CBaseNoIdObject, 0); CBulletTypeface.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletTypeface.prototype.createDuplicate = function () { var d = new CBulletTypeface(); d.type = this.type; d.typeface = this.typeface; return d; }; CBulletTypeface.prototype.merge = function (oBulletTypeface) { if (!oBulletTypeface) { return; } this.type = oBulletTypeface.type; this.typeface = oBulletTypeface.typeface; }; CBulletTypeface.prototype.IsIdentical = function (oBulletTypeface) { if (!oBulletTypeface) { return false; } return this.type === oBulletTypeface.type && this.typeface === oBulletTypeface.typeface; }; CBulletTypeface.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(typeof this.typeface === "string"); if (typeof this.typeface === "string") { w.WriteString2(this.typeface); } }; CBulletTypeface.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { (this.typeface) = r.GetString2(); } }; CBulletTypeface.prototype.readAttrXml = function (name, reader) { switch (name) { case "typeface": { if (this.type === AscFormat.BULLET_TYPE_TYPEFACE_BUFONT) { this.typeface = reader.GetValue(); } break; } } }; CBulletTypeface.prototype.toXml = function (writer) { if (this.type === AscFormat.BULLET_TYPE_TYPEFACE_BUFONT) { FontCollection.prototype.writeFont.call(this, writer, "a:buFont", this.typeface); } else { writer.WriteXmlString("<a:buFontTx/>"); } }; var numbering_presentationnumfrmt_AlphaLcParenBoth = 0; var numbering_presentationnumfrmt_AlphaLcParenR = 1; var numbering_presentationnumfrmt_AlphaLcPeriod = 2; var numbering_presentationnumfrmt_AlphaUcParenBoth = 3; var numbering_presentationnumfrmt_AlphaUcParenR = 4; var numbering_presentationnumfrmt_AlphaUcPeriod = 5; var numbering_presentationnumfrmt_Arabic1Minus = 6; var numbering_presentationnumfrmt_Arabic2Minus = 7; var numbering_presentationnumfrmt_ArabicDbPeriod = 8; var numbering_presentationnumfrmt_ArabicDbPlain = 9; var numbering_presentationnumfrmt_ArabicParenBoth = 10; var numbering_presentationnumfrmt_ArabicParenR = 11; var numbering_presentationnumfrmt_ArabicPeriod = 12; var numbering_presentationnumfrmt_ArabicPlain = 13; var numbering_presentationnumfrmt_CircleNumDbPlain = 14; var numbering_presentationnumfrmt_CircleNumWdBlackPlain = 15; var numbering_presentationnumfrmt_CircleNumWdWhitePlain = 16; var numbering_presentationnumfrmt_Ea1ChsPeriod = 17; var numbering_presentationnumfrmt_Ea1ChsPlain = 18; var numbering_presentationnumfrmt_Ea1ChtPeriod = 19; var numbering_presentationnumfrmt_Ea1ChtPlain = 20; var numbering_presentationnumfrmt_Ea1JpnChsDbPeriod = 21; var numbering_presentationnumfrmt_Ea1JpnKorPeriod = 22; var numbering_presentationnumfrmt_Ea1JpnKorPlain = 23; var numbering_presentationnumfrmt_Hebrew2Minus = 24; var numbering_presentationnumfrmt_HindiAlpha1Period = 25; var numbering_presentationnumfrmt_HindiAlphaPeriod = 26; var numbering_presentationnumfrmt_HindiNumParenR = 27; var numbering_presentationnumfrmt_HindiNumPeriod = 28; var numbering_presentationnumfrmt_RomanLcParenBoth = 29; var numbering_presentationnumfrmt_RomanLcParenR = 30; var numbering_presentationnumfrmt_RomanLcPeriod = 31; var numbering_presentationnumfrmt_RomanUcParenBoth = 32; var numbering_presentationnumfrmt_RomanUcParenR = 33; var numbering_presentationnumfrmt_RomanUcPeriod = 34; var numbering_presentationnumfrmt_ThaiAlphaParenBoth = 35; var numbering_presentationnumfrmt_ThaiAlphaParenR = 36; var numbering_presentationnumfrmt_ThaiAlphaPeriod = 37; var numbering_presentationnumfrmt_ThaiNumParenBoth = 38; var numbering_presentationnumfrmt_ThaiNumParenR = 39; var numbering_presentationnumfrmt_ThaiNumPeriod = 40; var numbering_presentationnumfrmt_None = 100; var numbering_presentationnumfrmt_Char = 101; var numbering_presentationnumfrmt_Blip = 102; AscFormat.numbering_presentationnumfrmt_AlphaLcParenBoth = numbering_presentationnumfrmt_AlphaLcParenBoth; AscFormat.numbering_presentationnumfrmt_AlphaLcParenR = numbering_presentationnumfrmt_AlphaLcParenR; AscFormat.numbering_presentationnumfrmt_AlphaLcPeriod = numbering_presentationnumfrmt_AlphaLcPeriod; AscFormat.numbering_presentationnumfrmt_AlphaUcParenBoth = numbering_presentationnumfrmt_AlphaUcParenBoth; AscFormat.numbering_presentationnumfrmt_AlphaUcParenR = numbering_presentationnumfrmt_AlphaUcParenR; AscFormat.numbering_presentationnumfrmt_AlphaUcPeriod = numbering_presentationnumfrmt_AlphaUcPeriod; AscFormat.numbering_presentationnumfrmt_Arabic1Minus = numbering_presentationnumfrmt_Arabic1Minus; AscFormat.numbering_presentationnumfrmt_Arabic2Minus = numbering_presentationnumfrmt_Arabic2Minus; AscFormat.numbering_presentationnumfrmt_ArabicDbPeriod = numbering_presentationnumfrmt_ArabicDbPeriod; AscFormat.numbering_presentationnumfrmt_ArabicDbPlain = numbering_presentationnumfrmt_ArabicDbPlain; AscFormat.numbering_presentationnumfrmt_ArabicParenBoth = numbering_presentationnumfrmt_ArabicParenBoth; AscFormat.numbering_presentationnumfrmt_ArabicParenR = numbering_presentationnumfrmt_ArabicParenR; AscFormat.numbering_presentationnumfrmt_ArabicPeriod = numbering_presentationnumfrmt_ArabicPeriod; AscFormat.numbering_presentationnumfrmt_ArabicPlain = numbering_presentationnumfrmt_ArabicPlain; AscFormat.numbering_presentationnumfrmt_CircleNumDbPlain = numbering_presentationnumfrmt_CircleNumDbPlain; AscFormat.numbering_presentationnumfrmt_CircleNumWdBlackPlain = numbering_presentationnumfrmt_CircleNumWdBlackPlain; AscFormat.numbering_presentationnumfrmt_CircleNumWdWhitePlain = numbering_presentationnumfrmt_CircleNumWdWhitePlain; AscFormat.numbering_presentationnumfrmt_Ea1ChsPeriod = numbering_presentationnumfrmt_Ea1ChsPeriod; AscFormat.numbering_presentationnumfrmt_Ea1ChsPlain = numbering_presentationnumfrmt_Ea1ChsPlain; AscFormat.numbering_presentationnumfrmt_Ea1ChtPeriod = numbering_presentationnumfrmt_Ea1ChtPeriod; AscFormat.numbering_presentationnumfrmt_Ea1ChtPlain = numbering_presentationnumfrmt_Ea1ChtPlain; AscFormat.numbering_presentationnumfrmt_Ea1JpnChsDbPeriod = numbering_presentationnumfrmt_Ea1JpnChsDbPeriod; AscFormat.numbering_presentationnumfrmt_Ea1JpnKorPeriod = numbering_presentationnumfrmt_Ea1JpnKorPeriod; AscFormat.numbering_presentationnumfrmt_Ea1JpnKorPlain = numbering_presentationnumfrmt_Ea1JpnKorPlain; AscFormat.numbering_presentationnumfrmt_Hebrew2Minus = numbering_presentationnumfrmt_Hebrew2Minus; AscFormat.numbering_presentationnumfrmt_HindiAlpha1Period = numbering_presentationnumfrmt_HindiAlpha1Period; AscFormat.numbering_presentationnumfrmt_HindiAlphaPeriod = numbering_presentationnumfrmt_HindiAlphaPeriod; AscFormat.numbering_presentationnumfrmt_HindiNumParenR = numbering_presentationnumfrmt_HindiNumParenR; AscFormat.numbering_presentationnumfrmt_HindiNumPeriod = numbering_presentationnumfrmt_HindiNumPeriod; AscFormat.numbering_presentationnumfrmt_RomanLcParenBoth = numbering_presentationnumfrmt_RomanLcParenBoth; AscFormat.numbering_presentationnumfrmt_RomanLcParenR = numbering_presentationnumfrmt_RomanLcParenR; AscFormat.numbering_presentationnumfrmt_RomanLcPeriod = numbering_presentationnumfrmt_RomanLcPeriod; AscFormat.numbering_presentationnumfrmt_RomanUcParenBoth = numbering_presentationnumfrmt_RomanUcParenBoth; AscFormat.numbering_presentationnumfrmt_RomanUcParenR = numbering_presentationnumfrmt_RomanUcParenR; AscFormat.numbering_presentationnumfrmt_RomanUcPeriod = numbering_presentationnumfrmt_RomanUcPeriod; AscFormat.numbering_presentationnumfrmt_ThaiAlphaParenBoth = numbering_presentationnumfrmt_ThaiAlphaParenBoth; AscFormat.numbering_presentationnumfrmt_ThaiAlphaParenR = numbering_presentationnumfrmt_ThaiAlphaParenR; AscFormat.numbering_presentationnumfrmt_ThaiAlphaPeriod = numbering_presentationnumfrmt_ThaiAlphaPeriod; AscFormat.numbering_presentationnumfrmt_ThaiNumParenBoth = numbering_presentationnumfrmt_ThaiNumParenBoth; AscFormat.numbering_presentationnumfrmt_ThaiNumParenR = numbering_presentationnumfrmt_ThaiNumParenR; AscFormat.numbering_presentationnumfrmt_ThaiNumPeriod = numbering_presentationnumfrmt_ThaiNumPeriod; AscFormat.numbering_presentationnumfrmt_None = numbering_presentationnumfrmt_None; AscFormat.numbering_presentationnumfrmt_Char = numbering_presentationnumfrmt_Char; AscFormat.numbering_presentationnumfrmt_Blip = numbering_presentationnumfrmt_Blip; var MAP_AUTONUM_TYPES = {}; MAP_AUTONUM_TYPES["alphaLcParenBot"] = numbering_presentationnumfrmt_AlphaLcParenBoth; MAP_AUTONUM_TYPES["alphaLcParen"] = numbering_presentationnumfrmt_AlphaLcParenR; MAP_AUTONUM_TYPES["alphaLcPerio"] = numbering_presentationnumfrmt_AlphaLcPeriod; MAP_AUTONUM_TYPES["alphaUcParenBot"] = numbering_presentationnumfrmt_AlphaUcParenBoth; MAP_AUTONUM_TYPES["alphaUcParen"] = numbering_presentationnumfrmt_AlphaUcParenR; MAP_AUTONUM_TYPES["alphaUcPerio"] = numbering_presentationnumfrmt_AlphaUcPeriod; MAP_AUTONUM_TYPES["arabic1Minu"] = numbering_presentationnumfrmt_Arabic1Minus; MAP_AUTONUM_TYPES["arabic2Minu"] = numbering_presentationnumfrmt_Arabic2Minus; MAP_AUTONUM_TYPES["arabicDbPerio"] = numbering_presentationnumfrmt_ArabicDbPeriod; MAP_AUTONUM_TYPES["arabicDbPlai"] = numbering_presentationnumfrmt_ArabicDbPlain; MAP_AUTONUM_TYPES["arabicParenBoth"] = numbering_presentationnumfrmt_ArabicParenBoth; MAP_AUTONUM_TYPES["arabicParenR"] = numbering_presentationnumfrmt_ArabicParenR; MAP_AUTONUM_TYPES["arabicPeriod"] = numbering_presentationnumfrmt_ArabicPeriod; MAP_AUTONUM_TYPES["arabicPlain"] = numbering_presentationnumfrmt_ArabicPlain; MAP_AUTONUM_TYPES["circleNumDbPlain"] = numbering_presentationnumfrmt_CircleNumDbPlain; MAP_AUTONUM_TYPES["circleNumWdBlackPlain"] = numbering_presentationnumfrmt_CircleNumWdBlackPlain; MAP_AUTONUM_TYPES["circleNumWdWhitePlain"] = numbering_presentationnumfrmt_CircleNumWdWhitePlain; MAP_AUTONUM_TYPES["ea1ChsPeriod"] = numbering_presentationnumfrmt_Ea1ChsPeriod; MAP_AUTONUM_TYPES["ea1ChsPlain"] = numbering_presentationnumfrmt_Ea1ChsPlain; MAP_AUTONUM_TYPES["ea1ChtPeriod"] = numbering_presentationnumfrmt_Ea1ChtPeriod; MAP_AUTONUM_TYPES["ea1ChtPlain"] = numbering_presentationnumfrmt_Ea1ChtPlain; MAP_AUTONUM_TYPES["ea1JpnChsDbPeriod"] = numbering_presentationnumfrmt_Ea1JpnChsDbPeriod; MAP_AUTONUM_TYPES["ea1JpnKorPeriod"] = numbering_presentationnumfrmt_Ea1JpnKorPeriod; MAP_AUTONUM_TYPES["ea1JpnKorPlain"] = numbering_presentationnumfrmt_Ea1JpnKorPlain; MAP_AUTONUM_TYPES["hebrew2Minus"] = numbering_presentationnumfrmt_Hebrew2Minus; MAP_AUTONUM_TYPES["hindiAlpha1Period"] = numbering_presentationnumfrmt_HindiAlpha1Period; MAP_AUTONUM_TYPES["hindiAlphaPeriod"] = numbering_presentationnumfrmt_HindiAlphaPeriod; MAP_AUTONUM_TYPES["hindiNumParenR"] = numbering_presentationnumfrmt_HindiNumParenR; MAP_AUTONUM_TYPES["hindiNumPeriod"] = numbering_presentationnumfrmt_HindiNumPeriod; MAP_AUTONUM_TYPES["romanLcParenBoth"] = numbering_presentationnumfrmt_RomanLcParenBoth; MAP_AUTONUM_TYPES["romanLcParenR"] = numbering_presentationnumfrmt_RomanLcParenR; MAP_AUTONUM_TYPES["romanLcPeriod"] = numbering_presentationnumfrmt_RomanLcPeriod; MAP_AUTONUM_TYPES["romanUcParenBoth"] = numbering_presentationnumfrmt_RomanUcParenBoth; MAP_AUTONUM_TYPES["romanUcParenR"] = numbering_presentationnumfrmt_RomanUcParenR; MAP_AUTONUM_TYPES["romanUcPeriod"] = numbering_presentationnumfrmt_RomanUcPeriod; MAP_AUTONUM_TYPES["thaiAlphaParenBoth"] = numbering_presentationnumfrmt_ThaiAlphaParenBoth; MAP_AUTONUM_TYPES["thaiAlphaParenR"] = numbering_presentationnumfrmt_ThaiAlphaParenR; MAP_AUTONUM_TYPES["thaiAlphaPeriod"] = numbering_presentationnumfrmt_ThaiAlphaPeriod; MAP_AUTONUM_TYPES["thaiNumParenBoth"] = numbering_presentationnumfrmt_ThaiNumParenBoth; MAP_AUTONUM_TYPES["thaiNumParenR"] = numbering_presentationnumfrmt_ThaiNumParenR; MAP_AUTONUM_TYPES["thaiNumPeriod"] = numbering_presentationnumfrmt_ThaiNumPeriod; function CBulletType(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : null;//BULLET_TYPE_BULLET_NONE; this.Char = null; this.AutoNumType = null; this.Blip = null; this.startAt = null; } InitClass(CBulletType, CBaseNoIdObject, 0); CBulletType.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletType.prototype.IsIdentical = function (oBulletType) { if (!oBulletType) { return false; } return this.type === oBulletType.type && this.Char === oBulletType.Char && this.AutoNumType === oBulletType.AutoNumType && this.startAt === oBulletType.startAt && ((this.Blip && this.Blip.isEqual(oBulletType.Blip)) || this.Blip === oBulletType.Blip); }; CBulletType.prototype.merge = function (oBulletType) { if (!oBulletType) { return; } if (oBulletType.type !== null && this.type !== oBulletType.type) { this.type = oBulletType.type; this.Char = oBulletType.Char; this.AutoNumType = oBulletType.AutoNumType; this.startAt = oBulletType.startAt; if (oBulletType.Blip) { this.Blip = oBulletType.Blip.createDuplicate(); } } else { if (this.type === AscFormat.BULLET_TYPE_BULLET_CHAR) { if (typeof oBulletType.Char === "string" && oBulletType.Char.length > 0) { if (this.Char !== oBulletType.Char) { this.Char = oBulletType.Char; } } } if (this.type === AscFormat.BULLET_TYPE_BULLET_BLIP) { if (this.Blip instanceof AscFormat.CBuBlip && this.Blip !== oBulletType.Blip) { this.Blip = oBulletType.Blip.createDuplicate(); } } if (this.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { if (oBulletType.AutoNumType !== null && this.AutoNumType !== oBulletType.AutoNumType) { this.AutoNumType = oBulletType.AutoNumType; } if (oBulletType.startAt !== null && this.startAt !== oBulletType.startAt) { this.startAt = oBulletType.startAt; } } } }; CBulletType.prototype.createDuplicate = function () { var d = new CBulletType(); d.type = this.type; d.Char = this.Char; d.AutoNumType = this.AutoNumType; d.startAt = this.startAt; if (this.Blip) { d.Blip = this.Blip.createDuplicate(); } return d; }; CBulletType.prototype.setBlip = function (oPr) { this.Blip = oPr; }; CBulletType.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(typeof this.Char === "string"); if (typeof this.Char === "string") { w.WriteString2(this.Char); } w.WriteBool(isRealNumber(this.AutoNumType)); if (isRealNumber(this.AutoNumType)) { w.WriteLong(this.AutoNumType); } w.WriteBool(isRealNumber(this.startAt)); if (isRealNumber(this.startAt)) { w.WriteLong(this.startAt); } w.WriteBool(isRealObject(this.Blip)); if (isRealObject(this.Blip)) { this.Blip.Write_ToBinary(w); } }; CBulletType.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { (this.Char) = r.GetString2(); if (AscFonts.IsCheckSymbols) AscFonts.FontPickerByCharacter.getFontsByString(this.Char); } if (r.GetBool()) { (this.AutoNumType) = r.GetLong(); } if (r.GetBool()) { (this.startAt) = r.GetLong(); } if (r.GetBool()) { this.Blip = new CBuBlip(); this.Blip.Read_FromBinary(r); var oUnifill = this.Blip.blip; var sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if (typeof AscCommon.CollaborativeEditing !== "undefined") { if (typeof sRasterImageId === "string" && sRasterImageId.length > 0) { AscCommon.CollaborativeEditing.Add_NewImage(sRasterImageId); } } } }; CBulletType.prototype.readAttrXml = function (name, reader) { switch (name) { case "startAt": { if (this.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { this.startAt = reader.GetValueInt(); } break; } case "type": { if (this.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { let sVal = reader.GetValue(); let nType = MAP_AUTONUM_TYPES[sVal]; if (AscFormat.isRealNumber(nType)) { this.AutoNumType = nType; } } break; } case "char": { if (this.type === AscFormat.BULLET_TYPE_BULLET_CHAR) { this.Char = reader.GetValue(); } } } }; CBulletType.prototype.GetAutonumTypeByCode = function (nCode) { switch (nCode) { case numbering_presentationnumfrmt_AlphaLcParenBoth: { return "alphaLcParenBot"; } case numbering_presentationnumfrmt_AlphaLcParenR: { return "alphaLcParen"; } case numbering_presentationnumfrmt_AlphaLcPeriod: { return "alphaLcPerio"; } case numbering_presentationnumfrmt_AlphaUcParenBoth: { return "alphaUcParenBot"; } case numbering_presentationnumfrmt_AlphaUcParenR: { return "alphaUcParen"; } case numbering_presentationnumfrmt_AlphaUcPeriod: { return "alphaUcPerio"; } case numbering_presentationnumfrmt_Arabic1Minus: { return "arabic1Minu"; } case numbering_presentationnumfrmt_Arabic2Minus: { return "arabic2Minu"; } case numbering_presentationnumfrmt_ArabicDbPeriod: { return "arabicDbPerio"; } case numbering_presentationnumfrmt_ArabicDbPlain: { return "arabicDbPlai"; } case numbering_presentationnumfrmt_ArabicParenBoth: { return "arabicParenBoth"; } case numbering_presentationnumfrmt_ArabicParenR: { return "arabicParenR"; } case numbering_presentationnumfrmt_ArabicPeriod: { return "arabicPeriod"; } case numbering_presentationnumfrmt_ArabicPlain: { return "arabicPlain"; } case numbering_presentationnumfrmt_CircleNumDbPlain: { return "circleNumDbPlain"; } case numbering_presentationnumfrmt_CircleNumWdBlackPlain: { return "circleNumWdBlackPlain"; } case numbering_presentationnumfrmt_CircleNumWdWhitePlain: { return "circleNumWdWhitePlain"; } case numbering_presentationnumfrmt_Ea1ChsPeriod: { return "ea1ChsPeriod"; } case numbering_presentationnumfrmt_Ea1ChsPlain: { return "ea1ChsPlain"; } case numbering_presentationnumfrmt_Ea1ChtPeriod: { return "ea1ChtPeriod"; } case numbering_presentationnumfrmt_Ea1ChtPlain: { return "ea1ChtPlain"; } case numbering_presentationnumfrmt_Ea1JpnChsDbPeriod: { return "ea1JpnChsDbPeriod"; } case numbering_presentationnumfrmt_Ea1JpnKorPeriod: { return "ea1JpnKorPeriod"; } case numbering_presentationnumfrmt_Ea1JpnKorPlain: { return "ea1JpnKorPlain"; } case numbering_presentationnumfrmt_Hebrew2Minus: { return "hebrew2Minus"; } case numbering_presentationnumfrmt_HindiAlpha1Period: { return "hindiAlpha1Period"; } case numbering_presentationnumfrmt_HindiAlphaPeriod: { return "hindiAlphaPeriod"; } case numbering_presentationnumfrmt_HindiNumParenR: { return "hindiNumParenR"; } case numbering_presentationnumfrmt_HindiNumPeriod: { return "hindiNumPeriod"; } case numbering_presentationnumfrmt_RomanLcParenBoth: { return "romanLcParenBoth"; } case numbering_presentationnumfrmt_RomanLcParenR: { return "romanLcParenR"; } case numbering_presentationnumfrmt_RomanLcPeriod: { return "romanLcPeriod"; } case numbering_presentationnumfrmt_RomanUcParenBoth: { return "romanUcParenBoth"; } case numbering_presentationnumfrmt_RomanUcParenR: { return "romanUcParenR"; } case numbering_presentationnumfrmt_RomanUcPeriod: { return "romanUcPeriod"; } case numbering_presentationnumfrmt_ThaiAlphaParenBoth: { return "thaiAlphaParenBoth"; } case numbering_presentationnumfrmt_ThaiAlphaParenR: { return "thaiAlphaParenR"; } case numbering_presentationnumfrmt_ThaiAlphaPeriod: { return "thaiAlphaPeriod"; } case numbering_presentationnumfrmt_ThaiNumParenBoth: { return "thaiNumParenBoth"; } case numbering_presentationnumfrmt_ThaiNumParenR: { return "thaiNumParenR"; } case numbering_presentationnumfrmt_ThaiNumPeriod: { return "thaiNumPeriod"; } } }; CBulletType.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { if (this.type === AscFormat.BULLET_TYPE_BULLET_BLIP) { this.Blip = new CBuBlip(); this.Blip.blip = new CUniFill(); this.Blip.blip.fromXml(reader, "blipFill"); this.Blip.blip.readChildXml(reader, "blip"); } break; } } }; CBulletType.prototype.toXml = function (writer) { switch (this.type) { case AscFormat.BULLET_TYPE_BULLET_NONE: { writer.WriteXmlString("<a:buNone/>"); break; } case AscFormat.BULLET_TYPE_BULLET_CHAR: { writer.WriteXmlNodeStart("a:buChar"); writer.WriteXmlNullableAttributeString("char", this.Char); writer.WriteXmlAttributesEnd(true); break; } case AscFormat.BULLET_TYPE_BULLET_AUTONUM: { writer.WriteXmlNodeStart("a:buAutoNum"); writer.WriteXmlNullableAttributeString("type", this.GetAutonumTypeByCode(this.AutoNumType)); writer.WriteXmlNullableAttributeUInt("startAt", this.startAt); writer.WriteXmlAttributesEnd(true); break; } case AscFormat.BULLET_TYPE_BULLET_BLIP: { if(this.Blip) { writer.WriteXmlNodeStart("a:blip"); writer.WriteXmlAttributesEnd(); this.Blip.toXml(writer); writer.WriteXmlNodeEnd("a:blip"); } break; } } }; function TextListStyle() { CBaseNoIdObject.call(this); this.levels = new Array(10); for (var i = 0; i < 10; i++) this.levels[i] = null; } InitClass(TextListStyle, CBaseNoIdObject, 0); TextListStyle.prototype.Get_Id = function () { return this.Id; }; TextListStyle.prototype.Refresh_RecalcData = function () { }; TextListStyle.prototype.createDuplicate = function () { var duplicate = new TextListStyle(); for (var i = 0; i < 10; ++i) { if (this.levels[i] != null) { duplicate.levels[i] = this.levels[i].Copy(); } } return duplicate; }; TextListStyle.prototype.Write_ToBinary = function (w) { for (var i = 0; i < 10; ++i) { w.WriteBool(isRealObject(this.levels[i])); if (isRealObject(this.levels[i])) { this.levels[i].Write_ToBinary(w); } } }; TextListStyle.prototype.Read_FromBinary = function (r) { for (var i = 0; i < 10; ++i) { if (r.GetBool()) { this.levels[i] = new CParaPr(); this.levels[i].Read_FromBinary(r); } else { this.levels[i] = null; } } }; TextListStyle.prototype.merge = function (oTextListStyle) { if (!oTextListStyle) { return; } for (var i = 0; i < this.levels.length; ++i) { if (oTextListStyle.levels[i]) { if (this.levels[i]) { this.levels[i].Merge(oTextListStyle.levels[i]); } else { this.levels[i] = oTextListStyle.levels[i].Copy(); } } } }; TextListStyle.prototype.Document_Get_AllFontNames = function (AllFonts) { for (var i = 0; i < 10; ++i) { if (this.levels[i]) { if (this.levels[i].DefaultRunPr) { this.levels[i].DefaultRunPr.Document_Get_AllFontNames(AllFonts); } if (this.levels[i].Bullet) { this.levels[i].Bullet.Get_AllFontNames(AllFonts); } } } }; TextListStyle.prototype.readChildXml = function (name, reader) { let nIdx = null; if (name.indexOf("lvl") === 0) { nIdx = parseInt(name.charAt(3)) - 1; } else if (name === "defPPr") { nIdx = 9; } if (AscFormat.isRealNumber(nIdx)) { let oParaPr = new AscCommonWord.CParaPr(); oParaPr.fromDrawingML(reader); this.levels[nIdx] = oParaPr; } }; TextListStyle.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); if(this.levels[9] || this.levels[0] || this.levels[1] || this.levels[2] || this.levels[3] || this.levels[4] || this.levels[5] || this.levels[6] || this.levels[7] || this.levels[8]) { writer.WriteXmlAttributesEnd(); this.levels[9] && this.levels[9].toDrawingML(writer,"a:defPPr"); this.levels[0] && this.levels[0].toDrawingML(writer,"a:lvl1pPr"); this.levels[1] && this.levels[1].toDrawingML(writer,"a:lvl2pPr"); this.levels[2] && this.levels[2].toDrawingML(writer,"a:lvl3pPr"); this.levels[3] && this.levels[3].toDrawingML(writer,"a:lvl4pPr"); this.levels[4] && this.levels[4].toDrawingML(writer,"a:lvl5pPr"); this.levels[5] && this.levels[5].toDrawingML(writer,"a:lvl6pPr"); this.levels[6] && this.levels[6].toDrawingML(writer,"a:lvl7pPr"); this.levels[7] && this.levels[7].toDrawingML(writer,"a:lvl8pPr"); this.levels[8] && this.levels[8].toDrawingML(writer,"a:lvl9pPr"); writer.WriteXmlNodeEnd(sName); } else { writer.WriteXmlAttributesEnd(true); } }; function CBaseAttrObject() { CBaseNoIdObject.call(this); this.attr = {}; } InitClass(CBaseAttrObject, CBaseNoIdObject, 0); CBaseAttrObject.prototype.readAttrXml = function (name, reader) { this.attr[name] = reader.GetValue(); }; CBaseAttrObject.prototype.readChildXml = function (name, reader) { }; CBaseAttrObject.prototype.toXml = function (writer) { //TODO:Implement in children }; AscFormat.CBaseAttrObject = CBaseAttrObject; function CChangesCorePr(Class, Old, New, Color) { AscDFH.CChangesBase.call(this, Class, Old, New, Color); if (Old && New) { this.OldTitle = Old.title; this.OldCreator = Old.creator; this.OldDescription = Old.description; this.OldSubject = Old.subject; this.NewTitle = New.title === Old.title ? undefined : New.title; this.NewCreator = New.creator === Old.creator ? undefined : New.creator; this.NewDescription = New.description === Old.description ? undefined : New.description; this.NewSubject = New.subject === Old.subject ? undefined : New.subject; } else { this.OldTitle = undefined; this.OldCreator = undefined; this.OldDescription = undefined; this.OldSubject = undefined; this.NewTitle = undefined; this.NewCreator = undefined; this.NewDescription = undefined; this.NewSubject = undefined; } } CChangesCorePr.prototype = Object.create(AscDFH.CChangesBase.prototype); CChangesCorePr.prototype.constructor = CChangesCorePr; CChangesCorePr.prototype.Type = AscDFH.historyitem_CoreProperties; CChangesCorePr.prototype.Undo = function () { if (!this.Class) { return; } this.Class.title = this.OldTitle; this.Class.creator = this.OldCreator; this.Class.description = this.OldDescription; this.Class.subject = this.OldSubject; }; CChangesCorePr.prototype.Redo = function () { if (!this.Class) { return; } if (this.NewTitle !== undefined) { this.Class.title = this.NewTitle; } if (this.NewCreator !== undefined) { this.Class.creator = this.NewCreator; } if (this.NewDescription !== undefined) { this.Class.description = this.NewDescription; } if (this.NewSubject !== undefined) { this.Class.subject = this.NewSubject; } }; CChangesCorePr.prototype.WriteToBinary = function (Writer) { var nFlags = 0; if (undefined !== this.NewTitle) { nFlags |= 1; } if (undefined !== this.NewCreator) { nFlags |= 2; } if (undefined !== this.NewDescription) { nFlags |= 4; } if (undefined !== this.NewSubject) { nFlags |= 8; } Writer.WriteLong(nFlags); var bIsField; if (nFlags & 1) { bIsField = typeof this.NewTitle === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewTitle); } } if (nFlags & 2) { bIsField = typeof this.NewCreator === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewCreator); } } if (nFlags & 4) { bIsField = typeof this.NewDescription === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewDescription); } } if (nFlags & 8) { bIsField = typeof this.NewSubject === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewSubject); } } }; CChangesCorePr.prototype.ReadFromBinary = function (Reader) { var nFlags = Reader.GetLong(); var bIsField; if (nFlags & 1) { bIsField = Reader.GetBool(); if (bIsField) { this.NewTitle = Reader.GetString2(); } else { this.NewTitle = null; } } if (nFlags & 2) { bIsField = Reader.GetBool(); if (bIsField) { this.NewCreator = Reader.GetString2(); } else { this.NewCreator = null; } } if (nFlags & 4) { bIsField = Reader.GetBool(); if (bIsField) { this.NewDescription = Reader.GetString2(); } else { this.NewDescription = null; } } if (nFlags & 8) { bIsField = Reader.GetBool(); if (bIsField) { this.NewSubject = Reader.GetString2(); } else { this.NewSubject = null; } } }; CChangesCorePr.prototype.CreateReverseChange = function () { var ret = new CChangesCorePr(this.Class); ret.OldTitle = this.NewTitle; ret.OldCreator = this.NewCreator; ret.OldDescription = this.NewCreator; ret.OldSubject = this.NewSubject; ret.NewTitle = this.OldTitle; ret.NewCreator = this.OldCreator; ret.NewDescription = this.OldCreator; ret.NewSubject = this.OldSubject; return ret; }; AscDFH.changesFactory[AscDFH.historyitem_CoreProperties] = CChangesCorePr; function CCore() { AscFormat.CBaseFormatObject.call(this); this.category = null; this.contentStatus = null;//Status in menu this.created = null; this.creator = null;// Authors in menu this.description = null;//Comments in menu this.identifier = null; this.keywords = null; this.language = null; this.lastModifiedBy = null; this.lastPrinted = null; this.modified = null; this.revision = null; this.subject = null; this.title = null; this.version = null; this.Lock = new AscCommon.CLock(); this.lockType = AscCommon.c_oAscLockTypes.kLockTypeNone; } InitClass(CCore, CBaseFormatObject, AscDFH.historyitem_type_Core); CCore.prototype.fromStream = function (s) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.title = s.GetString2(); break; } case 1: { this.creator = s.GetString2(); break; } case 2: { this.lastModifiedBy = s.GetString2(); break; } case 3: { this.revision = s.GetString2(); break; } case 4: { this.created = this.readDate(s.GetString2()); break; } case 5: { this.modified = this.readDate(s.GetString2()); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { var _end_rec2 = s.cur + s.GetLong() + 4; s.Skip2(1); // start attributes while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 6: { this.category = s.GetString2(); break; } case 7: { this.contentStatus = s.GetString2(); break; } case 8: { this.description = s.GetString2(); break; } case 9: { this.identifier = s.GetString2(); break; } case 10: { this.keywords = s.GetString2(); break; } case 11: { this.language = s.GetString2(); break; } case 12: { this.lastPrinted = this.readDate(s.GetString2()); break; } case 13: { this.subject = s.GetString2(); break; } case 14: { this.version = s.GetString2(); break; } default: return; } } s.Seek2(_end_rec2); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CCore.prototype.readDate = function (val) { val = new Date(val); return val instanceof Date && !isNaN(val) ? val : null; }; CCore.prototype.toStream = function (s, api) { s.StartRecord(AscCommon.c_oMainTables.Core); s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.title); s._WriteString2(1, this.creator); if (api && api.DocInfo) { s._WriteString2(2, api.DocInfo.get_UserName()); } var revision = 0; if (this.revision) { var rev = parseInt(this.revision); if (!isNaN(rev)) { revision = rev; } } s._WriteString2(3, (revision + 1).toString()); if (this.created) { s._WriteString2(4, this.created.toISOString().slice(0, 19) + 'Z'); } s._WriteString2(5, new Date().toISOString().slice(0, 19) + 'Z'); s.WriteUChar(g_nodeAttributeEnd); s.StartRecord(0); s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(6, this.category); s._WriteString2(7, this.contentStatus); s._WriteString2(8, this.description); s._WriteString2(9, this.identifier); s._WriteString2(10, this.keywords); s._WriteString2(11, this.language); // we don't track it // if (this.lastPrinted) { // s._WriteString1(12, this.lastPrinted.toISOString().slice(0, 19) + 'Z'); // } s._WriteString2(13, this.subject); s._WriteString2(14, this.version); s.WriteUChar(g_nodeAttributeEnd); s.EndRecord(); s.EndRecord(); }; CCore.prototype.asc_getTitle = function () { return this.title; }; CCore.prototype.asc_getCreator = function () { return this.creator; }; CCore.prototype.asc_getLastModifiedBy = function () { return this.lastModifiedBy; }; CCore.prototype.asc_getRevision = function () { return this.revision; }; CCore.prototype.asc_getCreated = function () { return this.created; }; CCore.prototype.asc_getModified = function () { return this.modified; }; CCore.prototype.asc_getCategory = function () { return this.category; }; CCore.prototype.asc_getContentStatus = function () { return this.contentStatus; }; CCore.prototype.asc_getDescription = function () { return this.description; }; CCore.prototype.asc_getIdentifier = function () { return this.identifier; }; CCore.prototype.asc_getKeywords = function () { return this.keywords; }; CCore.prototype.asc_getLanguage = function () { return this.language; }; CCore.prototype.asc_getLastPrinted = function () { return this.lastPrinted; }; CCore.prototype.asc_getSubject = function () { return this.subject; }; CCore.prototype.asc_getVersion = function () { return this.version; }; CCore.prototype.asc_putTitle = function (v) { this.title = v; }; CCore.prototype.asc_putCreator = function (v) { this.creator = v; }; CCore.prototype.asc_putLastModifiedBy = function (v) { this.lastModifiedBy = v; }; CCore.prototype.asc_putRevision = function (v) { this.revision = v; }; CCore.prototype.asc_putCreated = function (v) { this.created = v; }; CCore.prototype.asc_putModified = function (v) { this.modified = v; }; CCore.prototype.asc_putCategory = function (v) { this.category = v; }; CCore.prototype.asc_putContentStatus = function (v) { this.contentStatus = v; }; CCore.prototype.asc_putDescription = function (v) { this.description = v; }; CCore.prototype.asc_putIdentifier = function (v) { this.identifier = v; }; CCore.prototype.asc_putKeywords = function (v) { this.keywords = v; }; CCore.prototype.asc_putLanguage = function (v) { this.language = v; }; CCore.prototype.asc_putLastPrinted = function (v) { this.lastPrinted = v; }; CCore.prototype.asc_putSubject = function (v) { this.subject = v; }; CCore.prototype.asc_putVersion = function (v) { this.version = v; }; CCore.prototype.setProps = function (oProps) { History.Add(new CChangesCorePr(this, this, oProps, null)); this.title = oProps.title; this.creator = oProps.creator; this.description = oProps.description; this.subject = oProps.subject; }; CCore.prototype.Refresh_RecalcData = function () { }; CCore.prototype.Refresh_RecalcData2 = function () { }; CCore.prototype.copy = function () { return AscFormat.ExecuteNoHistory(function () { var oCopy = new CCore(); oCopy.category = this.category; oCopy.contentStatus = this.contentStatus; oCopy.created = this.created; oCopy.creator = this.creator; oCopy.description = this.description; oCopy.identifier = this.identifier; oCopy.keywords = this.keywords; oCopy.language = this.language; oCopy.lastModifiedBy = this.lastModifiedBy; oCopy.lastPrinted = this.lastPrinted; oCopy.modified = this.modified; oCopy.revision = this.revision; oCopy.subject = this.subject; oCopy.title = this.title; oCopy.version = this.version; return oCopy; }, this, []); }; CCore.prototype.writeDate = function(writer, sName, oDate) { if (!oDate) { return; } let sToWrite = oDate.toISOString().slice(0, 19) + 'Z'; writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributeString("xsi:type", "dcterms:W3CDTF"); writer.WriteXmlAttributesEnd(); writer.WriteXmlString(sToWrite); writer.WriteXmlNodeEnd(sName); } CCore.prototype.readChildXml = function (name, reader) { switch (name) { case "category": { this.category = reader.GetTextDecodeXml(); break; } case "contentStatus": { this.contentStatus = reader.GetTextDecodeXml(); break; } case "created": { this.created = this.readDate(reader.GetTextDecodeXml()); break; } case "creator": { this.creator = reader.GetTextDecodeXml(); break; } case "description": { this.description = reader.GetTextDecodeXml(); break; } case "identifier": { this.identifier = reader.GetTextDecodeXml(); break; } case "keywords": { this.keywords = reader.GetTextDecodeXml(); break; } case "language": { this.language = reader.GetTextDecodeXml(); break; } case "lastModifiedBy": { this.lastModifiedBy = reader.GetTextDecodeXml(); break; } case "lastPrinted": { this.lastPrinted = this.readDate(reader.GetTextDecodeXml()); break; } case "modified": { this.modified = this.readDate(reader.GetTextDecodeXml()); break; } case "revision": { this.revision = reader.GetTextDecodeXml(); break; } case "subject": { this.subject = reader.GetTextDecodeXml(); break; } case "title": { this.title = reader.GetTextDecodeXml(); break; } case "version": { this.version = reader.GetTextDecodeXml(); break; } } }; CCore.prototype.toXmlImpl = function(writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); writer.WriteXmlNodeStart("cp:coreProperties"); writer.WriteXmlNullableAttributeString("xmlns:cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); writer.WriteXmlNullableAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/"); writer.WriteXmlNullableAttributeString("xmlns:dcterms", "http://purl.org/dc/terms/"); writer.WriteXmlNullableAttributeString("xmlns:dcmitype", "http://purl.org/dc/dcmitype/"); writer.WriteXmlNullableAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullableValueStringEncode2("dc:title", this.title); writer.WriteXmlNullableValueStringEncode2("dc:subject", this.subject); writer.WriteXmlNullableValueStringEncode2("dc:creator", this.creator); writer.WriteXmlNullableValueStringEncode2("cp:keywords", this.keywords); writer.WriteXmlNullableValueStringEncode2("dc:description", this.description); writer.WriteXmlNullableValueStringEncode2("dc:identifier", this.identifier); writer.WriteXmlNullableValueStringEncode2("dc:language", this.language); writer.WriteXmlNullableValueStringEncode2("cp:lastModifiedBy", this.lastModifiedBy); writer.WriteXmlNullableValueStringEncode2("cp:revision", this.revision); if (this.lastPrinted && this.lastPrinted.length > 0) { writer.WriteXmlNullableValueStringEncode2("cp:lastPrinted", this.lastPrinted); } this.writeDate(writer, "dcterms:created", this.created); this.writeDate(writer, "dcterms:modified", this.modified); writer.WriteXmlNullableValueStringEncode2("cp:category", this.category); writer.WriteXmlNullableValueStringEncode2("cp:contentStatus", this.contentStatus); writer.WriteXmlNullableValueStringEncode2("cp:version", this.version); writer.WriteXmlNodeEnd("cp:coreProperties"); }; CCore.prototype.toXml = function (writer) { let oContext = writer.context; if(oContext.presentation) { let oCore = this.copy(); oCore.setRequiredDefaultsPresentationEditor(); oCore.toXmlImpl(writer); return; } this.toXmlImpl(writer); }; CCore.prototype.createDefaultPresentationEditor = function() { this.lastModifiedBy = ""; }; let DEFAULT_CREATOR = "CREATOR"; let DEFAULT_LAST_MODIFIED_BY = "CREATOR"; CCore.prototype.setRequiredDefaultsPresentationEditor = function() { if(!this.creator) { this.creator = DEFAULT_CREATOR; } if(!this.lastModifiedBy) { this.lastModifiedBy = DEFAULT_LAST_MODIFIED_BY; } }; window['AscCommon'].CCore = CCore; prot = CCore.prototype; prot["asc_getTitle"] = prot.asc_getTitle; prot["asc_getCreator"] = prot.asc_getCreator; prot["asc_getLastModifiedBy"] = prot.asc_getLastModifiedBy; prot["asc_getRevision"] = prot.asc_getRevision; prot["asc_getCreated"] = prot.asc_getCreated; prot["asc_getModified"] = prot.asc_getModified; prot["asc_getCategory"] = prot.asc_getCategory; prot["asc_getContentStatus"] = prot.asc_getContentStatus; prot["asc_getDescription"] = prot.asc_getDescription; prot["asc_getIdentifier"] = prot.asc_getIdentifier; prot["asc_getKeywords"] = prot.asc_getKeywords; prot["asc_getLanguage"] = prot.asc_getLanguage; prot["asc_getLastPrinted"] = prot.asc_getLastPrinted; prot["asc_getSubject"] = prot.asc_getSubject; prot["asc_getVersion"] = prot.asc_getVersion; prot["asc_putTitle"] = prot.asc_putTitle; prot["asc_putCreator"] = prot.asc_putCreator; prot["asc_putLastModifiedBy"] = prot.asc_putLastModifiedBy; prot["asc_putRevision"] = prot.asc_putRevision; prot["asc_putCreated"] = prot.asc_putCreated; prot["asc_putModified"] = prot.asc_putModified; prot["asc_putCategory"] = prot.asc_putCategory; prot["asc_putContentStatus"] = prot.asc_putContentStatus; prot["asc_putDescription"] = prot.asc_putDescription; prot["asc_putIdentifier"] = prot.asc_putIdentifier; prot["asc_putKeywords"] = prot.asc_putKeywords; prot["asc_putLanguage"] = prot.asc_putLanguage; prot["asc_putLastPrinted"] = prot.asc_putLastPrinted; prot["asc_putSubject"] = prot.asc_putSubject; prot["asc_putVersion"] = prot.asc_putVersion; function PartTitle() { CBaseNoIdObject.call(this); this.title = null; } InitClass(PartTitle, CBaseNoIdObject, 0); PartTitle.prototype.fromXml = function (reader) { this.title = reader.GetTextDecodeXml(); } PartTitle.prototype.toXml = function (writer) { if(this.title !== null) { writer.WriteXmlString("<vt:lpstr>"); writer.WriteXmlStringEncode(this.title); writer.WriteXmlString("</vt:lpstr>"); } } function CApp() { CBaseNoIdObject.call(this); this.Template = null; this.TotalTime = null; this.Words = null; this.Application = null; this.PresentationFormat = null; this.Paragraphs = null; this.Slides = null; this.Notes = null; this.HiddenSlides = null; this.MMClips = null; this.ScaleCrop = null; this.HeadingPairs = []; this.TitlesOfParts = []; this.Company = null; this.LinksUpToDate = null; this.SharedDoc = null; this.HyperlinksChanged = null; this.AppVersion = null; this.Characters = null; this.CharactersWithSpaces = null; this.DocSecurity = null; this.HyperlinkBase = null; this.Lines = null; this.Manager = null; this.Pages = null; } InitClass(CApp, CBaseNoIdObject, 0); CApp.prototype.getAppName = function() { return "@@AppName/@@Version"; }; CApp.prototype.setRequiredDefaults = function() { this.Application = this.getAppName(); }; CApp.prototype.merge = function(oOtherApp) { oOtherApp.Template !== null && (this.Template = oOtherApp.Template); oOtherApp.TotalTime !== null && (this.TotalTime = oOtherApp.TotalTime); oOtherApp.Words !== null && (this.Words = oOtherApp.Words); oOtherApp.Application !== null && (this.Application = oOtherApp.Application); oOtherApp.PresentationFormat !== null && (this.PresentationFormat = oOtherApp.PresentationFormat); oOtherApp.Paragraphs !== null && (this.Paragraphs = oOtherApp.Paragraphs); //oOtherApp.Slides !== null && (this.Slides = oOtherApp.Slides); //oOtherApp.Notes !== null && (this.Notes = oOtherApp.Notes); oOtherApp.HiddenSlides !== null && (this.HiddenSlides = oOtherApp.HiddenSlides); oOtherApp.MMClips !== null && (this.MMClips = oOtherApp.MMClips); oOtherApp.ScaleCrop !== null && (this.ScaleCrop = oOtherApp.ScaleCrop); oOtherApp.Company !== null && (this.Company = oOtherApp.Company); oOtherApp.LinksUpToDate !== null && (this.LinksUpToDate = oOtherApp.LinksUpToDate); oOtherApp.SharedDoc !== null && (this.SharedDoc = oOtherApp.SharedDoc); oOtherApp.HyperlinksChanged !== null && (this.HyperlinksChanged = oOtherApp.HyperlinksChanged); oOtherApp.AppVersion !== null && (this.AppVersion = oOtherApp.AppVersion); oOtherApp.Characters !== null && (this.Characters = oOtherApp.Characters); oOtherApp.CharactersWithSpaces !== null && (this.CharactersWithSpaces = oOtherApp.CharactersWithSpaces); oOtherApp.DocSecurity !== null && (this.DocSecurity = oOtherApp.DocSecurity); oOtherApp.HyperlinkBase !== null && (this.HyperlinkBase = oOtherApp.HyperlinkBase); oOtherApp.Lines !== null && (this.Lines = oOtherApp.Lines); oOtherApp.Manager !== null && (this.Manager = oOtherApp.Manager); oOtherApp.Pages !== null && (this.Pages = oOtherApp.Pages); }; CApp.prototype.createDefaultPresentationEditor = function(nCountSlides, nCountThemes) { this.TotalTime = 0; this.Words = 0; this.setRequiredDefaults(); this.PresentationFormat = "On-screen Show (4:3)"; this.Paragraphs = 0; this.Slides = nCountSlides; this.Notes = nCountSlides; this.HiddenSlides = 0; this.MMClips = 2; this.ScaleCrop = false; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[0].type = c_oVariantTypes.vtLpstr; this.HeadingPairs[0].strContent = "Theme"; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[1].type = c_oVariantTypes.vtI4; this.HeadingPairs[1].iContent = nCountThemes; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[2].type = c_oVariantTypes.vtLpstr; this.HeadingPairs[2].strContent = "Slide Titles"; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[3].type = c_oVariantTypes.vtI4; this.HeadingPairs[3].iContent = nCountSlides; for (let i = 0; i < nCountThemes; ++i) { let s = "Theme " + ( i + 1); this.TitlesOfParts.push(new PartTitle()); this.TitlesOfParts[i].title = s; } for (let i = 0; i < nCountSlides; ++i) { let s = "Slide " + (i + 1); this.TitlesOfParts.push( new PartTitle()); this.TitlesOfParts[nCountThemes + i].title = s; } this.LinksUpToDate = false; this.SharedDoc = false; this.HyperlinksChanged = false; }; CApp.prototype.fromStream = function (s) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.Template = s.GetString2(); break; } case 1: { this.Application = s.GetString2(); break; } case 2: { this.PresentationFormat = s.GetString2(); break; } case 3: { this.Company = s.GetString2(); break; } case 4: { this.AppVersion = s.GetString2(); break; } case 5: { this.TotalTime = s.GetLong(); break; } case 6: { this.Words = s.GetLong(); break; } case 7: { this.Paragraphs = s.GetLong(); break; } case 8: { this.Slides = s.GetLong(); break; } case 9: { this.Notes = s.GetLong(); break; } case 10: { this.HiddenSlides = s.GetLong(); break; } case 11: { this.MMClips = s.GetLong(); break; } case 12: { this.ScaleCrop = s.GetBool(); break; } case 13: { this.LinksUpToDate = s.GetBool(); break; } case 14: { this.SharedDoc = s.GetBool(); break; } case 15: { this.HyperlinksChanged = s.GetBool(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { var _end_rec2 = s.cur + s.GetLong() + 4; s.Skip2(1); // start attributes while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 16: { this.Characters = s.GetLong(); break; } case 17: { this.CharactersWithSpaces = s.GetLong(); break; } case 18: { this.DocSecurity = s.GetLong(); break; } case 19: { this.HyperlinkBase = s.GetString2(); break; } case 20: { this.Lines = s.GetLong(); break; } case 21: { this.Manager = s.GetString2(); break; } case 22: { this.Pages = s.GetLong(); break; } default: return; } } s.Seek2(_end_rec2); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CApp.prototype.toStream = function (s) { s.StartRecord(AscCommon.c_oMainTables.App); s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.Template); // just in case // s._WriteString2(1, this.Application); s._WriteString2(2, this.PresentationFormat); s._WriteString2(3, this.Company); // just in case // s._WriteString2(4, this.AppVersion); //we don't count these stats // s._WriteInt2(5, this.TotalTime); // s._WriteInt2(6, this.Words); // s._WriteInt2(7, this.Paragraphs); // s._WriteInt2(8, this.Slides); // s._WriteInt2(9, this.Notes); // s._WriteInt2(10, this.HiddenSlides); // s._WriteInt2(11, this.MMClips); s._WriteBool2(12, this.ScaleCrop); s._WriteBool2(13, this.LinksUpToDate); s._WriteBool2(14, this.SharedDoc); s._WriteBool2(15, this.HyperlinksChanged); s.WriteUChar(g_nodeAttributeEnd); s.StartRecord(0); s.WriteUChar(AscCommon.g_nodeAttributeStart); // s._WriteInt2(16, this.Characters); // s._WriteInt2(17, this.CharactersWithSpaces); s._WriteInt2(18, this.DocSecurity); s._WriteString2(19, this.HyperlinkBase); // s._WriteInt2(20, this.Lines); s._WriteString2(21, this.Manager); // s._WriteInt2(22, this.Pages); s.WriteUChar(g_nodeAttributeEnd); s.EndRecord(); s.EndRecord(); }; CApp.prototype.asc_getTemplate = function () { return this.Template; }; CApp.prototype.asc_getTotalTime = function () { return this.TotalTime; }; CApp.prototype.asc_getWords = function () { return this.Words; }; CApp.prototype.asc_getApplication = function () { return this.Application; }; CApp.prototype.asc_getPresentationFormat = function () { return this.PresentationFormat; }; CApp.prototype.asc_getParagraphs = function () { return this.Paragraphs; }; CApp.prototype.asc_getSlides = function () { return this.Slides; }; CApp.prototype.asc_getNotes = function () { return this.Notes; }; CApp.prototype.asc_getHiddenSlides = function () { return this.HiddenSlides; }; CApp.prototype.asc_getMMClips = function () { return this.MMClips; }; CApp.prototype.asc_getScaleCrop = function () { return this.ScaleCrop; }; CApp.prototype.asc_getCompany = function () { return this.Company; }; CApp.prototype.asc_getLinksUpToDate = function () { return this.LinksUpToDate; }; CApp.prototype.asc_getSharedDoc = function () { return this.SharedDoc; }; CApp.prototype.asc_getHyperlinksChanged = function () { return this.HyperlinksChanged; }; CApp.prototype.asc_getAppVersion = function () { return this.AppVersion; }; CApp.prototype.asc_getCharacters = function () { return this.Characters; }; CApp.prototype.asc_getCharactersWithSpaces = function () { return this.CharactersWithSpaces; }; CApp.prototype.asc_getDocSecurity = function () { return this.DocSecurity; }; CApp.prototype.asc_getHyperlinkBase = function () { return this.HyperlinkBase; }; CApp.prototype.asc_getLines = function () { return this.Lines; }; CApp.prototype.asc_getManager = function () { return this.Manager; }; CApp.prototype.asc_getPages = function () { return this.Pages; }; CApp.prototype.readChildXml = function (name, reader) { switch (name) { case "Template": { this.Template = reader.GetTextDecodeXml(); break; } case "Application": { this.Application = reader.GetTextDecodeXml(); break; } case "PresentationFormat": { this.PresentationFormat = reader.GetTextDecodeXml(); break; } case "Company": { this.Company = reader.GetTextDecodeXml(); break; } case "AppVersion": { this.AppVersion = reader.GetTextDecodeXml(); break; } case "TotalTime": { this.TotalTime = reader.GetTextInt(null, 10); break; } case "Words": { this.Words = reader.GetTextInt(null, 10); break; } case "Paragraphs": { this.Paragraphs = reader.GetTextInt(null, 10); break; } case "Slides": { this.Slides = reader.GetTextInt(null, 10); break; } case "Notes": { this.Notes = reader.GetTextInt(null, 10); break; } case "HiddenSlides": { this.HiddenSlides = reader.GetTextInt(null, 10); break; } case "MMClips": { this.MMClips = reader.GetTextInt(null, 10); break; } case "ScaleCrop": { this.ScaleCrop = reader.GetTextBool(); break; } case "LinksUpToDate": { this.LinksUpToDate = reader.GetTextBool(); break; } case "SharedDoc": { this.SharedDoc = reader.GetTextBool(); break; } case "HyperlinksChanged": { this.HyperlinksChanged = reader.GetTextBool(); break; } case "Pages": { this.Pages = reader.GetTextUInt(); break; } } }; CApp.prototype.toXml = function (writer) { let oContext = writer.context; if(oContext.presentation) { let oAppToWrite = new CApp(); oAppToWrite.createDefaultPresentationEditor(oContext.getSlidesCount(), oContext.getSlideMastersCount()); oAppToWrite.merge(this); oAppToWrite.toDrawingML(writer); } else { this.toXmlInternal(writer); } }; CApp.prototype.toDrawingML = function(writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); writer.WriteXmlNodeStart("Properties"); writer.WriteXmlNullableAttributeString("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"); writer.WriteXmlNullableAttributeString("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullableValueStringEncode2("Template", this.Template); writer.WriteXmlNullableValueUInt("TotalTime", this.TotalTime); writer.WriteXmlNullableValueUInt("Pages", this.Pages); writer.WriteXmlNullableValueUInt("Words", this.Words); writer.WriteXmlNullableValueUInt("Characters", this.Characters); writer.WriteXmlNullableValueUInt("CharactersWithSpaces", this.CharactersWithSpaces); writer.WriteXmlNullableValueStringEncode2("Application", this.Application); writer.WriteXmlNullableValueInt("DocSecurity", this.DocSecurity); writer.WriteXmlNullableValueStringEncode2("PresentationFormat", this.PresentationFormat); writer.WriteXmlNullableValueUInt("Lines", this.Lines); writer.WriteXmlNullableValueUInt("Paragraphs", this.Paragraphs); writer.WriteXmlNullableValueUInt("Slides", this.Slides); writer.WriteXmlNullableValueUInt("Notes", this.Notes); writer.WriteXmlNullableValueUInt("HiddenSlides", this.HiddenSlides); writer.WriteXmlNullableValueInt("MMClips", this.MMClips); if (this.ScaleCrop !== null) { writer.WriteXmlString("<ScaleCrop>"); writer.WriteXmlString(this.ScaleCrop ? "true" : "false"); writer.WriteXmlString("</ScaleCrop>"); } writer.WriteXmlNodeStart("HeadingPairs"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("vt:vector"); writer.WriteXmlNullableAttributeUInt("size", this.HeadingPairs.length); writer.WriteXmlNullableAttributeString("baseType", "variant"); writer.WriteXmlAttributesEnd(); writer.WriteXmlArray(this.HeadingPairs, "vt:variant"); writer.WriteXmlNodeEnd("vt:vector"); writer.WriteXmlNodeEnd("HeadingPairs"); writer.WriteXmlNodeStart("TitlesOfParts"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("vt:vector"); writer.WriteXmlNullableAttributeUInt("size", this.TitlesOfParts.length); writer.WriteXmlNullableAttributeString("baseType", "lpstr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlArray(this.TitlesOfParts, "vt:variant"); writer.WriteXmlNodeEnd("vt:vector"); writer.WriteXmlNodeEnd("TitlesOfParts"); writer.WriteXmlNullableValueStringEncode2("Manager", this.Manager); writer.WriteXmlNullableValueStringEncode2("Company", this.Company); writer.WriteXmlNullableValueStringEncode2("LinksUpToDate", this.LinksUpToDate); writer.WriteXmlNullableValueStringEncode2("SharedDoc", this.SharedDoc); writer.WriteXmlNullableValueStringEncode2("HyperlinkBase", this.HyperlinkBase); writer.WriteXmlNullableValueStringEncode2("HyperlinksChanged", this.HyperlinksChanged); writer.WriteXmlNullableValueStringEncode2("AppVersion", this.AppVersion); writer.WriteXmlNodeEnd("Properties"); }; CApp.prototype.toXmlInternal = function (writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); writer.WriteXmlNodeStart("Properties"); writer.WriteXmlNullableAttributeString("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"); writer.WriteXmlNullableAttributeString("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.WriteXmlAttributesEnd(); writer.WriteXmlString("<Application>"); writer.WriteXmlStringEncode(this.getAppName()); writer.WriteXmlString("</Application>"); if (this.Characters !== null) { writer.WriteXmlString("<Characters>"); writer.WriteXmlString(this.Characters + ""); writer.WriteXmlString("</Characters>"); } if (this.CharactersWithSpaces !== null) { writer.WriteXmlString("<CharactersWithSpaces>"); writer.WriteXmlString(this.CharactersWithSpaces + ""); writer.WriteXmlString("</CharactersWithSpaces>"); } if (this.Company !== null) { writer.WriteXmlString("<Company>"); writer.WriteXmlStringEncode(this.Company); writer.WriteXmlString("</Company>"); } if (this.DocSecurity !== null) { writer.WriteXmlString("<DocSecurity>"); writer.WriteXmlString(this.DocSecurity + ""); writer.WriteXmlString("</DocSecurity>"); } if (this.HiddenSlides !== null) { writer.WriteXmlString("<HiddenSlides>"); writer.WriteXmlString(this.HiddenSlides + ""); writer.WriteXmlString("</HiddenSlides>"); } if (this.HyperlinkBase !== null) { writer.WriteXmlString("<HyperlinkBase>"); writer.WriteXmlString(this.HyperlinkBase + ""); writer.WriteXmlString("</HyperlinkBase>"); } if (this.HyperlinksChanged !== null) { writer.WriteXmlString("<HyperlinksChanged>"); writer.WriteXmlString(this.HyperlinksChanged ? "true" : "false"); writer.WriteXmlString("</HyperlinksChanged>"); } if (this.Lines !== null) { writer.WriteXmlString("<Lines>"); writer.WriteXmlString(this.Lines + ""); writer.WriteXmlString("</Lines>"); } if (this.LinksUpToDate !== null) { writer.WriteXmlString("<LinksUpToDate>"); writer.WriteXmlString(this.LinksUpToDate ? "true" : "false"); writer.WriteXmlString("</LinksUpToDate>"); } if (this.Manager !== null) { writer.WriteXmlString("<Manager>"); writer.WriteXmlStringEncode(this.Manager); writer.WriteXmlString("</Manager>"); } if (this.MMClips !== null) { writer.WriteXmlString("<MMClips>"); writer.WriteXmlString(this.MMClips + ""); writer.WriteXmlString("</MMClips>"); } if (this.Notes !== null) { writer.WriteXmlString("<Notes>"); writer.WriteXmlString(this.Notes + ""); writer.WriteXmlString("</Notes>"); } if (this.Pages !== null) { writer.WriteXmlString("<Pages>"); writer.WriteXmlString(this.Pages + ""); writer.WriteXmlString("</Pages>"); } if (this.Paragraphs !== null) { writer.WriteXmlString("<Paragraphs>"); writer.WriteXmlString(this.Paragraphs + ""); writer.WriteXmlString("</Paragraphs>"); } if (this.ScaleCrop !== null) { writer.WriteXmlString("<ScaleCrop>"); writer.WriteXmlString(this.ScaleCrop ? "true" : "false"); writer.WriteXmlString("</ScaleCrop>"); } if (this.SharedDoc !== null) { writer.WriteXmlString("<SharedDoc>"); writer.WriteXmlString(this.SharedDoc ? "true" : "false"); writer.WriteXmlString("</SharedDoc>"); } if (this.Slides !== null) { writer.WriteXmlString("<Slides>"); writer.WriteXmlString(this.Slides + ""); writer.WriteXmlString("</Slides>"); } if (this.Template !== null) { writer.WriteXmlString("<Template>"); writer.WriteXmlStringEncode(this.Template); writer.WriteXmlString("</Template>"); } if (this.TotalTime !== null) { writer.WriteXmlString("<TotalTime>"); writer.WriteXmlString(this.TotalTime + ""); writer.WriteXmlString("</TotalTime>"); } if (this.Words !== null) { writer.WriteXmlString("<Words>"); writer.WriteXmlString(this.Words + ""); writer.WriteXmlString("</Words>"); } writer.WriteXmlNodeEnd("Properties"); }; window['AscCommon'].CApp = CApp; prot = CApp.prototype; prot["asc_getTemplate"] = prot.asc_getTemplate; prot["asc_getTotalTime"] = prot.asc_getTotalTime; prot["asc_getWords"] = prot.asc_getWords; prot["asc_getApplication"] = prot.asc_getApplication; prot["asc_getPresentationFormat"] = prot.asc_getPresentationFormat; prot["asc_getParagraphs"] = prot.asc_getParagraphs; prot["asc_getSlides"] = prot.asc_getSlides; prot["asc_getNotes"] = prot.asc_getNotes; prot["asc_getHiddenSlides"] = prot.asc_getHiddenSlides; prot["asc_getMMClips"] = prot.asc_getMMClips; prot["asc_getScaleCrop"] = prot.asc_getScaleCrop; prot["asc_getCompany"] = prot.asc_getCompany; prot["asc_getLinksUpToDate"] = prot.asc_getLinksUpToDate; prot["asc_getSharedDoc"] = prot.asc_getSharedDoc; prot["asc_getHyperlinksChanged"] = prot.asc_getHyperlinksChanged; prot["asc_getAppVersion"] = prot.asc_getAppVersion; prot["asc_getCharacters"] = prot.asc_getCharacters; prot["asc_getCharactersWithSpaces"] = prot.asc_getCharactersWithSpaces; prot["asc_getDocSecurity"] = prot.asc_getDocSecurity; prot["asc_getHyperlinkBase"] = prot.asc_getHyperlinkBase; prot["asc_getLines"] = prot.asc_getLines; prot["asc_getManager"] = prot.asc_getManager; prot["asc_getPages"] = prot.asc_getPages; function CCustomProperties() { CBaseNoIdObject.call(this); this.properties = []; } InitClass(CCustomProperties, CBaseNoIdObject, 0); CCustomProperties.prototype.fromStream = function (s) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { s.Skip2(4); var _c = s.GetULong(); for (var i = 0; i < _c; ++i) { s.Skip2(1); // type var tmp = new CCustomProperty(); tmp.fromStream(s); this.properties.push(tmp); } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CCustomProperties.prototype.toStream = function (s) { s.StartRecord(AscCommon.c_oMainTables.CustomProperties); s.WriteUChar(AscCommon.g_nodeAttributeStart); s.WriteUChar(g_nodeAttributeEnd); this.fillNewPid(); s.WriteRecordArray4(0, 0, this.properties); s.EndRecord(); }; CCustomProperties.prototype.fillNewPid = function (s) { var index = 2; this.properties.forEach(function (property) { property.pid = index++; }); }; CCustomProperties.prototype.add = function (name, variant, opt_linkTarget) { var newProperty = new CCustomProperty(); newProperty.fmtid = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProperty.pid = null; newProperty.name = name; newProperty.linkTarget = opt_linkTarget || null; newProperty.content = variant; this.properties.push(newProperty); }; CCustomProperties.prototype.readChildXml = function (name, reader) { switch (name) { case "property": { let oPr = new CCustomProperty(); oPr.fromXml(reader); this.properties.push(oPr); break; } } }; CCustomProperties.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("Properties"); writer.WriteXmlNullableAttributeString("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"); writer.WriteXmlNullableAttributeString("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.WriteXmlAttributesEnd(); for (let i = 0; i < m_arProperties.length; ++i) { this.properties[i].toXml(writer); } writer.WriteXmlNodeEnd("Properties"); }; window['AscCommon'].CCustomProperties = CCustomProperties; prot = CCustomProperties.prototype; prot["add"] = prot.add; function CCustomProperty() { CBaseNoIdObject.call(this); this.fmtid = null; this.pid = null; this.name = null; this.linkTarget = null; this.content = null; } InitClass(CCustomProperty, CBaseNoIdObject, 0); CCustomProperty.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.fmtid = s.GetString2(); break; } case 1: { this.pid = s.GetLong(); break; } case 2: { this.name = s.GetString2(); break; } case 3: { this.linkTarget = s.GetString2(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.content = new CVariant(this); this.content.fromStream(s); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CCustomProperty.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.fmtid); s._WriteInt2(1, this.pid); s._WriteString2(2, this.name); s._WriteString2(3, this.linkTarget); s.WriteUChar(g_nodeAttributeEnd); s.WriteRecord4(0, this.content); }; CCustomProperty.prototype.readAttrXml = function (name, reader) { switch (name) { case "fmtid": { this.fmtid = reader.GetValue(); break; } case "linkTarget": { this.linkTarget = reader.GetValue(); break; } case "name": { this.name = reader.GetValue(); break; } case "pid": { this.pid = reader.GetValueInt(); break; } } }; CCustomProperty.prototype.readChildXml = function (name, reader) { if (!this.content) { this.content = new CVariant(this); } this.content.readChildXml(name, reader); }; CCustomProperty.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("property"); writer.WriteXmlNullableAttributeString("fmtid", this.fmtid); writer.WriteXmlNullableAttributeInt("pid", this.pid); writer.WriteXmlNullableAttributeString("name", this.name); writer.WriteXmlNullableAttributeString("linkTarget", this.linkTarget); writer.WriteXmlAttributesEnd(); if (this.content) { this.content.toXmlWriterContent(writer); } writer.WriteXmlNodeEnd("property"); }; function CVariantVector() { CBaseNoIdObject.call(this); this.baseType = null; this.size = null; this.variants = []; } InitClass(CVariantVector, CBaseNoIdObject, 0); CVariantVector.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.baseType = s.GetUChar(); break; } case 1: { this.size = s.GetLong(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { s.Skip2(4); var _c = s.GetULong(); for (var i = 0; i < _c; ++i) { s.Skip2(1); // type var tmp = new CVariant(this); tmp.fromStream(s); this.variants.push(tmp); } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariantVector.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteUChar2(0, this.baseType); s._WriteInt2(1, this.size); s.WriteUChar(g_nodeAttributeEnd); s.WriteRecordArray4(0, 0, this.variants); }; CVariantVector.prototype.readAttrXml = function (name, reader) { switch (name) { case "baseType": { let sType = reader.GetValue(); this.baseTyep = CVariant.prototype.typeStrToEnum.call(this, sType); break; } case "size": { this.size = reader.GetValueInt(); break; } } }; CVariantVector.prototype.readChildXml = function (name, reader) { let oVar = new CVariant(this); oVar.readChildXml(name, reader); this.variants.push(oVar); }; CVariantVector.prototype.getVariantType = function () { return AscFormat.isRealNumber(this.baseType) ? this.baseType : c_oVariantTypes.vtEmpty; }; CVariantVector.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:vector"); writer.WriteXmlNullableAttributeString("baseType", CVariant.prototype.getStringByType.call(this, this.getVariantType())); writer.WriteXmlNullableAttributeInt("size", this.size); writer.WriteXmlAttributesEnd(); for (let i = 0; i < this.variants.length; ++i) { this.variants[i].toXmlWriterContent(writer); } writer.WriteXmlNodeEnd("vt:vector"); }; function CVariantArray() { CBaseNoIdObject.call(this); this.baseType = null; this.lBounds = null; this.uBounds = null; this.variants = []; } InitClass(CVariantArray, CBaseNoIdObject, 0); CVariantArray.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.baseType = s.GetUChar(); break; } case 1: { this.lBounds = s.GetString2(); break; } case 2: { this.uBounds = s.GetString2(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { s.Skip2(4); var _c = s.GetULong(); for (var i = 0; i < _c; ++i) { s.Skip2(1); // type var tmp = new CVariant(); tmp.fromStream(s); this.variants.push(tmp); } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariantArray.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteUChar2(0, this.baseType); s._WriteString2(1, this.lBounds); s._WriteString2(2, this.uBounds); s.WriteUChar(g_nodeAttributeEnd); s.WriteRecordArray4(0, 0, this.variants); }; CVariantArray.prototype.getVariantType = function () { return AscFormat.isRealNumber(this.baseType) ? this.baseType : c_oVariantTypes.vtEmpty; }; CVariantArray.prototype.readAttrXml = function (name, reader) { switch (name) { case "baseType": { let sType = reader.GetValue(); this.baseTyep = CVariant.prototype.typeStrToEnum.call(this, sType); break; } case "lBounds": { this.lBounds = reader.GetValueInt(); break; } case "uBounds": { this.uBounds = reader.GetValueInt(); break; } } }; CVariantArray.prototype.readChildXml = function (name, reader) { let oVar = new CVariant(this); oVar.readChildXml(name, reader); this.variants.push(oVar); }; CVariantArray.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:array"); writer.WriteXmlNullableAttributeInt("lBounds", this.lBounds); writer.WriteXmlNullableAttributeInt("uBounds", this.uBounds); writer.WriteXmlNullableAttributeString("baseType", CVariant.prototype.getStringByType.call(this, this.getVariantType())); writer.WriteXmlAttributesEnd(); for (let i = 0; i < this.variants.length; ++i) { this.variants[i].toXmlWriterContent(writer); } writer.WriteXmlNodeEnd("vt:array"); }; function CVariantVStream() { CBaseNoIdObject.call(this); this.version = null; this.strContent = null; } InitClass(CVariantVStream, CBaseNoIdObject, 0); CVariantVStream.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.version = s.GetString2(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.strContent = s.GetString2(); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariantVStream.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.version); s.WriteUChar(g_nodeAttributeEnd); s._WriteString2(0, this.strContent); }; CVariantVStream.prototype.fromXml = function (reader, bSkipFirstNode) { this.strContent = reader.GetValueDecodeXml(); CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); }; CVariantVStream.prototype.readAttrXml = function (name, reader) { switch (name) { case "version": { this.version = reader.GetValue(); break; } } }; CVariantVStream.prototype.readChildXml = function (name, reader) { let oVar = new CVariant(this); oVar.readChildXml(name, reader); this.variants.push(oVar); }; CVariantVStream.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:vstream"); writer.WriteXmlNullableAttributeString("version", this.version); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullableValueStringEncode2(this.content); writer.WriteXmlNodeEnd("vt:vstream"); }; function CVariant(parent) { CBaseNoIdObject.call(this); this.type = null; this.strContent = null; this.iContent = null; this.uContent = null; this.dContent = null; this.bContent = null; this.variant = null; this.vector = null; this.array = null; this.vStream = null; this.parent = parent; } InitClass(CVariant, CBaseNoIdObject, 0); CVariant.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.type = s.GetUChar(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.strContent = s.GetString2(); break; } case 1: { this.iContent = s.GetLong(); break; } case 2: { this.iContent = s.GetULong(); break; } case 3: { this.dContent = s.GetDouble(); break; } case 4: { this.bContent = s.GetBool(); break; } case 5: { this.variant = new CVariant(this); this.variant.fromStream(s); break; } case 6: { this.vector = new CVariantVector(); this.vector.fromStream(s); break; } case 7: { this.array = new CVariantArray(); this.array.fromStream(s); break; } case 8: { this.vStream = new CVariantVStream(); this.vStream.fromStream(s); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariant.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteUChar2(0, this.type); s.WriteUChar(g_nodeAttributeEnd); s._WriteString2(0, this.strContent); s._WriteInt2(1, this.iContent); s._WriteUInt2(2, this.uContent); s._WriteDoubleReal2(3, this.dContent); s._WriteBool2(4, this.bContent); s.WriteRecord4(5, this.variant); s.WriteRecord4(6, this.vector); s.WriteRecord4(7, this.array); s.WriteRecord4(8, this.vStream); }; CVariant.prototype.setText = function (val) { this.type = c_oVariantTypes.vtLpwstr; this.strContent = val; }; CVariant.prototype.setNumber = function (val) { this.type = c_oVariantTypes.vtI4; this.iContent = val; }; CVariant.prototype.setDate = function (val) { this.type = c_oVariantTypes.vtFiletime; this.strContent = val.toISOString().slice(0, 19) + 'Z'; }; CVariant.prototype.setBool = function (val) { this.type = c_oVariantTypes.vtBool; this.bContent = val; }; CVariant.prototype.readAttrXml = function (name, reader) { switch (name) { case "fmtid": { this.fmtid = reader.GetValue(); break; } case "linkTarget": { this.linkTarget = reader.GetValue(); break; } case "name": { this.name = reader.GetValue(); break; } case "pid": { this.name = reader.GetValueInt(); break; } } }; CVariant.prototype.typeStrToEnum = function (name) { switch (name) { case "vector": { return c_oVariantTypes.vtVector; break; } case "array": { return c_oVariantTypes.vtArray; break; } case "blob": { return c_oVariantTypes.vtBlob; break; } case "oblob": { return c_oVariantTypes.vtOBlob; break; } case "empty": { return c_oVariantTypes.vtEmpty; break; } case "null": { return c_oVariantTypes.vtNull; break; } case "i1": { return c_oVariantTypes.vtI1; break; } case "i2": { return c_oVariantTypes.vtI2; break; } case "i4": { return c_oVariantTypes.vtI4; break; } case "i8": { return c_oVariantTypes.vtI8; break; } case "int": { return c_oVariantTypes.vtInt; break; } case "ui1": { return c_oVariantTypes.vtUi1; break; } case "ui2": { return c_oVariantTypes.vtUi2; break; } case "ui4": { return c_oVariantTypes.vtUi4; break; } case "ui8": { return c_oVariantTypes.vtUi8; break; } case "uint": { return c_oVariantTypes.vtUint; break; } case "r4": { return c_oVariantTypes.vtR4; break; } case "r8": { return c_oVariantTypes.vtR8; break; } case "decimal": { return c_oVariantTypes.vtDecimal; break; } case "lpstr": { return c_oVariantTypes.vtLpstr; break; } case "lpwstr": { return c_oVariantTypes.vtLpwstr; break; } case "bstr": { return c_oVariantTypes.vtBstr; break; } case "date": { return c_oVariantTypes.vtDate; break; } case "filetime": { return c_oVariantTypes.vtFiletime; break; } case "bool": { return c_oVariantTypes.vtBool; break; } case "cy": { return c_oVariantTypes.vtCy; break; } case "error": { return c_oVariantTypes.vtError; break; } case "stream": { return c_oVariantTypes.vtStream; break; } case "ostream": { return c_oVariantTypes.vtOStream; break; } case "storage": { return c_oVariantTypes.vtStorage; break; } case "ostorage": { return c_oVariantTypes.vtOStorage; break; } case "vstream": { return c_oVariantTypes.vtVStream; break; } case "clsid": { return c_oVariantTypes.vtClsid; break; } } return null; }; CVariant.prototype.getStringByType = function (eType) { if (c_oVariantTypes.vtEmpty === eType) return "empty"; else if (c_oVariantTypes.vtNull === eType) return "null"; else if (c_oVariantTypes.vtVariant === eType) return "variant"; else if (c_oVariantTypes.vtVector === eType) return "vector"; else if (c_oVariantTypes.vtArray === eType) return "array"; else if (c_oVariantTypes.vtVStream === eType) return "vstream"; else if (c_oVariantTypes.vtBlob === eType) return "blob"; else if (c_oVariantTypes.vtOBlob === eType) return "oblob"; else if (c_oVariantTypes.vtI1 === eType) return "i1"; else if (c_oVariantTypes.vtI2 === eType) return "i2"; else if (c_oVariantTypes.vtI4 === eType) return "i4"; else if (c_oVariantTypes.vtI8 === eType) return "i8"; else if (c_oVariantTypes.vtInt === eType) return "int"; else if (c_oVariantTypes.vtUi1 === eType) return "ui1"; else if (c_oVariantTypes.vtUi2 === eType) return "ui2"; else if (c_oVariantTypes.vtUi4 === eType) return "ui4"; else if (c_oVariantTypes.vtUi8 === eType) return "ui8"; else if (c_oVariantTypes.vtUint === eType) return "uint"; else if (c_oVariantTypes.vtR4 === eType) return "r4"; else if (c_oVariantTypes.vtR8 === eType) return "r8"; else if (c_oVariantTypes.vtDecimal === eType) return "decimal"; else if (c_oVariantTypes.vtLpstr === eType) return "lpstr"; else if (c_oVariantTypes.vtLpwstr === eType) return "lpwstr"; else if (c_oVariantTypes.vtBstr === eType) return "bstr"; else if (c_oVariantTypes.vtDate === eType) return "date"; else if (c_oVariantTypes.vtFiletime === eType) return "filetime"; else if (c_oVariantTypes.vtBool === eType) return "bool"; else if (c_oVariantTypes.vtCy === eType) return "cy"; else if (c_oVariantTypes.vtError === eType) return "error"; else if (c_oVariantTypes.vtStream === eType) return "stream"; else if (c_oVariantTypes.vtOStream === eType) return "ostream"; else if (c_oVariantTypes.vtStorage === eType) return "storage"; else if (c_oVariantTypes.vtOStorage === eType) return "ostorage"; else if (c_oVariantTypes.vtClsid === eType) return "clsid"; return ""; } CVariant.prototype.readChildXml = function (name, reader) { this.type = this.typeStrToEnum(name); switch (name) { case "vector": { this.vector = new CVariantVector(); this.vector.fromXml(reader); break; } case "array": { this.array = new CVariantArray(); this.array.fromXml(reader); break; } case "blob": { this.strContent = reader.GetValue(); break; } case "oblob": { this.strContent = reader.GetValue(); break; } case "empty": { break; } case "null": { break; } case "i1": { this.iContent = reader.GetValueInt(); break; } case "i2": { this.iContent = reader.GetValueInt(); break; } case "i4": { this.iContent = reader.GetValueInt(); break; } case "i8": { this.iContent = reader.GetValueInt(); break; } case "int": { this.iContent = reader.GetValueInt(); break; } case "ui1": { this.uContent = reader.GetValueUInt(); break; } case "ui2": { this.uContent = reader.GetValueUInt(); break; } case "ui4": { this.uContent = reader.GetValueUInt(); break; } case "ui8": { this.uContent = reader.GetValueUInt(); break; } case "uint": { this.uContent = reader.GetValueUInt(); break; } case "r4": { this.dContent = reader.GetValueDouble(); break; } case "r8": { this.dContent = reader.GetValueDouble(); break; } case "decimal": { this.dContent = reader.GetValueDouble(); break; } case "lpstr": { this.strContent = reader.GetValue(); break; } case "lpwstr": { this.strContent = reader.GetValue(); break; } case "bstr": { this.strContent = reader.GetValue(); break; } case "date": { this.strContent = reader.GetValue(); break; } case "filetime": { this.strContent = reader.GetValue(); break; } case "bool": { this.bContent = reader.GetValueBool(); break; } case "cy": { this.strContent = reader.GetValue(); break; } case "error": { this.strContent = reader.GetValue(); break; } case "stream": { this.strContent = reader.GetValue(); break; } case "ostream": { this.strContent = reader.GetValue(); break; } case "storage": { this.strContent = reader.GetValue(); break; } case "ostorage": { this.strContent = reader.GetValue(); break; } case "vstream": { this.vStream = new CVariantVStream(); break; } case "clsid": { this.strContent = reader.GetValue(); break; } } }; CVariant.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:variant"); writer.WriteXmlAttributesEnd(); this.toXmlWriterContent(writer); writer.WriteXmlNodeEnd("vt:variant"); }; CVariant.prototype.getVariantType = function () { return AscFormat.isRealNumber(this.type) ? this.type : c_oVariantTypes.vtEmpty; }; CVariant.prototype.toXmlWriterContent = function (writer) { let eType = this.getVariantType(); let strNodeName = "vt:" + this.getStringByType(eType); if (c_oVariantTypes.vtEmpty === eType || c_oVariantTypes.vtNull === eType) { writer.WriteXmlNodeStart(strNodeName); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd(strNodeName); } writer.WriteXmlNullableValueStringEncode2(strNodeName, this.strContent); writer.WriteXmlNullableValueStringEncode2(strNodeName, this.iContent); writer.WriteXmlNullableValueStringEncode2(strNodeName, this.uContent); writer.WriteXmlNullableValueStringEncode2(strNodeName, this.dContent); if (this.bContent) { writer.WriteXmlNodeStart(strNodeName); writer.WriteXmlAttributesEnd(); if (this.bContent) writer.WriteXmlString("true"); else writer.WriteXmlString("false"); writer.WriteXmlNodeEnd(strNodeName); } if (this.variant) { this.variant.toXml(writer); } if (this.vector) { this.vector.toXml(writer); } if (this.array) { this.array.toXml(writer); } if (this.vStream) { this.vStream.toXml(writer); } }; window['AscCommon'].CVariant = CVariant; prot = CVariant.prototype; prot["setText"] = prot.setText; prot["setNumber"] = prot.setNumber; prot["setDate"] = prot.setDate; prot["setBool"] = prot.setBool; var c_oVariantTypes = { vtEmpty: 0, vtNull: 1, vtVariant: 2, vtVector: 3, vtArray: 4, vtVStream: 5, vtBlob: 6, vtOBlob: 7, vtI1: 8, vtI2: 9, vtI4: 10, vtI8: 11, vtInt: 12, vtUi1: 13, vtUi2: 14, vtUi4: 15, vtUi8: 16, vtUint: 17, vtR4: 18, vtR8: 19, vtDecimal: 20, vtLpstr: 21, vtLpwstr: 22, vtBstr: 23, vtDate: 24, vtFiletime: 25, vtBool: 26, vtCy: 27, vtError: 28, vtStream: 29, vtOStream: 30, vtStorage: 31, vtOStorage: 32, vtClsid: 33 }; window['AscCommon'].c_oVariantTypes = c_oVariantTypes; function CPres() { CBaseNoIdObject.call(this); this.defaultTextStyle = null; this.NotesSz = null; this.attrAutoCompressPictures = null; this.attrBookmarkIdSeed = null; this.attrCompatMode = null; this.attrConformance = null; this.attrEmbedTrueTypeFonts = null; this.attrFirstSlideNum = null; this.attrRemovePersonalInfoOnSave = null; this.attrRtl = null; this.attrSaveSubsetFonts = null; this.attrServerZoom = null; this.attrShowSpecialPlsOnTitleSld = null; this.attrStrictFirstAndLastChars = null; } InitClass(CPres, CBaseNoIdObject, 0); CPres.prototype.fromStream = function (s, reader) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; // attributes var _sa = s.GetUChar(); var oPresentattion = reader.presentation; while (true) { var _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.attrAutoCompressPictures = s.GetBool(); break; } case 1: { this.attrBookmarkIdSeed = s.GetLong(); break; } case 2: { this.attrCompatMode = s.GetBool(); break; } case 3: { this.attrConformance = s.GetUChar(); break; } case 4: { this.attrEmbedTrueTypeFonts = s.GetBool(); break; } case 5: { this.attrFirstSlideNum = s.GetLong(); break; } case 6: { this.attrRemovePersonalInfoOnSave = s.GetBool(); break; } case 7: { this.attrRtl = s.GetBool(); break; } case 8: { this.attrSaveSubsetFonts = s.GetBool(); break; } case 9: { this.attrServerZoom = s.GetString2(); break; } case 10: { this.attrShowSpecialPlsOnTitleSld = s.GetBool(); break; } case 11: { this.attrStrictFirstAndLastChars = s.GetBool(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.defaultTextStyle = reader.ReadTextListStyle(); break; } case 1: { s.SkipRecord(); break; } case 2: { s.SkipRecord(); break; } case 3: { s.SkipRecord(); break; } case 4: { s.SkipRecord(); break; } case 5: { var oSldSize = new AscCommonSlide.CSlideSize(); s.Skip2(5); // len + start attributes while (true) { var _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { oSldSize.setCX(s.GetLong()); break; } case 1: { oSldSize.setCY(s.GetLong()); break; } case 2: { oSldSize.setType(s.GetUChar()); break; } default: return; } } if (oPresentattion.setSldSz) { oPresentattion.setSldSz(oSldSize); } break; } case 6: { var _end_rec2 = s.cur + s.GetULong() + 4; while (s.cur < _end_rec2) { var _rec = s.GetUChar(); switch (_rec) { case 0: { s.Skip2(4); // len var lCount = s.GetULong(); for (var i = 0; i < lCount; i++) { s.Skip2(1); var _author = new AscCommon.CCommentAuthor(); var _end_rec3 = s.cur + s.GetLong() + 4; s.Skip2(1); // start attributes while (true) { var _at2 = s.GetUChar(); if (_at2 === g_nodeAttributeEnd) break; switch (_at2) { case 0: _author.Id = s.GetLong(); break; case 1: _author.LastId = s.GetLong(); break; case 2: var _clr_idx = s.GetLong(); break; case 3: _author.Name = s.GetString2(); break; case 4: _author.Initials = s.GetString2(); break; default: break; } } s.Seek2(_end_rec3); oPresentattion.CommentAuthors[_author.Name] = _author; } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_rec2); break; } case 8: { var _length = s.GetULong(); var _end_rec2 = s.cur + _length; oPresentattion.Api.vbaMacros = s.GetBuffer(_length); s.Seek2(_end_rec2); break; } case 9: { var _length = s.GetULong(); var _end_rec2 = s.cur + _length; oPresentattion.Api.macros.SetData(AscCommon.GetStringUtf8(s, _length)); s.Seek2(_end_rec2); break; } case 10: { reader.ReadComments(oPresentattion.writecomments); break; } default: { s.SkipRecord(); break; } } } if (oPresentattion.Load_Comments) { oPresentattion.Load_Comments(oPresentattion.CommentAuthors); } s.Seek2(_end_pos); }; window['AscCommon'].CPres = CPres; function CClrMapOvr() { CBaseNoIdObject.call(this); this.overrideClrMapping = null; } InitClass(CClrMapOvr, CBaseNoIdObject, 0); CClrMapOvr.prototype.readChildXml = function (name, reader) { if ( "overrideClrMapping" === name) { this.overrideClrMapping = new ClrMap(); this.overrideClrMapping.fromXml(reader); } }; CClrMapOvr.prototype.toXml = function (writer) { if (this.overrideClrMapping) { writer.WriteXmlString("<p:clrMapOvr>"); this.overrideClrMapping.toXml(writer, "a:overrideClrMapping"); writer.WriteXmlString("</p:clrMapOvr>"); } else { writer.WriteXmlString("<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>"); } }; CClrMapOvr.prototype.static_WriteCrlMapAsOvr = function(writer, oClrMap) { let oClrMapOvr = new CClrMapOvr(); oClrMapOvr.overrideClrMapping = oClrMap; oClrMapOvr.toXml(writer); }; function IdEntry(name) { AscFormat.CBaseNoIdObject.call(this); this.name = name; this.id = null; this.rId = null; } InitClass(IdEntry, CBaseNoIdObject, undefined); IdEntry.prototype.readAttrXml = function(name, reader) { switch (reader.GetName()) { case "id": { this.id = reader.GetValue(); break; } case "r:id": { this.rId = reader.GetValue(); break; } } }; IdEntry.prototype.toXml = function(writer) { writer.WriteXmlNodeStart(this.name); writer.WriteXmlNullableAttributeString("id", this.id); writer.WriteXmlNullableAttributeString("r:id", this.rId); writer.WriteXmlAttributesEnd(true); }; IdEntry.prototype.readItem = function(reader, fConstructor) { let oRel = reader.rels.getRelationship(this.rId); let oRelPart = reader.rels.pkg.getPartByUri(oRel.targetFullName); let oContent = oRelPart.getDocumentContent(); let oReader = new AscCommon.StaxParser(oContent, oRelPart, reader.context); let oElement = fConstructor(oReader); if(oElement) { oElement.fromXml(oReader, true); } return oElement; }; // DEFAULT OBJECTS function GenerateDefaultTheme(presentation, opt_fontName) { return ExecuteNoHistory(function () { if (!opt_fontName) { opt_fontName = "Arial"; } var theme = new CTheme(); theme.presentation = presentation; theme.setFontScheme(new FontScheme()); theme.themeElements.fontScheme.setMajorFont(new FontCollection(theme.themeElements.fontScheme)); theme.themeElements.fontScheme.setMinorFont(new FontCollection(theme.themeElements.fontScheme)); theme.themeElements.fontScheme.majorFont.setLatin(opt_fontName); theme.themeElements.fontScheme.minorFont.setLatin(opt_fontName); var scheme = theme.themeElements.clrScheme; scheme.colors[8] = CreateUniColorRGB(0, 0, 0); scheme.colors[12] = CreateUniColorRGB(255, 255, 255); scheme.colors[9] = CreateUniColorRGB(0x1F, 0x49, 0x7D); scheme.colors[13] = CreateUniColorRGB(0xEE, 0xEC, 0xE1); scheme.colors[0] = CreateUniColorRGB(0x4F, 0x81, 0xBD); //CreateUniColorRGB(0xFF, 0x81, 0xBD);// scheme.colors[1] = CreateUniColorRGB(0xC0, 0x50, 0x4D); scheme.colors[2] = CreateUniColorRGB(0x9B, 0xBB, 0x59); scheme.colors[3] = CreateUniColorRGB(0x80, 0x64, 0xA2); scheme.colors[4] = CreateUniColorRGB(0x4B, 0xAC, 0xC6); scheme.colors[5] = CreateUniColorRGB(0xF7, 0x96, 0x46); scheme.colors[11] = CreateUniColorRGB(0x00, 0x00, 0xFF); scheme.colors[10] = CreateUniColorRGB(0x80, 0x00, 0x80); // -------------- fill styles ------------------------- var brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(new CSchemeColor()); brush.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.fillStyleLst.push(brush); brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.fillStyleLst.push(brush); brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.fillStyleLst.push(brush); // ---------------------------------------------------- // -------------- back styles ------------------------- brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(new CSchemeColor()); brush.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.bgFillStyleLst.push(brush); brush = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.bgFillStyleLst.push(brush); brush = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.bgFillStyleLst.push(brush); // ---------------------------------------------------- var pen = new CLn(); pen.setW(9525); pen.setFill(new CUniFill()); pen.Fill.setFill(new CSolidFill()); pen.Fill.fill.setColor(new CUniColor()); pen.Fill.fill.color.setColor(new CSchemeColor()); pen.Fill.fill.color.color.setId(phClr); pen.Fill.fill.color.setMods(new CColorModifiers()); var mod = new CColorMod(); mod.setName("shade"); mod.setVal(95000); pen.Fill.fill.color.Mods.addMod(mod); mod = new CColorMod(); mod.setName("satMod"); mod.setVal(105000); pen.Fill.fill.color.Mods.addMod(mod); theme.themeElements.fmtScheme.lnStyleLst.push(pen); pen = new CLn(); pen.setW(25400); pen.setFill(new CUniFill()); pen.Fill.setFill(new CSolidFill()); pen.Fill.fill.setColor(new CUniColor()); pen.Fill.fill.color.setColor(new CSchemeColor()); pen.Fill.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.lnStyleLst.push(pen); pen = new CLn(); pen.setW(38100); pen.setFill(new CUniFill()); pen.Fill.setFill(new CSolidFill()); pen.Fill.fill.setColor(new CUniColor()); pen.Fill.fill.color.setColor(new CSchemeColor()); pen.Fill.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.lnStyleLst.push(pen); theme.extraClrSchemeLst = []; return theme; }, this, []); } function GetDefaultTheme() { if(!AscFormat.DEFAULT_THEME) { AscFormat.DEFAULT_THEME = GenerateDefaultTheme(null); } return AscFormat.DEFAULT_THEME; } function GenerateDefaultMasterSlide(theme) { var master = new MasterSlide(theme.presentation, theme); master.Theme = theme; master.sldLayoutLst[0] = GenerateDefaultSlideLayout(master); return master; } function GenerateDefaultSlideLayout(master) { var layout = new SlideLayout(); layout.Theme = master.Theme; layout.Master = master; return layout; } function GenerateDefaultSlide(layout) { var slide = new Slide(layout.Master.presentation, layout, 0); slide.Master = layout.Master; slide.Theme = layout.Master.Theme; slide.setNotes(AscCommonSlide.CreateNotes()); slide.notes.setNotesMaster(layout.Master.presentation.notesMasters[0]); slide.notes.setSlide(slide); return slide; } function CreateDefaultTextRectStyle() { var style = new CShapeStyle(); var lnRef = new StyleRef(); lnRef.setIdx(0); var unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); var mod = new CColorMod(); mod.setName("shade"); mod.setVal(50000); unicolor.setMods(new CColorModifiers()); unicolor.Mods.addMod(mod); lnRef.setColor(unicolor); style.setLnRef(lnRef); var fillRef = new StyleRef(); fillRef.setIdx(0); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); fillRef.setColor(unicolor); style.setFillRef(fillRef); var effectRef = new StyleRef(); effectRef.setIdx(0); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); effectRef.setColor(unicolor); style.setEffectRef(effectRef); var fontRef = new FontRef(); fontRef.setIdx(AscFormat.fntStyleInd_minor); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(8); fontRef.setColor(unicolor); style.setFontRef(fontRef); return style; } function GenerateDefaultColorMap() { return AscFormat.ExecuteNoHistory(function () { var clrMap = new ClrMap(); clrMap.color_map[0] = 0; clrMap.color_map[1] = 1; clrMap.color_map[2] = 2; clrMap.color_map[3] = 3; clrMap.color_map[4] = 4; clrMap.color_map[5] = 5; clrMap.color_map[10] = 10; clrMap.color_map[11] = 11; clrMap.color_map[6] = 12; clrMap.color_map[7] = 13; clrMap.color_map[15] = 8; clrMap.color_map[16] = 9; return clrMap; }, [], null); } function GetDefaultColorMap() { if(!AscFormat.DEFAULT_COLOR_MAP) { AscFormat.DEFAULT_COLOR_MAP = GenerateDefaultColorMap(); } return AscFormat.DEFAULT_COLOR_MAP; } function CreateAscFill(unifill) { if (null == unifill || null == unifill.fill) return new asc_CShapeFill(); var ret = new asc_CShapeFill(); var _fill = unifill.fill; switch (_fill.type) { case c_oAscFill.FILL_TYPE_SOLID: { ret.type = c_oAscFill.FILL_TYPE_SOLID; ret.fill = new Asc.asc_CFillSolid(); ret.fill.color = CreateAscColor(_fill.color); break; } case c_oAscFill.FILL_TYPE_PATT: { ret.type = c_oAscFill.FILL_TYPE_PATT; ret.fill = new Asc.asc_CFillHatch(); ret.fill.PatternType = _fill.ftype; ret.fill.fgClr = CreateAscColor(_fill.fgClr); ret.fill.bgClr = CreateAscColor(_fill.bgClr); break; } case c_oAscFill.FILL_TYPE_GRAD: { ret.type = c_oAscFill.FILL_TYPE_GRAD; ret.fill = new Asc.asc_CFillGrad(); var bCheckTransparent = true, nLastTransparent = null, nLastTempTransparent, j, aMods; for (var i = 0; i < _fill.colors.length; i++) { if (0 == i) { ret.fill.Colors = []; ret.fill.Positions = []; } if (bCheckTransparent) { if (_fill.colors[i].color.Mods) { aMods = _fill.colors[i].color.Mods.Mods; nLastTempTransparent = null; for (j = 0; j < aMods.length; ++j) { if (aMods[j].name === "alpha") { if (nLastTempTransparent === null) { nLastTempTransparent = aMods[j].val; if (nLastTransparent === null) { nLastTransparent = nLastTempTransparent; } else { if (nLastTransparent !== nLastTempTransparent) { bCheckTransparent = false; break; } } } else { bCheckTransparent = false; break; } } } } else { bCheckTransparent = false; } } ret.fill.Colors.push(CreateAscColor(_fill.colors[i].color)); ret.fill.Positions.push(_fill.colors[i].pos); } if (bCheckTransparent && nLastTransparent !== null) { ret.transparent = (nLastTransparent / 100000) * 255; } if (_fill.lin) { ret.fill.GradType = c_oAscFillGradType.GRAD_LINEAR; ret.fill.LinearAngle = _fill.lin.angle; ret.fill.LinearScale = _fill.lin.scale; } else if (_fill.path) { ret.fill.GradType = c_oAscFillGradType.GRAD_PATH; ret.fill.PathType = 0; } else { ret.fill.GradType = c_oAscFillGradType.GRAD_LINEAR; ret.fill.LinearAngle = 0; ret.fill.LinearScale = false; } break; } case c_oAscFill.FILL_TYPE_BLIP: { ret.type = c_oAscFill.FILL_TYPE_BLIP; ret.fill = new Asc.asc_CFillBlip(); ret.fill.url = _fill.RasterImageId; ret.fill.type = (_fill.tile == null) ? c_oAscFillBlipType.STRETCH : c_oAscFillBlipType.TILE; break; } case c_oAscFill.FILL_TYPE_NOFILL: { ret.type = c_oAscFill.FILL_TYPE_NOFILL; break; } default: break; } if (isRealNumber(unifill.transparent)) { ret.transparent = unifill.transparent; } return ret; } function CorrectUniFill(asc_fill, unifill, editorId) { if (asc_fill instanceof CUniFill) { return asc_fill; } if (null == asc_fill) return unifill; var ret = unifill; if (null == ret) ret = new CUniFill(); var _fill = asc_fill.fill; var _type = asc_fill.type; if (null != _type) { switch (_type) { case c_oAscFill.FILL_TYPE_NOFILL: { ret.fill = new CNoFill(); break; } case c_oAscFill.FILL_TYPE_GRP: { ret.fill = new CGrpFill(); break; } case c_oAscFill.FILL_TYPE_BLIP: { var _url = _fill.url; var _tx_id = _fill.texture_id; if (null != _tx_id && (0 <= _tx_id) && (_tx_id < AscCommon.g_oUserTexturePresets.length)) { _url = AscCommon.g_oUserTexturePresets[_tx_id]; } if (ret.fill == null) { ret.fill = new CBlipFill(); } if (ret.fill.type !== c_oAscFill.FILL_TYPE_BLIP) { if (!(typeof (_url) === "string" && _url.length > 0) || !isRealNumber(_fill.type)) { break; } ret.fill = new CBlipFill(); } if (_url != null && _url !== undefined && _url != "") ret.fill.setRasterImageId(_url); if (ret.fill.RasterImageId == null) ret.fill.RasterImageId = ""; var tile = _fill.type; if (tile === c_oAscFillBlipType.STRETCH) { ret.fill.tile = null; ret.fill.srcRect = null; ret.fill.stretch = true; } else if (tile === c_oAscFillBlipType.TILE) { ret.fill.tile = new CBlipFillTile(); ret.fill.stretch = false; ret.fill.srcRect = null; } break; } case c_oAscFill.FILL_TYPE_PATT: { if (ret.fill == null) { ret.fill = new CPattFill(); } if (ret.fill.type != c_oAscFill.FILL_TYPE_PATT) { if (undefined != _fill.PatternType && undefined != _fill.fgClr && undefined != _fill.bgClr) { ret.fill = new CPattFill(); } else { break; } } if (undefined != _fill.PatternType) { ret.fill.ftype = _fill.PatternType; } if (undefined != _fill.fgClr) { ret.fill.fgClr = CorrectUniColor(_fill.fgClr, ret.fill.fgClr, editorId); } if (!ret.fill.fgClr) { ret.fill.fgClr = CreateUniColorRGB(0, 0, 0); } if (undefined != _fill.bgClr) { ret.fill.bgClr = CorrectUniColor(_fill.bgClr, ret.fill.bgClr, editorId); } if (!ret.fill.bgClr) { ret.fill.bgClr = CreateUniColorRGB(0, 0, 0); } break; } case c_oAscFill.FILL_TYPE_GRAD: { if (ret.fill == null) { ret.fill = new CGradFill(); } var _colors = _fill.Colors; var _positions = _fill.Positions; if (ret.fill.type != c_oAscFill.FILL_TYPE_GRAD) { if (undefined != _colors && undefined != _positions) { ret.fill = new CGradFill(); } else { break; } } if (undefined != _colors && undefined != _positions) { if (_colors.length === _positions.length) { if (ret.fill.colors.length === _colors.length) { for (var i = 0; i < _colors.length; i++) { var _gs = ret.fill.colors[i] ? ret.fill.colors[i] : new CGs(); _gs.color = CorrectUniColor(_colors[i], _gs.color, editorId); _gs.pos = _positions[i]; ret.fill.colors[i] = _gs; } } else { ret.fill.colors.length = 0; for (var i = 0; i < _colors.length; i++) { var _gs = new CGs(); _gs.color = CorrectUniColor(_colors[i], _gs.color, editorId); _gs.pos = _positions[i]; ret.fill.colors.push(_gs); } } } } else if (undefined != _colors) { if (_colors.length === ret.fill.colors.length) { for (var i = 0; i < _colors.length; i++) { ret.fill.colors[i].color = CorrectUniColor(_colors[i], ret.fill.colors[i].color, editorId); } } } else if (undefined != _positions) { if (_positions.length <= ret.fill.colors.length) { if (_positions.length < ret.fill.colors.length) { ret.fill.colors.splice(_positions.length, ret.fill.colors.length - _positions.length); } for (var i = 0; i < _positions.length; i++) { ret.fill.colors[i].pos = _positions[i]; } } } var _grad_type = _fill.GradType; if (c_oAscFillGradType.GRAD_LINEAR === _grad_type) { var _angle = _fill.LinearAngle; var _scale = _fill.LinearScale; if (!ret.fill.lin) { ret.fill.lin = new GradLin(); ret.fill.lin.angle = 0; ret.fill.lin.scale = false; } if (undefined != _angle) ret.fill.lin.angle = _angle; if (undefined != _scale) ret.fill.lin.scale = _scale; ret.fill.path = null; } else if (c_oAscFillGradType.GRAD_PATH === _grad_type) { ret.fill.lin = null; ret.fill.path = new GradPath(); } break; } default: { if (ret.fill == null || ret.fill.type !== c_oAscFill.FILL_TYPE_SOLID) { ret.fill = new CSolidFill(); } ret.fill.color = CorrectUniColor(_fill.color, ret.fill.color, editorId); } } } var _alpha = asc_fill.transparent; if (null != _alpha) { ret.transparent = _alpha; } if (ret.transparent != null) { if (ret.fill && ret.fill.type === c_oAscFill.FILL_TYPE_BLIP) { for (var i = 0; i < ret.fill.Effects.length; ++i) { if (ret.fill.Effects[i].Type === EFFECT_TYPE_ALPHAMODFIX) { ret.fill.Effects[i].amt = ((ret.transparent * 100000 / 255) >> 0); break; } } if (i === ret.fill.Effects.length) { var oEffect = new CAlphaModFix(); oEffect.amt = ((ret.transparent * 100000 / 255) >> 0); ret.fill.Effects.push(oEffect); } } } return ret; } // ัั‚ะฐ ั„ัƒะฝะบั†ะธั ะ”ะžะ›ะ–ะะ ะผะธะฝะธะผะธะทะธั€ะพะฒะฐั‚ัŒัั function CreateAscStroke(ln, _canChangeArrows) { if (null == ln || null == ln.Fill || ln.Fill.fill == null) return new Asc.asc_CStroke(); var ret = new Asc.asc_CStroke(); var _fill = ln.Fill.fill; if (_fill != null) { switch (_fill.type) { case c_oAscFill.FILL_TYPE_BLIP: { break; } case c_oAscFill.FILL_TYPE_SOLID: { ret.color = CreateAscColor(_fill.color); ret.type = c_oAscStrokeType.STROKE_COLOR; break; } case c_oAscFill.FILL_TYPE_GRAD: { var _c = _fill.colors; if (_c != 0) { ret.color = CreateAscColor(_fill.colors[0].color); ret.type = c_oAscStrokeType.STROKE_COLOR; } break; } case c_oAscFill.FILL_TYPE_PATT: { ret.color = CreateAscColor(_fill.fgClr); ret.type = c_oAscStrokeType.STROKE_COLOR; break; } case c_oAscFill.FILL_TYPE_NOFILL: { ret.color = null; ret.type = c_oAscStrokeType.STROKE_NONE; break; } default: { break; } } } ret.width = (ln.w == null) ? 12700 : (ln.w >> 0); ret.width /= 36000.0; if (ln.cap != null) ret.asc_putLinecap(ln.cap); if (ln.Join != null) ret.asc_putLinejoin(ln.Join.type); if (ln.headEnd != null) { ret.asc_putLinebeginstyle((ln.headEnd.type == null) ? LineEndType.None : ln.headEnd.type); var _len = (null == ln.headEnd.len) ? 1 : (2 - ln.headEnd.len); var _w = (null == ln.headEnd.w) ? 1 : (2 - ln.headEnd.w); ret.asc_putLinebeginsize(_w * 3 + _len); } else { ret.asc_putLinebeginstyle(LineEndType.None); } if (ln.tailEnd != null) { ret.asc_putLineendstyle((ln.tailEnd.type == null) ? LineEndType.None : ln.tailEnd.type); var _len = (null == ln.tailEnd.len) ? 1 : (2 - ln.tailEnd.len); var _w = (null == ln.tailEnd.w) ? 1 : (2 - ln.tailEnd.w); ret.asc_putLineendsize(_w * 3 + _len); } else { ret.asc_putLineendstyle(LineEndType.None); } if (AscFormat.isRealNumber(ln.prstDash)) { ret.prstDash = ln.prstDash; } else if (ln.prstDash === null) { ret.prstDash = Asc.c_oDashType.solid; } if (true === _canChangeArrows) ret.canChangeArrows = true; return ret; } function CorrectUniStroke(asc_stroke, unistroke, flag) { if (null == asc_stroke) return unistroke; var ret = unistroke; if (null == ret) ret = new CLn(); var _type = asc_stroke.type; var _w = asc_stroke.width; if (_w !== null && _w !== undefined) ret.w = _w * 36000.0; var _color = asc_stroke.color; if (_type === c_oAscStrokeType.STROKE_NONE) { ret.Fill = new CUniFill(); ret.Fill.fill = new CNoFill(); } else if (_type != null) { if (null !== _color && undefined !== _color) { ret.Fill = new CUniFill(); ret.Fill.type = c_oAscFill.FILL_TYPE_SOLID; ret.Fill.fill = new CSolidFill(); ret.Fill.fill.color = CorrectUniColor(_color, ret.Fill.fill.color, flag); } } var _join = asc_stroke.LineJoin; if (null != _join) { ret.Join = new LineJoin(); ret.Join.type = _join; } var _cap = asc_stroke.LineCap; if (null != _cap) { ret.cap = _cap; } var _begin_style = asc_stroke.LineBeginStyle; if (null != _begin_style) { if (ret.headEnd == null) ret.headEnd = new EndArrow(); ret.headEnd.type = _begin_style; } var _end_style = asc_stroke.LineEndStyle; if (null != _end_style) { if (ret.tailEnd == null) ret.tailEnd = new EndArrow(); ret.tailEnd.type = _end_style; } var _begin_size = asc_stroke.LineBeginSize; if (null != _begin_size) { if (ret.headEnd == null) ret.headEnd = new EndArrow(); ret.headEnd.w = 2 - ((_begin_size / 3) >> 0); ret.headEnd.len = 2 - (_begin_size % 3); } var _end_size = asc_stroke.LineEndSize; if (null != _end_size) { if (ret.tailEnd == null) ret.tailEnd = new EndArrow(); ret.tailEnd.w = 2 - ((_end_size / 3) >> 0); ret.tailEnd.len = 2 - (_end_size % 3); } if (AscFormat.isRealNumber(asc_stroke.prstDash)) { ret.prstDash = asc_stroke.prstDash; } return ret; } // ัั‚ะฐ ั„ัƒะฝะบั†ะธั ะ”ะžะ›ะ–ะะ ะผะธะฝะธะผะธะทะธั€ะพะฒะฐั‚ัŒัั function CreateAscShapeProp(shape) { if (null == shape) return new asc_CShapeProperty(); var ret = new asc_CShapeProperty(); ret.fill = CreateAscFill(shape.brush); ret.stroke = CreateAscStroke(shape.pen); ret.lockAspect = shape.getNoChangeAspect(); var paddings = null; if (shape.textBoxContent) { var body_pr = shape.bodyPr; paddings = new Asc.asc_CPaddings(); if (typeof body_pr.lIns === "number") paddings.Left = body_pr.lIns; else paddings.Left = 2.54; if (typeof body_pr.tIns === "number") paddings.Top = body_pr.tIns; else paddings.Top = 1.27; if (typeof body_pr.rIns === "number") paddings.Right = body_pr.rIns; else paddings.Right = 2.54; if (typeof body_pr.bIns === "number") paddings.Bottom = body_pr.bIns; else paddings.Bottom = 1.27; } return ret; } function CreateAscShapePropFromProp(shapeProp) { var obj = new asc_CShapeProperty(); if (!isRealObject(shapeProp)) return obj; if (isRealBool(shapeProp.locked)) { obj.Locked = shapeProp.locked; } obj.lockAspect = shapeProp.lockAspect; if (typeof shapeProp.type === "string") obj.type = shapeProp.type; if (isRealObject(shapeProp.fill)) obj.fill = CreateAscFill(shapeProp.fill); if (isRealObject(shapeProp.stroke)) obj.stroke = CreateAscStroke(shapeProp.stroke, shapeProp.canChangeArrows); if (isRealObject(shapeProp.paddings)) obj.paddings = shapeProp.paddings; if (shapeProp.canFill === true || shapeProp.canFill === false) { obj.canFill = shapeProp.canFill; } obj.bFromChart = shapeProp.bFromChart; obj.bFromSmartArt = shapeProp.bFromSmartArt; obj.bFromSmartArtInternal = shapeProp.bFromSmartArtInternal; obj.bFromGroup = shapeProp.bFromGroup; obj.bFromImage = shapeProp.bFromImage; obj.w = shapeProp.w; obj.h = shapeProp.h; obj.rot = shapeProp.rot; obj.flipH = shapeProp.flipH; obj.flipV = shapeProp.flipV; obj.vert = shapeProp.vert; obj.verticalTextAlign = shapeProp.verticalTextAlign; if (shapeProp.textArtProperties) { obj.textArtProperties = CreateAscTextArtProps(shapeProp.textArtProperties); } obj.title = shapeProp.title; obj.description = shapeProp.description; obj.columnNumber = shapeProp.columnNumber; obj.columnSpace = shapeProp.columnSpace; obj.textFitType = shapeProp.textFitType; obj.vertOverflowType = shapeProp.vertOverflowType; obj.shadow = shapeProp.shadow; if (shapeProp.signatureId) { obj.signatureId = shapeProp.signatureId; } if (shapeProp.signatureId) { obj.signatureId = shapeProp.signatureId; } obj.Position = new Asc.CPosition({X: shapeProp.x, Y: shapeProp.y}); return obj; } function CorrectShapeProp(asc_shape_prop, shape) { if (null == shape || null == asc_shape_prop) return; shape.spPr.Fill = CorrectUniFill(asc_shape_prop.asc_getFill(), shape.spPr.Fill); shape.spPr.ln = CorrectUniFill(asc_shape_prop.asc_getStroke(), shape.spPr.ln); } function CreateAscTextArtProps(oTextArtProps) { if (!oTextArtProps) { return undefined; } var oRet = new Asc.asc_TextArtProperties(); if (oTextArtProps.Fill) { oRet.asc_putFill(CreateAscFill(oTextArtProps.Fill)); } if (oTextArtProps.Line) { oRet.asc_putLine(CreateAscStroke(oTextArtProps.Line, false)); } oRet.asc_putForm(oTextArtProps.Form); return oRet; } function CreateUnifillFromAscColor(asc_color, editorId) { var Unifill = new CUniFill(); Unifill.fill = new CSolidFill(); Unifill.fill.color = CorrectUniColor(asc_color, Unifill.fill.color, editorId); return Unifill; } function CorrectUniColor(asc_color, unicolor, flag) { if (null == asc_color) return unicolor; var ret = unicolor; if (null == ret) ret = new CUniColor(); var _type = asc_color.asc_getType(); switch (_type) { case c_oAscColor.COLOR_TYPE_PRST: { if (ret.color == null || ret.color.type !== c_oAscColor.COLOR_TYPE_PRST) { ret.color = new CPrstColor(); } ret.color.id = asc_color.value; if (ret.Mods.Mods.length != 0) ret.Mods.Mods.splice(0, ret.Mods.Mods.length); break; } case c_oAscColor.COLOR_TYPE_SCHEME: { if (ret.color == null || ret.color.type !== c_oAscColor.COLOR_TYPE_SCHEME) { ret.color = new CSchemeColor(); } // ั‚ัƒั‚ ะฒั‹ัั‚ะฐะฒะปัะตั‚ัั ะขะžะ›ะฌะšะž ะธะท ะผะตะฝัŽ. ะฟะพัั‚ะพะผัƒ: var _index = parseInt(asc_color.value); if (isNaN(_index)) break; var _id = (_index / 6) >> 0; var _pos = _index - _id * 6; var array_colors_types = [6, 15, 7, 16, 0, 1, 2, 3, 4, 5]; ret.color.id = array_colors_types[_id]; if (!ret.Mods) { ret.setMods(new CColorModifiers()); } if (ret.Mods.Mods.length != 0) ret.Mods.Mods.splice(0, ret.Mods.Mods.length); var __mods = null; var _flag; if (editor && editor.WordControl && editor.WordControl.m_oDrawingDocument && editor.WordControl.m_oDrawingDocument.GuiControlColorsMap) { var _map = editor.WordControl.m_oDrawingDocument.GuiControlColorsMap; _flag = isRealNumber(flag) ? flag : 1; __mods = AscCommon.GetDefaultMods(_map[_id].r, _map[_id].g, _map[_id].b, _pos, _flag); } else { var _editor = window["Asc"] && window["Asc"]["editor"]; if (_editor && _editor.wbModel) { var _theme = _editor.wbModel.theme; var _clrMap = _editor.wbModel.clrSchemeMap; if (_theme && _clrMap) { var _schemeClr = new CSchemeColor(); _schemeClr.id = array_colors_types[_id]; var _rgba = {R: 0, G: 0, B: 0, A: 255}; _schemeClr.Calculate(_theme, _clrMap.color_map, _rgba); _flag = isRealNumber(flag) ? flag : 0; __mods = AscCommon.GetDefaultMods(_schemeClr.RGBA.R, _schemeClr.RGBA.G, _schemeClr.RGBA.B, _pos, _flag); } } } if (null != __mods) { ret.Mods.Mods = __mods; } break; } default: { if (ret.color == null || ret.color.type !== c_oAscColor.COLOR_TYPE_SRGB) { ret.color = new CRGBColor(); } ret.color.RGBA.R = asc_color.r; ret.color.RGBA.G = asc_color.g; ret.color.RGBA.B = asc_color.b; ret.color.RGBA.A = asc_color.a; if (ret.Mods && ret.Mods.Mods.length !== 0) ret.Mods.Mods.splice(0, ret.Mods.Mods.length); } } return ret; } function deleteDrawingBase(aObjects, graphicId) { var position = null; for (var i = 0; i < aObjects.length; i++) { if (aObjects[i].graphicObject.Get_Id() == graphicId) { aObjects.splice(i, 1); position = i; break; } } return position; } /* Common Functions For Builder*/ function builder_CreateShape(sType, nWidth, nHeight, oFill, oStroke, oParent, oTheme, oDrawingDocument, bWord, worksheet) { var oShapeTrack = new AscFormat.NewShapeTrack(sType, 0, 0, oTheme, null, null, null, 0); oShapeTrack.track({}, nWidth, nHeight); var oShape = oShapeTrack.getShape(bWord === true, oDrawingDocument, null); oShape.setParent(oParent); if (worksheet) { oShape.setWorksheet(worksheet); } if (bWord) { oShape.createTextBoxContent(); } else { oShape.createTextBody(); } oShape.spPr.setFill(oFill); oShape.spPr.setLn(oStroke); return oShape; } function ChartBuilderTypeToInternal(sType) { switch (sType) { case "bar" : { return Asc.c_oAscChartTypeSettings.barNormal; } case "barStacked": { return Asc.c_oAscChartTypeSettings.barStacked; } case "barStackedPercent": { return Asc.c_oAscChartTypeSettings.barStackedPer; } case "bar3D": { return Asc.c_oAscChartTypeSettings.barNormal3d; } case "barStacked3D": { return Asc.c_oAscChartTypeSettings.barStacked3d; } case "barStackedPercent3D": { return Asc.c_oAscChartTypeSettings.barStackedPer3d; } case "barStackedPercent3DPerspective": { return Asc.c_oAscChartTypeSettings.barNormal3dPerspective; } case "horizontalBar": { return Asc.c_oAscChartTypeSettings.hBarNormal; } case "horizontalBarStacked": { return Asc.c_oAscChartTypeSettings.hBarStacked; } case "horizontalBarStackedPercent": { return Asc.c_oAscChartTypeSettings.hBarStackedPer; } case "horizontalBar3D": { return Asc.c_oAscChartTypeSettings.hBarNormal3d; } case "horizontalBarStacked3D": { return Asc.c_oAscChartTypeSettings.hBarStacked3d; } case "horizontalBarStackedPercent3D": { return Asc.c_oAscChartTypeSettings.hBarStackedPer3d; } case "lineNormal": { return Asc.c_oAscChartTypeSettings.lineNormal; } case "lineStacked": { return Asc.c_oAscChartTypeSettings.lineStacked; } case "lineStackedPercent": { return Asc.c_oAscChartTypeSettings.lineStackedPer; } case "line3D": { return Asc.c_oAscChartTypeSettings.line3d; } case "pie": { return Asc.c_oAscChartTypeSettings.pie; } case "pie3D": { return Asc.c_oAscChartTypeSettings.pie3d; } case "doughnut": { return Asc.c_oAscChartTypeSettings.doughnut; } case "scatter": { return Asc.c_oAscChartTypeSettings.scatter; } case "stock": { return Asc.c_oAscChartTypeSettings.stock; } case "area": { return Asc.c_oAscChartTypeSettings.areaNormal; } case "areaStacked": { return Asc.c_oAscChartTypeSettings.areaStacked; } case "areaStackedPercent": { return Asc.c_oAscChartTypeSettings.areaStackedPer; } } return null; } function builder_CreateChart(nW, nH, sType, aCatNames, aSeriesNames, aSeries, nStyleIndex, aNumFormats) { var settings = new Asc.asc_ChartSettings(); settings.type = ChartBuilderTypeToInternal(sType); var aAscSeries = []; var aAlphaBet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; var oCat, i; if (aCatNames.length > 0) { var aNumCache = []; for (i = 0; i < aCatNames.length; ++i) { aNumCache.push({val: aCatNames[i] + ""}); } oCat = { Formula: "Sheet1!$B$1:$" + AscFormat.CalcLiterByLength(aAlphaBet, aCatNames.length) + "$1", NumCache: aNumCache }; } for (i = 0; i < aSeries.length; ++i) { var oAscSeries = new AscFormat.asc_CChartSeria(); oAscSeries.Val.NumCache = []; var aData = aSeries[i]; var sEndLiter = AscFormat.CalcLiterByLength(aAlphaBet, aData.length); oAscSeries.Val.Formula = 'Sheet1!' + '$B$' + (i + 2) + ':$' + sEndLiter + '$' + (i + 2); if (aSeriesNames[i]) { oAscSeries.TxCache.Formula = 'Sheet1!' + '$A$' + (i + 2); oAscSeries.TxCache.NumCache = [{ numFormatStr: "General", isDateTimeFormat: false, val: aSeriesNames[i], isHidden: false }]; } if (oCat) { oAscSeries.Cat = oCat; } if (Array.isArray(aNumFormats) && typeof (aNumFormats[i]) === "string") oAscSeries.FormatCode = aNumFormats[i]; for (var j = 0; j < aData.length; ++j) { oAscSeries.Val.NumCache.push({ numFormatStr: oAscSeries.FormatCode !== "" ? null : "General", isDateTimeFormat: false, val: aData[j], isHidden: false }); } aAscSeries.push(oAscSeries); } var oChartSpace = AscFormat.DrawingObjectsController.prototype._getChartSpace(aAscSeries, settings, true); if (!oChartSpace) { return null; } oChartSpace.setBDeleted(false); oChartSpace.extX = nW; oChartSpace.extY = nH; if (AscFormat.isRealNumber(nStyleIndex)) { oChartSpace.setStyle(nStyleIndex); } AscFormat.CheckSpPrXfrm(oChartSpace); return oChartSpace; } function builder_CreateGroup(aDrawings, oController) { if (!oController) { return null; } var aForGroup = []; for (var i = 0; i < aDrawings.length; ++i) { if (!aDrawings[i].Drawing || !aDrawings[i].Drawing.canGroup()) { return null; } aForGroup.push(aDrawings[i].Drawing); } return oController.getGroup(aForGroup); } function builder_CreateSchemeColor(sColorId) { var oUniColor = new AscFormat.CUniColor(); oUniColor.setColor(new AscFormat.CSchemeColor()); switch (sColorId) { case "accent1": { oUniColor.color.id = 0; break; } case "accent2": { oUniColor.color.id = 1; break; } case "accent3": { oUniColor.color.id = 2; break; } case "accent4": { oUniColor.color.id = 3; break; } case "accent5": { oUniColor.color.id = 4; break; } case "accent6": { oUniColor.color.id = 5; break; } case "bg1": { oUniColor.color.id = 6; break; } case "bg2": { oUniColor.color.id = 7; break; } case "dk1": { oUniColor.color.id = 8; break; } case "dk2": { oUniColor.color.id = 9; break; } case "lt1": { oUniColor.color.id = 12; break; } case "lt2": { oUniColor.color.id = 13; break; } case "tx1": { oUniColor.color.id = 15; break; } case "tx2": { oUniColor.color.id = 16; break; } default: { oUniColor.color.id = 16; break; } } return oUniColor; } function builder_CreatePresetColor(sPresetColor) { var oUniColor = new AscFormat.CUniColor(); oUniColor.setColor(new AscFormat.CPrstColor()); oUniColor.color.id = sPresetColor; return oUniColor; } function builder_CreateGradientStop(oUniColor, nPos) { var Gs = new AscFormat.CGs(); Gs.pos = nPos; Gs.color = oUniColor; return Gs; } function builder_CreateGradient(aGradientStop) { var oUniFill = new AscFormat.CUniFill(); oUniFill.fill = new AscFormat.CGradFill(); for (var i = 0; i < aGradientStop.length; ++i) { oUniFill.fill.colors.push(aGradientStop[i].Gs); } return oUniFill; } function builder_CreateLinearGradient(aGradientStop, Angle) { var oUniFill = builder_CreateGradient(aGradientStop); oUniFill.fill.lin = new AscFormat.GradLin(); if (!AscFormat.isRealNumber(Angle)) { oUniFill.fill.lin.angle = 0; } else { oUniFill.fill.lin.angle = Angle; } return oUniFill; } function builder_CreateRadialGradient(aGradientStop) { var oUniFill = builder_CreateGradient(aGradientStop); oUniFill.fill.path = new AscFormat.GradPath(); return oUniFill; } function builder_CreatePatternFill(sPatternType, BgColor, FgColor) { var oUniFill = new AscFormat.CUniFill(); oUniFill.fill = new AscFormat.CPattFill(); oUniFill.fill.ftype = AscCommon.global_hatch_offsets[sPatternType]; oUniFill.fill.fgClr = FgColor && FgColor.Unicolor; oUniFill.fill.bgClr = BgColor && BgColor.Unicolor; return oUniFill; } function builder_CreateBlipFill(sImageUrl, sBlipFillType) { var oUniFill = new AscFormat.CUniFill(); oUniFill.fill = new AscFormat.CBlipFill(); oUniFill.fill.RasterImageId = sImageUrl; if (sBlipFillType === "tile") { oUniFill.fill.tile = new AscFormat.CBlipFillTile(); } else if (sBlipFillType === "stretch") { oUniFill.fill.stretch = true; } return oUniFill; } function builder_CreateLine(nWidth, oFill) { if (nWidth === 0) { return new AscFormat.CreateNoFillLine(); } var oLn = new AscFormat.CLn(); oLn.w = nWidth; oLn.Fill = oFill.UniFill; return oLn; } function builder_CreateChartTitle(sTitle, nFontSize, bIsBold, oDrawingDocument) { if (typeof sTitle === "string" && sTitle.length > 0) { var oTitle = new AscFormat.CTitle(); oTitle.setOverlay(false); oTitle.setTx(new AscFormat.CChartText()); var oTextBody = AscFormat.CreateTextBodyFromString(sTitle, oDrawingDocument, oTitle.tx); if (AscFormat.isRealNumber(nFontSize)) { oTextBody.content.SetApplyToAll(true); oTextBody.content.AddToParagraph(new ParaTextPr({FontSize: nFontSize, Bold: bIsBold})); oTextBody.content.SetApplyToAll(false); } oTitle.tx.setRich(oTextBody); return oTitle; } return null; } function builder_CreateTitle(sTitle, nFontSize, bIsBold, oChartSpace) { if (typeof sTitle === "string" && sTitle.length > 0) { var oTitle = new AscFormat.CTitle(); oTitle.setOverlay(false); oTitle.setTx(new AscFormat.CChartText()); var oTextBody = AscFormat.CreateTextBodyFromString(sTitle, oChartSpace.getDrawingDocument(), oTitle.tx); if (AscFormat.isRealNumber(nFontSize)) { oTextBody.content.SetApplyToAll(true); oTextBody.content.AddToParagraph(new ParaTextPr({FontSize: nFontSize, Bold: bIsBold})); oTextBody.content.SetApplyToAll(false); } oTitle.tx.setRich(oTextBody); return oTitle; } return null; } function builder_SetChartTitle(oChartSpace, sTitle, nFontSize, bIsBold) { if (oChartSpace) { oChartSpace.chart.setTitle(builder_CreateChartTitle(sTitle, nFontSize, bIsBold, oChartSpace.getDrawingDocument())); } } function builder_SetChartHorAxisTitle(oChartSpace, sTitle, nFontSize, bIsBold) { if (oChartSpace) { var horAxis = oChartSpace.chart.plotArea.getHorizontalAxis(); if (horAxis) { horAxis.setTitle(builder_CreateTitle(sTitle, nFontSize, bIsBold, oChartSpace)); } } } function builder_SetChartVertAxisTitle(oChartSpace, sTitle, nFontSize, bIsBold) { if (oChartSpace) { var verAxis = oChartSpace.chart.plotArea.getVerticalAxis(); if (verAxis) { if (typeof sTitle === "string" && sTitle.length > 0) { verAxis.setTitle(builder_CreateTitle(sTitle, nFontSize, bIsBold, oChartSpace)); if (verAxis.title) { var _body_pr = new AscFormat.CBodyPr(); _body_pr.reset(); if (!verAxis.title.txPr) { verAxis.title.setTxPr(AscFormat.CreateTextBodyFromString("", oChartSpace.getDrawingDocument(), verAxis.title)); } var _text_body = verAxis.title.txPr; _text_body.setBodyPr(_body_pr); verAxis.title.setOverlay(false); } } else { verAxis.setTitle(null); } } } } function builder_SetChartVertAxisOrientation(oChartSpace, bIsMinMax) { if (oChartSpace) { var verAxis = oChartSpace.chart.plotArea.getVerticalAxis(); if (verAxis) { if (!verAxis.scaling) verAxis.setScaling(new AscFormat.CScaling()); var scaling = verAxis.scaling; if (bIsMinMax) { scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); } else { scaling.setOrientation(AscFormat.ORIENTATION_MAX_MIN); } } } } function builder_SetChartHorAxisOrientation(oChartSpace, bIsMinMax) { if (oChartSpace) { var horAxis = oChartSpace.chart.plotArea.getHorizontalAxis(); if (horAxis) { if (!horAxis.scaling) horAxis.setScaling(new AscFormat.CScaling()); var scaling = horAxis.scaling; if (bIsMinMax) { scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); } else { scaling.setOrientation(AscFormat.ORIENTATION_MAX_MIN); } } } } function builder_SetChartLegendPos(oChartSpace, sLegendPos) { if (oChartSpace && oChartSpace.chart) { if (sLegendPos === "none") { if (oChartSpace.chart.legend) { oChartSpace.chart.setLegend(null); } } else { var nLegendPos = null; switch (sLegendPos) { case "left": { nLegendPos = Asc.c_oAscChartLegendShowSettings.left; break; } case "top": { nLegendPos = Asc.c_oAscChartLegendShowSettings.top; break; } case "right": { nLegendPos = Asc.c_oAscChartLegendShowSettings.right; break; } case "bottom": { nLegendPos = Asc.c_oAscChartLegendShowSettings.bottom; break; } } if (null !== nLegendPos) { if (!oChartSpace.chart.legend) { oChartSpace.chart.setLegend(new AscFormat.CLegend()); } if (oChartSpace.chart.legend.legendPos !== nLegendPos) oChartSpace.chart.legend.setLegendPos(nLegendPos); if (oChartSpace.chart.legend.overlay !== false) { oChartSpace.chart.legend.setOverlay(false); } } } } } function builder_SetObjectFontSize(oObject, nFontSize, oDrawingDocument) { if (!oObject) { return; } if (!oObject.txPr) { oObject.setTxPr(new AscFormat.CTextBody()); } if (!oObject.txPr.bodyPr) { oObject.txPr.setBodyPr(new AscFormat.CBodyPr()); } if (!oObject.txPr.content) { oObject.txPr.setContent(new AscFormat.CDrawingDocContent(oObject.txPr, oDrawingDocument, 0, 0, 100, 500, false, false, true)); } var oPr = oObject.txPr.content.Content[0].Pr.Copy(); if (!oPr.DefaultRunPr) { oPr.DefaultRunPr = new AscCommonWord.CTextPr(); } oPr.DefaultRunPr.FontSize = nFontSize; oObject.txPr.content.Content[0].Set_Pr(oPr); } function builder_SetLegendFontSize(oChartSpace, nFontSize) { builder_SetObjectFontSize(oChartSpace.chart.legend, nFontSize, oChartSpace.getDrawingDocument()); } function builder_SetHorAxisFontSize(oChartSpace, nFontSize) { builder_SetObjectFontSize(oChartSpace.chart.plotArea.getHorizontalAxis(), nFontSize, oChartSpace.getDrawingDocument()); } function builder_SetVerAxisFontSize(oChartSpace, nFontSize) { builder_SetObjectFontSize(oChartSpace.chart.plotArea.getVerticalAxis(), nFontSize, oChartSpace.getDrawingDocument()); } function builder_SetShowPointDataLabel(oChartSpace, nSeriesIndex, nPointIndex, bShowSerName, bShowCatName, bShowVal, bShowPerecent) { if (oChartSpace && oChartSpace.chart && oChartSpace.chart.plotArea && oChartSpace.chart.plotArea.charts[0]) { var oChart = oChartSpace.chart.plotArea.charts[0]; var bPieChart = oChart.getObjectType() === AscDFH.historyitem_type_PieChart || oChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart; var ser = oChart.series[nSeriesIndex]; if (ser) { { if (!ser.dLbls) { if (oChart.dLbls) { ser.setDLbls(oChart.dLbls.createDuplicate()); } else { ser.setDLbls(new AscFormat.CDLbls()); ser.dLbls.setSeparator(","); ser.dLbls.setShowSerName(false); ser.dLbls.setShowCatName(false); ser.dLbls.setShowVal(false); ser.dLbls.setShowLegendKey(false); if (bPieChart) { ser.dLbls.setShowPercent(false); } ser.dLbls.setShowBubbleSize(false); } } var dLbl = ser.dLbls && ser.dLbls.findDLblByIdx(nPointIndex); if (!dLbl) { dLbl = new AscFormat.CDLbl(); dLbl.setIdx(nPointIndex); if (ser.dLbls.txPr) { dLbl.merge(ser.dLbls); } ser.dLbls.addDLbl(dLbl); } dLbl.setSeparator(","); dLbl.setShowSerName(true == bShowSerName); dLbl.setShowCatName(true == bShowCatName); dLbl.setShowVal(true == bShowVal); dLbl.setShowLegendKey(false); if (bPieChart) { dLbl.setShowPercent(true === bShowPerecent); } dLbl.setShowBubbleSize(false); } } } } function builder_SetShowDataLabels(oChartSpace, bShowSerName, bShowCatName, bShowVal, bShowPerecent) { if (oChartSpace && oChartSpace.chart && oChartSpace.chart.plotArea && oChartSpace.chart.plotArea.charts[0]) { var oChart = oChartSpace.chart.plotArea.charts[0]; var bPieChart = oChart.getObjectType() === AscDFH.historyitem_type_PieChart || oChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart; if (false == bShowSerName && false == bShowCatName && false == bShowVal && (bPieChart && bShowPerecent === false)) { if (oChart.dLbls) { oChart.setDLbls(null); } } if (!oChart.dLbls) { oChart.setDLbls(new AscFormat.CDLbls()); } oChart.dLbls.setSeparator(","); oChart.dLbls.setShowSerName(true == bShowSerName); oChart.dLbls.setShowCatName(true == bShowCatName); oChart.dLbls.setShowVal(true == bShowVal); oChart.dLbls.setShowLegendKey(false); if (bPieChart) { oChart.dLbls.setShowPercent(true === bShowPerecent); } oChart.dLbls.setShowBubbleSize(false); } } function builder_SetChartAxisLabelsPos(oAxis, sPosition) { if (!oAxis || !oAxis.setTickLblPos) { return; } var nPositionType = null; var c_oAscTickLabelsPos = window['Asc'].c_oAscTickLabelsPos; switch (sPosition) { case "high": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH; break; } case "low": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW; break; } case "nextTo": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO; break; } case "none": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE; break; } } if (nPositionType !== null) { oAxis.setTickLblPos(nPositionType); } } function builder_SetChartVertAxisTickLablePosition(oChartSpace, sPosition) { if (oChartSpace) { builder_SetChartAxisLabelsPos(oChartSpace.chart.plotArea.getVerticalAxis(), sPosition); } } function builder_SetChartHorAxisTickLablePosition(oChartSpace, sPosition) { if (oChartSpace) { builder_SetChartAxisLabelsPos(oChartSpace.chart.plotArea.getHorizontalAxis(), sPosition); } } function builder_GetTickMark(sTickMark) { var nNewTickMark = null; switch (sTickMark) { case 'cross': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_CROSS; break; } case 'in': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_IN; break; } case 'none': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_NONE; break; } case 'out': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_OUT; break; } } return nNewTickMark; } function builder_SetChartAxisMajorTickMark(oAxis, sTickMark) { if (!oAxis) { return; } var nNewTickMark = builder_GetTickMark(sTickMark); if (nNewTickMark !== null) { oAxis.setMajorTickMark(nNewTickMark); } } function builder_SetChartAxisMinorTickMark(oAxis, sTickMark) { if (!oAxis) { return; } var nNewTickMark = builder_GetTickMark(sTickMark); if (nNewTickMark !== null) { oAxis.setMinorTickMark(nNewTickMark); } } function builder_SetChartHorAxisMajorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMajorTickMark(oChartSpace.chart.plotArea.getHorizontalAxis(), sTickMark); } } function builder_SetChartHorAxisMinorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMinorTickMark(oChartSpace.chart.plotArea.getHorizontalAxis(), sTickMark); } } function builder_SetChartVerAxisMajorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMajorTickMark(oChartSpace.chart.plotArea.getVerticalAxis(), sTickMark); } } function builder_SetChartVerAxisMinorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMinorTickMark(oChartSpace.chart.plotArea.getVerticalAxis(), sTickMark); } } function builder_SetAxisMajorGridlines(oAxis, oLn) { if (oAxis) { if (!oAxis.majorGridlines) { oAxis.setMajorGridlines(new AscFormat.CSpPr()); } oAxis.majorGridlines.setLn(oLn); if (!oAxis.majorGridlines.Fill && !oAxis.majorGridlines.ln) { oAxis.setMajorGridlines(null); } } } function builder_SetAxisMinorGridlines(oAxis, oLn) { if (oAxis) { if (!oAxis.minorGridlines) { oAxis.setMinorGridlines(new AscFormat.CSpPr()); } oAxis.minorGridlines.setLn(oLn); if (!oAxis.minorGridlines.Fill && !oAxis.minorGridlines.ln) { oAxis.setMinorGridlines(null); } } } function builder_SetHorAxisMajorGridlines(oChartSpace, oLn) { builder_SetAxisMajorGridlines(oChartSpace.chart.plotArea.getVerticalAxis(), oLn); } function builder_SetHorAxisMinorGridlines(oChartSpace, oLn) { builder_SetAxisMinorGridlines(oChartSpace.chart.plotArea.getVerticalAxis(), oLn); } function builder_SetVerAxisMajorGridlines(oChartSpace, oLn) { builder_SetAxisMajorGridlines(oChartSpace.chart.plotArea.getHorizontalAxis(), oLn); } function builder_SetVerAxisMinorGridlines(oChartSpace, oLn) { builder_SetAxisMinorGridlines(oChartSpace.chart.plotArea.getHorizontalAxis(), oLn); } //----------------------------------------------------------export---------------------------------------------------- window['AscFormat'] = window['AscFormat'] || {}; window['AscFormat'].CreateFontRef = CreateFontRef; window['AscFormat'].CreatePresetColor = CreatePresetColor; window['AscFormat'].isRealNumber = isRealNumber; window['AscFormat'].isRealBool = isRealBool; window['AscFormat'].writeLong = writeLong; window['AscFormat'].readLong = readLong; window['AscFormat'].writeDouble = writeDouble; window['AscFormat'].readDouble = readDouble; window['AscFormat'].writeBool = writeBool; window['AscFormat'].readBool = readBool; window['AscFormat'].writeString = writeString; window['AscFormat'].readString = readString; window['AscFormat'].writeObject = writeObject; window['AscFormat'].readObject = readObject; window['AscFormat'].checkThemeFonts = checkThemeFonts; window['AscFormat'].ExecuteNoHistory = ExecuteNoHistory; window['AscFormat'].checkTableCellPr = checkTableCellPr; window['AscFormat'].CColorMod = CColorMod; window['AscFormat'].CColorModifiers = CColorModifiers; window['AscFormat'].CSysColor = CSysColor; window['AscFormat'].CPrstColor = CPrstColor; window['AscFormat'].CRGBColor = CRGBColor; window['AscFormat'].CSchemeColor = CSchemeColor; window['AscFormat'].CStyleColor = CStyleColor; window['AscFormat'].CUniColor = CUniColor; window['AscFormat'].CreateUniColorRGB = CreateUniColorRGB; window['AscFormat'].CreateUniColorRGB2 = CreateUniColorRGB2; window['AscFormat'].CreateSolidFillRGB = CreateSolidFillRGB; window['AscFormat'].CreateSolidFillRGBA = CreateSolidFillRGBA; window['AscFormat'].CSrcRect = CSrcRect; window['AscFormat'].CBlipFillTile = CBlipFillTile; window['AscFormat'].CBlipFill = CBlipFill; window['AscFormat'].CSolidFill = CSolidFill; window['AscFormat'].CGs = CGs; window['AscFormat'].GradLin = GradLin; window['AscFormat'].GradPath = GradPath; window['AscFormat'].CGradFill = CGradFill; window['AscFormat'].CPattFill = CPattFill; window['AscFormat'].CNoFill = CNoFill; window['AscFormat'].CGrpFill = CGrpFill; window['AscFormat'].CUniFill = CUniFill; window['AscFormat'].CompareUniFill = CompareUniFill; window['AscFormat'].CompareUnifillBool = CompareUnifillBool; window['AscFormat'].CompareShapeProperties = CompareShapeProperties; window['AscFormat'].CompareProtectionFlags = CompareProtectionFlags; window['AscFormat'].EndArrow = EndArrow; window['AscFormat'].ConvertJoinAggType = ConvertJoinAggType; window['AscFormat'].LineJoin = LineJoin; window['AscFormat'].CLn = CLn; window['AscFormat'].DefaultShapeDefinition = DefaultShapeDefinition; window['AscFormat'].CNvPr = CNvPr; window['AscFormat'].NvPr = NvPr; window['AscFormat'].Ph = Ph; window['AscFormat'].UniNvPr = UniNvPr; window['AscFormat'].StyleRef = StyleRef; window['AscFormat'].FontRef = FontRef; window['AscFormat'].CShapeStyle = CShapeStyle; window['AscFormat'].CreateDefaultShapeStyle = CreateDefaultShapeStyle; window['AscFormat'].CXfrm = CXfrm; window['AscFormat'].CEffectProperties = CEffectProperties; window['AscFormat'].CEffectLst = CEffectLst; window['AscFormat'].CSpPr = CSpPr; window['AscFormat'].ClrScheme = ClrScheme; window['AscFormat'].ClrMap = ClrMap; window['AscFormat'].ExtraClrScheme = ExtraClrScheme; window['AscFormat'].FontCollection = FontCollection; window['AscFormat'].FontScheme = FontScheme; window['AscFormat'].FmtScheme = FmtScheme; window['AscFormat'].ThemeElements = ThemeElements; window['AscFormat'].CTheme = CTheme; window['AscFormat'].HF = HF; window['AscFormat'].CBgPr = CBgPr; window['AscFormat'].CBg = CBg; window['AscFormat'].CSld = CSld; window['AscFormat'].CTextStyles = CTextStyles; window['AscFormat'].redrawSlide = redrawSlide; window['AscFormat'].CTextFit = CTextFit; window['AscFormat'].CBodyPr = CBodyPr; window['AscFormat'].CTextParagraphPr = CTextParagraphPr; window['AscFormat'].CompareBullets = CompareBullets; window['AscFormat'].CBuBlip = CBuBlip; window['AscFormat'].CBullet = CBullet; window['AscFormat'].CBulletColor = CBulletColor; window['AscFormat'].CBulletSize = CBulletSize; window['AscFormat'].CBulletTypeface = CBulletTypeface; window['AscFormat'].CBulletType = CBulletType; window['AscFormat'].TextListStyle = TextListStyle; window['AscFormat'].GenerateDefaultTheme = GenerateDefaultTheme; window['AscFormat'].GenerateDefaultMasterSlide = GenerateDefaultMasterSlide; window['AscFormat'].GenerateDefaultSlideLayout = GenerateDefaultSlideLayout; window['AscFormat'].GenerateDefaultSlide = GenerateDefaultSlide; window['AscFormat'].CreateDefaultTextRectStyle = CreateDefaultTextRectStyle; window['AscFormat'].GenerateDefaultColorMap = GenerateDefaultColorMap; window['AscFormat'].CreateAscFill = CreateAscFill; window['AscFormat'].CorrectUniFill = CorrectUniFill; window['AscFormat'].CreateAscStroke = CreateAscStroke; window['AscFormat'].CorrectUniStroke = CorrectUniStroke; window['AscFormat'].CreateAscShapePropFromProp = CreateAscShapePropFromProp; window['AscFormat'].CreateAscTextArtProps = CreateAscTextArtProps; window['AscFormat'].CreateUnifillFromAscColor = CreateUnifillFromAscColor; window['AscFormat'].CorrectUniColor = CorrectUniColor; window['AscFormat'].deleteDrawingBase = deleteDrawingBase; window['AscFormat'].CNvUniSpPr = CNvUniSpPr; window['AscFormat'].UniMedia = UniMedia; window['AscFormat'].CT_Hyperlink = CT_Hyperlink; window['AscFormat'].builder_CreateShape = builder_CreateShape; window['AscFormat'].builder_CreateChart = builder_CreateChart; window['AscFormat'].builder_CreateGroup = builder_CreateGroup; window['AscFormat'].builder_CreateSchemeColor = builder_CreateSchemeColor; window['AscFormat'].builder_CreatePresetColor = builder_CreatePresetColor; window['AscFormat'].builder_CreateGradientStop = builder_CreateGradientStop; window['AscFormat'].builder_CreateLinearGradient = builder_CreateLinearGradient; window['AscFormat'].builder_CreateRadialGradient = builder_CreateRadialGradient; window['AscFormat'].builder_CreatePatternFill = builder_CreatePatternFill; window['AscFormat'].builder_CreateBlipFill = builder_CreateBlipFill; window['AscFormat'].builder_CreateLine = builder_CreateLine; window['AscFormat'].builder_SetChartTitle = builder_SetChartTitle; window['AscFormat'].builder_SetChartHorAxisTitle = builder_SetChartHorAxisTitle; window['AscFormat'].builder_SetChartVertAxisTitle = builder_SetChartVertAxisTitle; window['AscFormat'].builder_SetChartLegendPos = builder_SetChartLegendPos; window['AscFormat'].builder_SetShowDataLabels = builder_SetShowDataLabels; window['AscFormat'].builder_SetChartVertAxisOrientation = builder_SetChartVertAxisOrientation; window['AscFormat'].builder_SetChartHorAxisOrientation = builder_SetChartHorAxisOrientation; window['AscFormat'].builder_SetChartVertAxisTickLablePosition = builder_SetChartVertAxisTickLablePosition; window['AscFormat'].builder_SetChartHorAxisTickLablePosition = builder_SetChartHorAxisTickLablePosition; window['AscFormat'].builder_SetChartHorAxisMajorTickMark = builder_SetChartHorAxisMajorTickMark; window['AscFormat'].builder_SetChartHorAxisMinorTickMark = builder_SetChartHorAxisMinorTickMark; window['AscFormat'].builder_SetChartVerAxisMajorTickMark = builder_SetChartVerAxisMajorTickMark; window['AscFormat'].builder_SetChartVerAxisMinorTickMark = builder_SetChartVerAxisMinorTickMark; window['AscFormat'].builder_SetLegendFontSize = builder_SetLegendFontSize; window['AscFormat'].builder_SetHorAxisMajorGridlines = builder_SetHorAxisMajorGridlines; window['AscFormat'].builder_SetHorAxisMinorGridlines = builder_SetHorAxisMinorGridlines; window['AscFormat'].builder_SetVerAxisMajorGridlines = builder_SetVerAxisMajorGridlines; window['AscFormat'].builder_SetVerAxisMinorGridlines = builder_SetVerAxisMinorGridlines; window['AscFormat'].builder_SetHorAxisFontSize = builder_SetHorAxisFontSize; window['AscFormat'].builder_SetVerAxisFontSize = builder_SetVerAxisFontSize; window['AscFormat'].builder_SetShowPointDataLabel = builder_SetShowPointDataLabel; window['AscFormat'].Ax_Counter = Ax_Counter; window['AscFormat'].TYPE_TRACK = TYPE_TRACK; window['AscFormat'].TYPE_KIND = TYPE_KIND; window['AscFormat'].mapPrstColor = map_prst_color; window['AscFormat'].map_hightlight = map_hightlight; window['AscFormat'].ar_arrow = ar_arrow; window['AscFormat'].ar_diamond = ar_diamond; window['AscFormat'].ar_none = ar_none; window['AscFormat'].ar_oval = ar_oval; window['AscFormat'].ar_stealth = ar_stealth; window['AscFormat'].ar_triangle = ar_triangle; window['AscFormat'].LineEndType = LineEndType; window['AscFormat'].LineEndSize = LineEndSize; window['AscFormat'].LineJoinType = LineJoinType; //ั‚ะธะฟั‹ ะฟะปะตะนัั…ะพะปะดะตั€ะพะฒ window['AscFormat'].phType_body = 0; window['AscFormat'].phType_chart = 1; window['AscFormat'].phType_clipArt = 2; //(Clip Art) window['AscFormat'].phType_ctrTitle = 3; //(Centered Title) window['AscFormat'].phType_dgm = 4; //(Diagram) window['AscFormat'].phType_dt = 5; //(Date and Time) window['AscFormat'].phType_ftr = 6; //(Footer) window['AscFormat'].phType_hdr = 7; //(Header) window['AscFormat'].phType_media = 8; //(Media) window['AscFormat'].phType_obj = 9; //(Object) window['AscFormat'].phType_pic = 10; //(Picture) window['AscFormat'].phType_sldImg = 11; //(Slide Image) window['AscFormat'].phType_sldNum = 12; //(Slide Number) window['AscFormat'].phType_subTitle = 13; //(Subtitle) window['AscFormat'].phType_tbl = 14; //(Table) window['AscFormat'].phType_title = 15; //(Title) window['AscFormat'].fntStyleInd_none = 2; window['AscFormat'].fntStyleInd_major = 0; window['AscFormat'].fntStyleInd_minor = 1; window['AscFormat'].VERTICAL_ANCHOR_TYPE_BOTTOM = 0; window['AscFormat'].VERTICAL_ANCHOR_TYPE_CENTER = 1; window['AscFormat'].VERTICAL_ANCHOR_TYPE_DISTRIBUTED = 2; window['AscFormat'].VERTICAL_ANCHOR_TYPE_JUSTIFIED = 3; window['AscFormat'].VERTICAL_ANCHOR_TYPE_TOP = 4; //Vertical Text Types window['AscFormat'].nVertTTeaVert = 0; //( ( East Asian Vertical )) window['AscFormat'].nVertTThorz = 1; //( ( Horizontal )) window['AscFormat'].nVertTTmongolianVert = 2; //( ( Mongolian Vertical )) window['AscFormat'].nVertTTvert = 3; //( ( Vertical )) window['AscFormat'].nVertTTvert270 = 4;//( ( Vertical 270 )) window['AscFormat'].nVertTTwordArtVert = 5;//( ( WordArt Vertical )) window['AscFormat'].nVertTTwordArtVertRtl = 6;//(Vertical WordArt Right to Left) //Text Wrapping Types window['AscFormat'].nTWTNone = 0; window['AscFormat'].nTWTSquare = 1; window['AscFormat'].BULLET_TYPE_COLOR_NONE = 0; window['AscFormat'].BULLET_TYPE_COLOR_CLRTX = 1; window['AscFormat'].BULLET_TYPE_COLOR_CLR = 2; window['AscFormat'].BULLET_TYPE_SIZE_NONE = 0; window['AscFormat'].BULLET_TYPE_SIZE_TX = 1; window['AscFormat'].BULLET_TYPE_SIZE_PCT = 2; window['AscFormat'].BULLET_TYPE_SIZE_PTS = 3; window['AscFormat'].BULLET_TYPE_TYPEFACE_NONE = 0; window['AscFormat'].BULLET_TYPE_TYPEFACE_TX = 1; window['AscFormat'].BULLET_TYPE_TYPEFACE_BUFONT = 2; window['AscFormat'].PARRUN_TYPE_NONE = 0; window['AscFormat'].PARRUN_TYPE_RUN = 1; window['AscFormat'].PARRUN_TYPE_FLD = 2; window['AscFormat'].PARRUN_TYPE_BR = 3; window['AscFormat'].PARRUN_TYPE_MATH = 4; window['AscFormat'].PARRUN_TYPE_MATHPARA = 5; window['AscFormat']._weight_body = _weight_body; window['AscFormat']._weight_chart = _weight_chart; window['AscFormat']._weight_clipArt = _weight_clipArt; window['AscFormat']._weight_ctrTitle = _weight_ctrTitle; window['AscFormat']._weight_dgm = _weight_dgm; window['AscFormat']._weight_media = _weight_media; window['AscFormat']._weight_obj = _weight_obj; window['AscFormat']._weight_pic = _weight_pic; window['AscFormat']._weight_subTitle = _weight_subTitle; window['AscFormat']._weight_tbl = _weight_tbl; window['AscFormat']._weight_title = _weight_title; window['AscFormat']._ph_multiplier = _ph_multiplier; window['AscFormat'].nSldLtTTitle = nSldLtTTitle; window['AscFormat'].nSldLtTObj = nSldLtTObj; window['AscFormat'].nSldLtTTx = nSldLtTTx; window['AscFormat']._arr_lt_types_weight = _arr_lt_types_weight; window['AscFormat']._global_layout_summs_array = _global_layout_summs_array; window['AscFormat'].AUDIO_CD = AUDIO_CD; window['AscFormat'].WAV_AUDIO_FILE = WAV_AUDIO_FILE; window['AscFormat'].AUDIO_FILE = AUDIO_FILE; window['AscFormat'].VIDEO_FILE = VIDEO_FILE; window['AscFormat'].QUICK_TIME_FILE = QUICK_TIME_FILE; window['AscFormat'].fCreateEffectByType = fCreateEffectByType; window['AscFormat'].COuterShdw = COuterShdw; window['AscFormat'].CGlow = CGlow; window['AscFormat'].CDuotone = CDuotone; window['AscFormat'].CXfrmEffect = CXfrmEffect; window['AscFormat'].CBlur = CBlur; window['AscFormat'].CPrstShdw = CPrstShdw; window['AscFormat'].CInnerShdw = CInnerShdw; window['AscFormat'].CReflection = CReflection; window['AscFormat'].CSoftEdge = CSoftEdge; window['AscFormat'].CFillOverlay = CFillOverlay; window['AscFormat'].CAlphaCeiling = CAlphaCeiling; window['AscFormat'].CAlphaFloor = CAlphaFloor; window['AscFormat'].CTintEffect = CTintEffect; window['AscFormat'].CRelOff = CRelOff; window['AscFormat'].CLumEffect = CLumEffect; window['AscFormat'].CHslEffect = CHslEffect; window['AscFormat'].CGrayscl = CGrayscl; window['AscFormat'].CEffectElement = CEffectElement; window['AscFormat'].CAlphaRepl = CAlphaRepl; window['AscFormat'].CAlphaOutset = CAlphaOutset; window['AscFormat'].CAlphaModFix = CAlphaModFix; window['AscFormat'].CAlphaBiLevel = CAlphaBiLevel; window['AscFormat'].CBiLevel = CBiLevel; window['AscFormat'].CEffectContainer = CEffectContainer; window['AscFormat'].CFillEffect = CFillEffect; window['AscFormat'].CClrRepl = CClrRepl; window['AscFormat'].CClrChange = CClrChange; window['AscFormat'].CAlphaInv = CAlphaInv; window['AscFormat'].CAlphaMod = CAlphaMod; window['AscFormat'].CBlend = CBlend; window['AscFormat'].CreateNoneBullet = CreateNoneBullet; window['AscFormat'].ChartBuilderTypeToInternal = ChartBuilderTypeToInternal; window['AscFormat'].InitClass = InitClass; window['AscFormat'].InitClassWithoutType = InitClassWithoutType; window['AscFormat'].CBaseObject = CBaseObject; window['AscFormat'].CBaseFormatObject = CBaseFormatObject; window['AscFormat'].CBaseNoIdObject = CBaseNoIdObject; window['AscFormat'].checkRasterImageId = checkRasterImageId; window['AscFormat'].IdEntry = IdEntry; window['AscFormat'].DEFAULT_COLOR_MAP = null; window['AscFormat'].DEFAULT_THEME = null; window['AscFormat'].GetDefaultColorMap = GetDefaultColorMap; window['AscFormat'].GetDefaultTheme = GetDefaultTheme; window['AscFormat'].getPercentageValue = getPercentageValue; window['AscFormat'].getPercentageValueForWrite = getPercentageValueForWrite; window['AscFormat'].CSpTree = CSpTree; window['AscFormat'].CClrMapOvr = CClrMapOvr; window['AscFormat'].fReadXmlRasterImageId = fReadXmlRasterImageId; }) (window);
common/Drawings/Format/Format.js
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; ( /** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { var recalcSlideInterval = 30; // Import var CreateAscColor = AscCommon.CreateAscColor; var g_oIdCounter = AscCommon.g_oIdCounter; var g_oTableId = AscCommon.g_oTableId; var isRealObject = AscCommon.isRealObject; var History = AscCommon.History; var c_oAscColor = Asc.c_oAscColor; var c_oAscFill = Asc.c_oAscFill; var asc_CShapeFill = Asc.asc_CShapeFill; var c_oAscFillGradType = Asc.c_oAscFillGradType; var c_oAscFillBlipType = Asc.c_oAscFillBlipType; var c_oAscStrokeType = Asc.c_oAscStrokeType; var asc_CShapeProperty = Asc.asc_CShapeProperty; var g_nodeAttributeStart = AscCommon.g_nodeAttributeStart; var g_nodeAttributeEnd = AscCommon.g_nodeAttributeEnd; var CChangesDrawingsBool = AscDFH.CChangesDrawingsBool; var CChangesDrawingsLong = AscDFH.CChangesDrawingsLong; var CChangesDrawingsDouble = AscDFH.CChangesDrawingsDouble; var CChangesDrawingsString = AscDFH.CChangesDrawingsString; var CChangesDrawingsObjectNoId = AscDFH.CChangesDrawingsObjectNoId; var CChangesDrawingsObject = AscDFH.CChangesDrawingsObject; var CChangesDrawingsContentNoId = AscDFH.CChangesDrawingsContentNoId; var CChangesDrawingsContentLong = AscDFH.CChangesDrawingsContentLong; var CChangesDrawingsContentLongMap = AscDFH.CChangesDrawingsContentLongMap; var CChangesDrawingsContent = AscDFH.CChangesDrawingsContent; function CBaseNoIdObject() { } CBaseNoIdObject.prototype.classType = AscDFH.historyitem_type_Unknown; CBaseNoIdObject.prototype.notAllowedWithoutId = function () { return false; }; CBaseNoIdObject.prototype.getObjectType = function () { return this.classType; }; CBaseNoIdObject.prototype.Get_Id = function () { return this.Id; }; CBaseNoIdObject.prototype.Write_ToBinary2 = function (oWriter) { oWriter.WriteLong(this.getObjectType()); oWriter.WriteString2(this.Get_Id()); }; CBaseNoIdObject.prototype.Read_FromBinary2 = function (oReader) { this.Id = oReader.GetString2(); }; CBaseNoIdObject.prototype.Refresh_RecalcData = function (oChange) { }; //open/save from/to xml CBaseNoIdObject.prototype.readAttr = function (reader) { while (reader.MoveToNextAttribute()) { this.readAttrXml(reader.GetNameNoNS(), reader); } }; CBaseNoIdObject.prototype.readAttrXml = function (name, reader) { //TODO:Implement in children }; CBaseNoIdObject.prototype.readChildXml = function (name, reader) { //TODO:Implement in children }; CBaseNoIdObject.prototype.writeAttrXmlImpl = function (writer) { //TODO:Implement in children }; CBaseNoIdObject.prototype.writeChildrenXml = function (writer) { //TODO:Implement in children }; CBaseNoIdObject.prototype.fromXml = function (reader, bSkipFirstNode) { if (bSkipFirstNode) { if (!reader.ReadNextNode()) { return; } } this.readAttr(reader); var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { var name = reader.GetNameNoNS(); this.readChildXml(name, reader); } }; CBaseNoIdObject.prototype.toXml = function (writer, name) { writer.WriteXmlNodeStart(name); this.writeAttrXml(writer); this.writeChildrenXml(writer); writer.WriteXmlNodeEnd(name); }; CBaseNoIdObject.prototype.writeAttrXml = function (writer) { this.writeAttrXmlImpl(writer); writer.WriteXmlAttributesEnd(); }; function CBaseObject() { CBaseNoIdObject.call(this); this.Id = null; if (AscCommon.g_oIdCounter.m_bLoad || History.CanAddChanges() || this.notAllowedWithoutId()) { this.Id = AscCommon.g_oIdCounter.Get_NewId(); AscCommon.g_oTableId.Add(this, this.Id); } } InitClass(CBaseObject, CBaseNoIdObject, AscDFH.historyitem_type_Unknown); function InitClassWithoutType(fClass, fBase) { fClass.prototype = Object.create(fBase.prototype); fClass.prototype.superclass = fBase; fClass.prototype.constructor = fClass; } function InitClass(fClass, fBase, nType) { InitClassWithoutType(fClass, fBase); fClass.prototype.classType = nType; } function CBaseFormatObject() { CBaseObject.call(this); this.parent = null; } CBaseFormatObject.prototype = Object.create(CBaseObject.prototype); CBaseFormatObject.prototype.constructor = CBaseFormatObject; CBaseFormatObject.prototype.classType = AscDFH.historyitem_type_Unknown; CBaseFormatObject.prototype.getObjectType = function () { return this.classType; }; CBaseFormatObject.prototype.setParent = function (oParent) { History.CanAddChanges() && History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_CommonChartFormat_SetParent, this.parent, oParent)); this.parent = oParent; }; CBaseFormatObject.prototype.getImageFromBulletsMap = function(oImages) {}; CBaseFormatObject.prototype.getDocContentsWithImageBullets = function (arrContents) {}; CBaseFormatObject.prototype.setParentToChild = function (oChild) { if (oChild && oChild.setParent) { oChild.setParent(this); } }; CBaseFormatObject.prototype.createDuplicate = function (oIdMap) { var oCopy = new this.constructor(); this.fillObject(oCopy, oIdMap); return oCopy; }; CBaseFormatObject.prototype.fillObject = function (oCopy, oIdMap) { }; CBaseFormatObject.prototype.fromPPTY = function (pReader) { var oStream = pReader.stream; var nStart = oStream.cur; var nEnd = nStart + oStream.GetULong() + 4; if (this.readAttribute) { this.readAttributes(pReader); } this.readChildren(nEnd, pReader); oStream.Seek2(nEnd); }; CBaseFormatObject.prototype.readAttributes = function (pReader) { var oStream = pReader.stream; oStream.Skip2(1); // start attributes while (true) { var nType = oStream.GetUChar(); if (nType == g_nodeAttributeEnd) break; this.readAttribute(nType, pReader) } }; CBaseFormatObject.prototype.readAttribute = function (nType, pReader) { }; CBaseFormatObject.prototype.readChildren = function (nEnd, pReader) { var oStream = pReader.stream; while (oStream.cur < nEnd) { var nType = oStream.GetUChar(); this.readChild(nType, pReader); } }; CBaseFormatObject.prototype.readChild = function (nType, pReader) { pReader.stream.SkipRecord(); }; CBaseFormatObject.prototype.toPPTY = function (pWriter) { if (this.privateWriteAttributes) { this.writeAttributes(pWriter); } this.writeChildren(pWriter); }; CBaseFormatObject.prototype.writeAttributes = function (pWriter) { pWriter.WriteUChar(g_nodeAttributeStart); this.privateWriteAttributes(pWriter); pWriter.WriteUChar(g_nodeAttributeEnd); }; CBaseFormatObject.prototype.privateWriteAttributes = function (pWriter) { }; CBaseFormatObject.prototype.writeChildren = function (pWriter) { }; CBaseFormatObject.prototype.writeRecord1 = function (pWriter, nType, oChild) { if (AscCommon.isRealObject(oChild)) { pWriter.WriteRecord1(nType, oChild, function (oChild) { oChild.toPPTY(pWriter); }); } else { //TODO: throw an error } }; CBaseFormatObject.prototype.writeRecord2 = function (pWriter, nType, oChild) { if (AscCommon.isRealObject(oChild)) { this.writeRecord1(pWriter, nType, oChild); } }; CBaseFormatObject.prototype.getChildren = function () { return []; }; CBaseFormatObject.prototype.traverse = function (fCallback) { if (fCallback(this)) { return true; } var aChildren = this.getChildren(); for (var nChild = aChildren.length - 1; nChild > -1; --nChild) { var oChild = aChildren[nChild]; if (oChild && oChild.traverse) { if (oChild.traverse(fCallback)) { return true; } } } return false; }; CBaseFormatObject.prototype.handleRemoveObject = function (sObjectId) { return false; }; CBaseFormatObject.prototype.onRemoveChild = function (oChild) { if (this.parent) { this.parent.onRemoveChild(this); } }; CBaseFormatObject.prototype.notAllowedWithoutId = function () { return true; }; CBaseFormatObject.prototype.isEqual = function (oOther) { if (!oOther) { return false; } if (this.getObjectType() !== oOther.getObjectType()) { return false; } var aThisChildren = this.getChildren(); var aOtherChildren = oOther.getChildren(); if (aThisChildren.length !== aOtherChildren.length) { return false; } for (var nChild = 0; nChild < aThisChildren.length; ++nChild) { var oThisChild = aThisChildren[nChild]; var oOtherChild = aOtherChildren[nChild]; if (oThisChild !== this.checkEqualChild(oThisChild, oOtherChild)) { return false; } } return true; }; CBaseFormatObject.prototype.checkEqualChild = function (oThisChild, oOtherChild) { if (AscCommon.isRealObject(oThisChild) && oThisChild.isEqual) { if (!oThisChild.isEqual(oOtherChild)) { return undefined; } } else { if (oThisChild !== oOtherChild) { return undefined; } } return oThisChild; }; //Method for debug CBaseObject.prototype.compareTypes = function (oOther) { if (!oOther || !oOther.compareTypes) { debugger; } for (var sKey in oOther) { if ((oOther[sKey] === null || oOther[sKey] === undefined) && (this[sKey] !== null && this[sKey] !== undefined) || (this[sKey] === null || this[sKey] === undefined) && (oOther[sKey] !== null && oOther[sKey] !== undefined) || (typeof this[sKey]) !== (typeof oOther[sKey])) { debugger; } if (this[sKey] !== this.parent && this[sKey] !== this.group && typeof this[sKey] === "object" && this[sKey] && this[sKey].compareTypes) { this[sKey].compareTypes(oOther[sKey]); } if (Array.isArray(this[sKey])) { if (!Array.isArray(oOther[sKey])) { debugger; } else { var a1 = this[sKey]; var a2 = oOther[sKey]; if (a1.length !== a2.length) { debugger; } else { for (var i = 0; i < a1.length; ++i) { if (!a1[i] || !a2[i]) { debugger; } if (typeof a1[i] === "object" && a1[i] && a1[i].compareTypes) { a1[i].compareTypes(a2[i]); } } } } } } }; function CT_Hyperlink() { CBaseNoIdObject.call(this); this.snd = null; this.id = null; this.invalidUrl = null; this.action = null; this.tgtFrame = null; this.tooltip = null; this.history = null; this.highlightClick = null; this.endSnd = null; } InitClass(CT_Hyperlink, CBaseNoIdObject, 0); CT_Hyperlink.prototype.Write_ToBinary = function (w) { var nStartPos = w.GetCurPosition(); var nFlags = 0; w.WriteLong(0); if (null !== this.snd) { nFlags |= 1; w.WriteString2(this.snd); } if (null !== this.id) { nFlags |= 2; w.WriteString2(this.id); } if (null !== this.invalidUrl) { nFlags |= 4; w.WriteString2(this.invalidUrl); } if (null !== this.action) { nFlags |= 8; w.WriteString2(this.action); } if (null !== this.tgtFrame) { nFlags |= 16; w.WriteString2(this.tgtFrame); } if (null !== this.tooltip) { nFlags |= 32; w.WriteString2(this.tooltip); } if (null !== this.history) { nFlags |= 64; w.WriteBool(this.history); } if (null !== this.highlightClick) { nFlags |= 128; w.WriteBool(this.highlightClick); } if (null !== this.endSnd) { nFlags |= 256; w.WriteBool(this.endSnd); } var nEndPos = w.GetCurPosition(); w.Seek(nStartPos); w.WriteLong(nFlags); w.Seek(nEndPos); }; CT_Hyperlink.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.snd = r.GetString2(); } if (nFlags & 2) { this.id = r.GetString2(); } if (nFlags & 4) { this.invalidUrl = r.GetString2(); } if (nFlags & 8) { this.action = r.GetString2(); } if (nFlags & 16) { this.tgtFrame = r.GetString2(); } if (nFlags & 32) { this.tooltip = r.GetString2(); } if (nFlags & 64) { this.history = r.GetBool(); } if (nFlags & 128) { this.highlightClick = r.GetBool(); } if (nFlags & 256) { this.endSnd = r.GetBool(); } }; CT_Hyperlink.prototype.createDuplicate = function () { var ret = new CT_Hyperlink(); ret.snd = this.snd; ret.id = this.id; ret.invalidUrl = this.invalidUrl; ret.action = this.action; ret.tgtFrame = this.tgtFrame; ret.tooltip = this.tooltip; ret.history = this.history; ret.highlightClick = this.highlightClick; ret.endSnd = this.endSnd; return ret; }; CT_Hyperlink.prototype.readAttrXml = function (name, reader) { switch (name) { case "action": { this.action = reader.GetValue(); break; } case "endSnd": { this.endSnd = reader.GetValueBool(); break; } case "highlightClick": { this.highlightClick = reader.GetValueBool(); break; } case "history": { this.history = reader.GetValueBool(); break; } case "id": { let id = reader.GetValueDecodeXml(); let rel = reader.rels.getRelationship(id); if (rel) { this.id = rel.target; } break; } case "invalidUrl": { this.invalidUrl = reader.GetValue(); break; } case "tgtFrame": { this.tgtFrame = reader.GetValue(); break; } case "tooltip": { this.tooltip = reader.GetValue(); break; } } }; CT_Hyperlink.prototype.writeAttrXmlImpl = function (writer) { if (this.id) { let id = writer.context.part.addRelationship(AscCommon.openXml.Types.hyperlink.relationType, this.id, AscCommon.openXml.TargetMode.external); writer.WriteXmlNullableAttributeString("r:id", id); } writer.WriteXmlNullableAttributeString("invalidUrl", this.invalidUrl); writer.WriteXmlNullableAttributeString("action", this.action); writer.WriteXmlNullableAttributeString("tgtFrame", this.tgtFrame); writer.WriteXmlNullableAttributeBool("history", this.history); writer.WriteXmlNullableAttributeBool("highlightClick", this.highlightClick); writer.WriteXmlNullableAttributeBool("endSnd", this.endSnd); }; var drawingsChangesMap = window['AscDFH'].drawingsChangesMap; var drawingConstructorsMap = window['AscDFH'].drawingsConstructorsMap; var drawingContentChanges = window['AscDFH'].drawingContentChanges; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetSpPr] = function (oClass, value) { oClass.spPr = value; }; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr] = function (oClass, value) { oClass.bodyPr = value; }; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle] = function (oClass, value) { oClass.lstStyle = value; }; drawingsChangesMap[AscDFH.historyitem_DefaultShapeDefinition_SetStyle] = function (oClass, value) { oClass.style = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetId] = function (oClass, value) { oClass.id = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetName] = function (oClass, value) { oClass.name = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetIsHidden] = function (oClass, value) { oClass.isHidden = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetDescr] = function (oClass, value) { oClass.descr = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetTitle] = function (oClass, value) { oClass.title = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetHlinkClick] = function (oClass, value) { oClass.hlinkClick = value; }; drawingsChangesMap[AscDFH.historyitem_CNvPr_SetHlinkHover] = function (oClass, value) { oClass.hlinkHover = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetIsPhoto] = function (oClass, value) { oClass.isPhoto = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetUserDrawn] = function (oClass, value) { oClass.userDrawn = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetPh] = function (oClass, value) { oClass.ph = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetHasCustomPrompt] = function (oClass, value) { oClass.hasCustomPrompt = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetIdx] = function (oClass, value) { oClass.idx = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetOrient] = function (oClass, value) { oClass.orient = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetSz] = function (oClass, value) { oClass.sz = value; }; drawingsChangesMap[AscDFH.historyitem_Ph_SetType] = function (oClass, value) { oClass.type = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetCNvPr] = function (oClass, value) { oClass.cNvPr = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetUniPr] = function (oClass, value) { oClass.uniPr = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetNvPr] = function (oClass, value) { oClass.nvPr = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetLnRef] = function (oClass, value) { oClass.lnRef = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetFillRef] = function (oClass, value) { oClass.fillRef = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetFontRef] = function (oClass, value) { oClass.fontRef = value; }; drawingsChangesMap[AscDFH.historyitem_ShapeStyle_SetEffectRef] = function (oClass, value) { oClass.effectRef = value; }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetParent] = function (oClass, value) { oClass.parent = value; }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetOffX] = function (oClass, value) { oClass.offX = value; oClass.handleUpdatePosition(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetOffY] = function (oClass, value) { oClass.offY = value; oClass.handleUpdatePosition(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetExtX] = function (oClass, value) { oClass.extX = value; oClass.handleUpdateExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetExtY] = function (oClass, value) { oClass.extY = value; oClass.handleUpdateExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChOffX] = function (oClass, value) { oClass.chOffX = value; oClass.handleUpdateChildOffset(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChOffY] = function (oClass, value) { oClass.chOffY = value; oClass.handleUpdateChildOffset(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChExtX] = function (oClass, value) { oClass.chExtX = value; oClass.handleUpdateChildExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetChExtY] = function (oClass, value) { oClass.chExtY = value; oClass.handleUpdateChildExtents(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetFlipH] = function (oClass, value) { oClass.flipH = value; oClass.handleUpdateFlip(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetFlipV] = function (oClass, value) { oClass.flipV = value; oClass.handleUpdateFlip(); }; drawingsChangesMap[AscDFH.historyitem_Xfrm_SetRot] = function (oClass, value) { oClass.rot = value; oClass.handleUpdateRot(); }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetParent] = function (oClass, value) { oClass.parent = value; }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetBwMode] = function (oClass, value) { oClass.bwMode = value; }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetXfrm] = function (oClass, value) { oClass.xfrm = value; }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetGeometry] = function (oClass, value) { oClass.geometry = value; oClass.handleUpdateGeometry(); }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetFill] = function (oClass, value, FromLoad) { oClass.Fill = value; oClass.handleUpdateFill(); if (FromLoad) { if (typeof AscCommon.CollaborativeEditing !== "undefined") { if (oClass.Fill && oClass.Fill.fill && oClass.Fill.fill.type === c_oAscFill.FILL_TYPE_BLIP && typeof oClass.Fill.fill.RasterImageId === "string" && oClass.Fill.fill.RasterImageId.length > 0) { AscCommon.CollaborativeEditing.Add_NewImage(oClass.Fill.fill.RasterImageId); } } } }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetLn] = function (oClass, value) { oClass.ln = value; oClass.handleUpdateLn(); }; drawingsChangesMap[AscDFH.historyitem_SpPr_SetEffectPr] = function (oClass, value) { oClass.effectProps = value; oClass.handleUpdateGeometry(); }; drawingsChangesMap[AscDFH.historyitem_ExtraClrScheme_SetClrScheme] = function (oClass, value) { oClass.clrScheme = value; }; drawingsChangesMap[AscDFH.historyitem_ExtraClrScheme_SetClrMap] = function (oClass, value) { oClass.clrMap = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetColorScheme] = function (oClass, value) { oClass.themeElements.clrScheme = value; var oWordGraphicObjects = oClass.GetWordDrawingObjects(); if (oWordGraphicObjects) { oWordGraphicObjects.drawingDocument.CheckGuiControlColors(); oWordGraphicObjects.document.Api.chartPreviewManager.clearPreviews(); oWordGraphicObjects.document.Api.textArtPreviewManager.clear(); } }; drawingsChangesMap[AscDFH.historyitem_ThemeSetFontScheme] = function (oClass, value) { oClass.themeElements.fontScheme = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetFmtScheme] = function (oClass, value, bFromLoad) { oClass.themeElements.fmtScheme = value; if(bFromLoad) { if(typeof AscCommon.CollaborativeEditing !== "undefined") { if(value) { let aImages = []; value.getAllRasterImages(aImages); for(let nImage = 0; nImage < aImages.length; ++nImage) { AscCommon.CollaborativeEditing.Add_NewImage(aImages[nImage]); } } } } }; drawingsChangesMap[AscDFH.historyitem_ThemeSetName] = function (oClass, value) { oClass.name = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetIsThemeOverride] = function (oClass, value) { oClass.isThemeOverride = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetSpDef] = function (oClass, value) { oClass.spDef = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetLnDef] = function (oClass, value) { oClass.lnDef = value; }; drawingsChangesMap[AscDFH.historyitem_ThemeSetTxDef] = function (oClass, value) { oClass.txDef = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetDt] = function (oClass, value) { oClass.dt = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetFtr] = function (oClass, value) { oClass.ftr = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetHdr] = function (oClass, value) { oClass.hdr = value; }; drawingsChangesMap[AscDFH.historyitem_HF_SetSldNum] = function (oClass, value) { oClass.sldNum = value; }; drawingsChangesMap[AscDFH.historyitem_UniNvPr_SetUniSpPr] = function (oClass, value) { oClass.nvUniSpPr = value; }; drawingsChangesMap[AscDFH.historyitem_NvPr_SetUniMedia] = function (oClass, value) { oClass.unimedia = value; }; drawingContentChanges[AscDFH.historyitem_ClrMap_SetClr] = function (oClass) { return oClass.color_map }; drawingContentChanges[AscDFH.historyitem_ThemeAddExtraClrScheme] = function (oClass) { return oClass.extraClrSchemeLst; }; drawingContentChanges[AscDFH.historyitem_ThemeRemoveExtraClrScheme] = function (oClass) { return oClass.extraClrSchemeLst; }; drawingConstructorsMap[AscDFH.historyitem_ClrMap_SetClr] = CUniColor; drawingConstructorsMap[AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr] = CBodyPr; drawingConstructorsMap[AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle] = TextListStyle; drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetLnRef] = drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetFillRef] = drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetEffectRef] = StyleRef; drawingConstructorsMap[AscDFH.historyitem_ShapeStyle_SetFontRef] = FontRef; drawingConstructorsMap[AscDFH.historyitem_SpPr_SetFill] = CUniFill; drawingConstructorsMap[AscDFH.historyitem_SpPr_SetLn] = CLn; drawingConstructorsMap[AscDFH.historyitem_SpPr_SetEffectPr] = CEffectProperties; drawingConstructorsMap[AscDFH.historyitem_ThemeSetColorScheme] = ClrScheme; drawingConstructorsMap[AscDFH.historyitem_ThemeSetFontScheme] = FontScheme; drawingConstructorsMap[AscDFH.historyitem_ThemeSetFmtScheme] = FmtScheme; drawingConstructorsMap[AscDFH.historyitem_UniNvPr_SetUniSpPr] = CNvUniSpPr; drawingConstructorsMap[AscDFH.historyitem_CNvPr_SetHlinkClick] = CT_Hyperlink; drawingConstructorsMap[AscDFH.historyitem_CNvPr_SetHlinkHover] = CT_Hyperlink; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetSpPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_DefaultShapeDefinition_SetStyle] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetId] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetName] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetIsHidden] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetDescr] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetTitle] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetHlinkClick] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_CNvPr_SetHlinkHover] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetIsPhoto] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetUserDrawn] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetPh] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_NvPr_SetUniMedia] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetHasCustomPrompt] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetIdx] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetOrient] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetSz] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_Ph_SetType] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetCNvPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetUniPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetNvPr] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_UniNvPr_SetUniSpPr] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetLnRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetFillRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetFontRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ShapeStyle_SetEffectRef] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetParent] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetOffX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetOffY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetExtX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetExtY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChOffX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChOffY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChExtX] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetChExtY] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetFlipH] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetFlipV] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_Xfrm_SetRot] = CChangesDrawingsDouble; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetParent] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetBwMode] = CChangesDrawingsLong; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetXfrm] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetGeometry] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetFill] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetLn] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_SpPr_SetEffectPr] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ClrMap_SetClr] = CChangesDrawingsContentLongMap; AscDFH.changesFactory[AscDFH.historyitem_ExtraClrScheme_SetClrScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ExtraClrScheme_SetClrMap] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetColorScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetFontScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetFmtScheme] = CChangesDrawingsObjectNoId; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetName] = CChangesDrawingsString; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetIsThemeOverride] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetSpDef] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetLnDef] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeSetTxDef] = CChangesDrawingsObject; AscDFH.changesFactory[AscDFH.historyitem_ThemeAddExtraClrScheme] = CChangesDrawingsContent; AscDFH.changesFactory[AscDFH.historyitem_ThemeRemoveExtraClrScheme] = CChangesDrawingsContent; AscDFH.changesFactory[AscDFH.historyitem_HF_SetDt] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HF_SetFtr] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HF_SetHdr] = CChangesDrawingsBool; AscDFH.changesFactory[AscDFH.historyitem_HF_SetSldNum] = CChangesDrawingsBool; // COLOR ----------------------- /* var map_color_scheme = {}; map_color_scheme["accent1"] = 0; map_color_scheme["accent2"] = 1; map_color_scheme["accent3"] = 2; map_color_scheme["accent4"] = 3; map_color_scheme["accent5"] = 4; map_color_scheme["accent6"] = 5; map_color_scheme["bg1"] = 6; map_color_scheme["bg2"] = 7; map_color_scheme["dk1"] = 8; map_color_scheme["dk2"] = 9; map_color_scheme["folHlink"] = 10; map_color_scheme["hlink"] = 11; map_color_scheme["lt1"] = 12; map_color_scheme["lt2"] = 13; map_color_scheme["phClr"] = 14; map_color_scheme["tx1"] = 15; map_color_scheme["tx2"] = 16; */ //ะขะธะฟั‹ ะธะทะผะตะฝะตะฝะธะน ะฒ ะบะปะฐััะต CTheme function CreateFontRef(idx, color) { var ret = new FontRef(); ret.idx = idx; ret.Color = color; return ret; } function CreateStyleRef(idx, color) { var ret = new StyleRef(); ret.idx = idx; ret.Color = color; return ret; } function CreatePresetColor(id) { var ret = new CPrstColor(); ret.id = id; return ret; } function sRGB_to_scRGB(value) { if (value < 0) return 0; if (value <= 0.04045) return value / 12.92; if (value <= 1) return Math.pow(((value + 0.055) / 1.055), 2.4); return 1; } function scRGB_to_sRGB(value) { if (value < 0) return 0; if (value <= 0.0031308) return value * 12.92; if (value < 1) return 1.055 * (Math.pow(value, (1 / 2.4))) - 0.055; return 1; } function checkRasterImageId(rasterImageId) { var imageLocal = AscCommon.g_oDocumentUrls.getImageLocal(rasterImageId); return imageLocal ? imageLocal : rasterImageId; } var g_oThemeFontsName = {}; g_oThemeFontsName["+mj-cs"] = true; g_oThemeFontsName["+mj-ea"] = true; g_oThemeFontsName["+mj-lt"] = true; g_oThemeFontsName["+mn-cs"] = true; g_oThemeFontsName["+mn-ea"] = true; g_oThemeFontsName["+mn-lt"] = true; g_oThemeFontsName["majorAscii"] = true; g_oThemeFontsName["majorBidi"] = true; g_oThemeFontsName["majorEastAsia"] = true; g_oThemeFontsName["majorHAnsi"] = true; g_oThemeFontsName["minorAscii"] = true; g_oThemeFontsName["minorBidi"] = true; g_oThemeFontsName["minorEastAsia"] = true; g_oThemeFontsName["minorHAnsi"] = true; function isRealNumber(n) { return typeof n === "number" && !isNaN(n); } function isRealBool(b) { return b === true || b === false; } function writeLong(w, val) { w.WriteBool(isRealNumber(val)); if (isRealNumber(val)) { w.WriteLong(val); } } function readLong(r) { var ret; if (r.GetBool()) { ret = r.GetLong(); } else { ret = null; } return ret; } function writeDouble(w, val) { w.WriteBool(isRealNumber(val)); if (isRealNumber(val)) { w.WriteDouble(val); } } function readDouble(r) { var ret; if (r.GetBool()) { ret = r.GetDouble(); } else { ret = null; } return ret; } function writeBool(w, val) { w.WriteBool(isRealBool(val)); if (isRealBool(val)) { w.WriteBool(val); } } function readBool(r) { var ret; if (r.GetBool()) { ret = r.GetBool(); } else { ret = null; } return ret; } function writeString(w, val) { w.WriteBool(typeof val === "string"); if (typeof val === "string") { w.WriteString2(val); } } function readString(r) { var ret; if (r.GetBool()) { ret = r.GetString2(); } else { ret = null; } return ret; } function writeObject(w, val) { w.WriteBool(isRealObject(val)); if (isRealObject(val)) { w.WriteString2(val.Get_Id()); } } function readObject(r) { var ret; if (r.GetBool()) { ret = g_oTableId.Get_ById(r.GetString2()); } else { ret = null; } return ret; } function checkThemeFonts(oFontMap, font_scheme) { if (oFontMap["+mj-lt"]) { if (font_scheme.majorFont && typeof font_scheme.majorFont.latin === "string" && font_scheme.majorFont.latin.length > 0) oFontMap[font_scheme.majorFont.latin] = 1; delete oFontMap["+mj-lt"]; } if (oFontMap["+mj-ea"]) { if (font_scheme.majorFont && typeof font_scheme.majorFont.ea === "string" && font_scheme.majorFont.ea.length > 0) oFontMap[font_scheme.majorFont.ea] = 1; delete oFontMap["+mj-ea"]; } if (oFontMap["+mj-cs"]) { if (font_scheme.majorFont && typeof font_scheme.majorFont.cs === "string" && font_scheme.majorFont.cs.length > 0) oFontMap[font_scheme.majorFont.cs] = 1; delete oFontMap["+mj-cs"]; } if (oFontMap["+mn-lt"]) { if (font_scheme.minorFont && typeof font_scheme.minorFont.latin === "string" && font_scheme.minorFont.latin.length > 0) oFontMap[font_scheme.minorFont.latin] = 1; delete oFontMap["+mn-lt"]; } if (oFontMap["+mn-ea"]) { if (font_scheme.minorFont && typeof font_scheme.minorFont.ea === "string" && font_scheme.minorFont.ea.length > 0) oFontMap[font_scheme.minorFont.ea] = 1; delete oFontMap["+mn-ea"]; } if (oFontMap["+mn-cs"]) { if (font_scheme.minorFont && typeof font_scheme.minorFont.cs === "string" && font_scheme.minorFont.cs.length > 0) oFontMap[font_scheme.minorFont.cs] = 1; delete oFontMap["+mn-cs"]; } } function ExecuteNoHistory(f, oThis, args) { History.TurnOff && History.TurnOff(); var b_table_id = false; if (g_oTableId && !g_oTableId.m_bTurnOff) { g_oTableId.m_bTurnOff = true; b_table_id = true; } var ret = f.apply(oThis, args); History.TurnOn && History.TurnOn(); if (b_table_id) { g_oTableId.m_bTurnOff = false; } return ret; } function checkObjectUnifill(obj, theme, colorMap) { if (obj && obj.Unifill) { obj.Unifill.check(theme, colorMap); var rgba = obj.Unifill.getRGBAColor(); obj.Color = new CDocumentColor(rgba.R, rgba.G, rgba.B, false); } } function checkTableCellPr(cellPr, slide, layout, master, theme) { cellPr.Check_PresentationPr(theme); var color_map, rgba; if (slide.clrMap) { color_map = slide.clrMap; } else if (layout.clrMap) { color_map = layout.clrMap; } else if (master.clrMap) { color_map = master.clrMap; } else { color_map = AscFormat.GetDefaultColorMap(); } checkObjectUnifill(cellPr.Shd, theme, color_map); if (cellPr.TableCellBorders) { checkObjectUnifill(cellPr.TableCellBorders.Left, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.Top, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.Right, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.Bottom, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.InsideH, theme, color_map); checkObjectUnifill(cellPr.TableCellBorders.InsideV, theme, color_map); } return cellPr; } var Ax_Counter = { GLOBAL_AX_ID_COUNTER: 1000 }; var TYPE_TRACK = { SHAPE: 0, GROUP: 0, GROUP_PASSIVE: 1, TEXT: 2, EMPTY_PH: 3, CHART_TEXT: 4, CROP: 5 }; var TYPE_KIND = { SLIDE: 0, LAYOUT: 1, MASTER: 2, NOTES: 3, NOTES_MASTER: 4 }; var TYPE_TRACK_SHAPE = 0; var TYPE_TRACK_GROUP = TYPE_TRACK_SHAPE; var TYPE_TRACK_GROUP_PASSIVE = 1; var TYPE_TRACK_TEXT = 2; var TYPE_TRACK_EMPTY_PH = 3; var TYPE_TRACK_CHART = 4; var SLIDE_KIND = 0; var LAYOUT_KIND = 1; var MASTER_KIND = 2; var map_hightlight = {}; map_hightlight["black"] = 0x000000; map_hightlight["blue"] = 0x0000FF; map_hightlight["cyan"] = 0x00FFFF; map_hightlight["darkBlue"] = 0x00008B; map_hightlight["darkCyan"] = 0x008B8B; map_hightlight["darkGray"] = 0x0A9A9A9; map_hightlight["darkGreen"] = 0x006400; map_hightlight["darkMagenta"] = 0x800080; map_hightlight["darkRed"] = 0x8B0000; map_hightlight["darkYellow"] = 0x808000; map_hightlight["green"] = 0x00FF00; map_hightlight["lightGray"] = 0xD3D3D3; map_hightlight["magenta"] = 0xFF00FF; map_hightlight["none"] = 0x000000; map_hightlight["red"] = 0xFF0000; map_hightlight["white"] = 0xFFFFFF; map_hightlight["yellow"] = 0xFFFF00; var map_prst_color = {}; map_prst_color["aliceBlue"] = 0xF0F8FF; map_prst_color["antiqueWhite"] = 0xFAEBD7; map_prst_color["aqua"] = 0x00FFFF; map_prst_color["aquamarine"] = 0x7FFFD4; map_prst_color["azure"] = 0xF0FFFF; map_prst_color["beige"] = 0xF5F5DC; map_prst_color["bisque"] = 0xFFE4C4; map_prst_color["black"] = 0x000000; map_prst_color["blanchedAlmond"] = 0xFFEBCD; map_prst_color["blue"] = 0x0000FF; map_prst_color["blueViolet"] = 0x8A2BE2; map_prst_color["brown"] = 0xA52A2A; map_prst_color["burlyWood"] = 0xDEB887; map_prst_color["cadetBlue"] = 0x5F9EA0; map_prst_color["chartreuse"] = 0x7FFF00; map_prst_color["chocolate"] = 0xD2691E; map_prst_color["coral"] = 0xFF7F50; map_prst_color["cornflowerBlue"] = 0x6495ED; map_prst_color["cornsilk"] = 0xFFF8DC; map_prst_color["crimson"] = 0xDC143C; map_prst_color["cyan"] = 0x00FFFF; map_prst_color["darkBlue"] = 0x00008B; map_prst_color["darkCyan"] = 0x008B8B; map_prst_color["darkGoldenrod"] = 0xB8860B; map_prst_color["darkGray"] = 0xA9A9A9; map_prst_color["darkGreen"] = 0x006400; map_prst_color["darkGrey"] = 0xA9A9A9; map_prst_color["darkKhaki"] = 0xBDB76B; map_prst_color["darkMagenta"] = 0x8B008B; map_prst_color["darkOliveGreen"] = 0x556B2F; map_prst_color["darkOrange"] = 0xFF8C00; map_prst_color["darkOrchid"] = 0x9932CC; map_prst_color["darkRed"] = 0x8B0000; map_prst_color["darkSalmon"] = 0xE9967A; map_prst_color["darkSeaGreen"] = 0x8FBC8F; map_prst_color["darkSlateBlue"] = 0x483D8B; map_prst_color["darkSlateGray"] = 0x2F4F4F; map_prst_color["darkSlateGrey"] = 0x2F4F4F; map_prst_color["darkTurquoise"] = 0x00CED1; map_prst_color["darkViolet"] = 0x9400D3; map_prst_color["deepPink"] = 0xFF1493; map_prst_color["deepSkyBlue"] = 0x00BFFF; map_prst_color["dimGray"] = 0x696969; map_prst_color["dimGrey"] = 0x696969; map_prst_color["dkBlue"] = 0x00008B; map_prst_color["dkCyan"] = 0x008B8B; map_prst_color["dkGoldenrod"] = 0xB8860B; map_prst_color["dkGray"] = 0xA9A9A9; map_prst_color["dkGreen"] = 0x006400; map_prst_color["dkGrey"] = 0xA9A9A9; map_prst_color["dkKhaki"] = 0xBDB76B; map_prst_color["dkMagenta"] = 0x8B008B; map_prst_color["dkOliveGreen"] = 0x556B2F; map_prst_color["dkOrange"] = 0xFF8C00; map_prst_color["dkOrchid"] = 0x9932CC; map_prst_color["dkRed"] = 0x8B0000; map_prst_color["dkSalmon"] = 0xE9967A; map_prst_color["dkSeaGreen"] = 0x8FBC8B; map_prst_color["dkSlateBlue"] = 0x483D8B; map_prst_color["dkSlateGray"] = 0x2F4F4F; map_prst_color["dkSlateGrey"] = 0x2F4F4F; map_prst_color["dkTurquoise"] = 0x00CED1; map_prst_color["dkViolet"] = 0x9400D3; map_prst_color["dodgerBlue"] = 0x1E90FF; map_prst_color["firebrick"] = 0xB22222; map_prst_color["floralWhite"] = 0xFFFAF0; map_prst_color["forestGreen"] = 0x228B22; map_prst_color["fuchsia"] = 0xFF00FF; map_prst_color["gainsboro"] = 0xDCDCDC; map_prst_color["ghostWhite"] = 0xF8F8FF; map_prst_color["gold"] = 0xFFD700; map_prst_color["goldenrod"] = 0xDAA520; map_prst_color["gray"] = 0x808080; map_prst_color["green"] = 0x008000; map_prst_color["greenYellow"] = 0xADFF2F; map_prst_color["grey"] = 0x808080; map_prst_color["honeydew"] = 0xF0FFF0; map_prst_color["hotPink"] = 0xFF69B4; map_prst_color["indianRed"] = 0xCD5C5C; map_prst_color["indigo"] = 0x4B0082; map_prst_color["ivory"] = 0xFFFFF0; map_prst_color["khaki"] = 0xF0E68C; map_prst_color["lavender"] = 0xE6E6FA; map_prst_color["lavenderBlush"] = 0xFFF0F5; map_prst_color["lawnGreen"] = 0x7CFC00; map_prst_color["lemonChiffon"] = 0xFFFACD; map_prst_color["lightBlue"] = 0xADD8E6; map_prst_color["lightCoral"] = 0xF08080; map_prst_color["lightCyan"] = 0xE0FFFF; map_prst_color["lightGoldenrodYellow"] = 0xFAFAD2; map_prst_color["lightGray"] = 0xD3D3D3; map_prst_color["lightGreen"] = 0x90EE90; map_prst_color["lightGrey"] = 0xD3D3D3; map_prst_color["lightPink"] = 0xFFB6C1; map_prst_color["lightSalmon"] = 0xFFA07A; map_prst_color["lightSeaGreen"] = 0x20B2AA; map_prst_color["lightSkyBlue"] = 0x87CEFA; map_prst_color["lightSlateGray"] = 0x778899; map_prst_color["lightSlateGrey"] = 0x778899; map_prst_color["lightSteelBlue"] = 0xB0C4DE; map_prst_color["lightYellow"] = 0xFFFFE0; map_prst_color["lime"] = 0x00FF00; map_prst_color["limeGreen"] = 0x32CD32; map_prst_color["linen"] = 0xFAF0E6; map_prst_color["ltBlue"] = 0xADD8E6; map_prst_color["ltCoral"] = 0xF08080; map_prst_color["ltCyan"] = 0xE0FFFF; map_prst_color["ltGoldenrodYellow"] = 0xFAFA78; map_prst_color["ltGray"] = 0xD3D3D3; map_prst_color["ltGreen"] = 0x90EE90; map_prst_color["ltGrey"] = 0xD3D3D3; map_prst_color["ltPink"] = 0xFFB6C1; map_prst_color["ltSalmon"] = 0xFFA07A; map_prst_color["ltSeaGreen"] = 0x20B2AA; map_prst_color["ltSkyBlue"] = 0x87CEFA; map_prst_color["ltSlateGray"] = 0x778899; map_prst_color["ltSlateGrey"] = 0x778899; map_prst_color["ltSteelBlue"] = 0xB0C4DE; map_prst_color["ltYellow"] = 0xFFFFE0; map_prst_color["magenta"] = 0xFF00FF; map_prst_color["maroon"] = 0x800000; map_prst_color["medAquamarine"] = 0x66CDAA; map_prst_color["medBlue"] = 0x0000CD; map_prst_color["mediumAquamarine"] = 0x66CDAA; map_prst_color["mediumBlue"] = 0x0000CD; map_prst_color["mediumOrchid"] = 0xBA55D3; map_prst_color["mediumPurple"] = 0x9370DB; map_prst_color["mediumSeaGreen"] = 0x3CB371; map_prst_color["mediumSlateBlue"] = 0x7B68EE; map_prst_color["mediumSpringGreen"] = 0x00FA9A; map_prst_color["mediumTurquoise"] = 0x48D1CC; map_prst_color["mediumVioletRed"] = 0xC71585; map_prst_color["medOrchid"] = 0xBA55D3; map_prst_color["medPurple"] = 0x9370DB; map_prst_color["medSeaGreen"] = 0x3CB371; map_prst_color["medSlateBlue"] = 0x7B68EE; map_prst_color["medSpringGreen"] = 0x00FA9A; map_prst_color["medTurquoise"] = 0x48D1CC; map_prst_color["medVioletRed"] = 0xC71585; map_prst_color["midnightBlue"] = 0x191970; map_prst_color["mintCream"] = 0xF5FFFA; map_prst_color["mistyRose"] = 0xFFE4FF; map_prst_color["moccasin"] = 0xFFE4B5; map_prst_color["navajoWhite"] = 0xFFDEAD; map_prst_color["navy"] = 0x000080; map_prst_color["oldLace"] = 0xFDF5E6; map_prst_color["olive"] = 0x808000; map_prst_color["oliveDrab"] = 0x6B8E23; map_prst_color["orange"] = 0xFFA500; map_prst_color["orangeRed"] = 0xFF4500; map_prst_color["orchid"] = 0xDA70D6; map_prst_color["paleGoldenrod"] = 0xEEE8AA; map_prst_color["paleGreen"] = 0x98FB98; map_prst_color["paleTurquoise"] = 0xAFEEEE; map_prst_color["paleVioletRed"] = 0xDB7093; map_prst_color["papayaWhip"] = 0xFFEFD5; map_prst_color["peachPuff"] = 0xFFDAB9; map_prst_color["peru"] = 0xCD853F; map_prst_color["pink"] = 0xFFC0CB; map_prst_color["plum"] = 0xD3A0D3; map_prst_color["powderBlue"] = 0xB0E0E6; map_prst_color["purple"] = 0x800080; map_prst_color["red"] = 0xFF0000; map_prst_color["rosyBrown"] = 0xBC8F8F; map_prst_color["royalBlue"] = 0x4169E1; map_prst_color["saddleBrown"] = 0x8B4513; map_prst_color["salmon"] = 0xFA8072; map_prst_color["sandyBrown"] = 0xF4A460; map_prst_color["seaGreen"] = 0x2E8B57; map_prst_color["seaShell"] = 0xFFF5EE; map_prst_color["sienna"] = 0xA0522D; map_prst_color["silver"] = 0xC0C0C0; map_prst_color["skyBlue"] = 0x87CEEB; map_prst_color["slateBlue"] = 0x6A5AEB; map_prst_color["slateGray"] = 0x708090; map_prst_color["slateGrey"] = 0x708090; map_prst_color["snow"] = 0xFFFAFA; map_prst_color["springGreen"] = 0x00FF7F; map_prst_color["steelBlue"] = 0x4682B4; map_prst_color["tan"] = 0xD2B48C; map_prst_color["teal"] = 0x008080; map_prst_color["thistle"] = 0xD8BFD8; map_prst_color["tomato"] = 0xFF7347; map_prst_color["turquoise"] = 0x40E0D0; map_prst_color["violet"] = 0xEE82EE; map_prst_color["wheat"] = 0xF5DEB3; map_prst_color["white"] = 0xFFFFFF; map_prst_color["whiteSmoke"] = 0xF5F5F5; map_prst_color["yellow"] = 0xFFFF00; map_prst_color["yellowGreen"] = 0x9ACD32; function CColorMod() { this.name = ""; this.val = 0; } CColorMod.prototype.setName = function (name) { this.name = name; }; CColorMod.prototype.setVal = function (val) { this.val = val; }; CColorMod.prototype.createDuplicate = function () { var duplicate = new CColorMod(); duplicate.name = this.name; duplicate.val = this.val; return duplicate; }; CColorMod.prototype.toXml = function (writer) { let sName; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sName = "w14:" + this.name; sAttrNamespace = "w14:"; } else { sName = "a:" + this.name; } let sValAttrName = sAttrNamespace + "val"; writer.WriteXmlNodeStart(sName); writer.WriteXmlNullableAttributeUInt(sValAttrName, this.val); writer.WriteXmlAttributesEnd(true); }; var cd16 = 1.0 / 6.0; var cd13 = 1.0 / 3.0; var cd23 = 2.0 / 3.0; var max_hls = 255.0; var DEC_GAMMA = 2.3; var INC_GAMMA = 1.0 / DEC_GAMMA; var MAX_PERCENT = 100000; function CColorModifiers() { this.Mods = []; } CColorModifiers.prototype.isUsePow = (!AscCommon.AscBrowser.isSailfish || !AscCommon.AscBrowser.isEmulateDevicePixelRatio); CColorModifiers.prototype.getModValue = function (sName) { if (Array.isArray(this.Mods)) { for (var i = 0; i < this.Mods.length; ++i) { if (this.Mods[i] && this.Mods[i].name === sName) { return this.Mods[i].val; } } } return null; }; CColorModifiers.prototype.Write_ToBinary = function (w) { w.WriteLong(this.Mods.length); for (var i = 0; i < this.Mods.length; ++i) { w.WriteString2(this.Mods[i].name); w.WriteLong(this.Mods[i].val); } }; CColorModifiers.prototype.Read_FromBinary = function (r) { var len = r.GetLong(); for (var i = 0; i < len; ++i) { var mod = new CColorMod(); mod.name = r.GetString2(); mod.val = r.GetLong(); this.Mods.push(mod); } }; CColorModifiers.prototype.addMod = function (mod) { this.Mods.push(mod); }; CColorModifiers.prototype.removeMod = function (pos) { this.Mods.splice(pos, 1)[0]; }; CColorModifiers.prototype.IsIdentical = function (mods) { if (mods == null) { return false } if (mods.Mods == null || this.Mods.length !== mods.Mods.length) { return false; } for (var i = 0; i < this.Mods.length; ++i) { if (this.Mods[i].name !== mods.Mods[i].name || this.Mods[i].val !== mods.Mods[i].val) { return false; } } return true; }; CColorModifiers.prototype.createDuplicate = function () { var duplicate = new CColorModifiers(); for (var i = 0; i < this.Mods.length; ++i) { duplicate.Mods[i] = this.Mods[i].createDuplicate(); } return duplicate; }; CColorModifiers.prototype.RGB2HSL = function (R, G, B, HLS) { var iMin = (R < G ? R : G); iMin = iMin < B ? iMin : B;//Math.min(R, G, B); var iMax = (R > G ? R : G); iMax = iMax > B ? iMax : B;//Math.max(R, G, B); var iDelta = iMax - iMin; var dMax = (iMax + iMin) / 255.0; var dDelta = iDelta / 255.0; var H = 0; var S = 0; var L = dMax / 2.0; if (iDelta != 0) { if (L < 0.5) S = dDelta / dMax; else S = dDelta / (2.0 - dMax); dDelta = dDelta * 1530.0; var dR = (iMax - R) / dDelta; var dG = (iMax - G) / dDelta; var dB = (iMax - B) / dDelta; if (R == iMax) H = dB - dG; else if (G == iMax) H = cd13 + dR - dB; else if (B == iMax) H = cd23 + dG - dR; if (H < 0.0) H += 1.0; if (H > 1.0) H -= 1.0; } H = ((H * max_hls) >> 0) & 0xFF; if (H < 0) H = 0; if (H > 255) H = 255; S = ((S * max_hls) >> 0) & 0xFF; if (S < 0) S = 0; if (S > 255) S = 255; L = ((L * max_hls) >> 0) & 0xFF; if (L < 0) L = 0; if (L > 255) L = 255; HLS.H = H; HLS.S = S; HLS.L = L; }; CColorModifiers.prototype.HSL2RGB = function (HSL, RGB) { if (HSL.S == 0) { RGB.R = HSL.L; RGB.G = HSL.L; RGB.B = HSL.L; } else { var H = HSL.H / max_hls; var S = HSL.S / max_hls; var L = HSL.L / max_hls; var v2 = 0; if (L < 0.5) v2 = L * (1.0 + S); else v2 = L + S - S * L; var v1 = 2.0 * L - v2; var R = (255 * this.Hue_2_RGB(v1, v2, H + cd13)) >> 0; var G = (255 * this.Hue_2_RGB(v1, v2, H)) >> 0; var B = (255 * this.Hue_2_RGB(v1, v2, H - cd13)) >> 0; if (R < 0) R = 0; if (R > 255) R = 255; if (G < 0) G = 0; if (G > 255) G = 255; if (B < 0) B = 0; if (B > 255) B = 255; RGB.R = R; RGB.G = G; RGB.B = B; } }; CColorModifiers.prototype.Hue_2_RGB = function (v1, v2, vH) { if (vH < 0.0) vH += 1.0; if (vH > 1.0) vH -= 1.0; if (vH < cd16) return v1 + (v2 - v1) * 6.0 * vH; if (vH < 0.5) return v2; if (vH < cd23) return v1 + (v2 - v1) * (cd23 - vH) * 6.0; return v1; }; CColorModifiers.prototype.lclRgbCompToCrgbComp = function (value) { return (value * MAX_PERCENT / 255); }; CColorModifiers.prototype.lclCrgbCompToRgbComp = function (value) { return (value * 255 / MAX_PERCENT); }; CColorModifiers.prototype.lclGamma = function (nComp, fGamma) { return (Math.pow(nComp / MAX_PERCENT, fGamma) * MAX_PERCENT + 0.5) >> 0; }; CColorModifiers.prototype.RgbtoCrgb = function (RGBA) { //RGBA.R = this.lclGamma(this.lclRgbCompToCrgbComp(RGBA.R), DEC_GAMMA); //RGBA.G = this.lclGamma(this.lclRgbCompToCrgbComp(RGBA.G), DEC_//GAMMA); //RGBA.B = this.lclGamma(this.lclRgbCompToCrgbComp(RGBA.B), DEC_GAMMA); if (this.isUsePow) { RGBA.R = (Math.pow(RGBA.R / 255, DEC_GAMMA) * MAX_PERCENT + 0.5) >> 0; RGBA.G = (Math.pow(RGBA.G / 255, DEC_GAMMA) * MAX_PERCENT + 0.5) >> 0; RGBA.B = (Math.pow(RGBA.B / 255, DEC_GAMMA) * MAX_PERCENT + 0.5) >> 0; } }; CColorModifiers.prototype.CrgbtoRgb = function (RGBA) { //RGBA.R = (this.lclCrgbCompToRgbComp(this.lclGamma(RGBA.R, INC_GAMMA)) + 0.5) >> 0; //RGBA.G = (this.lclCrgbCompToRgbComp(this.lclGamma(RGBA.G, INC_GAMMA)) + 0.5) >> 0; //RGBA.B = (this.lclCrgbCompToRgbComp(this.lclGamma(RGBA.B, INC_GAMMA)) + 0.5) >> 0; if (this.isUsePow) { RGBA.R = (Math.pow(RGBA.R / 100000, INC_GAMMA) * 255 + 0.5) >> 0; RGBA.G = (Math.pow(RGBA.G / 100000, INC_GAMMA) * 255 + 0.5) >> 0; RGBA.B = (Math.pow(RGBA.B / 100000, INC_GAMMA) * 255 + 0.5) >> 0; } else { RGBA.R = AscFormat.ClampColor(RGBA.R); RGBA.G = AscFormat.ClampColor(RGBA.G); RGBA.B = AscFormat.ClampColor(RGBA.B); } }; CColorModifiers.prototype.Apply = function (RGBA) { if (null == this.Mods) return; var _len = this.Mods.length; for (var i = 0; i < _len; i++) { var colorMod = this.Mods[i]; var val = colorMod.val / 100000.0; if (colorMod.name === "alpha") { RGBA.A = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "blue") { RGBA.B = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "blueMod") { RGBA.B = AscFormat.ClampColor(RGBA.B * val); } else if (colorMod.name === "blueOff") { RGBA.B = AscFormat.ClampColor(RGBA.B + val * 255); } else if (colorMod.name === "green") { RGBA.G = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "greenMod") { RGBA.G = AscFormat.ClampColor(RGBA.G * val); } else if (colorMod.name === "greenOff") { RGBA.G = AscFormat.ClampColor(RGBA.G + val * 255); } else if (colorMod.name === "red") { RGBA.R = AscFormat.ClampColor(255 * val); } else if (colorMod.name === "redMod") { RGBA.R = AscFormat.ClampColor(RGBA.R * val); } else if (colorMod.name === "redOff") { RGBA.R = AscFormat.ClampColor(RGBA.R + val * 255); } else if (colorMod.name === "hueOff") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var res = (HSL.H + (val * 10.0) / 9.0 + 0.5) >> 0; HSL.H = AscFormat.ClampColor2(res, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "inv") { RGBA.R ^= 0xFF; RGBA.G ^= 0xFF; RGBA.B ^= 0xFF; } else if (colorMod.name === "lumMod") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); HSL.L = AscFormat.ClampColor2(HSL.L * val, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "lumOff") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var res = (HSL.L + val * max_hls + 0.5) >> 0; HSL.L = AscFormat.ClampColor2(res, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "satMod") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); HSL.S = AscFormat.ClampColor2(HSL.S * val, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "satOff") { var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var res = (HSL.S + val * max_hls + 0.5) >> 0; HSL.S = AscFormat.ClampColor2(res, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "wordShade") { var val_ = colorMod.val / 255; //GBA.R = Math.max(0, (RGBA.R * (1 - val_)) >> 0); //GBA.G = Math.max(0, (RGBA.G * (1 - val_)) >> 0); //GBA.B = Math.max(0, (RGBA.B * (1 - val_)) >> 0); //RGBA.R = Math.max(0, ((1 - val_)*(- RGBA.R) + RGBA.R) >> 0); //RGBA.G = Math.max(0, ((1 - val_)*(- RGBA.G) + RGBA.G) >> 0); //RGBA.B = Math.max(0, ((1 - val_)*(- RGBA.B) + RGBA.B) >> 0); var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); HSL.L = AscFormat.ClampColor2(HSL.L * val_, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "wordTint") { var _val = colorMod.val / 255; //RGBA.R = Math.max(0, ((1 - _val)*(255 - RGBA.R) + RGBA.R) >> 0); //RGBA.G = Math.max(0, ((1 - _val)*(255 - RGBA.G) + RGBA.G) >> 0); //RGBA.B = Math.max(0, ((1 - _val)*(255 - RGBA.B) + RGBA.B) >> 0); var HSL = {H: 0, S: 0, L: 0}; this.RGB2HSL(RGBA.R, RGBA.G, RGBA.B, HSL); var L_ = HSL.L * _val + (255 - colorMod.val); HSL.L = AscFormat.ClampColor2(L_, 0, max_hls); this.HSL2RGB(HSL, RGBA); } else if (colorMod.name === "shade") { this.RgbtoCrgb(RGBA); if (val < 0) val = 0; if (val > 1) val = 1; RGBA.R = (RGBA.R * val); RGBA.G = (RGBA.G * val); RGBA.B = (RGBA.B * val); this.CrgbtoRgb(RGBA); } else if (colorMod.name === "tint") { this.RgbtoCrgb(RGBA); if (val < 0) val = 0; if (val > 1) val = 1; RGBA.R = (MAX_PERCENT - (MAX_PERCENT - RGBA.R) * val); RGBA.G = (MAX_PERCENT - (MAX_PERCENT - RGBA.G) * val); RGBA.B = (MAX_PERCENT - (MAX_PERCENT - RGBA.B) * val); this.CrgbtoRgb(RGBA); } else if (colorMod.name === "gamma") { this.RgbtoCrgb(RGBA); RGBA.R = this.lclGamma(RGBA.R, INC_GAMMA); RGBA.G = this.lclGamma(RGBA.G, INC_GAMMA); RGBA.B = this.lclGamma(RGBA.B, INC_GAMMA); this.CrgbtoRgb(RGBA); } else if (colorMod.name === "invGamma") { this.RgbtoCrgb(RGBA); RGBA.R = this.lclGamma(RGBA.R, DEC_GAMMA); RGBA.G = this.lclGamma(RGBA.G, DEC_GAMMA); RGBA.B = this.lclGamma(RGBA.B, DEC_GAMMA); this.CrgbtoRgb(RGBA); } } }; CColorModifiers.prototype.Merge = function (oOther) { if (!oOther) { return; } this.Mods = oOther.Mods.concat(this.Mods); }; CColorModifiers.prototype.toXml = function (writer) { for (let nMod = 0; nMod < this.Mods.length; ++nMod) { this.Mods[nMod].toXml(writer); } }; function getPercentageValue(sVal) { var _len = sVal.length; if (_len === 0) return null; var _ret = null; if ((_len - 1) === sVal.indexOf("%")) { sVal.substring(0, _len - 1); _ret = parseFloat(sVal); if (isNaN(_ret)) _ret = null; } else { _ret = parseFloat(sVal); if (isNaN(_ret)) _ret = null; else _ret /= 1000; } return _ret; // let nVal = 0; // if (sVal.indexOf("%") > -1) { // let nPct = parseInt(sVal.slice(0, sVal.length - 1)); // if (AscFormat.isRealNumber(nPct)) { // return ((100000 * nPct / 100 + 0.5 >> 0) - 1); // } // return 0; // } // let nValPct = parseInt(sVal); // if (AscFormat.isRealNumber(nValPct)) { // return nValPct; // } // return 0; } function getPercentageValueForWrite(dVal) { if (!AscFormat.isRealNumber(dVal)) { return null; } return (dVal * 1000 + 0.5 >> 0); } function CBaseColor() { CBaseNoIdObject.call(this); this.RGBA = { R: 0, G: 0, B: 0, A: 255, needRecalc: true }; this.Mods = null; //[]; } InitClass(CBaseColor, CBaseNoIdObject, 0); CBaseColor.prototype.type = c_oAscColor.COLOR_TYPE_NONE; CBaseColor.prototype.setR = function (pr) { this.RGBA.R = pr; }; CBaseColor.prototype.setG = function (pr) { this.RGBA.G = pr; }; CBaseColor.prototype.setB = function (pr) { this.RGBA.B = pr; }; CBaseColor.prototype.readModifier = function (name, reader) { if (MODS_MAP[name]) { var oMod = new CColorMod(); oMod.name = name; while (reader.MoveToNextAttribute()) { if (reader.GetNameNoNS() === "val") { oMod.val = reader.GetValueInt(); break; } } if (!Array.isArray(this.Mods)) { this.Mods = []; } this.Mods.push(oMod); } return false; }; CBaseColor.prototype.getChannelValue = function (sVal) { let nValPct = getPercentageValue(sVal); return (255 * nValPct / 100000 + 0.5 >> 0); }; CBaseColor.prototype.getTypeName = function () { return ""; }; CBaseColor.prototype.getNodeNS = function (writer) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.docType) { return ("w14:"); } else return ("a:"); }; CBaseColor.prototype.toXml = function (writer) { let sName = this.getNodeNS(writer) + this.getTypeName(); writer.WriteXmlNodeStart(sName); this.writeAttrXmlImpl(writer); writer.WriteXmlAttributesEnd(); this.writeChildrenXml(writer); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sName); }; CBaseColor.prototype.writeModifiers = function (writer) { if (Array.isArray(this.Mods)) { for (let nMod = 0; nMod < this.Mods.length; ++nMod) { this.Mods[nMod].toXml(writer); } } }; const COLOR_3DDKSHADOW = 21; const COLOR_3DFACE = 15; const COLOR_3DHIGHLIGHT = 20; const COLOR_3DHILIGHT = 20; const COLOR_3DLIGHT = 22; const COLOR_3DSHADOW = 16; const COLOR_ACTIVEBORDER = 10; const COLOR_ACTIVECAPTION = 2; const COLOR_APPWORKSPACE = 12; const COLOR_BACKGROUND = 1; const COLOR_BTNFACE = 15; const COLOR_BTNHIGHLIGHT = 20; const COLOR_BTNHILIGHT = 20; const COLOR_BTNSHADOW = 16; const COLOR_BTNTEXT = 18; const COLOR_CAPTIONTEXT = 9; const COLOR_DESKTOP = 1; const COLOR_GRAYTEXT = 17; const COLOR_HIGHLIGHT = 13; const COLOR_HIGHLIGHTTEXT = 14; const COLOR_HOTLIGHT = 26; const COLOR_INACTIVEBORDER = 11; const COLOR_INACTIVECAPTION = 3; const COLOR_INACTIVECAPTIONTEXT = 19; const COLOR_INFOBK = 24; const COLOR_INFOTEXT = 23; const COLOR_MENU = 4; const COLOR_GRADIENTACTIVECAPTION = 27; const COLOR_GRADIENTINACTIVECAPTION = 28; const COLOR_MENUHILIGHT = 29; const COLOR_MENUBAR = 30; const COLOR_MENUTEXT = 7; const COLOR_SCROLLBAR = 0; const COLOR_WINDOW = 5; const COLOR_WINDOWFRAME = 6; const COLOR_WINDOWTEXT = 8; function GetSysColor(nIndex) { // get color values from any windows theme // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724371(v=vs.85).aspx //***************** GetSysColor values begin (Win7 x64) ***************** let nValue = 0x0; //***************** GetSysColor values begin (Win7 x64) ***************** switch (nIndex) { case COLOR_3DDKSHADOW: nValue = 0x696969; break; case COLOR_3DFACE: nValue = 0xf0f0f0; break; case COLOR_3DHIGHLIGHT: nValue = 0xffffff; break; // case COLOR_3DHILIGHT: nValue = 0xffffff; break; // is COLOR_3DHIGHLIGHT case COLOR_3DLIGHT: nValue = 0xe3e3e3; break; case COLOR_3DSHADOW: nValue = 0xa0a0a0; break; case COLOR_ACTIVEBORDER: nValue = 0xb4b4b4; break; case COLOR_ACTIVECAPTION: nValue = 0xd1b499; break; case COLOR_APPWORKSPACE: nValue = 0xababab; break; case COLOR_BACKGROUND: nValue = 0x0; break; // case COLOR_BTNFACE: nValue = 0xf0f0f0; break; // is COLOR_3DFACE // case COLOR_BTNHIGHLIGHT: nValue = 0xffffff; break; // is COLOR_3DHIGHLIGHT // case COLOR_BTNHILIGHT: nValue = 0xffffff; break; // is COLOR_3DHIGHLIGHT // case COLOR_BTNSHADOW: nValue = 0xa0a0a0; break; // is COLOR_3DSHADOW case COLOR_BTNTEXT: nValue = 0x0; break; case COLOR_CAPTIONTEXT: nValue = 0x0; break; // case COLOR_DESKTOP: nValue = 0x0; break; // is COLOR_BACKGROUND case COLOR_GRADIENTACTIVECAPTION: nValue = 0xead1b9; break; case COLOR_GRADIENTINACTIVECAPTION: nValue = 0xf2e4d7; break; case COLOR_GRAYTEXT: nValue = 0x6d6d6d; break; case COLOR_HIGHLIGHT: nValue = 0xff9933; break; case COLOR_HIGHLIGHTTEXT: nValue = 0xffffff; break; case COLOR_HOTLIGHT: nValue = 0xcc6600; break; case COLOR_INACTIVEBORDER: nValue = 0xfcf7f4; break; case COLOR_INACTIVECAPTION: nValue = 0xdbcdbf; break; case COLOR_INACTIVECAPTIONTEXT: nValue = 0x544e43; break; case COLOR_INFOBK: nValue = 0xe1ffff; break; case COLOR_INFOTEXT: nValue = 0x0; break; case COLOR_MENU: nValue = 0xf0f0f0; break; case COLOR_MENUHILIGHT: nValue = 0xff9933; break; case COLOR_MENUBAR: nValue = 0xf0f0f0; break; case COLOR_MENUTEXT: nValue = 0x0; break; case COLOR_SCROLLBAR: nValue = 0xc8c8c8; break; case COLOR_WINDOW: nValue = 0xffffff; break; case COLOR_WINDOWFRAME: nValue = 0x646464; break; case COLOR_WINDOWTEXT: nValue = 0x0; break; default: nValue = 0x0; break; } // switch (nIndex) //***************** GetSysColor values end ***************** return nValue; } function CSysColor() { CBaseColor.call(this); this.id = ""; } InitClass(CSysColor, CBaseColor, 0); CSysColor.prototype.type = c_oAscColor.COLOR_TYPE_SYS; CSysColor.prototype.check = function () { var ret = this.RGBA.needRecalc; this.RGBA.needRecalc = false; return ret; }; CSysColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteString2(this.id); w.WriteLong(((this.RGBA.R << 16) & 0xFF0000) + ((this.RGBA.G << 8) & 0xFF00) + this.RGBA.B); }; CSysColor.prototype.Read_FromBinary = function (r) { this.id = r.GetString2(); var RGB = r.GetLong(); this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CSysColor.prototype.setId = function (id) { this.id = id; }; CSysColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.id === this.id; }; CSysColor.prototype.Calculate = function (obj) { }; CSysColor.prototype.createDuplicate = function () { var duplicate = new CSysColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CSysColor.prototype.FillRGBFromVal = function(str) { let RGB = 0; if (str && str !== "") { switch (str.charAt(0)) { case '3': if (str === ("3dDkShadow")) { RGB = GetSysColor(COLOR_3DDKSHADOW); break; } if (str === ("3dLight")) { RGB = GetSysColor(COLOR_3DLIGHT); break; } break; case 'a': if (str === ("activeBorder")) { RGB = GetSysColor(COLOR_ACTIVEBORDER); break; } if (str === ("activeCaption")) { RGB = GetSysColor(COLOR_ACTIVECAPTION); break; } if (str === ("appWorkspace")) { RGB = GetSysColor(COLOR_APPWORKSPACE); break; } break; case 'b': if (str === ("background")) { RGB = GetSysColor(COLOR_BACKGROUND); break; } if (str === ("btnFace")) { RGB = GetSysColor(COLOR_BTNFACE); break; } if (str === ("btnHighlight")) { RGB = GetSysColor(COLOR_BTNHIGHLIGHT); break; } if (str === ("btnShadow")) { RGB = GetSysColor(COLOR_BTNSHADOW); break; } if (str === ("btnText")) { RGB = GetSysColor(COLOR_BTNTEXT); break; } break; case 'c': if (str === ("captionText")) { RGB = GetSysColor(COLOR_CAPTIONTEXT); break; } break; case 'g': if (str === ("gradientActiveCaption")) { RGB = GetSysColor(COLOR_GRADIENTACTIVECAPTION); break; } if (str === ("gradientInactiveCaption")) { RGB = GetSysColor(COLOR_GRADIENTINACTIVECAPTION); break; } if (str === ("grayText")) { RGB = GetSysColor(COLOR_GRAYTEXT); break; } break; case 'h': if (str === ("highlight")) { RGB = GetSysColor(COLOR_HIGHLIGHT); break; } if (str === ("highlightText")) { RGB = GetSysColor(COLOR_HIGHLIGHTTEXT); break; } if (str === ("hotLight")) { RGB = GetSysColor(COLOR_HOTLIGHT); break; } break; case 'i': if (str === ("inactiveBorder")) { RGB = GetSysColor(COLOR_INACTIVEBORDER); break; } if (str === ("inactiveCaption")) { RGB = GetSysColor(COLOR_INACTIVECAPTION); break; } if (str === ("inactiveCaptionText")) { RGB = GetSysColor(COLOR_INACTIVECAPTIONTEXT); break; } if (str === ("infoBk")) { RGB = GetSysColor(COLOR_INFOBK); break; } if (str === ("infoText")) { RGB = GetSysColor(COLOR_INFOTEXT); break; } break; case 'm': if (str === ("menu")) { RGB = GetSysColor(COLOR_MENU); break; } if (str === ("menuBar")) { RGB = GetSysColor(COLOR_MENUBAR); break; } if (str === ("menuHighlight")) { RGB = GetSysColor(COLOR_MENUHILIGHT); break; } if (str === ("menuText")) { RGB = GetSysColor(COLOR_MENUTEXT); break; } break; case 's': if (str === ("scrollBar")) { RGB = GetSysColor(COLOR_SCROLLBAR); break; } break; case 'w': if (str === ("window")) { RGB = GetSysColor(COLOR_WINDOW); break; } if (str === ("windowFrame")) { RGB = GetSysColor(COLOR_WINDOWFRAME); break; } if (str === ("windowText")) { RGB = GetSysColor(COLOR_WINDOWTEXT); break; } break; } } this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; } CSysColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { this.id = reader.GetValue(); this.FillRGBFromVal(this.id); } else if (name === "lastClr") { // this.RGBA = AscCommon.RgbaHexToRGBA(reader.GetValue()); } }; CSysColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CSysColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("sysClr")); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), this.id); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("lastClr"), fRGBAToHexString(this.RGBA)); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("sysClr")); } else { writer.WriteXmlAttributesEnd(true); } }; function CPrstColor() { CBaseColor.call(this); this.id = ""; } InitClass(CPrstColor, CBaseColor, 0); CPrstColor.prototype.type = c_oAscColor.COLOR_TYPE_PRST; CPrstColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteString2(this.id); }; CPrstColor.prototype.Read_FromBinary = function (r) { this.id = r.GetString2(); }; CPrstColor.prototype.setId = function (id) { this.id = id; }; CPrstColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.id === this.id; }; CPrstColor.prototype.createDuplicate = function () { var duplicate = new CPrstColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CPrstColor.prototype.Calculate = function (obj) { var RGB = map_prst_color[this.id]; this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CPrstColor.prototype.check = function () { var r, g, b, rgb; rgb = map_prst_color[this.id]; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = rgb & 0xFF; var RGBA = this.RGBA; if (RGBA.needRecalc) { RGBA.R = r; RGBA.G = g; RGBA.B = b; RGBA.needRecalc = false; return true; } else { if (RGBA.R === r && RGBA.G === g && RGBA.B === b) return false; else { RGBA.R = r; RGBA.G = g; RGBA.B = b; return true; } } }; CPrstColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { this.id = reader.GetValue(); } }; CPrstColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CPrstColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("prstClr")); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), this.id); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("prstClr")); } else { writer.WriteXmlAttributesEnd(true); } }; var MODS_MAP = {}; MODS_MAP["alpha"] = true; MODS_MAP["alphaMod"] = true; MODS_MAP["alphaOff"] = true; MODS_MAP["blue"] = true; MODS_MAP["blueMod"] = true; MODS_MAP["blueOff"] = true; MODS_MAP["comp"] = true; MODS_MAP["gamma"] = true; MODS_MAP["gray"] = true; MODS_MAP["green"] = true; MODS_MAP["greenMod"] = true; MODS_MAP["greenOff"] = true; MODS_MAP["hue"] = true; MODS_MAP["hueMod"] = true; MODS_MAP["hueOff"] = true; MODS_MAP["inv"] = true; MODS_MAP["invGamma"] = true; MODS_MAP["lum"] = true; MODS_MAP["lumMod"] = true; MODS_MAP["lumOff"] = true; MODS_MAP["red"] = true; MODS_MAP["redMod"] = true; MODS_MAP["redOff"] = true; MODS_MAP["sat"] = true; MODS_MAP["satMod"] = true; MODS_MAP["satOff"] = true; MODS_MAP["shade"] = true; MODS_MAP["tint"] = true; function toHex(c) { var res = Number(c).toString(16).toUpperCase(); return res.length === 1 ? "0" + res : res; } function fRGBAToHexString(oRGBA) { return "" + toHex(oRGBA.R) + toHex(oRGBA.G) + toHex(oRGBA.B); } function CRGBColor() { CBaseColor.call(this); this.h = null; this.s = null; this.l = null; } InitClass(CRGBColor, CBaseColor, 0); CRGBColor.prototype.type = c_oAscColor.COLOR_TYPE_SRGB; CRGBColor.prototype.check = function () { var ret = this.RGBA.needRecalc; this.RGBA.needRecalc = false; return ret; }; CRGBColor.prototype.writeToBinaryLong = function (w) { w.WriteLong(((this.RGBA.R << 16) & 0xFF0000) + ((this.RGBA.G << 8) & 0xFF00) + this.RGBA.B); }; CRGBColor.prototype.readFromBinaryLong = function (r) { var RGB = r.GetLong(); this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CRGBColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteLong(((this.RGBA.R << 16) & 0xFF0000) + ((this.RGBA.G << 8) & 0xFF00) + this.RGBA.B); }; CRGBColor.prototype.Read_FromBinary = function (r) { var RGB = r.GetLong(); this.RGBA.R = (RGB >> 16) & 0xFF; this.RGBA.G = (RGB >> 8) & 0xFF; this.RGBA.B = RGB & 0xFF; }; CRGBColor.prototype.setColor = function (r, g, b) { this.RGBA.R = r; this.RGBA.G = g; this.RGBA.B = b; }; CRGBColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.RGBA.R === this.RGBA.R && color.RGBA.G === this.RGBA.G && color.RGBA.B === this.RGBA.B && color.RGBA.A === this.RGBA.A; }; CRGBColor.prototype.createDuplicate = function () { var duplicate = new CRGBColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CRGBColor.prototype.Calculate = function (obj) { }; CRGBColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { this.RGBA = AscCommon.RgbaHexToRGBA(reader.GetValue()); } else if (name === "r") { this.RGBA.R = this.getChannelValue(reader.GetValue()); } else if (name === "g") { this.RGBA.G = this.getChannelValue(reader.GetValue()); } else if (name === "b") { this.RGBA.B = this.getChannelValue(reader.GetValue()); } else if (name === "h") { this.h = this.getChannelValue(reader.GetValue()); this.checkHSL(); } else if (name === "s") { this.s = this.getChannelValue(reader.GetValue()); this.checkHSL(); } else if (name === "l") { this.l = this.getChannelValue(reader.GetValue()); this.checkHSL(); } }; CRGBColor.prototype.checkHSL = function () { if (this.h !== null && this.s !== null && this.l !== null) { CColorModifiers.prototype.HSL2RGB.call(this, {H: this.h, S: this.s, L: this.l}, this.RGBA); this.h = null; this.s = null; this.l = null; } }; CRGBColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CRGBColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("srgbClr")); writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), fRGBAToHexString(this.RGBA)); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("srgbClr")); } else { writer.WriteXmlAttributesEnd(true); } }; CRGBColor.prototype.fromScRgb = function() { this.RGBA.R = 255 * this.scRGB_to_sRGB(this.RGBA.R); this.RGBA.G = 255 * this.scRGB_to_sRGB(this.RGBA.G); this.RGBA.B = 255 * this.scRGB_to_sRGB(this.RGBA.B); }; CRGBColor.prototype.scRGB_to_sRGB = function(value) { if( value < 0) return 0; if(value <= 0.0031308) return value * 12.92; if(value < 1) return 1.055 * (Math.pow(value , (1 / 2.4))) - 0.055; return 1; }; function CSchemeColor() { CBaseColor.call(this); this.id = 0; } InitClass(CSchemeColor, CBaseColor, 0); CSchemeColor.prototype.type = c_oAscColor.COLOR_TYPE_SCHEME; CSchemeColor.prototype.check = function (theme, colorMap) { var RGBA, colors = theme.themeElements.clrScheme.colors; if (colorMap[this.id] != null && colors[colorMap[this.id]] != null) RGBA = colors[colorMap[this.id]].color.RGBA; else if (colors[this.id] != null) RGBA = colors[this.id].color.RGBA; if (!RGBA) { RGBA = {R: 0, G: 0, B: 0, A: 255}; } var _RGBA = this.RGBA; if (this.RGBA.needRecalc) { _RGBA.R = RGBA.R; _RGBA.G = RGBA.G; _RGBA.B = RGBA.B; _RGBA.A = RGBA.A; this.RGBA.needRecalc = false; return true; } else { if (_RGBA.R === RGBA.R && _RGBA.G === RGBA.G && _RGBA.B === RGBA.B && _RGBA.A === RGBA.A) { return false; } else { _RGBA.R = RGBA.R; _RGBA.G = RGBA.G; _RGBA.B = RGBA.B; _RGBA.A = RGBA.A; return true; } } }; CSchemeColor.prototype.getObjectType = function () { return AscDFH.historyitem_type_SchemeColor; }; CSchemeColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); w.WriteLong(this.id); }; CSchemeColor.prototype.Read_FromBinary = function (r) { this.id = r.GetLong(); }; CSchemeColor.prototype.setId = function (id) { this.id = id; }; CSchemeColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.id === this.id; }; CSchemeColor.prototype.createDuplicate = function () { var duplicate = new CSchemeColor(); duplicate.id = this.id; duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CSchemeColor.prototype.Calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { if (theme.themeElements.clrScheme) { if (this.id === phClr) { this.RGBA = RGBA; } else { var clrMap; if (colorMap && colorMap.color_map) { clrMap = colorMap.color_map; } else if (slide != null && slide.clrMap != null) { clrMap = slide.clrMap.color_map; } else if (layout != null && layout.clrMap != null) { clrMap = layout.clrMap.color_map; } else if (masterSlide != null && masterSlide.clrMap != null) { clrMap = masterSlide.clrMap.color_map; } else { clrMap = AscFormat.GetDefaultColorMap().color_map; } if (clrMap[this.id] != null && theme.themeElements.clrScheme.colors[clrMap[this.id]] != null && theme.themeElements.clrScheme.colors[clrMap[this.id]].color != null) this.RGBA = theme.themeElements.clrScheme.colors[clrMap[this.id]].color.RGBA; else if (theme.themeElements.clrScheme.colors[this.id] != null && theme.themeElements.clrScheme.colors[this.id].color != null) this.RGBA = theme.themeElements.clrScheme.colors[this.id].color.RGBA; } } }; CSchemeColor.prototype.readAttrXml = function (name, reader) { if (name === "val") { var sVal = reader.GetValue(); if ("accent1" === sVal) this.id = 0; if ("accent2" === sVal) this.id = 1; if ("accent3" === sVal) this.id = 2; if ("accent4" === sVal) this.id = 3; if ("accent5" === sVal) this.id = 4; if ("accent6" === sVal) this.id = 5; if ("bg1" === sVal) this.id = 6; if ("bg2" === sVal) this.id = 7; if ("dk1" === sVal) this.id = 8; if ("dk2" === sVal) this.id = 9; if ("folHlink" === sVal) this.id = 10; if ("hlink" === sVal) this.id = 11; if ("lt1" === sVal) this.id = 12; if ("lt2" === sVal) this.id = 13; if ("phClr" === sVal) this.id = 14; if ("tx1" === sVal) this.id = 15; if ("tx2" === sVal) this.id = 16; } }; CSchemeColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CSchemeColor.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("schemeClr")); let sVal = ""; switch (this.id) { case 0: sVal = "accent1"; break; case 1: sVal = "accent2"; break; case 2: sVal = "accent3"; break; case 3: sVal = "accent4"; break; case 4: sVal = "accent5"; break; case 5: sVal = "accent6"; break; case 6: sVal = "bg1"; break; case 7: sVal = "bg2"; break; case 8: sVal = "dk1"; break; case 9: sVal = "dk2"; break; case 10: sVal = "folHlink"; break; case 11: sVal = "hlink"; break; case 12: sVal = "lt1"; break; case 13: sVal = "lt2"; break; case 14: sVal = "phClr"; break; case 15: sVal = "tx1"; break; case 16: sVal = "tx2"; break; } writer.WriteXmlNullableAttributeString(sAttrNamespace + ("val"), sVal); if (Array.isArray(this.Mods) && this.Mods.length > 0) { writer.WriteXmlAttributesEnd(); this.writeModifiers(writer); writer.WriteXmlNodeEnd(sNodeNamespace + ("schemeClr")); } else { writer.WriteXmlAttributesEnd(true); } }; function CStyleColor() { CBaseColor.call(this); this.bAuto = false; this.val = null; } InitClass(CStyleColor, CBaseColor, 0); CStyleColor.prototype.type = c_oAscColor.COLOR_TYPE_STYLE; CStyleColor.prototype.check = function (theme, colorMap) { }; CStyleColor.prototype.Write_ToBinary = function (w) { w.WriteLong(this.type); writeBool(w, this.bAuto); writeLong(w, this.val); }; CStyleColor.prototype.Read_FromBinary = function (r) { this.bAuto = readBool(r); this.val = readLong(r); }; CStyleColor.prototype.IsIdentical = function (color) { return color && color.type === this.type && color.bAuto === this.bAuto && this.val === color.val; }; CStyleColor.prototype.createDuplicate = function () { var duplicate = new CStyleColor(); duplicate.bAuto = this.bAuto; duplicate.val = this.val; return duplicate; }; CStyleColor.prototype.Calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { }; CStyleColor.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (this.bAuto || this.val === null) { return aColors[nIdx % aColors.length]; } else { return aColors[this.val % aColors.length]; } }; CStyleColor.prototype.readAttrXml = function (name, reader) { //TODO:Implement in children }; CStyleColor.prototype.readChildXml = function (name, reader) { this.readModifier(name, reader); }; CStyleColor.prototype.toXml = function (writer) { //TODO:Implement in children }; function CUniColor() { CBaseNoIdObject.call(this); this.color = null; this.Mods = null;//new CColorModifiers(); this.RGBA = { R: 0, G: 0, B: 0, A: 255 }; } InitClass(CUniColor, CBaseNoIdObject, 0); CUniColor.prototype.checkPhColor = function (unicolor, bMergeMods) { if (this.color && this.color.type === c_oAscColor.COLOR_TYPE_SCHEME && this.color.id === 14) { if (unicolor) { if (unicolor.color) { this.color = unicolor.color.createDuplicate(); } if (unicolor.Mods) { if (!this.Mods || this.Mods.Mods.length === 0) { this.Mods = unicolor.Mods.createDuplicate(); } else { if (bMergeMods) { this.Mods.Merge(unicolor.Mods); } } } } } }; CUniColor.prototype.saveSourceFormatting = function () { var _ret = new CUniColor(); _ret.color = new CRGBColor(); _ret.color.RGBA.R = this.RGBA.R; _ret.color.RGBA.G = this.RGBA.G; _ret.color.RGBA.B = this.RGBA.B; return _ret; }; CUniColor.prototype.addColorMod = function (mod) { if (!this.Mods) { this.Mods = new CColorModifiers(); } this.Mods.addMod(mod.createDuplicate()); }; CUniColor.prototype.check = function (theme, colorMap) { if (this.color && this.color.check(theme, colorMap.color_map)/*ะฒะพะทะฒั€ะฐั‰ะฐะตั‚ ะฑั‹ะป ะปะธ ะธะทะผะตะฝะตะฝ RGBA*/) { this.RGBA.R = this.color.RGBA.R; this.RGBA.G = this.color.RGBA.G; this.RGBA.B = this.color.RGBA.B; if (this.Mods) this.Mods.Apply(this.RGBA); } }; CUniColor.prototype.getModValue = function (sModName) { if (this.Mods && this.Mods.getModValue) { return this.Mods.getModValue(sModName); } return null; }; CUniColor.prototype.checkWordMods = function () { return this.Mods && this.Mods.Mods.length === 1 && (this.Mods.Mods[0].name === "wordTint" || this.Mods.Mods[0].name === "wordShade"); }; CUniColor.prototype.convertToPPTXMods = function () { if (this.checkWordMods()) { var val_, mod_; if (this.Mods.Mods[0].name === "wordShade") { mod_ = new CColorMod(); mod_.setName("lumMod"); mod_.setVal(((this.Mods.Mods[0].val / 255) * 100000) >> 0); this.Mods.Mods.splice(0, this.Mods.Mods.length); this.Mods.Mods.push(mod_); } else { val_ = ((this.Mods.Mods[0].val / 255) * 100000) >> 0; this.Mods.Mods.splice(0, this.Mods.Mods.length); mod_ = new CColorMod(); mod_.setName("lumMod"); mod_.setVal(val_); this.Mods.Mods.push(mod_); mod_ = new CColorMod(); mod_.setName("lumOff"); mod_.setVal(100000 - val_); this.Mods.Mods.push(mod_); } } }; CUniColor.prototype.canConvertPPTXModsToWord = function () { return this.Mods && ((this.Mods.Mods.length === 1 && this.Mods.Mods[0].name === "lumMod" && this.Mods.Mods[0].val > 0) || (this.Mods.Mods.length === 2 && this.Mods.Mods[0].name === "lumMod" && this.Mods.Mods[0].val > 0 && this.Mods.Mods[1].name === "lumOff" && this.Mods.Mods[1].val > 0)); }; CUniColor.prototype.convertToWordMods = function () { if (this.canConvertPPTXModsToWord()) { var mod_ = new CColorMod(); mod_.setName(this.Mods.Mods.length === 1 ? "wordShade" : "wordTint"); mod_.setVal(((this.Mods.Mods[0].val * 255) / 100000) >> 0); this.Mods.Mods.splice(0, this.Mods.Mods.length); this.Mods.Mods.push(mod_); } }; CUniColor.prototype.setColor = function (color) { this.color = color; }; CUniColor.prototype.setMods = function (mods) { this.Mods = mods; }; CUniColor.prototype.Write_ToBinary = function (w) { if (this.color) { w.WriteBool(true); this.color.Write_ToBinary(w); } else { w.WriteBool(false); } if (this.Mods) { w.WriteBool(true); this.Mods.Write_ToBinary(w); } else { w.WriteBool(false); } }; CUniColor.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { var type = r.GetLong(); switch (type) { case c_oAscColor.COLOR_TYPE_NONE: { break; } case c_oAscColor.COLOR_TYPE_SRGB: { this.color = new CRGBColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_PRST: { this.color = new CPrstColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_SCHEME: { this.color = new CSchemeColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_SYS: { this.color = new CSysColor(); this.color.Read_FromBinary(r); break; } case c_oAscColor.COLOR_TYPE_STYLE: { this.color = new CStyleColor(); this.color.Read_FromBinary(r); break; } } } if (r.GetBool()) { this.Mods = new CColorModifiers(); this.Mods.Read_FromBinary(r); } else { this.Mods = null; } }; CUniColor.prototype.createDuplicate = function () { var duplicate = new CUniColor(); if (this.color != null) { duplicate.color = this.color.createDuplicate(); } if (this.Mods) duplicate.Mods = this.Mods.createDuplicate(); duplicate.RGBA.R = this.RGBA.R; duplicate.RGBA.G = this.RGBA.G; duplicate.RGBA.B = this.RGBA.B; duplicate.RGBA.A = this.RGBA.A; return duplicate; }; CUniColor.prototype.IsIdentical = function (unicolor) { if (!isRealObject(unicolor)) { return false; } if (!isRealObject(unicolor.color) && isRealObject(this.color) || !isRealObject(this.color) && isRealObject(unicolor.color) || isRealObject(this.color) && !this.color.IsIdentical(unicolor.color)) { return false; } if (!isRealObject(unicolor.Mods) && isRealObject(this.Mods) && this.Mods.Mods.length > 0 || !isRealObject(this.Mods) && isRealObject(unicolor.Mods) && unicolor.Mods.Mods.length > 0 || isRealObject(this.Mods) && !this.Mods.IsIdentical(unicolor.Mods)) { return false; } return true; }; CUniColor.prototype.Calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { if (this.color == null) return this.RGBA; this.color.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); this.RGBA = {R: this.color.RGBA.R, G: this.color.RGBA.G, B: this.color.RGBA.B, A: this.color.RGBA.A}; if (this.Mods) this.Mods.Apply(this.RGBA); }; CUniColor.prototype.compare = function (unicolor) { if (unicolor == null) { return null; } var _ret = new CUniColor(); if (this.color == null || unicolor.color == null || this.color.type !== unicolor.color.type) { return _ret; } if (this.Mods && unicolor.Mods) { var aMods = this.Mods.Mods; var aMods2 = unicolor.Mods.Mods; if (aMods.length === aMods2.length) { for (var i = 0; i < aMods.length; ++i) { if (aMods2[i].name !== aMods[i].name || aMods2[i].val !== aMods[i].val) { break; } } if (i === aMods.length) { _ret.Mods = this.Mods.createDuplicate(); } } } switch (this.color.type) { case c_oAscColor.COLOR_TYPE_NONE: { break; } case c_oAscColor.COLOR_TYPE_PRST: { _ret.color = new CPrstColor(); if (unicolor.color.id == this.color.id) { _ret.color.id = this.color.id; _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.color.RGBA.A = this.color.RGBA.A; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; _ret.RGBA.A = this.RGBA.A; } break; } case c_oAscColor.COLOR_TYPE_SCHEME: { _ret.color = new CSchemeColor(); if (unicolor.color.id == this.color.id) { _ret.color.id = this.color.id; _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.color.RGBA.A = this.color.RGBA.A; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; _ret.RGBA.A = this.RGBA.A; } break; } case c_oAscColor.COLOR_TYPE_SRGB: { _ret.color = new CRGBColor(); var _RGBA1 = this.color.RGBA; var _RGBA2 = this.color.RGBA; if (_RGBA1.R === _RGBA2.R && _RGBA1.G === _RGBA2.G && _RGBA1.B === _RGBA2.B) { _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; } if (_RGBA1.A === _RGBA2.A) { _ret.color.RGBA.A = this.color.RGBA.A; } break; } case c_oAscColor.COLOR_TYPE_SYS: { _ret.color = new CSysColor(); if (unicolor.color.id == this.color.id) { _ret.color.id = this.color.id; _ret.color.RGBA.R = this.color.RGBA.R; _ret.color.RGBA.G = this.color.RGBA.G; _ret.color.RGBA.B = this.color.RGBA.B; _ret.color.RGBA.A = this.color.RGBA.A; _ret.RGBA.R = this.RGBA.R; _ret.RGBA.G = this.RGBA.G; _ret.RGBA.B = this.RGBA.B; _ret.RGBA.A = this.RGBA.A; } break; } } return _ret; }; CUniColor.prototype.getCSSColor = function (transparent) { if (transparent != null) { var _css = "rgba(" + this.RGBA.R + "," + this.RGBA.G + "," + this.RGBA.B + ",1)"; return _css; } var _css = "rgba(" + this.RGBA.R + "," + this.RGBA.G + "," + this.RGBA.B + "," + (this.RGBA.A / 255) + ")"; return _css; }; CUniColor.prototype.isCorrect = function () { if (this.color !== null && this.color !== undefined) { return true; } return false; }; CUniColor.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (!this.color) { return null; } if (this.color.type !== c_oAscColor.COLOR_TYPE_STYLE) { return this; } return this.color.getNoStyleUnicolor(nIdx, aColors); }; CUniColor.prototype.fromXml = function (reader, name) { switch (name) { case "hslClr": case "scrgbClr": case "srgbClr": { this.color = new CRGBColor(); break; } case "prstClr": { this.color = new CPrstColor(); break; } case "schemeClr": { this.color = new CSchemeColor(); break; } case "sysClr": { this.color = new CSysColor(); break; } } if (this.color) { this.color.fromXml(reader); if(name === "scrgbClr") { this.color.fromScRgb(); } if (Array.isArray(this.color.Mods)) { this.Mods = new CColorModifiers(); this.Mods.Mods = this.color.Mods; this.color.Mods = undefined; } } }; CUniColor.prototype.toXml = function (writer) { if (this.color) { this.color.Mods = this.Mods && this.Mods.Mods; this.color.toXml(writer); this.color.Mods = undefined; } }; CUniColor.prototype.UNICOLOR_MAP = { "hslClr": true, "scrgbClr": true, "srgbClr": true, "prstClr": true, "schemeClr": true, "sysClr": true }; CUniColor.prototype.isUnicolor = function (sName) { return !!CUniColor.prototype.UNICOLOR_MAP[sName]; }; function CreateUniColorRGB(r, g, b) { var ret = new CUniColor(); ret.setColor(new CRGBColor()); ret.color.setColor(r, g, b); return ret; } function CreateUniColorRGB2(color) { var ret = new CUniColor(); ret.setColor(new CRGBColor()); ret.color.setColor(ret.RGBA.R = color.getR(), ret.RGBA.G = color.getG(), ret.RGBA.B = color.getB()); return ret; } function CreateSolidFillRGB(r, g, b) { return AscFormat.CreateUniFillByUniColor(CreateUniColorRGB(r, g, b)); } function CreateSolidFillRGBA(r, g, b, a) { var ret = new CUniFill(); ret.setFill(new CSolidFill()); ret.fill.setColor(new CUniColor()); var _uni_color = ret.fill.color; _uni_color.setColor(new CRGBColor()); _uni_color.color.setColor(r, g, b); _uni_color.RGBA.R = r; _uni_color.RGBA.G = g; _uni_color.RGBA.B = b; _uni_color.RGBA.A = a; return ret; } // ----------------------------- function CSrcRect() { CBaseNoIdObject.call(this); this.l = null; this.t = null; this.r = null; this.b = null; } InitClass(CSrcRect, CBaseNoIdObject, 0); CSrcRect.prototype.setLTRB = function (l, t, r, b) { this.l = l; this.t = t; this.r = r; this.b = b; }; CSrcRect.prototype.setValueForFitBlipFill = function (shapeWidth, shapeHeight, imageWidth, imageHeight) { if ((imageHeight / imageWidth) > (shapeHeight / shapeWidth)) { this.l = 0; this.r = 100; var widthAspectRatio = imageWidth / shapeWidth; var heightAspectRatio = shapeHeight / imageHeight; var stretchPercentage = ((1 - widthAspectRatio * heightAspectRatio) / 2) * 100; this.t = stretchPercentage; this.b = 100 - stretchPercentage; } else { this.t = 0; this.b = 100; heightAspectRatio = imageHeight / shapeHeight; widthAspectRatio = shapeWidth / imageWidth; stretchPercentage = ((1 - heightAspectRatio * widthAspectRatio) / 2) * 100; this.l = stretchPercentage; this.r = 100 - stretchPercentage; } }; CSrcRect.prototype.Write_ToBinary = function (w) { writeDouble(w, this.l); writeDouble(w, this.t); writeDouble(w, this.r); writeDouble(w, this.b); }; CSrcRect.prototype.Read_FromBinary = function (r) { this.l = readDouble(r); this.t = readDouble(r); this.r = readDouble(r); this.b = readDouble(r); }; CSrcRect.prototype.createDublicate = function () { var _ret = new CSrcRect(); _ret.l = this.l; _ret.t = this.t; _ret.r = this.r; _ret.b = this.b; return _ret; }; CSrcRect.prototype.fromXml = function (reader, bSkipFirstNode, bIsMain) { CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); let _ret = this; if (_ret.l == null) _ret.l = 0; if (_ret.t == null) _ret.t = 0; if (_ret.r == null) _ret.r = 0; if (_ret.b == null) _ret.b = 0; if (!bIsMain) { var _absW = Math.abs(_ret.l) + Math.abs(_ret.r) + 100; var _absH = Math.abs(_ret.t) + Math.abs(_ret.b) + 100; _ret.l = -100 * _ret.l / _absW; _ret.t = -100 * _ret.t / _absH; _ret.r = -100 * _ret.r / _absW; _ret.b = -100 * _ret.b / _absH; } _ret.r = 100 - _ret.r; _ret.b = 100 - _ret.b; if (_ret.l > _ret.r) { var tmp = _ret.l; _ret.l = _ret.r; _ret.r = tmp; } if (_ret.t > _ret.b) { var tmp = _ret.t; _ret.t = _ret.b; _ret.b = tmp; } this.setLTRB(_ret.l, _ret.t, _ret.r, _ret.b); }; CSrcRect.prototype.readAttrXml = function (name, reader) { var sVal = reader.GetValue(); switch (name) { case "l": { this.l = getPercentageValue(sVal); break; } case "t": { this.t = getPercentageValue(sVal); break; } case "r": { this.r = getPercentageValue(sVal); break; } case "b": { this.b = getPercentageValue(sVal); break; } } }; CSrcRect.prototype.toXml = function (writer, sName) { let sName_ = sName || "a:srcRect"; writer.WriteXmlNodeStart(sName_); writer.WriteXmlNullableAttributeUInt("l", getPercentageValueForWrite(this.l)); writer.WriteXmlNullableAttributeUInt("t", getPercentageValueForWrite(this.t)); if(AscFormat.isRealNumber(this.r)) { writer.WriteXmlAttributeUInt("r", getPercentageValueForWrite(100 - this.r)); } if(AscFormat.isRealNumber(this.b)) { writer.WriteXmlAttributeUInt("b", getPercentageValueForWrite(100 - this.b)); } writer.WriteXmlAttributesEnd(true); }; CSrcRect.prototype.isFullRect = function() { let r = this; let fAE = AscFormat.fApproxEqual; if(fAE(r.l, 0) && fAE(r.t, 0) && fAE(r.r, 100) && fAE(r.b, 100)) { return true; } return false; }; function CBlipFillTile() { CBaseNoIdObject.call(this) this.tx = null; this.ty = null; this.sx = null; this.sy = null; this.flip = null; this.algn = null; } InitClass(CBlipFillTile, CBaseNoIdObject, 0); CBlipFillTile.prototype.Write_ToBinary = function (w) { writeLong(w, this.tx); writeLong(w, this.ty); writeLong(w, this.sx); writeLong(w, this.sy); writeLong(w, this.flip); writeLong(w, this.algn); }; CBlipFillTile.prototype.Read_FromBinary = function (r) { this.tx = readLong(r); this.ty = readLong(r); this.sx = readLong(r); this.sy = readLong(r); this.flip = readLong(r); this.algn = readLong(r); }; CBlipFillTile.prototype.createDuplicate = function () { var ret = new CBlipFillTile(); ret.tx = this.tx; ret.ty = this.ty; ret.sx = this.sx; ret.sy = this.sy; ret.flip = this.flip; ret.algn = this.algn; return ret; }; CBlipFillTile.prototype.IsIdentical = function (o) { if (!o) { return false; } return (o.tx == this.tx && o.ty == this.ty && o.sx == this.sx && o.sy == this.sy && o.flip == this.flip && o.algn == this.algn) }; CBlipFillTile.prototype.readAttrXml = function (name, reader) { switch (name) { case "algn" : { this.algn = this.GetAlignBYTECode(reader.GetValue()); break; } case "flip" : { this.flip = reader.GetValue(); break; } case "sx" : { this.sx = reader.GetValueInt(); break; } case "sy" : { this.sy = reader.GetValueInt(); break; } case "tx" : { this.tx = reader.GetValueInt(); break; } case "ty" : { this.ty = reader.GetValueInt(); break; } } }; CBlipFillTile.prototype.GetAlignBYTECode = function (sVal) { if ("b" === sVal) return 0; if ("bl" === sVal) return 1; if ("br" === sVal) return 2; if ("ctr" === sVal) return 3; if ("l" === sVal) return 4; if ("r" === sVal) return 5; if ("t" === sVal) return 6; if ("tl" === sVal) return 7; if ("tr" === sVal) return 8; return 7; }; CBlipFillTile.prototype.SetAlignBYTECode = function (src) { switch (src) { case 0: return ("b"); break; case 1: return ("bl"); break; case 2: return ("br"); break; case 3: return ("ctr"); break; case 4: return ("l"); break; case 5: return ("r"); break; case 6: return ("t"); break; case 7: return ("tl"); break; case 8: return ("tr"); break; default: break; } return null; }; CBlipFillTile.prototype.GetFlipBYTECode = function (sVal) { if ("none" === sVal) return 0; if ("x" === sVal) return 1; if ("y" === sVal) return 2; if ("xy" === sVal) return 3; return 0; } CBlipFillTile.prototype.SetFlipBYTECode = function (src) { switch (src) { case 0: return ("none"); break; case 1: return ("x"); break; case 2: return ("y"); break; case 3: return ("xy"); break; default: break; } return null; } CBlipFillTile.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:tile"); writer.WriteXmlNullableAttributeString("algn", this.SetAlignBYTECode(this.algn)); writer.WriteXmlNullableAttributeString("flip", this.SetFlipBYTECode(this.flip)); writer.WriteXmlNullableAttributeInt("sx", this.sx); writer.WriteXmlNullableAttributeInt("sy", this.sy); writer.WriteXmlNullableAttributeInt("tx", this.tx); writer.WriteXmlNullableAttributeInt("ty", this.ty); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:tile"); }; function fReadEffectXML(name, reader) { var oEffect = null; switch (name) { case "alphaBiLevel": { oEffect = new CAlphaBiLevel(); break; } case "alphaCeiling": { oEffect = new CAlphaCeiling(); break; } case "alphaFloor": { oEffect = new CAlphaFloor(); break; } case "alphaInv": { oEffect = new CAlphaInv(); break; } case "alphaMod": { oEffect = new CAlphaMod(); break; } case "alphaModFix": { oEffect = new CAlphaModFix(); break; } case "alphaOutset": { oEffect = new CAlphaOutset(); break; } case "alphaRepl": { oEffect = new CAlphaRepl(); break; } case "biLevel": { oEffect = new CBiLevel(); break; } case "blend": { oEffect = new CBlend(); break; } case "blur": { oEffect = new CBlur(); break; } case "clrChange": { oEffect = new CClrChange(); break; } case "clrRepl": { oEffect = new CClrRepl(); break; } case "cont": { oEffect = new CEffectContainer(); break; } case "duotone": { oEffect = new CDuotone(); break; } case "effect": { //oEffect = new CEfect(); break; } case "fill": { oEffect = new CFillEffect(); break; } case "fillOverlay": { oEffect = new CFillOverlay(); break; } case "glow": { oEffect = new CGlow(); break; } case "grayscl": { oEffect = new CGrayscl(); break; } case "hsl": { oEffect = new CHslEffect(); break; } case "innerShdw": { oEffect = new CInnerShdw(); break; } case "lum": { oEffect = new CLumEffect(); break; } case "outerShdw": { oEffect = new COuterShdw(); break; } case "prstShdw": { oEffect = new CPrstShdw(); break; } case "reflection": { oEffect = new CReflection(); break; } case "relOff": { oEffect = new CRelOff(); break; } case "softEdge": { oEffect = new CSoftEdge(); break; } case "tint": { oEffect = new CTintEffect(); break; } case "xfrm": { oEffect = new CXfrmEffect(); break; } } return oEffect; } function CBaseFill() { CBaseNoIdObject.call(this); } InitClass(CBaseFill, CBaseNoIdObject, 0); CBaseFill.prototype.type = c_oAscFill.FILL_TYPE_NONE; function fReadXmlRasterImageId(reader, rId, blipFill) { var rel = reader.rels.getRelationship(rId); if (rel) { var context = reader.context; if ("Internal" === rel.targetMode) { var blipFills = context.imageMap[rel.targetFullName.substring(1)]; if (!blipFills) { context.imageMap[rel.targetFullName.substring(1)] = blipFills = []; } blipFills.push(blipFill); } } } function CBlip(oBlipFill) { CBaseNoIdObject.call(this); this.blipFill = oBlipFill; this.link = null; } InitClass(CBlip, CBaseNoIdObject, 0); CBlip.prototype.readAttrXml = function (name, reader) { switch (name) { case "embed" : { var rId = reader.GetValue(); fReadXmlRasterImageId(reader, rId, this.blipFill); break; } } }; CBlip.prototype.readChildXml = function (name, reader) { let oEffect = fReadEffectXML(name, reader); if (oEffect) { this.blipFill.Effects.push(oEffect); } }; CBlip.prototype.toXml = function (writer, sNamespace, sRasterImageId) { let sNamespace_ = sNamespace || "a"; let strName = ("" === sNamespace_) ? ("blip") : (sNamespace_ + (":blip")); let context = writer.context; //writer.WriteXmlNullable(blip); writer.WriteXmlNodeStart(strName); writer.WriteXmlString(' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'); writer.WriteXmlAttributeString("r:embed", context.getImageRId(sRasterImageId)); writer.WriteXmlAttributesEnd(); writer.WriteXmlString('<a:extLst><a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}"><a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/></a:ext></a:extLst>'); writer.WriteXmlNodeEnd(strName); }; function CBlipFill() { CBaseFill.call(this); this.RasterImageId = ""; this.srcRect = null; this.stretch = null; this.tile = null; this.rotWithShape = null; this.Effects = []; } InitClass(CBlipFill, CBaseFill, 0); CBlipFill.prototype.type = c_oAscFill.FILL_TYPE_BLIP; CBlipFill.prototype.saveSourceFormatting = function () { return this.createDuplicate(); }; CBlipFill.prototype.Write_ToBinary = function (w) { writeString(w, this.RasterImageId); if (this.srcRect) { writeBool(w, true); writeDouble(w, this.srcRect.l); writeDouble(w, this.srcRect.t); writeDouble(w, this.srcRect.r); writeDouble(w, this.srcRect.b); } else { writeBool(w, false); } writeBool(w, this.stretch); if (isRealObject(this.tile)) { w.WriteBool(true); this.tile.Write_ToBinary(w); } else { w.WriteBool(false); } writeBool(w, this.rotWithShape); w.WriteLong(this.Effects.length); for (var i = 0; i < this.Effects.length; ++i) { this.Effects[i].Write_ToBinary(w); } }; CBlipFill.prototype.Read_FromBinary = function (r) { this.RasterImageId = readString(r); var _correct_id = AscCommon.getImageFromChanges(this.RasterImageId); if (null != _correct_id) this.RasterImageId = _correct_id; //var srcUrl = readString(r); //if(srcUrl) { // AscCommon.g_oDocumentUrls.addImageUrl(this.RasterImageId, srcUrl); //} if (readBool(r)) { this.srcRect = new CSrcRect(); this.srcRect.l = readDouble(r); this.srcRect.t = readDouble(r); this.srcRect.r = readDouble(r); this.srcRect.b = readDouble(r); } else { this.srcRect = null; } this.stretch = readBool(r); if (r.GetBool()) { this.tile = new CBlipFillTile(); this.tile.Read_FromBinary(r); } else { this.tile = null; } this.rotWithShape = readBool(r); var count = r.GetLong(); for (var i = 0; i < count; ++i) { var effect = fReadEffect(r); if (!effect) { break; } this.Effects.push(effect); } }; CBlipFill.prototype.Refresh_RecalcData = function () { }; CBlipFill.prototype.check = function () { }; CBlipFill.prototype.checkWordMods = function () { return false; }; CBlipFill.prototype.convertToPPTXMods = function () { }; CBlipFill.prototype.canConvertPPTXModsToWord = function () { return false; }; CBlipFill.prototype.convertToWordMods = function () { }; CBlipFill.prototype.getObjectType = function () { return AscDFH.historyitem_type_BlipFill; }; CBlipFill.prototype.setRasterImageId = function (rasterImageId) { this.RasterImageId = checkRasterImageId(rasterImageId); }; CBlipFill.prototype.setSrcRect = function (srcRect) { this.srcRect = srcRect; }; CBlipFill.prototype.setStretch = function (stretch) { this.stretch = stretch; }; CBlipFill.prototype.setTile = function (tile) { this.tile = tile; }; CBlipFill.prototype.setRotWithShape = function (rotWithShape) { this.rotWithShape = rotWithShape; }; CBlipFill.prototype.createDuplicate = function () { var duplicate = new CBlipFill(); duplicate.RasterImageId = this.RasterImageId; duplicate.stretch = this.stretch; if (isRealObject(this.tile)) { duplicate.tile = this.tile.createDuplicate(); } if (null != this.srcRect) duplicate.srcRect = this.srcRect.createDublicate(); duplicate.rotWithShape = this.rotWithShape; if (Array.isArray(this.Effects)) { for (var i = 0; i < this.Effects.length; ++i) { if (this.Effects[i] && this.Effects[i].createDuplicate) { duplicate.Effects.push(this.Effects[i].createDuplicate()); } } } return duplicate; }; CBlipFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_BLIP) { return false; } if (fill.RasterImageId !== this.RasterImageId) { return false; } /*if(fill.VectorImageBin != this.VectorImageBin) { return false; } */ if (fill.stretch != this.stretch) { return false; } if (isRealObject(this.tile)) { if (!this.tile.IsIdentical(fill.tile)) { return false; } } else { if (fill.tile) { return false; } } /* if(fill.rotWithShape != this.rotWithShape) { return false; } */ return true; }; CBlipFill.prototype.compare = function (fill) { if (fill == null || fill.type !== c_oAscFill.FILL_TYPE_BLIP) { return null; } var _ret = new CBlipFill(); if (this.RasterImageId == fill.RasterImageId) { _ret.RasterImageId = this.RasterImageId; } if (fill.stretch == this.stretch) { _ret.stretch = this.stretch; } if (isRealObject(fill.tile)) { if (fill.tile.IsIdentical(this.tile)) { _ret.tile = this.tile.createDuplicate(); } else { _ret.tile = new CBlipFillTile(); } } if (fill.rotWithShape === this.rotWithShape) { _ret.rotWithShape = this.rotWithShape; } return _ret; }; CBlipFill.prototype.getBase64Data = function (bReduce, bReturnOrigIfCantDraw) { var sRasterImageId = this.RasterImageId; if (typeof sRasterImageId !== "string" || sRasterImageId.length === 0) { return null; } var oApi = Asc.editor || editor; var sDefaultResult = sRasterImageId; if(bReturnOrigIfCantDraw === false) { sDefaultResult = null; } if (!oApi) { return {img: sDefaultResult, w: null, h: null}; } var oImageLoader = oApi.ImageLoader; if (!oImageLoader) { return {img: sDefaultResult, w: null, h: null}; } var oImage = oImageLoader.map_image_index[AscCommon.getFullImageSrc2(sRasterImageId)]; if (!oImage || !oImage.Image || oImage.Status !== AscFonts.ImageLoadStatus.Complete) { return {img: sDefaultResult, w: null, h: null}; } if (sRasterImageId.indexOf("data:") === 0 && sRasterImageId.indexOf("base64") > 0) { return {img: sRasterImageId, w: oImage.Image.width, h: oImage.Image.height}; } var sResult = sDefaultResult; if (!window["NATIVE_EDITOR_ENJINE"]) { var oCanvas = document.createElement("canvas"); var nW = Math.max(oImage.Image.width, 1); var nH = Math.max(oImage.Image.height, 1); if (bReduce) { var nMaxSize = 640; var dWK = nW / nMaxSize; var dHK = nH / nMaxSize; var dK = Math.max(dWK, dHK); if (dK > 1) { nW = ((nW / dK) + 0.5 >> 0); nH = ((nH / dK) + 0.5 >> 0); } } oCanvas.width = nW; oCanvas.height = nH; var oCtx = oCanvas.getContext("2d"); oCtx.drawImage(oImage.Image, 0, 0, oCanvas.width, oCanvas.height); try { sResult = oCanvas.toDataURL("image/png"); } catch (err) { sResult = sDefaultResult; } return {img: sResult, w: oCanvas.width, h: oCanvas.height}; } return {img: sRasterImageId, w: null, h: null}; }; CBlipFill.prototype.getBase64RasterImageId = function (bReduce, bReturnOrigIfCantDraw) { return this.getBase64Data(bReduce, bReturnOrigIfCantDraw).img; }; CBlipFill.prototype.readAttrXml = function (name, reader) { if (name === "rotWithShape") { this.rotWithShape = reader.GetValueBool(); } else if (name === "dpi") { //todo } }; CBlipFill.prototype.fromXml = function (reader, bSkipFirstNode) { CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); if(this.srcRect && this.srcRect.isFullRect()) { this.srcRect = null; } } CBlipFill.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { let oBlip = new CBlip(this); oBlip.fromXml(reader); break; } case "srcRect": { this.srcRect = new CSrcRect(); this.srcRect.fromXml(reader, false, true); break; } case "stretch": { this.stretch = true; let oThis = this; let oPr = new CT_XmlNode(function (reader, name) { if (name === "fillRect") { let oSrcRect = new CSrcRect(); oSrcRect.fromXml(reader, false, false); if(!oSrcRect.isFullRect()) { oThis.srcRect = oSrcRect; } } return true; }); oPr.fromXml(reader); break; } case "tile": { this.tile = new CBlipFillTile(); this.tile.fromXml(reader); break; } } }; CBlipFill.prototype.writeBlip = function (writer) { CBlip.prototype.toXml.call(this, writer, "a", this.RasterImageId); }; CBlipFill.prototype.toXml = function (writer, sNamespace) { let sNamespace_ = sNamespace || "a"; let strName = ("" === sNamespace_) ? ("blipFill") : (sNamespace_ + (":blipFill")); writer.WriteXmlNodeStart(strName); //writer.WriteXmlNullableAttributeString("dpi", dpi); writer.WriteXmlNullableAttributeBool("rotWithShape", this.rotWithShape); writer.WriteXmlAttributesEnd(); this.writeBlip(writer); if (this.srcRect) { this.srcRect.toXml(writer) } //writer.WriteXmlNullable(tile); if (this.tile) { this.tile.toXml(writer); } //writer.WriteXmlNullable(stretch); if (this.stretch) { writer.WriteXmlNodeStart("a:stretch"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:fillRect"); writer.WriteXmlAttributesEnd(true); writer.WriteXmlNodeEnd("a:stretch"); } writer.WriteXmlNodeEnd(strName); }; //-----Effects----- var EFFECT_TYPE_NONE = 0; var EFFECT_TYPE_OUTERSHDW = 1; var EFFECT_TYPE_GLOW = 2; var EFFECT_TYPE_DUOTONE = 3; var EFFECT_TYPE_XFRM = 4; var EFFECT_TYPE_BLUR = 5; var EFFECT_TYPE_PRSTSHDW = 6; var EFFECT_TYPE_INNERSHDW = 7; var EFFECT_TYPE_REFLECTION = 8; var EFFECT_TYPE_SOFTEDGE = 9; var EFFECT_TYPE_FILLOVERLAY = 10; var EFFECT_TYPE_ALPHACEILING = 11; var EFFECT_TYPE_ALPHAFLOOR = 12; var EFFECT_TYPE_TINTEFFECT = 13; var EFFECT_TYPE_RELOFF = 14; var EFFECT_TYPE_LUM = 15; var EFFECT_TYPE_HSL = 16; var EFFECT_TYPE_GRAYSCL = 17; var EFFECT_TYPE_ELEMENT = 18; var EFFECT_TYPE_ALPHAREPL = 19; var EFFECT_TYPE_ALPHAOUTSET = 20; var EFFECT_TYPE_ALPHAMODFIX = 21; var EFFECT_TYPE_ALPHABILEVEL = 22; var EFFECT_TYPE_BILEVEL = 23; var EFFECT_TYPE_DAG = 24; var EFFECT_TYPE_FILL = 25; var EFFECT_TYPE_CLRREPL = 26; var EFFECT_TYPE_CLRCHANGE = 27; var EFFECT_TYPE_ALPHAINV = 28; var EFFECT_TYPE_ALPHAMOD = 29; var EFFECT_TYPE_BLEND = 30; function fCreateEffectByType(type) { var ret = null; switch (type) { case EFFECT_TYPE_NONE: { break; } case EFFECT_TYPE_OUTERSHDW: { ret = new COuterShdw(); break; } case EFFECT_TYPE_GLOW: { ret = new CGlow(); break; } case EFFECT_TYPE_DUOTONE: { ret = new CDuotone(); break; } case EFFECT_TYPE_XFRM: { ret = new CXfrmEffect(); break; } case EFFECT_TYPE_BLUR: { ret = new CBlur(); break; } case EFFECT_TYPE_PRSTSHDW: { ret = new CPrstShdw(); break; } case EFFECT_TYPE_INNERSHDW: { ret = new CInnerShdw(); break; } case EFFECT_TYPE_REFLECTION: { ret = new CReflection(); break; } case EFFECT_TYPE_SOFTEDGE: { ret = new CSoftEdge(); break; } case EFFECT_TYPE_FILLOVERLAY: { ret = new CFillOverlay(); break; } case EFFECT_TYPE_ALPHACEILING: { ret = new CAlphaCeiling(); break; } case EFFECT_TYPE_ALPHAFLOOR: { ret = new CAlphaFloor(); break; } case EFFECT_TYPE_TINTEFFECT: { ret = new CTintEffect(); break; } case EFFECT_TYPE_RELOFF: { ret = new CRelOff(); break; } case EFFECT_TYPE_LUM: { ret = new CLumEffect(); break; } case EFFECT_TYPE_HSL: { ret = new CHslEffect(); break; } case EFFECT_TYPE_GRAYSCL: { ret = new CGrayscl(); break; } case EFFECT_TYPE_ELEMENT: { ret = new CEffectElement(); break; } case EFFECT_TYPE_ALPHAREPL: { ret = new CAlphaRepl(); break; } case EFFECT_TYPE_ALPHAOUTSET: { ret = new CAlphaOutset(); break; } case EFFECT_TYPE_ALPHAMODFIX: { ret = new CAlphaModFix(); break; } case EFFECT_TYPE_ALPHABILEVEL: { ret = new CAlphaBiLevel(); break; } case EFFECT_TYPE_BILEVEL: { ret = new CBiLevel(); break; } case EFFECT_TYPE_DAG: { ret = new CEffectContainer(); break; } case EFFECT_TYPE_FILL: { ret = new CFillEffect(); break; } case EFFECT_TYPE_CLRREPL: { ret = new CClrRepl(); break; } case EFFECT_TYPE_CLRCHANGE: { ret = new CClrChange(); break; } case EFFECT_TYPE_ALPHAINV: { ret = new CAlphaInv(); break; } case EFFECT_TYPE_ALPHAMOD: { ret = new CAlphaMod(); break; } case EFFECT_TYPE_BLEND: { ret = new CBlend(); break; } } return ret; } function fReadEffect(r) { var type = r.GetLong(); var ret = fCreateEffectByType(type); ret.Read_FromBinary(r); return ret; } function CAlphaBiLevel() { CBaseNoIdObject.call(this); this.tresh = 0; } InitClass(CAlphaBiLevel, CBaseNoIdObject, 0); CAlphaBiLevel.prototype.Type = EFFECT_TYPE_ALPHABILEVEL; CAlphaBiLevel.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHABILEVEL); w.WriteLong(this.tresh); }; CAlphaBiLevel.prototype.Read_FromBinary = function (r) { this.tresh = r.GetLong(); }; CAlphaBiLevel.prototype.createDuplicate = function () { var oCopy = new CAlphaBiLevel(); oCopy.tresh = this.tresh; return oCopy; }; CAlphaBiLevel.prototype.readAttrXml = function (name, reader) { if (name === "tresh") { this.tresh = reader.GetValueInt(); } }; CAlphaBiLevel.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaBiLevel"); writer.WriteXmlNullableAttributeInt("thresh", this.tresh); writer.WriteXmlAttributesEnd(true); }; function CAlphaCeiling() { CBaseNoIdObject.call(this); } InitClass(CAlphaCeiling, CBaseNoIdObject, 0); CAlphaCeiling.prototype.Type = EFFECT_TYPE_ALPHACEILING; CAlphaCeiling.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHACEILING); }; CAlphaCeiling.prototype.Read_FromBinary = function (r) { }; CAlphaCeiling.prototype.createDuplicate = function () { var oCopy = new CAlphaCeiling(); return oCopy; }; CAlphaCeiling.prototype.toXml = function (writer) { writer.WriteXmlString("<a:alphaCeiling/>"); }; function CAlphaFloor() { CBaseNoIdObject.call(this); } InitClass(CBaseNoIdObject, CBaseNoIdObject, 0); CAlphaFloor.prototype.Type = EFFECT_TYPE_ALPHAFLOOR; CAlphaFloor.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAFLOOR); }; CAlphaFloor.prototype.Read_FromBinary = function (r) { }; CAlphaFloor.prototype.createDuplicate = function () { var oCopy = new CAlphaFloor(); return oCopy; }; CAlphaFloor.prototype.toXml = function (writer) { writer.WriteXmlString("<a:alphaFloor/>"); }; function CAlphaInv() { CBaseNoIdObject.call(this); this.unicolor = null; } InitClass(CAlphaInv, CBaseNoIdObject, 0); CAlphaInv.prototype.Type = EFFECT_TYPE_ALPHAINV; CAlphaInv.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAINV); if (this.unicolor) { w.WriteBool(true); this.unicolor.Write_ToBinary(w); } else { w.WriteBool(false); } }; CAlphaInv.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.unicolor = new CUniColor(); this.unicolor.Read_FromBinary(r); } }; CAlphaInv.prototype.createDuplicate = function () { var oCopy = new CAlphaInv(); if (this.unicolor) { oCopy.unicolor = this.unicolor.createDuplicate(); } return oCopy; }; CAlphaInv.prototype.readAttrXml = function (name, reader) { }; CAlphaInv.prototype.readChildXml = function (name, reader) { var oUniColor = new CUniColor(); oUniColor.fromXml(reader, name); if (oUniColor.color) { this.unicolor = oUniColor; } }; CAlphaInv.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaInv"); writer.WriteXmlAttributesEnd(); this.unicolor.toXml(writer); writer.WriteXmlNodeEnd("a:alphaInv"); }; var effectcontainertypeSib = 0; var effectcontainertypeTree = 1; function CEffectContainer() { CBaseNoIdObject.call(this); this.type = null; this.name = null; this.effectList = []; } InitClass(CEffectContainer, CBaseNoIdObject, 0); CEffectContainer.prototype.Type = EFFECT_TYPE_DAG; CEffectContainer.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_DAG); writeLong(w, this.type); writeString(w, this.name); w.WriteLong(this.effectList.length); for (var i = 0; i < this.effectList.length; ++i) { this.effectList[i].Write_ToBinary(w); } }; CEffectContainer.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.name = readString(r); var count = r.GetLong(); for (var i = 0; i < count; ++i) { var effect = fReadEffect(r); if (!effect) { //error break; } this.effectList.push(effect); } }; CEffectContainer.prototype.createDuplicate = function () { var oCopy = new CEffectContainer(); oCopy.type = this.type; oCopy.name = this.name; for (var i = 0; i < this.effectList.length; ++i) { oCopy.effectList.push(this.effectList[i].createDuplicate()); } return oCopy; }; CEffectContainer.prototype.readAttrXml = function (name, reader) { if (name === "name") { this.name = reader.GetValue() } else if (name === "type") { let sType = reader.GetValue(); if (sType === "sib") { this.type = effectcontainertypeSib; } else { this.type = effectcontainertypeTree; } } }; CEffectContainer.prototype.readChildXml = function (name, reader) { let oEffect = fReadEffectXML(name, reader); if (oEffect) { this.effectList.push(oEffect); } }; CEffectContainer.prototype.toXml = function (writer, sName) { let sName_ = (sName && sName.length > 0) ? sNname : "a:effectDag"; writer.WriteXmlNodeStart(sName_); writer.WriteXmlNullableAttributeString("name", name); writer.WriteXmlNullableAttributeString("type", type); writer.WriteXmlAttributesEnd(); for (let i = 0; i < this.effectList.length; i++) { this.effectList[i].toXml(writer); } writer.WriteXmlNodeEnd(sName_); }; function CAlphaMod() { CBaseNoIdObject.call(this); this.cont = new CEffectContainer(); } InitClass(CAlphaMod, CBaseNoIdObject, 0); CAlphaMod.prototype.Type = EFFECT_TYPE_ALPHAMOD; CAlphaMod.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAMOD); this.cont.Write_ToBinary(w); }; CAlphaMod.prototype.Read_FromBinary = function (r) { this.cont.Read_FromBinary(r); }; CAlphaMod.prototype.createDuplicate = function () { var oCopy = new CAlphaMod(); oCopy.cont = this.cont.createDuplicate(); return oCopy; }; CAlphaMod.prototype.readChildXml = function (name, reader) { if (name === "cont") { this.cont.fromXml(reader); } }; CAlphaMod.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaMod"); writer.WriteXmlAttributesEnd(); this.cont.toXml(writer, "a:cont"); writer.WriteXmlNodeEnd("a:alphaMod"); }; function CAlphaModFix() { CBaseNoIdObject.call(this); this.amt = null; } InitClass(CAlphaModFix, CBaseNoIdObject, 0); CAlphaModFix.prototype.Type = EFFECT_TYPE_ALPHAMODFIX; CAlphaModFix.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAMODFIX); writeLong(w, this.amt); }; CAlphaModFix.prototype.Read_FromBinary = function (r) { this.amt = readLong(r); }; CAlphaModFix.prototype.createDuplicate = function () { var oCopy = new CAlphaModFix(); oCopy.amt = this.amt; return oCopy; }; CAlphaModFix.prototype.readAttrXml = function (name, reader) { switch (name) { case "amt": { this.amt = reader.GetValueInt(); break; } } }; CAlphaModFix.prototype.readChildXml = function (name, reader) { }; CAlphaModFix.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaModFix"); writer.WriteXmlNullableAttributeInt("amt", this.amt); writer.WriteXmlAttributesEnd(true); }; function CAlphaOutset() { CBaseNoIdObject.call(this); this.rad = null; } InitClass(CAlphaOutset, CBaseNoIdObject, 0); CAlphaOutset.prototype.Type = EFFECT_TYPE_ALPHAOUTSET; CAlphaOutset.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAOUTSET); writeLong(w, this.rad); }; CAlphaOutset.prototype.Read_FromBinary = function (r) { this.rad = readLong(r); }; CAlphaOutset.prototype.createDuplicate = function () { var oCopy = new CAlphaOutset(); oCopy.rad = this.rad; return oCopy; }; CAlphaOutset.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } } }; CAlphaOutset.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaOutset"); writer.WriteXmlNullableAttributeInt("rad", this.rad); writer.WriteXmlAttributesEnd(true); }; function CAlphaRepl() { CBaseNoIdObject.call(this); this.a = null; } InitClass(CAlphaRepl, CBaseNoIdObject, 0); CAlphaRepl.prototype.Type = EFFECT_TYPE_ALPHAREPL; CAlphaRepl.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ALPHAREPL); writeLong(w, this.a); }; CAlphaRepl.prototype.Read_FromBinary = function (r) { this.a = readLong(r); }; CAlphaRepl.prototype.createDuplicate = function () { var oCopy = new CAlphaRepl(); oCopy.a = this.a; return oCopy; }; CAlphaRepl.prototype.readAttrXml = function (name, reader) { switch (name) { case "a": { this.a = reader.GetValueInt(); break; } } }; CAlphaRepl.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:alphaRepl"); writer.WriteXmlNullableAttributeInt("a", this.a); writer.WriteXmlAttributesEnd(true); }; function CBiLevel() { CBaseNoIdObject.call(this); this.thresh = null; } InitClass(CBiLevel, CBaseNoIdObject, 0); CBiLevel.prototype.Type = EFFECT_TYPE_BILEVEL; CBiLevel.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_BILEVEL); writeLong(w, this.thresh); }; CBiLevel.prototype.Read_FromBinary = function (r) { this.thresh = readLong(r); }; CBiLevel.prototype.createDuplicate = function () { var oCopy = new CBiLevel(); oCopy.thresh = this.thresh; return oCopy; }; CBiLevel.prototype.readAttrXml = function (name, reader) { switch (name) { case "thresh": { this.thresh = reader.GetValueInt(); break; } } }; CBiLevel.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:biLevel"); writer.WriteXmlNullableAttributeInt("thresh", this.thresh); writer.WriteXmlAttributesEnd(true); }; var blendmodeDarken = 0; var blendmodeLighten = 1; var blendmodeMult = 2; var blendmodeOver = 3; var blendmodeScreen = 4; function CBlend() { CBaseNoIdObject.call(this); this.blend = null; this.cont = new CEffectContainer(); } InitClass(CBlend, CBaseNoIdObject, 0); CBlend.prototype.Type = EFFECT_TYPE_BLEND; CBlend.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_BLEND); writeLong(w, this.blend); this.cont.Write_ToBinary(w); }; CBlend.prototype.Read_FromBinary = function (r) { this.blend = readLong(r); this.cont.Read_FromBinary(r); }; CBlend.prototype.createDuplicate = function () { var oCopy = new CBlend(); oCopy.blend = this.blend; oCopy.cont = this.cont.createDuplicate(); return oCopy; }; CBlend.prototype.readAttrXml = function (name, reader) { switch (name) { case "blend": { this.blend = reader.GetValueInt(); break; } } }; CBlend.prototype.readChildXml = function (name, reader) { switch (name) { case "cont": { this.cont.fromXml(reader); break; } } }; CBlend.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:blend"); writer.WriteXmlNullableAttributeInt("blend", this.blend); writer.WriteXmlAttributesEnd(); this.cont.toXml(writer, "a:cont"); writer.WriteXmlNodeEnd("a:blend"); }; function CBlur() { CBaseNoIdObject.call(this); this.rad = null; this.grow = null; } InitClass(CBlur, CBaseNoIdObject, 0); CBlur.prototype.Type = EFFECT_TYPE_BLUR; CBlur.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_BLUR); writeLong(w, this.rad); writeBool(w, this.grow); }; CBlur.prototype.Read_FromBinary = function (r) { this.rad = readLong(r); this.grow = readBool(r); }; CBlur.prototype.createDuplicate = function () { var oCopy = new CBlur(); oCopy.rad = this.rad; oCopy.grow = this.grow; return oCopy; }; CBlur.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } case "grow": { this.grow = reader.GetValueBool(); break; } } }; CBlur.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:blur"); writer.WriteXmlNullableAttributeInt("rad", this.rad); writer.WriteXmlNullableAttributeBool("grow", this.grow); writer.WriteXmlAttributesEnd(true); }; function CClrChange() { CBaseNoIdObject.call(this); this.clrFrom = new CUniColor(); this.clrTo = new CUniColor(); this.useA = null; } InitClass(CClrChange, CBaseNoIdObject, 0); CClrChange.prototype.Type = EFFECT_TYPE_CLRCHANGE; CClrChange.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_CLRCHANGE); this.clrFrom.Write_ToBinary(w); this.clrTo.Write_ToBinary(w); writeBool(w, this.useA); }; CClrChange.prototype.Read_FromBinary = function (r) { this.clrFrom.Read_FromBinary(r); this.clrTo.Read_FromBinary(r); this.useA = readBool(r); }; CClrChange.prototype.createDuplicate = function () { var oCopy = new CClrChange(); oCopy.clrFrom = this.clrFrom.createDuplicate(); oCopy.clrTo = this.clrTo.createDuplicate(); oCopy.useA = this.useA; return oCopy; }; CClrChange.prototype.readAttrXml = function (name, reader) { switch (name) { case "useA": { this.useA = reader.GetValueBool(); break; } } }; CClrChange.prototype.readChildXml = function (name, reader) { if (name === "clrFrom" || name === "clrTo") { let oColor = null; let oPr = new CT_XmlNode(function (reader, name) { if (CUniColor.prototype.isUnicolor(name)) { oColor = new CUniColor(); oColor.fromXml(reader, name); } return true; }); oPr.fromXml(reader); if (name === "clrFrom") { this.clrFrom = oColor; } else { this.clrTo = oColor; } } }; CClrChange.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:clrChange"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:clrFrom"); writer.WriteXmlAttributesEnd(); this.clrFrom.toXml(writer); writer.WriteXmlNodeEnd("a:clrFrom"); writer.WriteXmlNodeStart("a:clrTo"); writer.WriteXmlAttributesEnd(); this.clrTo.toXml(writer); writer.WriteXmlNodeEnd("a:clrTo"); writer.WriteXmlNodeEnd("a:clrChange"); }; function CClrRepl() { CBaseNoIdObject.call(this); this.color = new CUniColor(); } InitClass(CClrRepl, CBaseNoIdObject, 0); CClrRepl.prototype.Type = EFFECT_TYPE_CLRREPL; CClrRepl.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_CLRREPL); this.color.Write_ToBinary(w); }; CClrRepl.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); }; CClrRepl.prototype.createDuplicate = function () { var oCopy = new CClrRepl(); oCopy.color = this.color.createDuplicate(); return oCopy; }; CClrRepl.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CClrRepl.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:clrRepl"); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:clrRepl"); }; function CDuotone() { CBaseNoIdObject.call(this); this.colors = []; } InitClass(CDuotone, CBaseNoIdObject, 0); CDuotone.prototype.Type = EFFECT_TYPE_DUOTONE; CDuotone.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_DUOTONE); w.WriteLong(this.colors.length); for (var i = 0; i < this.colors.length; ++i) { this.colors[i].Write_ToBinary(w); } }; CDuotone.prototype.Read_FromBinary = function (r) { var count = r.GetLong(); for (var i = 0; i < count; ++i) { this.colors[i] = new CUniColor(); this.colors[i].Read_FromBinary(r); } }; CDuotone.prototype.createDuplicate = function () { var oCopy = new CDuotone(); for (var i = 0; i < this.colors.length; ++i) { oCopy.colors[i] = this.colors[i].createDuplicate(); } return oCopy; }; CDuotone.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { let oColor = new CUniColor(); oColor.fromXml(reader, name); this.colors.push(oColor); } }; CDuotone.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:duotone"); writer.WriteXmlAttributesEnd(); for (let nClr = 0; nClr < this.colors.length; ++nClr) { this.colors[nClr].toXml(writer); } writer.WriteXmlNodeEnd("a:duotone"); }; function CEffectElement() { CBaseNoIdObject.call(this); this.ref = null; } InitClass(CEffectElement, CBaseNoIdObject, 0); CEffectElement.prototype.Type = EFFECT_TYPE_ELEMENT; CEffectElement.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_ELEMENT); writeString(w, this.ref); }; CEffectElement.prototype.Read_FromBinary = function (r) { this.ref = readString(r); }; CEffectElement.prototype.createDuplicate = function () { var oCopy = new CEffectElement(); oCopy.ref = this.ref; return oCopy; }; CEffectElement.prototype.readAttrXml = function (name, reader) { switch (name) { case "ref": { this.ref = reader.GetValue(); break; } } }; CEffectElement.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:effect"); writer.WriteXmlNullableAttributeString("ref", this.ref); writer.WriteXmlAttributesEnd(true); }; function CFillEffect() { CBaseNoIdObject.call(this); this.fill = new CUniFill(); } InitClass(CFillEffect, CBaseNoIdObject, 0); CFillEffect.prototype.Type = EFFECT_TYPE_FILL; CFillEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_FILL); this.fill.Write_ToBinary(w); }; CFillEffect.prototype.Read_FromBinary = function (r) { this.fill.Read_FromBinary(r); }; CFillEffect.prototype.createDuplicate = function () { var oCopy = new CFillEffect(); oCopy.fill = this.fill.createDuplicate(); return oCopy; }; CFillEffect.prototype.readAttrXml = function (name, reader) { }; CFillEffect.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.fill.fromXml(reader, name); } }; CFillEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:fill"); writer.WriteXmlAttributesEnd(); this.fill.toXml(writer); writer.WriteXmlNodeEnd("a:fill"); }; function CFillOverlay() { CBaseNoIdObject.call(this); this.fill = new CUniFill(); this.blend = 0; } InitClass(CFillOverlay, CBaseNoIdObject, 0); CFillOverlay.prototype.Type = EFFECT_TYPE_FILLOVERLAY; CFillOverlay.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_FILLOVERLAY); this.fill.Write_ToBinary(w); w.WriteLong(this.blend); }; CFillOverlay.prototype.Read_FromBinary = function (r) { this.fill.Read_FromBinary(r); this.blend = r.GetLong(); }; CFillOverlay.prototype.createDuplicate = function () { var oCopy = new CFillOverlay(); oCopy.fill = this.fill.createDuplicate(); oCopy.blend = this.blend; return oCopy; }; CFillOverlay.prototype.readAttrXml = function (name, reader) { switch (name) { case "blend": { this.blend = reader.GetValueInt(); break; } } }; CFillOverlay.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.fill.fromXml(reader, name); } }; CFillOverlay.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:fillOverlay"); writer.WriteXmlNullableAttributeInt("blend", this.blend); writer.WriteXmlAttributesEnd(); this.fill.toXml(writer); writer.WriteXmlNodeEnd("a:fillOverlay"); }; function CGlow() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.rad = null; } InitClass(CGlow, CBaseNoIdObject, 0); CGlow.prototype.Type = EFFECT_TYPE_GLOW; CGlow.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_GLOW); this.color.Write_ToBinary(w); writeLong(w, this.rad); }; CGlow.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.rad = readLong(r); }; CGlow.prototype.createDuplicate = function () { var oCopy = new CGlow(); oCopy.color = this.color.createDuplicate(); oCopy.rad = this.rad; return oCopy; }; CGlow.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } } }; CGlow.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CGlow.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:glow"); writer.WriteXmlNullableAttributeInt("rad", this.rad); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:glow"); }; function CGrayscl() { CBaseNoIdObject.call(this); } InitClass(CGrayscl, CBaseNoIdObject, 0); CGrayscl.prototype.Type = EFFECT_TYPE_GRAYSCL; CGrayscl.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_GRAYSCL); }; CGrayscl.prototype.Read_FromBinary = function (r) { }; CGrayscl.prototype.createDuplicate = function () { var oCopy = new CGrayscl(); return oCopy; }; CGrayscl.prototype.toXml = function (writer) { writer.WriteXmlString("<a:grayscl/>"); }; function CHslEffect() { CBaseNoIdObject.call(this); this.h = null; this.s = null; this.l = null; } InitClass(CHslEffect, CBaseNoIdObject, 0); CHslEffect.prototype.Type = EFFECT_TYPE_HSL; CHslEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_HSL); writeLong(w, this.h); writeLong(w, this.s); writeLong(w, this.l); }; CHslEffect.prototype.Read_FromBinary = function (r) { this.h = readLong(r); this.s = readLong(r); this.l = readLong(r); }; CHslEffect.prototype.createDuplicate = function () { var oCopy = new CHslEffect(); oCopy.h = this.h; oCopy.s = this.s; oCopy.l = this.l; return oCopy; }; CHslEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "h": { this.h = reader.GetValueInt(); break; } case "s": { this.s = reader.GetValueInt(); break; } case "l": { this.l = reader.GetValueInt(); break; } } }; CHslEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:hsl"); writer.WriteXmlNullableAttributeInt("hue", this.hue); writer.WriteXmlNullableAttributeInt("sat", this.sat); writer.WriteXmlNullableAttributeInt("lum", this.lum); writer.WriteXmlAttributesEnd(true); }; function CInnerShdw() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.blurRad = null; this.dir = null; this.dist = null; } InitClass(CInnerShdw, CBaseNoIdObject, 0); CInnerShdw.prototype.Type = EFFECT_TYPE_INNERSHDW; CInnerShdw.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_INNERSHDW); this.color.Write_ToBinary(w); writeLong(w, this.blurRad); writeLong(w, this.dir); writeLong(w, this.dist); }; CInnerShdw.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.blurRad = readLong(r); this.dir = readLong(r); this.dist = readLong(r); }; CInnerShdw.prototype.createDuplicate = function () { var oCopy = new CInnerShdw(); oCopy.color = this.color.createDuplicate(); oCopy.blurRad = this.blurRad; oCopy.dir = this.dir; oCopy.dist = this.dist; return oCopy; }; CInnerShdw.prototype.readAttrXml = function (name, reader) { switch (name) { case "blurRad": { this.blurRad = reader.GetValueInt(); break; } case "dist": { this.dist = reader.GetValueInt(); break; } case "dir": { this.dir = reader.GetValueInt(); break; } } }; CInnerShdw.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CInnerShdw.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:innerShdw"); writer.WriteXmlNullableAttributeInt("blurRad", this.blurRad); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:innerShdw"); }; function CLumEffect() { CBaseNoIdObject.call(this); this.bright = null; this.contrast = null; } InitClass(CLumEffect, CBaseNoIdObject, 0); CLumEffect.prototype.Type = EFFECT_TYPE_LUM; CLumEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_LUM); writeLong(w, this.bright); writeLong(w, this.contrast); }; CLumEffect.prototype.Read_FromBinary = function (r) { this.bright = readLong(r); this.contrast = readLong(r); }; CLumEffect.prototype.createDuplicate = function () { var oCopy = new CLumEffect(); oCopy.bright = this.bright; oCopy.contrast = this.contrast; return oCopy; }; CLumEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "bright": { this.bright = reader.GetValueInt(); break; } case "contrast": { this.contrast = reader.GetValueInt(); break; } } }; CLumEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:lum"); writer.WriteXmlNullableAttributeInt("bright", this.bright); writer.WriteXmlNullableAttributeInt("contrast", this.contrast); writer.WriteXmlAttributesEnd(true); }; function COuterShdw() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.algn = null; this.blurRad = null; this.dir = null; this.dist = null; this.kx = null; this.ky = null; this.rotWithShape = null; this.sx = null; this.sy = null; } InitClass(COuterShdw, CBaseNoIdObject, 0); COuterShdw.prototype.Type = EFFECT_TYPE_OUTERSHDW; COuterShdw.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_OUTERSHDW); this.color.Write_ToBinary(w); writeLong(w, this.algn); writeLong(w, this.blurRad); writeLong(w, this.dir); writeLong(w, this.dist); writeLong(w, this.kx); writeLong(w, this.ky); writeBool(w, this.rotWithShape); writeLong(w, this.sx); writeLong(w, this.sy); }; COuterShdw.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.algn = readLong(r); this.blurRad = readLong(r); this.dir = readLong(r); this.dist = readLong(r); this.kx = readLong(r); this.ky = readLong(r); this.rotWithShape = readBool(r); this.sx = readLong(r); this.sy = readLong(r); }; COuterShdw.prototype.createDuplicate = function () { var oCopy = new COuterShdw(); oCopy.color = this.color.createDuplicate(); oCopy.algn = this.algn; oCopy.blurRad = this.blurRad; oCopy.dir = this.dir; oCopy.dist = this.dist; oCopy.kx = this.kx; oCopy.ky = this.ky; oCopy.rotWithShape = this.rotWithShape; oCopy.sx = this.sx; oCopy.sy = this.sy; return oCopy; }; COuterShdw.prototype.IsIdentical = function (other) { if (!other) { return false; } if (!this.color && other.color || this.color && !other.color || !this.color.IsIdentical(other.color)) { return false; } if (other.algn !== this.algn || other.blurRad !== this.blurRad || other.dir !== this.dir || other.dist !== this.dist || other.kx !== this.kx || other.ky !== this.ky || other.rotWithShape !== this.rotWithShape || other.sx !== this.sx || other.sy !== this.sy) { return false; } return true; }; COuterShdw.prototype.readAttrXml = function (name, reader) { switch (name) { case "algn": { this.algn = reader.GetValueInt(); break; } case "blurRad": { this.blurRad = reader.GetValueInt(); break; } case "dir": { this.dir = reader.GetValueInt(); break; } case "dist": { this.dist = reader.GetValueInt(); break; } case "kx": { this.kx = reader.GetValueInt(); break; } case "ky": { this.ky = reader.GetValueInt(); break; } case "rotWithShape": { this.rotWithShape = reader.GetValueBool(); break; } case "sx": { this.sx = reader.GetValueInt(); break; } case "sy": { this.sy = reader.GetValueInt(); break; } } }; COuterShdw.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; COuterShdw.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:outerShdw"); writer.WriteXmlNullableAttributeInt("blurRad", this.blurRad); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlNullableAttributeInt("kx", this.kx); writer.WriteXmlNullableAttributeInt("ky", this.ky); writer.WriteXmlNullableAttributeInt("sx", this.sx); writer.WriteXmlNullableAttributeInt("sy", this.sy); writer.WriteXmlNullableAttributeBool("rotWithShape", this.rotWithShape); writer.WriteXmlNullableAttributeInt("algn", this.algn); writer.WriteXmlAttributesEnd(); this.color.toXml(writer); writer.WriteXmlNodeEnd("a:outerShdw"); }; function asc_CShadowProperty() { COuterShdw.call(this); this.algn = 7; this.blurRad = 50800; this.color = new CUniColor(); this.color.color = new CPrstColor(); this.color.color.id = "black"; this.color.Mods = new CColorModifiers(); var oMod = new CColorMod(); oMod.name = "alpha"; oMod.val = 40000; this.color.Mods.Mods.push(oMod); this.dir = 2700000; this.dist = 38100; this.rotWithShape = false; } asc_CShadowProperty.prototype = Object.create(COuterShdw.prototype); asc_CShadowProperty.prototype.constructor = asc_CShadowProperty; window['Asc'] = window['Asc'] || {}; window['Asc']['asc_CShadowProperty'] = window['Asc'].asc_CShadowProperty = asc_CShadowProperty; function CPrstShdw() { CBaseNoIdObject.call(this); this.color = new CUniColor(); this.prst = null; this.dir = null; this.dist = null; } InitClass(CPrstShdw, CBaseNoIdObject, 0); CPrstShdw.prototype.Type = EFFECT_TYPE_PRSTSHDW; CPrstShdw.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_PRSTSHDW); this.color.Write_ToBinary(w); writeLong(w, this.prst); writeLong(w, this.dir); writeLong(w, this.dist); }; CPrstShdw.prototype.Read_FromBinary = function (r) { this.color.Read_FromBinary(r); this.prst = readLong(r); this.dir = readLong(r); this.dist = readLong(r); }; CPrstShdw.prototype.createDuplicate = function () { var oCopy = new CPrstShdw(); oCopy.color = this.color.createDuplicate(); oCopy.prst = this.prst; oCopy.dir = this.dir; oCopy.dist = this.dist; return oCopy; }; CPrstShdw.prototype.readAttrXml = function (name, reader) { switch (name) { case "prst": { let sVal = reader.GetValue(); this.prst = this.GetBYTECode(sVal); break; } case "dir": { this.dir = reader.GetValueInt(); break; } case "dist": { this.dist = reader.GetValueInt(); break; } } }; CPrstShdw.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color.fromXml(reader, name); } }; CPrstShdw.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:prstShdw"); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlNullableAttributeString("prst", this.SetBYTECode(prst)); writer.WriteXmlAttributesEnd(); if (this.color) { this.color.toXml(writer); } else { writer.WriteXmlNodeStart("a:scrgbClr"); writer.WriteXmlNullableAttributeInt("r", 0); writer.WriteXmlNullableAttributeInt("g", 0); writer.WriteXmlNullableAttributeInt("b", 0); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd("a:prstShdw"); }; CPrstShdw.prototype.GetBYTECode = function (sValue) { if ("shdw1" === sValue) return 0; if ("shdw2" === sValue) return 1; if ("shdw3" === sValue) return 2; if ("shdw4" === sValue) return 3; if ("shdw5" === sValue) return 4; if ("shdw6" === sValue) return 5; if ("shdw7" === sValue) return 6; if ("shdw8" === sValue) return 7; if ("shdw9" === sValue) return 8; if ("shdw10" === sValue) return 9; if ("shdw11" === sValue) return 10; if ("shdw12" === sValue) return 11; if ("shdw13" === sValue) return 12; if ("shdw14" === sValue) return 13; if ("shdw15" === sValue) return 14; if ("shdw16" === sValue) return 15; if ("shdw17" === sValue) return 16; if ("shdw18" === sValue) return 17; if ("shdw19" === sValue) return 18; if ("shdw20" === sValue) return 19; return 0; }; CPrstShdw.prototype.SetBYTECode = function (src) { switch (src) { case 0: return "shdw1"; break; case 1: return "shdw2"; break; case 2: return "shdw3"; break; case 3: return "shdw4"; break; case 4: return "shdw5"; break; case 5: return "shdw6"; break; case 6: return "shdw7"; break; case 7: return "shdw8"; break; case 8: return "shdw9"; break; case 9: return "shdw10"; break; case 10: return "shdw11"; break; case 11: return "shdw12"; break; case 12: return "shdw13"; break; case 13: return "shdw14"; break; case 14: return "shdw15"; break; case 15: return "shdw16"; break; case 16: return "shdw17"; break; case 17: return "shdw18"; break; case 18: return "shdw19"; break; case 19: return "shdw20"; break; } }; function CReflection() { CBaseNoIdObject.call(this); this.algn = null; this.blurRad = null; this.stA = null; this.endA = null; this.stPos = null; this.endPos = null; this.dir = null; this.fadeDir = null; this.dist = null; this.kx = null; this.ky = null; this.rotWithShape = null; this.sx = null; this.sy = null; } InitClass(CReflection, CBaseNoIdObject, 0); CReflection.prototype.Type = EFFECT_TYPE_REFLECTION; CReflection.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_REFLECTION); writeLong(w, this.algn); writeLong(w, this.blurRad); writeLong(w, this.stA); writeLong(w, this.endA); writeLong(w, this.stPos); writeLong(w, this.endPos); writeLong(w, this.dir); writeLong(w, this.fadeDir); writeLong(w, this.dist); writeLong(w, this.kx); writeLong(w, this.ky); writeBool(w, this.rotWithShape); writeLong(w, this.sx); writeLong(w, this.sy); }; CReflection.prototype.Read_FromBinary = function (r) { this.algn = readLong(r); this.blurRad = readLong(r); this.stA = readLong(r); this.endA = readLong(r); this.stPos = readLong(r); this.endPos = readLong(r); this.dir = readLong(r); this.fadeDir = readLong(r); this.dist = readLong(r); this.kx = readLong(r); this.ky = readLong(r); this.rotWithShape = readBool(r); this.sx = readLong(r); this.sy = readLong(r); }; CReflection.prototype.createDuplicate = function () { var oCopy = new CReflection(); oCopy.algn = this.algn; oCopy.blurRad = this.blurRad; oCopy.stA = this.stA; oCopy.endA = this.endA; oCopy.stPos = this.stPos; oCopy.endPos = this.endPos; oCopy.dir = this.dir; oCopy.fadeDir = this.fadeDir; oCopy.dist = this.dist; oCopy.kx = this.kx; oCopy.ky = this.ky; oCopy.rotWithShape = this.rotWithShape; oCopy.sx = this.sx; oCopy.sy = this.sy; return oCopy; }; CReflection.prototype.readAttrXml = function (name, reader) { switch (name) { case "blurRad": this.blurRad = reader.GetValueInt(); break; case "dist": this.dist = reader.GetValueInt(); break; case "dir": this.dir = reader.GetValueInt(); break; case "kx": this.kx = reader.GetValueInt(); break; case "ky": this.ky = reader.GetValueInt(); break; case "sx": this.sx = reader.GetValueInt(); break; case "sy": this.sy = reader.GetValueInt(); break; case "rotWithShape": this.rotWithShape = reader.GetValueBool(); break; case "fadeDir": this.fadeDir = reader.GetValueInt(); break; case "algn": this.algn = reader.GetValueInt(); break; case "stA": this.stA = reader.GetValueInt(); break; case "stPos": this.stPos = reader.GetValueInt(); break; case "endA": this.endA = reader.GetValueInt(); break; case "endPos": this.endPos = reader.GetValueInt(); break; } }; CReflection.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:reflection"); writer.WriteXmlNullableAttributeInt("blurRad", this.blurRad); writer.WriteXmlNullableAttributeInt("dist", this.dist); writer.WriteXmlNullableAttributeInt("dir", this.dir); writer.WriteXmlNullableAttributeInt("kx", this.kx); writer.WriteXmlNullableAttributeInt("ky", this.ky); writer.WriteXmlNullableAttributeInt("sx", this.sx); writer.WriteXmlNullableAttributeInt("sy", this.sy); writer.WriteXmlNullableAttributeBool("rotWithShape", this.rotWithShape); writer.WriteXmlNullableAttributeInt("fadeDir", this.fadeDir); writer.WriteXmlNullableAttributeInt("algn", this.algn); writer.WriteXmlNullableAttributeInt("stA", this.stA); writer.WriteXmlNullableAttributeInt("stPos", this.stPos); writer.WriteXmlNullableAttributeInt("endA", this.endA); writer.WriteXmlNullableAttributeInt("endPos", this.endPos); writer.WriteXmlAttributesEnd(true); }; function CRelOff() { CBaseNoIdObject.call(this); this.tx = null; this.ty = null; } InitClass(CRelOff, CBaseNoIdObject, 0); CRelOff.prototype.Type = EFFECT_TYPE_RELOFF; CRelOff.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_RELOFF); writeLong(w, this.tx); writeLong(w, this.ty); }; CRelOff.prototype.Read_FromBinary = function (r) { this.tx = readLong(r); this.ty = readLong(r); }; CRelOff.prototype.createDuplicate = function () { var oCopy = new CRelOff(); oCopy.tx = this.tx; oCopy.ty = this.ty; return oCopy; }; CRelOff.prototype.readAttrXml = function (name, reader) { switch (name) { case "tx": { this.tx = reader.GetValueInt(); break; } case "ty": { this.ty = reader.GetValueInt(); break; } } }; CRelOff.prototype.readChildXml = function (name, reader) { switch (name) { case "tx": { this.tx = reader.GetValueInt() break; } case "ty": { this.ty = reader.GetValueInt() break; } } }; CRelOff.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:relOff"); writer.WriteXmlNullableAttributeInt("tx", this.tx); writer.WriteXmlNullableAttributeInt("ty", this.ty); writer.WriteXmlAttributesEnd(true); }; function CSoftEdge() { CBaseNoIdObject.call(this); this.rad = null; } InitClass(CSoftEdge, CBaseNoIdObject, 0); CSoftEdge.prototype.Type = EFFECT_TYPE_SOFTEDGE; CSoftEdge.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_SOFTEDGE); writeLong(w, this.rad); }; CSoftEdge.prototype.Read_FromBinary = function (r) { this.rad = readLong(r); }; CSoftEdge.prototype.createDuplicate = function () { var oCopy = new CSoftEdge(); oCopy.rad = this.rad; return oCopy; }; CSoftEdge.prototype.readAttrXml = function (name, reader) { switch (name) { case "rad": { this.rad = reader.GetValueInt(); break; } } }; CSoftEdge.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:softEdge"); writer.WriteXmlNullableAttributeString("rad", this.rad); writer.WriteXmlAttributesEnd(true); }; function CTintEffect() { CBaseNoIdObject.call(this); this.amt = null; this.hue = null; } InitClass(CTintEffect, CBaseNoIdObject, 0); CTintEffect.prototype.Type = EFFECT_TYPE_TINTEFFECT; CTintEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_TINTEFFECT); writeLong(w, this.amt); writeLong(w, this.hue); }; CTintEffect.prototype.Read_FromBinary = function (r) { this.amt = readLong(r); this.hue = readLong(r); }; CTintEffect.prototype.createDuplicate = function () { var oCopy = new CTintEffect(); oCopy.amt = this.amt; oCopy.hue = this.hue; return oCopy; }; CTintEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "amt": { this.amt = reader.GetValueInt(); break; } case "hue": { this.hue = reader.GetValueInt(); break; } } }; CTintEffect.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:tint"); writer.WriteXmlNullableAttributeString("hue", this.hue); writer.WriteXmlNullableAttributeString("amt", this.amt); writer.WriteXmlAttributesEnd(true); }; function CXfrmEffect() { CBaseNoIdObject.call(this); this.kx = null; this.ky = null; this.sx = null; this.sy = null; this.tx = null; this.ty = null; } InitClass(CXfrmEffect, CBaseNoIdObject, 0); CXfrmEffect.prototype.Type = EFFECT_TYPE_XFRM; CXfrmEffect.prototype.Write_ToBinary = function (w) { w.WriteLong(EFFECT_TYPE_XFRM); writeLong(w, this.kx); writeLong(w, this.ky); writeLong(w, this.sx); writeLong(w, this.sy); writeLong(w, this.tx); writeLong(w, this.ty); }; CXfrmEffect.prototype.Read_FromBinary = function (r) { this.kx = readLong(r); this.ky = readLong(r); this.sx = readLong(r); this.sy = readLong(r); this.tx = readLong(r); this.ty = readLong(r); }; CXfrmEffect.prototype.createDuplicate = function () { var oCopy = new CXfrmEffect(); oCopy.kx = this.kx; oCopy.ky = this.ky; oCopy.sx = this.sx; oCopy.sy = this.sy; oCopy.tx = this.tx; oCopy.ty = this.ty; return oCopy; }; CXfrmEffect.prototype.readAttrXml = function (name, reader) { switch (name) { case "kx": { this.kx = reader.GetValueInt(); break; } case "ky": { this.ky = reader.GetValueInt(); break; } case "sx": { this.sx = reader.GetValueInt(); break; } case "sy": { this.sy = reader.GetValueInt(); break; } case "tx": { this.tx = reader.GetValueInt(); break; } case "ty": { this.kx = reader.GetValueInt(); break; } } }; CXfrmEffect.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNodeStart("a:xfrm"); writer.WriteXmlNullableAttributeString("kx", kx); writer.WriteXmlNullableAttributeString("ky", ky); writer.WriteXmlNullableAttributeString("sx", sx); writer.WriteXmlNullableAttributeString("sy", sy); writer.WriteXmlNullableAttributeString("tx", tx); writer.WriteXmlNullableAttributeString("ty", ty); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:xfrm"); }; //----------------- function CSolidFill() { CBaseNoIdObject.call(this); this.type = c_oAscFill.FILL_TYPE_SOLID; this.color = null; } InitClass(CSolidFill, CBaseNoIdObject, 0); CSolidFill.prototype.check = function (theme, colorMap) { if (this.color) { this.color.check(theme, colorMap); } }; CSolidFill.prototype.saveSourceFormatting = function () { var _ret = new CSolidFill(); if (this.color) { _ret.color = this.color.saveSourceFormatting(); } return _ret; }; CSolidFill.prototype.setColor = function (color) { this.color = color; }; CSolidFill.prototype.Write_ToBinary = function (w) { if (this.color) { w.WriteBool(true); this.color.Write_ToBinary(w); } else { w.WriteBool(false); } }; CSolidFill.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.color = new CUniColor(); this.color.Read_FromBinary(r); } }; CSolidFill.prototype.checkWordMods = function () { return this.color && this.color.checkWordMods(); }; CSolidFill.prototype.convertToPPTXMods = function () { this.color && this.color.convertToPPTXMods(); }; CSolidFill.prototype.canConvertPPTXModsToWord = function () { return this.color && this.color.canConvertPPTXModsToWord(); }; CSolidFill.prototype.convertToWordMods = function () { this.color && this.color.convertToWordMods(); }; CSolidFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_SOLID) { return false; } if (this.color) { return this.color.IsIdentical(fill.color); } return (fill.color === null); }; CSolidFill.prototype.createDuplicate = function () { var duplicate = new CSolidFill(); if (this.color) { duplicate.color = this.color.createDuplicate(); } return duplicate; }; CSolidFill.prototype.compare = function (fill) { if (fill == null || fill.type !== c_oAscFill.FILL_TYPE_SOLID) { return null; } if (this.color && fill.color) { var _ret = new CSolidFill(); _ret.color = this.color.compare(fill.color); return _ret; } return null; }; CSolidFill.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color = new CUniColor(); this.color.fromXml(reader, name); } }; CSolidFill.prototype.toXml = function (writer, sNamespace) { let strName; let sNamespace_ = sNamespace || "a" if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) strName = ("w14:solidFill"); else strName = ("" === sNamespace_) ? ("solidFill") : (sNamespace_ + (":solidFill")); writer.WriteXmlNodeStart(strName); writer.WriteXmlAttributesEnd(); if (this.color) this.color.toXml(writer); writer.WriteXmlNodeEnd(strName); }; function CGs() { CBaseNoIdObject.call(this); this.color = null; this.pos = 0; } InitClass(CGs, CBaseNoIdObject, 0); CGs.prototype.setColor = function (color) { this.color = color; }; CGs.prototype.setPos = function (pos) { this.pos = pos; }; CGs.prototype.saveSourceFormatting = function () { var _ret = new CGs(); _ret.pos = this.pos; if (this.color) { _ret.color = this.color.saveSourceFormatting(); } return _ret; }; CGs.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.color)); if (isRealObject(this.color)) { this.color.Write_ToBinary(w); } writeLong(w, this.pos); }; CGs.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.color = new CUniColor(); this.color.Read_FromBinary(r); } else { this.color = null; } this.pos = readLong(r); }; CGs.prototype.IsIdentical = function (fill) { if (!fill) return false; if (this.pos !== fill.pos) return false; if (!this.color && fill.color || this.color && !fill.color || (this.color && fill.color && !this.color.IsIdentical(fill.color))) return false; return true; }; CGs.prototype.createDuplicate = function () { var duplicate = new CGs(); duplicate.pos = this.pos; if (this.color) { duplicate.color = this.color.createDuplicate(); } return duplicate; }; CGs.prototype.compare = function (gs) { if (gs.pos !== this.pos) { return null; } var compare_unicolor = this.color.compare(gs.color); if (!isRealObject(compare_unicolor)) { return null; } var ret = new CGs(); ret.color = compare_unicolor; ret.pos = gs.pos === this.pos ? this.pos : 0; return ret; }; CGs.prototype.readAttrXml = function (name, reader) { switch (name) { case "pos": { this.pos = getPercentageValue(reader.GetValue()) * 1000; break; } } }; CGs.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.color = new CUniColor(); this.color.fromXml(reader, name); } }; CGs.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + ("gs")); writer.WriteXmlNullableAttributeInt(sAttrNamespace + ("pos"), this.pos); writer.WriteXmlAttributesEnd(); if (this.color) { this.color.toXml(writer); } writer.WriteXmlNodeEnd(sNodeNamespace + ("gs")); }; function GradLin() { CBaseNoIdObject.call(this); this.angle = 5400000; this.scale = true; } InitClass(GradLin, CBaseNoIdObject, 0); GradLin.prototype.setAngle = function (angle) { this.angle = angle; }; GradLin.prototype.setScale = function (scale) { this.scale = scale; }; GradLin.prototype.Write_ToBinary = function (w) { writeLong(w, this.angle); writeBool(w, this.scale); }; GradLin.prototype.Read_FromBinary = function (r) { this.angle = readLong(r); this.scale = readBool(r); }; GradLin.prototype.IsIdentical = function (lin) { if (this.angle != lin.angle) return false; if (this.scale != lin.scale) return false; return true; }; GradLin.prototype.createDuplicate = function () { var duplicate = new GradLin(); duplicate.angle = this.angle; duplicate.scale = this.scale; return duplicate; }; GradLin.prototype.compare = function (lin) { return null; }; GradLin.prototype.readAttrXml = function (name, reader) { switch (name) { case "ang": { this.angle = reader.GetValueInt(); break; } case "scaled": { this.scale = reader.GetValueBool(); break; } } }; GradLin.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = ("a:"); writer.WriteXmlNodeStart(sNodeNamespace + "lin"); writer.WriteXmlNullableAttributeInt(sAttrNamespace + "ang", this.angle); writer.WriteXmlNullableAttributeBool(sAttrNamespace + "scaled", this.scale); writer.WriteXmlAttributesEnd(true); }; function GradPath() { CBaseNoIdObject.call(this); this.path = 0; this.rect = null; } InitClass(GradPath, CBaseNoIdObject, 0); GradPath.prototype.setPath = function (path) { this.path = path; }; GradPath.prototype.setRect = function (rect) { this.rect = rect; }; GradPath.prototype.Write_ToBinary = function (w) { writeLong(w, this.path); w.WriteBool(isRealObject(this.rect)); if (isRealObject(this.rect)) { this.rect.Write_ToBinary(w); } }; GradPath.prototype.Read_FromBinary = function (r) { this.path = readLong(r); if (r.GetBool()) { this.rect = new CSrcRect(); this.rect.Read_FromBinary(r); } }; GradPath.prototype.IsIdentical = function (path) { if (this.path !== path.path) return false; return true; }; GradPath.prototype.createDuplicate = function () { var duplicate = new GradPath(); duplicate.path = this.path; return duplicate; }; GradPath.prototype.compare = function (path) { return null; }; GradPath.prototype.readAttrXml = function (name, reader) { switch (name) { case "path": { break; } } }; GradPath.prototype.readChildXml = function (name, reader) { switch (name) { case "fillToRect": { this.rect = new CSrcRect(); this.rect.fromXml(reader); break; } } }; GradPath.prototype.toXml = function (writer) { let sNodeNamespace; let sAttrNamespace; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = ("w14:"); sAttrNamespace = sNodeNamespace; } else sNodeNamespace = "a:"; writer.WriteXmlNodeStart(sNodeNamespace + "path"); writer.WriteXmlNullableAttributeString("path", "circle"); writer.WriteXmlAttributesEnd(); //writer.WriteXmlNullable(rect); if (this.rect) { this.rect.toXml(writer, "a:fillToRect"); } writer.WriteXmlNodeEnd(sNodeNamespace + ("path")); }; function CGradFill() { CBaseFill.call(this); // ะฟะพะบะฐ ะฟั€ะพัั‚ะพ front color this.colors = []; this.lin = null; this.path = null; this.rotateWithShape = null; } InitClass(CGradFill, CBaseFill, 0); CGradFill.prototype.type = c_oAscFill.FILL_TYPE_GRAD; CGradFill.prototype.saveSourceFormatting = function () { var _ret = new CGradFill(); if (this.lin) { _ret.lin = this.lin.createDuplicate(); } if (this.path) { _ret.path = this.path.createDuplicate(); } for (var i = 0; i < this.colors.length; ++i) { _ret.colors.push(this.colors[i].saveSourceFormatting()); } return _ret; }; CGradFill.prototype.check = function (theme, colorMap) { for (var i = 0; i < this.colors.length; ++i) { if (this.colors[i].color) { this.colors[i].color.check(theme, colorMap); } } }; CGradFill.prototype.checkWordMods = function () { for (var i = 0; i < this.colors.length; ++i) { if (this.colors[i] && this.colors[i].color && this.colors[i].color.checkWordMods()) { return true; } } return false; }; CGradFill.prototype.convertToPPTXMods = function () { for (var i = 0; i < this.colors.length; ++i) { this.colors[i] && this.colors[i].color && this.colors[i].color.convertToPPTXMods(); } }; CGradFill.prototype.canConvertPPTXModsToWord = function () { for (var i = 0; i < this.colors.length; ++i) { if (this.colors[i] && this.colors[i].color && this.colors[i].color.canConvertPPTXModsToWord()) { return true; } } return false; }; CGradFill.prototype.convertToWordMods = function () { for (var i = 0; i < this.colors.length; ++i) { this.colors[i] && this.colors[i].color && this.colors[i].color.convertToWordMods(); } }; CGradFill.prototype.addColor = function (color) { this.colors.push(color); }; CGradFill.prototype.setLin = function (lin) { this.lin = lin; }; CGradFill.prototype.setPath = function (path) { this.path = path; }; CGradFill.prototype.Write_ToBinary = function (w) { w.WriteLong(this.colors.length); for (var i = 0; i < this.colors.length; ++i) { this.colors[i].Write_ToBinary(w); } w.WriteBool(isRealObject(this.lin)); if (isRealObject(this.lin)) { this.lin.Write_ToBinary(w); } w.WriteBool(isRealObject(this.path)); if (isRealObject(this.path)) { this.path.Write_ToBinary(w); } writeBool(w, this.rotateWithShape); }; CGradFill.prototype.Read_FromBinary = function (r) { var len = r.GetLong(); for (var i = 0; i < len; ++i) { this.colors[i] = new CGs(); this.colors[i].Read_FromBinary(r); } if (r.GetBool()) { this.lin = new GradLin(); this.lin.Read_FromBinary(r); } else { this.lin = null; } if (r.GetBool()) { this.path = new GradPath(); this.path.Read_FromBinary(r); } else { this.path = null; } this.rotateWithShape = readBool(r); }; CGradFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_GRAD) { return false; } if (fill.colors.length !== this.colors.length) { return false; } for (var i = 0; i < this.colors.length; ++i) { if (!this.colors[i].IsIdentical(fill.colors[i])) { return false; } } if (!this.path && fill.path || this.path && !fill.path || (this.path && fill.path && !this.path.IsIdentical(fill.path))) return false; if (!this.lin && fill.lin || !fill.lin && this.lin || (this.lin && fill.lin && !this.lin.IsIdentical(fill.lin))) return false; if(this.rotateWithShape !== fill.rotateWithShape) { return false; } return true; }; CGradFill.prototype.createDuplicate = function () { var duplicate = new CGradFill(); for (var i = 0; i < this.colors.length; ++i) { duplicate.colors[i] = this.colors[i].createDuplicate(); } if (this.lin) duplicate.lin = this.lin.createDuplicate(); if (this.path) duplicate.path = this.path.createDuplicate(); if (this.rotateWithShape != null) duplicate.rotateWithShape = this.rotateWithShape; return duplicate; }; CGradFill.prototype.compare = function (fill) { if (fill == null || fill.type !== c_oAscFill.FILL_TYPE_GRAD) { return null; } var _ret = new CGradFill(); if (this.lin == null || fill.lin == null) _ret.lin = null; else { _ret.lin = new GradLin(); _ret.lin.angle = this.lin && this.lin.angle === fill.lin.angle ? fill.lin.angle : 5400000; _ret.lin.scale = this.lin && this.lin.scale === fill.lin.scale ? fill.lin.scale : true; } if (this.path == null || fill.path == null) { _ret.path = null; } else { _ret.path = new GradPath(); } if (this.colors.length === fill.colors.length) { for (var i = 0; i < this.colors.length; ++i) { var compare_unicolor = this.colors[i].compare(fill.colors[i]); if (!isRealObject(compare_unicolor)) { return null; } _ret.colors[i] = compare_unicolor; } } if(this.rotateWithShape === fill.rotateWithShape) { _ret.rotateWithShape = this.rotateWithShape; } return _ret; }; CGradFill.prototype.readAttrXml = function (name, reader) { switch (name) { case "flip": { break; } case "rotWithShape": { this.rotateWithShape = reader.GetValueBool(); break; } } }; CGradFill.prototype.readChildXml = function (name, reader) { let oGradFill = this; switch (name) { case "gsLst": { let oPr = new CT_XmlNode(function (reader, name) { if (name === "gs") { let oGs = new CGs(); oGs.fromXml(reader); oGradFill.colors.push(oGs); return oGs; } }); oPr.fromXml(reader); break; } case "lin": { let oLin = new GradLin(); oLin.fromXml(reader); this.lin = oLin; break; } case "path": { this.path = new GradPath(); this.path.fromXml(reader); break; } case "tileRect": { break; } } }; CGradFill.prototype.fromXml = function (reader, bSkipFirstNode) { CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); this.colors.sort(function(a,b){return a.pos- b.pos;}); } CGradFill.prototype.toXml = function (writer, sNamespace) { let sAttrNamespace = ""; let strName = ""; let sNamespace_ = sNamespace || "a"; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sAttrNamespace = ("w14:"); strName = ("w14:gradFill"); } else { strName = sNamespace_.length === 0 ? ("gradFill") : (sNamespace_ + (":gradFill")); } writer.WriteXmlNodeStart(strName); // writer.WriteXmlNullableAttributeString(sAttrNamespace + ("flip"), this.flip); writer.WriteXmlNullableAttributeBool(sAttrNamespace + ("rotWithShape"), this.rotWithShape); writer.WriteXmlAttributesEnd(); let sListName; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) sListName = "w14:gsLst"; else sListName = "a:gsLst"; writer.WriteXmlNodeStart(sListName); writer.WriteXmlAttributesEnd(); for (let nGs = 0; nGs < this.colors.length; ++nGs) { this.colors[nGs].toXml(writer); } writer.WriteXmlNodeEnd(sListName); if (this.path) { this.path.toXml(writer); } if (this.lin) { this.lin.toXml(writer); } //writer.WriteXmlNullable(tileRect); writer.WriteXmlNodeEnd(strName); }; CGradFill.prototype.getColorsCount = function() { return this.colors.length; }; function CPattFill() { CBaseFill.call(this); this.ftype = 0; this.fgClr = null;//new CUniColor(); this.bgClr = null;//new CUniColor(); } InitClass(CPattFill, CBaseFill, 0); CPattFill.prototype.type = c_oAscFill.FILL_TYPE_PATT; CPattFill.prototype.check = function (theme, colorMap) { if (this.fgClr) this.fgClr.check(theme, colorMap); if (this.bgClr) this.bgClr.check(theme, colorMap); }; CPattFill.prototype.checkWordMods = function () { if (this.fgClr && this.fgClr.checkWordMods()) { return true; } return this.bgClr && this.bgClr.checkWordMods(); }; CPattFill.prototype.saveSourceFormatting = function () { var _ret = new CPattFill(); if (this.fgClr) { _ret.fgClr = this.fgClr.saveSourceFormatting(); } if (this.bgClr) { _ret.bgClr = this.bgClr.saveSourceFormatting(); } _ret.ftype = this.ftype; return _ret; }; CPattFill.prototype.convertToPPTXMods = function () { this.fgClr && this.fgClr.convertToPPTXMods(); this.bgClr && this.bgClr.convertToPPTXMods(); }; CPattFill.prototype.canConvertPPTXModsToWord = function () { if (this.fgClr && this.fgClr.canConvertPPTXModsToWord()) { return true; } return this.bgClr && this.bgClr.canConvertPPTXModsToWord(); }; CPattFill.prototype.convertToWordMods = function () { this.fgClr && this.fgClr.convertToWordMods(); this.bgClr && this.bgClr.convertToWordMods(); }; CPattFill.prototype.setFType = function (fType) { this.ftype = fType; }; CPattFill.prototype.setFgColor = function (fgClr) { this.fgClr = fgClr; }; CPattFill.prototype.setBgColor = function (bgClr) { this.bgClr = bgClr; }; CPattFill.prototype.Write_ToBinary = function (w) { writeLong(w, this.ftype); w.WriteBool(isRealObject(this.fgClr)); if (isRealObject(this.fgClr)) { this.fgClr.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bgClr)); if (isRealObject(this.bgClr)) { this.bgClr.Write_ToBinary(w); } }; CPattFill.prototype.Read_FromBinary = function (r) { this.ftype = readLong(r); if (r.GetBool()) { this.fgClr = new CUniColor(); this.fgClr.Read_FromBinary(r); } if (r.GetBool()) { this.bgClr = new CUniColor(); this.bgClr.Read_FromBinary(r); } }; CPattFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } if (fill.type !== c_oAscFill.FILL_TYPE_PATT && this.ftype !== fill.ftype) { return false; } return this.fgClr.IsIdentical(fill.fgClr) && this.bgClr.IsIdentical(fill.bgClr) && this.ftype === fill.ftype; }; CPattFill.prototype.createDuplicate = function () { var duplicate = new CPattFill(); duplicate.ftype = this.ftype; if (this.fgClr) { duplicate.fgClr = this.fgClr.createDuplicate(); } if (this.bgClr) { duplicate.bgClr = this.bgClr.createDuplicate(); } return duplicate; }; CPattFill.prototype.compare = function (fill) { if (fill == null) { return null; } if (fill.type !== c_oAscFill.FILL_TYPE_PATT) { return null; } var _ret = new CPattFill(); if (fill.ftype == this.ftype) { _ret.ftype = this.ftype; } if (this.fgClr) { _ret.fgClr = this.fgClr.compare(fill.fgClr); } else { _ret.fgClr = null; } if (this.bgClr) { _ret.bgClr = this.bgClr.compare(fill.bgClr); } else { _ret.bgClr = null; } if (!_ret.bgClr && !_ret.fgClr) { return null; } return _ret; }; CPattFill.prototype.readAttrXml = function (name, reader) { switch (name) { case "prst": { let sVal = reader.GetValue(); switch (sVal) { case "cross": this.ftype = AscCommon.global_hatch_offsets.cross; break; case "dashDnDiag": this.ftype = AscCommon.global_hatch_offsets.dashDnDiag; break; case "dashHorz": this.ftype = AscCommon.global_hatch_offsets.dashHorz; break; case "dashUpDiag": this.ftype = AscCommon.global_hatch_offsets.dashUpDiag; break; case "dashVert": this.ftype = AscCommon.global_hatch_offsets.dashVert; break; case "diagBrick": this.ftype = AscCommon.global_hatch_offsets.diagBrick; break; case "diagCross": this.ftype = AscCommon.global_hatch_offsets.diagCross; break; case "divot": this.ftype = AscCommon.global_hatch_offsets.divot; break; case "dkDnDiag": this.ftype = AscCommon.global_hatch_offsets.dkDnDiag; break; case "dkHorz": this.ftype = AscCommon.global_hatch_offsets.dkHorz; break; case "dkUpDiag": this.ftype = AscCommon.global_hatch_offsets.dkUpDiag; break; case "dkVert": this.ftype = AscCommon.global_hatch_offsets.dkVert; break; case "dnDiag": this.ftype = AscCommon.global_hatch_offsets.dnDiag; break; case "dotDmnd": this.ftype = AscCommon.global_hatch_offsets.dotDmnd; break; case "dotGrid": this.ftype = AscCommon.global_hatch_offsets.dotGrid; break; case "horz": this.ftype = AscCommon.global_hatch_offsets.horz; break; case "horzBrick": this.ftype = AscCommon.global_hatch_offsets.horzBrick; break; case "lgCheck": this.ftype = AscCommon.global_hatch_offsets.lgCheck; break; case "lgConfetti": this.ftype = AscCommon.global_hatch_offsets.lgConfetti; break; case "lgGrid": this.ftype = AscCommon.global_hatch_offsets.lgGrid; break; case "ltDnDiag": this.ftype = AscCommon.global_hatch_offsets.ltDnDiag; break; case "ltHorz": this.ftype = AscCommon.global_hatch_offsets.ltHorz; break; case "ltUpDiag": this.ftype = AscCommon.global_hatch_offsets.ltUpDiag; break; case "ltVert": this.ftype = AscCommon.global_hatch_offsets.ltVert; break; case "narHorz": this.ftype = AscCommon.global_hatch_offsets.narHorz; break; case "narVert": this.ftype = AscCommon.global_hatch_offsets.narVert; break; case "openDmnd": this.ftype = AscCommon.global_hatch_offsets.openDmnd; break; case "pct10": this.ftype = AscCommon.global_hatch_offsets.pct10; break; case "pct20": this.ftype = AscCommon.global_hatch_offsets.pct20; break; case "pct25": this.ftype = AscCommon.global_hatch_offsets.pct25; break; case "pct30": this.ftype = AscCommon.global_hatch_offsets.pct30; break; case "pct40": this.ftype = AscCommon.global_hatch_offsets.pct40; break; case "pct5": this.ftype = AscCommon.global_hatch_offsets.pct5; break; case "pct50": this.ftype = AscCommon.global_hatch_offsets.pct50; break; case "pct60": this.ftype = AscCommon.global_hatch_offsets.pct60; break; case "pct70": this.ftype = AscCommon.global_hatch_offsets.pct70; break; case "pct75": this.ftype = AscCommon.global_hatch_offsets.pct75; break; case "pct80": this.ftype = AscCommon.global_hatch_offsets.pct80; break; case "pct90": this.ftype = AscCommon.global_hatch_offsets.pct90; break; case "plaid": this.ftype = AscCommon.global_hatch_offsets.plaid; break; case "shingle": this.ftype = AscCommon.global_hatch_offsets.shingle; break; case "smCheck": this.ftype = AscCommon.global_hatch_offsets.smCheck; break; case "smConfetti": this.ftype = AscCommon.global_hatch_offsets.smConfetti; break; case "smGrid": this.ftype = AscCommon.global_hatch_offsets.smGrid; break; case "solidDmnd": this.ftype = AscCommon.global_hatch_offsets.solidDmnd; break; case "sphere": this.ftype = AscCommon.global_hatch_offsets.sphere; break; case "trellis": this.ftype = AscCommon.global_hatch_offsets.trellis; break; case "upDiag": this.ftype = AscCommon.global_hatch_offsets.upDiag; break; case "vert": this.ftype = AscCommon.global_hatch_offsets.vert; break; case "wave": this.ftype = AscCommon.global_hatch_offsets.wave; break; case "wdDnDiag": this.ftype = AscCommon.global_hatch_offsets.wdDnDiag; break; case "wdUpDiag": this.ftype = AscCommon.global_hatch_offsets.wdUpDiag; break; case "weave": this.ftype = AscCommon.global_hatch_offsets.weave; break; case "zigZag": this.ftype = AscCommon.global_hatch_offsets.zigZag; break; } break; } } }; CPattFill.prototype.readChildXml = function (name, reader) { let oPatt = this; switch (name) { case "bgClr": { let oClr = new CT_XmlNode(function (reader, name) { if (CUniColor.prototype.isUnicolor(name)) { oPatt.bgClr = new CUniColor(); oPatt.bgClr.fromXml(reader, name); return oPatt.bgClr; } }); oClr.fromXml(reader); break; } case "fgClr": { let oClr = new CT_XmlNode(function (reader, name) { if (CUniColor.prototype.isUnicolor(name)) { oPatt.fgClr = new CUniColor(); oPatt.fgClr.fromXml(reader, name); return oPatt.fgClr; } }); oClr.fromXml(reader); break; } } }; CPattFill.prototype.toXml = function (writer, sNamespace) { let sNamespace_ = sNamespace || "a"; let strName = ("" === sNamespace_) ? "pattFill" : (sNamespace_ + ":pattFill"); writer.WriteXmlNodeStart(strName); writer.WriteXmlNullableAttributeString("prst", this.prst); writer.WriteXmlAttributesEnd(); if (this.fgClr) { writer.WriteXmlNodeStart("a:fgClr"); writer.WriteXmlAttributesEnd(); this.fgClr.toXml(writer); writer.WriteXmlNodeEnd("a:fgClr"); } if (this.bgClr) { writer.WriteXmlNodeStart("a:bgClr"); writer.WriteXmlAttributesEnd(); this.bgClr.toXml(writer); writer.WriteXmlNodeEnd("a:bgClr"); } writer.WriteXmlNodeEnd(strName); }; function CNoFill() { CBaseFill.call(this); } InitClass(CNoFill, CBaseFill, 0); CNoFill.prototype.type = c_oAscFill.FILL_TYPE_NOFILL; CNoFill.prototype.check = function () { }; CNoFill.prototype.saveSourceFormatting = function () { return this.createDuplicate(); }; CNoFill.prototype.Write_ToBinary = function (w) { }; CNoFill.prototype.Read_FromBinary = function (r) { }; CNoFill.prototype.checkWordMods = function () { return false; }; CNoFill.prototype.convertToPPTXMods = function () { }; CNoFill.prototype.canConvertPPTXModsToWord = function () { return false; }; CNoFill.prototype.convertToWordMods = function () { }; CNoFill.prototype.createDuplicate = function () { return new CNoFill(); }; CNoFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } return fill.type === c_oAscFill.FILL_TYPE_NOFILL; }; CNoFill.prototype.compare = function (nofill) { if (nofill == null) { return null; } if (nofill.type === this.type) { return new CNoFill(); } return null; }; CNoFill.prototype.readAttrXml = function (name, reader) { }; CNoFill.prototype.readChildXml = function (name, reader) { }; CNoFill.prototype.toXml = function (writer) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) writer.WriteXmlString("<w14:noFill/>"); else writer.WriteXmlString("<a:noFill/>"); }; function CGrpFill() { CBaseFill.call(this); } InitClass(CGrpFill, CBaseFill, 0); CGrpFill.prototype.type = c_oAscFill.FILL_TYPE_GRP; CGrpFill.prototype.check = function () { }; CGrpFill.prototype.getObjectType = function () { return AscDFH.historyitem_type_GrpFill; }; CGrpFill.prototype.Write_ToBinary = function (w) { }; CGrpFill.prototype.Read_FromBinary = function (r) { }; CGrpFill.prototype.checkWordMods = function () { return false; }; CGrpFill.prototype.convertToPPTXMods = function () { }; CGrpFill.prototype.canConvertPPTXModsToWord = function () { return false; }; CGrpFill.prototype.convertToWordMods = function () { }; CGrpFill.prototype.createDuplicate = function () { return new CGrpFill(); }; CGrpFill.prototype.IsIdentical = function (fill) { if (fill == null) { return false; } return fill.type === c_oAscFill.FILL_TYPE_GRP; }; CGrpFill.prototype.compare = function (grpfill) { if (grpfill == null) { return null; } if (grpfill.type === this.type) { return new CGrpFill(); } return null; }; CGrpFill.prototype.toXml = function (writer) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) writer.WriteXmlString("<w14:grpFill/>"); else writer.WriteXmlString("<a:grpFill/>"); }; function FormatRGBAColor() { this.R = 0; this.G = 0; this.B = 0; this.A = 255; } function CUniFill() { CBaseNoIdObject.call(this); this.fill = null; this.transparent = null; } InitClass(CUniFill, CBaseNoIdObject, 0); CUniFill.prototype.check = function (theme, colorMap) { if (this.fill) { this.fill.check(theme, colorMap); } }; CUniFill.prototype.addColorMod = function (mod) { if (this.fill) { switch (this.fill.type) { case c_oAscFill.FILL_TYPE_BLIP: case c_oAscFill.FILL_TYPE_NOFILL: case c_oAscFill.FILL_TYPE_GRP: { break; } case c_oAscFill.FILL_TYPE_SOLID: { if (this.fill.color && this.fill.color) { this.fill.color.addColorMod(mod); } break; } case c_oAscFill.FILL_TYPE_GRAD: { for (var i = 0; i < this.fill.colors.length; ++i) { if (this.fill.colors[i] && this.fill.colors[i].color) { this.fill.colors[i].color.addColorMod(mod); } } break; } case c_oAscFill.FILL_TYPE_PATT: { if (this.fill.bgClr) { this.fill.bgClr.addColorMod(mod); } if (this.fill.fgClr) { this.fill.fgClr.addColorMod(mod); } break; } } } }; CUniFill.prototype.checkPhColor = function (unicolor, bMergeMods) { if (this.fill) { switch (this.fill.type) { case c_oAscFill.FILL_TYPE_BLIP: case c_oAscFill.FILL_TYPE_NOFILL: case c_oAscFill.FILL_TYPE_GRP: { break; } case c_oAscFill.FILL_TYPE_SOLID: { if (this.fill.color && this.fill.color) { this.fill.color.checkPhColor(unicolor, bMergeMods); } break; } case c_oAscFill.FILL_TYPE_GRAD: { for (var i = 0; i < this.fill.colors.length; ++i) { if (this.fill.colors[i] && this.fill.colors[i].color) { this.fill.colors[i].color.checkPhColor(unicolor, bMergeMods); } } break; } case c_oAscFill.FILL_TYPE_PATT: { if (this.fill.bgClr) { this.fill.bgClr.checkPhColor(unicolor, bMergeMods); } if (this.fill.fgClr) { this.fill.fgClr.checkPhColor(unicolor, bMergeMods); } break; } } } }; CUniFill.prototype.checkPatternType = function (nType) { if (this.fill) { if (this.fill.type === c_oAscFill.FILL_TYPE_PATT) { this.fill.ftype = nType; } } }; CUniFill.prototype.Get_TextBackGroundColor = function () { if (!this.fill) { return undefined; } var oColor = undefined, RGBA; switch (this.fill.type) { case c_oAscFill.FILL_TYPE_SOLID: { if (this.fill.color) { RGBA = this.fill.color.RGBA; if (RGBA) { oColor = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false); } } break; } case c_oAscFill.FILL_TYPE_PATT: { var oClr; if (this.fill.ftype === 38) { oClr = this.fill.fgClr; } else { oClr = this.fill.bgClr; } if (oClr) { RGBA = oClr.RGBA; if (RGBA) { oColor = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false); } } break; } } return oColor; }; CUniFill.prototype.checkWordMods = function () { return this.fill && this.fill.checkWordMods(); }; CUniFill.prototype.convertToPPTXMods = function () { this.fill && this.fill.convertToPPTXMods(); }; CUniFill.prototype.canConvertPPTXModsToWord = function () { return this.fill && this.fill.canConvertPPTXModsToWord(); }; CUniFill.prototype.convertToWordMods = function () { this.fill && this.fill.convertToWordMods(); }; CUniFill.prototype.setFill = function (fill) { this.fill = fill; }; CUniFill.prototype.setTransparent = function (transparent) { this.transparent = transparent; }; CUniFill.prototype.Set_FromObject = function (o) { //TODO: }; CUniFill.prototype.Write_ToBinary = function (w) { writeDouble(w, this.transparent); w.WriteBool(isRealObject(this.fill)); if (isRealObject(this.fill)) { w.WriteLong(this.fill.type); this.fill.Write_ToBinary(w); } }; CUniFill.prototype.Read_FromBinary = function (r) { this.transparent = readDouble(r); if (r.GetBool()) { var type = r.GetLong(); switch (type) { case c_oAscFill.FILL_TYPE_BLIP: { this.fill = new CBlipFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_NOFILL: { this.fill = new CNoFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_SOLID: { this.fill = new CSolidFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_GRAD: { this.fill = new CGradFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_PATT: { this.fill = new CPattFill(); this.fill.Read_FromBinary(r); break; } case c_oAscFill.FILL_TYPE_GRP: { this.fill = new CGrpFill(); this.fill.Read_FromBinary(r); break; } } } }; CUniFill.prototype.calculate = function (theme, slide, layout, masterSlide, RGBA, colorMap) { if (this.fill) { if (this.fill.color) { this.fill.color.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); } if (this.fill.colors) { for (var i = 0; i < this.fill.colors.length; ++i) { this.fill.colors[i].color.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); } } if (this.fill.fgClr) this.fill.fgClr.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); if (this.fill.bgClr) this.fill.bgClr.Calculate(theme, slide, layout, masterSlide, RGBA, colorMap); } }; CUniFill.prototype.getRGBAColor = function () { if (this.fill) { if (this.fill.type === c_oAscFill.FILL_TYPE_SOLID) { if (this.fill.color) { return this.fill.color.RGBA; } else { return new FormatRGBAColor(); } } if (this.fill.type === c_oAscFill.FILL_TYPE_GRAD) { var RGBA = new FormatRGBAColor(); var _colors = this.fill.colors; var _len = _colors.length; if (0 === _len) return RGBA; for (var i = 0; i < _len; i++) { RGBA.R += _colors[i].color.RGBA.R; RGBA.G += _colors[i].color.RGBA.G; RGBA.B += _colors[i].color.RGBA.B; } RGBA.R = (RGBA.R / _len) >> 0; RGBA.G = (RGBA.G / _len) >> 0; RGBA.B = (RGBA.B / _len) >> 0; return RGBA; } if (this.fill.type === c_oAscFill.FILL_TYPE_PATT) { return this.fill.fgClr.RGBA; } if (this.fill.type === c_oAscFill.FILL_TYPE_NOFILL) { return {R: 0, G: 0, B: 0}; } } return new FormatRGBAColor(); }; CUniFill.prototype.createDuplicate = function () { var duplicate = new CUniFill(); if (this.fill != null) { duplicate.fill = this.fill.createDuplicate(); } duplicate.transparent = this.transparent; return duplicate; }; CUniFill.prototype.saveSourceFormatting = function () { var duplicate = new CUniFill(); if (this.fill) { if (this.fill.saveSourceFormatting) { duplicate.fill = this.fill.saveSourceFormatting(); } else { duplicate.fill = this.fill.createDuplicate(); } } duplicate.transparent = this.transparent; return duplicate; }; CUniFill.prototype.merge = function (unifill) { if (unifill) { if (unifill.fill != null) { this.fill = unifill.fill.createDuplicate(); if (this.fill.type === c_oAscFill.FILL_TYPE_PATT) { var _patt_fill = this.fill; if (!_patt_fill.fgClr) { _patt_fill.setFgColor(CreateUniColorRGB(0, 0, 0)); } if (!_patt_fill.bgClr) { _patt_fill.bgClr = CreateUniColorRGB(255, 255, 255); } } } if (unifill.transparent != null) { this.transparent = unifill.transparent; } } }; CUniFill.prototype.IsIdentical = function (unifill) { if (unifill == null) { return false; } if (isRealNumber(this.transparent) !== isRealNumber(unifill.transparent) || isRealNumber(this.transparent) && this.transparent !== unifill.transparent) { return false; } if (this.fill == null && unifill.fill == null) { return true; } if (this.fill != null) { return this.fill.IsIdentical(unifill.fill); } else { return false; } }; CUniFill.prototype.Is_Equal = function (unfill) { return this.IsIdentical(unfill); }; CUniFill.prototype.isEqual = function (unfill) { return this.IsIdentical(unfill); }; CUniFill.prototype.compare = function (unifill) { if (unifill == null) { return null; } var _ret = new CUniFill(); if (!(this.fill == null || unifill.fill == null)) { if (this.fill.compare) { _ret.fill = this.fill.compare(unifill.fill); } } return _ret.fill; }; CUniFill.prototype.isSolidFillRGB = function () { return (this.fill && this.fill.color && this.fill.color.color && this.fill.color.color.type === window['Asc'].c_oAscColor.COLOR_TYPE_SRGB) }; CUniFill.prototype.isSolidFillScheme = function () { return (this.fill && this.fill.color && this.fill.color.color && this.fill.color.color.type === window['Asc'].c_oAscColor.COLOR_TYPE_SCHEME) }; CUniFill.prototype.isNoFill = function () { return this.fill && this.fill.type === window['Asc'].c_oAscFill.FILL_TYPE_NOFILL; }; CUniFill.prototype.isVisible = function () { return this.fill && this.fill.type !== window['Asc'].c_oAscFill.FILL_TYPE_NOFILL; }; CUniFill.prototype.fromXml = function (reader, name) { switch (name) { case "blipFill": { this.fill = new CBlipFill(); break; } case "gradFill": { this.fill = new CGradFill(); break; } case "grpFill": { this.fill = new CGrpFill(); break; } case "noFill": { this.fill = new CNoFill(); break; } case "pattFill": { this.fill = new CPattFill(); break; } case "solidFill": { this.fill = new CSolidFill(); break; } } if (this.fill) { this.fill.fromXml(reader); if(this.checkTransparent) { this.checkTransparent(); } } }; CUniFill.prototype.FILL_NAMES = { "blipFill": true, "gradFill": true, "grpFill": true, "noFill": true, "pattFill": true, "solidFill": true }; CUniFill.prototype.isFillName = function (sName) { return !!CUniFill.prototype.FILL_NAMES[sName]; }; CUniFill.prototype.toXml = function (writer, ns) { var fill = this.fill; if (!fill) return; fill.toXml(writer, ns); }; CUniFill.prototype.addAlpha = function(dValue) { this.setTransparent(Math.max(0, Math.min(255, (dValue * 255 + 0.5) >> 0))); // let oMod = new CColorMod(); // oMod.name = "alpha"; // oMod.val = nPctValue; // this.addColorMod(oMod); }; CUniFill.prototype.isBlipFill = function() { if(this.fill && this.fill.type === c_oAscFill.FILL_TYPE_BLIP) { return true; } }; CUniFill.prototype.checkTransparent = function() { let oFill = this.fill; if(oFill) { switch (oFill.type) { case c_oAscFill.FILL_TYPE_BLIP: { let aEffects = oFill.Effects; for(let nEffect = 0; nEffect < aEffects.length; ++nEffect) { let oEffect = aEffects[nEffect]; if(oEffect instanceof AscFormat.CAlphaModFix && AscFormat.isRealNumber(oEffect.amt)) { this.setTransparent(255 * oEffect.amt / 100000); } } break; } case c_oAscFill.FILL_TYPE_SOLID: { let oColor = oFill.color; if(oColor) { let fAlphaVal = oColor.getModValue("alpha"); if(fAlphaVal !== null) { this.setTransparent(255 * fAlphaVal / 100000); let aMods = oColor.Mods && oColor.Mods.Mods; if(Array.isArray(aMods)) { for(let nMod = aMods.length -1; nMod > -1; nMod--) { let oMod = aMods[nMod]; if(oMod && oMod.name === "alpha") { aMods.splice(nMod); } } } } } break; } case c_oAscFill.FILL_TYPE_PATT: { if(oFill.fgClr && oFill.bgClr) { let fAlphaVal = oFill.fgClr.getModValue("alpha"); if(fAlphaVal !== null) { if(fAlphaVal === oFill.bgClr.getModValue("alpha")) { this.setTransparent(255 * fAlphaVal / 100000) } } } break; } } } }; function CBuBlip() { CBaseNoIdObject.call(this); this.blip = null; } InitClass(CBuBlip, CBaseNoIdObject, 0); CBuBlip.prototype.setBlip = function (oPr) { this.blip = oPr; }; CBuBlip.prototype.fillObject = function (oCopy, oIdMap) { if (this.blip) { oCopy.setBlip(this.blip.createDuplicate(oIdMap)); } }; CBuBlip.prototype.createDuplicate = function () { var oCopy = new CBuBlip(); this.fillObject(oCopy, {}); return oCopy; }; CBuBlip.prototype.getChildren = function () { return [this.blip]; }; CBuBlip.prototype.isEqual = function (oBlip) { return this.blip.isEqual(oBlip.blip); }; CBuBlip.prototype.toPPTY = function (pWriter) { var _src = this.blip.fill.RasterImageId; var imageLocal = AscCommon.g_oDocumentUrls.getImageLocal(_src); if (imageLocal) _src = imageLocal; pWriter.image_map[_src] = true; _src = pWriter.prepareRasterImageIdForWrite(_src); pWriter.WriteBlip(this.blip.fill, _src); }; CBuBlip.prototype.fromPPTY = function (pReader, oParagraph, oBullet) { this.setBlip(new AscFormat.CUniFill()); this.blip.setFill(new AscFormat.CBlipFill()); pReader.ReadBlip(this.blip, undefined, undefined, undefined, oParagraph, oBullet); }; CBuBlip.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.blip = new CUniFill(); this.blip.Read_FromBinary(r); } }; CBuBlip.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.blip)); if (isRealObject(this.blip)) { this.blip.Write_ToBinary(w); } }; CBuBlip.prototype.compare = function (compareObj) { var ret = null; if (compareObj instanceof CBuBlip) { ret = new CBuBlip(); if (this.blip) { ret.blip = CompareUniFill(this.blip, compareObj.blip); } } return ret; }; CBuBlip.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { this.blip = new CUniFill(); this.blip.fill = new CBlipFill(); this.blip.fill.readChildXml("blip", reader); break; } } }; CBuBlip.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:buBlip"); writer.WriteXmlAttributesEnd(); this.blip.fill.writeBlip(writer); writer.WriteXmlNodeEnd("a:buBlip"); }; function CompareUniFill(unifill_1, unifill_2) { if (unifill_1 == null || unifill_2 == null) { return null; } var _ret = new CUniFill(); if (!(unifill_1.transparent === null || unifill_2.transparent === null || unifill_1.transparent !== unifill_2.transparent)) { _ret.transparent = unifill_1.transparent; } if (unifill_1.fill == null || unifill_2.fill == null || unifill_1.fill.type != unifill_2.fill.type) { return _ret; } _ret.fill = unifill_1.compare(unifill_2); return _ret; } function CompareBlipTiles(tile1, tile2) { if (isRealObject(tile1)) { return tile1.IsIdentical(tile2); } return tile1 === tile2; } function CompareUnifillBool(u1, u2) { if (!u1 && !u2) return true; if (!u1 && u2 || u1 && !u2) return false; if (isRealNumber(u1.transparent) !== isRealNumber(u2.transparent) || isRealNumber(u1.transparent) && u1.transparent !== u2.transparent) { return false; } if (!u1.fill && !u2.fill) return true; if (!u1.fill && u2.fill || u1.fill && !u2.fill) return false; if (u1.fill.type !== u2.fill.type) return false; switch (u1.fill.type) { case c_oAscFill.FILL_TYPE_BLIP: { if (u1.fill.RasterImageId && !u2.fill.RasterImageId || u2.fill.RasterImageId && !u1.fill.RasterImageId) return false; if (typeof u1.fill.RasterImageId === "string" && typeof u2.fill.RasterImageId === "string" && AscCommon.getFullImageSrc2(u1.fill.RasterImageId) !== AscCommon.getFullImageSrc2(u2.fill.RasterImageId)) return false; if (u1.fill.srcRect && !u2.fill.srcRect || !u1.fill.srcRect && u2.fill.srcRect) return false; if (u1.fill.srcRect && u2.fill.srcRect) { if (u1.fill.srcRect.l !== u2.fill.srcRect.l || u1.fill.srcRect.t !== u2.fill.srcRect.t || u1.fill.srcRect.r !== u2.fill.srcRect.r || u1.fill.srcRect.b !== u2.fill.srcRect.b) return false; } if (u1.fill.stretch !== u2.fill.stretch || !CompareBlipTiles(u1.fill.tile, u2.fill.tile) || u1.fill.rotWithShape !== u2.fill.rotWithShape) return false; break; } case c_oAscFill.FILL_TYPE_SOLID: { if (u1.fill.color && u2.fill.color) { return CompareUniColor(u1.fill.color, u2.fill.color) } break; } case c_oAscFill.FILL_TYPE_GRAD: { if (u1.fill.colors.length !== u2.fill.colors.length) return false; if (isRealObject(u1.fill.path) !== isRealObject(u2.fill.path)) return false; if (u1.fill.path && !u1.fill.path.IsIdentical(u2.fill.path)) return false; if (isRealObject(u1.fill.lin) !== isRealObject(u2.fill.lin)) return false; if (u1.fill.lin && !u1.fill.lin.IsIdentical(u2.fill.lin)) return false; for (var i = 0; i < u1.fill.colors.length; ++i) { if (u1.fill.colors[i].pos !== u2.fill.colors[i].pos || !CompareUniColor(u1.fill.colors[i].color, u2.fill.colors[i].color)) return false; } break; } case c_oAscFill.FILL_TYPE_PATT: { if (u1.fill.ftype !== u2.fill.ftype || !CompareUniColor(u1.fill.fgClr, u2.fill.fgClr) || !CompareUniColor(u1.fill.bgClr, u2.fill.bgClr)) return false; break; } } return true; } function CompareUniColor(u1, u2) { if (!u1 && !u2) return true; if (!u1 && u2 || u1 && !u2) return false; if (!u1.color && u2.color || u1.color && !u2.color) return false; if (u1.color && u2.color) { if (u1.color.type !== u2.color.type) return false; switch (u1.color.type) { case c_oAscColor.COLOR_TYPE_NONE: { break; } case c_oAscColor.COLOR_TYPE_SRGB: { if (u1.color.RGBA.R !== u2.color.RGBA.R || u1.color.RGBA.G !== u2.color.RGBA.G || u1.color.RGBA.B !== u2.color.RGBA.B || u1.color.RGBA.A !== u2.color.RGBA.A) { return false; } break; } case c_oAscColor.COLOR_TYPE_PRST: case c_oAscColor.COLOR_TYPE_SCHEME: { if (u1.color.id !== u2.color.id) return false; break; } case c_oAscColor.COLOR_TYPE_SYS: { if (u1.color.RGBA.R !== u2.color.RGBA.R || u1.color.RGBA.G !== u2.color.RGBA.G || u1.color.RGBA.B !== u2.color.RGBA.B || u1.color.RGBA.A !== u2.color.RGBA.A || u1.color.id !== u2.color.id) { return false; } break; } case c_oAscColor.COLOR_TYPE_STYLE: { if (u1.bAuto !== u2.bAuto || u1.val !== u2.val) { return false; } break; } } } if (!u1.Mods && u2.Mods || !u2.Mods && u1.Mods) return false; if (u1.Mods && u2.Mods) { if (u1.Mods.Mods.length !== u2.Mods.Mods.length) return false; for (var i = 0; i < u1.Mods.Mods.length; ++i) { if (u1.Mods.Mods[i].name !== u2.Mods.Mods[i].name || u1.Mods.Mods[i].val !== u2.Mods.Mods[i].val) return false; } } return true; } // ----------------------------- function CompareShapeProperties(shapeProp1, shapeProp2) { var _result_shape_prop = {}; if (shapeProp1.type === shapeProp2.type) { _result_shape_prop.type = shapeProp1.type; } else { _result_shape_prop.type = null; } if (shapeProp1.h === shapeProp2.h) { _result_shape_prop.h = shapeProp1.h; } else { _result_shape_prop.h = null; } if (shapeProp1.w === shapeProp2.w) { _result_shape_prop.w = shapeProp1.w; } else { _result_shape_prop.w = null; } if (shapeProp1.x === shapeProp2.x) { _result_shape_prop.x = shapeProp1.x; } else { _result_shape_prop.x = null; } if (shapeProp1.y === shapeProp2.y) { _result_shape_prop.y = shapeProp1.y; } else { _result_shape_prop.y = null; } if (shapeProp1.rot === shapeProp2.rot) { _result_shape_prop.rot = shapeProp1.rot; } else { _result_shape_prop.rot = null; } if (shapeProp1.flipH === shapeProp2.flipH) { _result_shape_prop.flipH = shapeProp1.flipH; } else { _result_shape_prop.flipH = null; } if (shapeProp1.flipV === shapeProp2.flipV) { _result_shape_prop.flipV = shapeProp1.flipV; } else { _result_shape_prop.flipV = null; } if (shapeProp1.anchor === shapeProp2.anchor) { _result_shape_prop.anchor = shapeProp1.anchor; } else { _result_shape_prop.anchor = null; } if (shapeProp1.stroke == null || shapeProp2.stroke == null) { _result_shape_prop.stroke = null; } else { _result_shape_prop.stroke = shapeProp1.stroke.compare(shapeProp2.stroke) } /* if(shapeProp1.verticalTextAlign === shapeProp2.verticalTextAlign) { _result_shape_prop.verticalTextAlign = shapeProp1.verticalTextAlign; } else */ { _result_shape_prop.verticalTextAlign = null; _result_shape_prop.vert = null; } if (shapeProp1.canChangeArrows !== true || shapeProp2.canChangeArrows !== true) _result_shape_prop.canChangeArrows = false; else _result_shape_prop.canChangeArrows = true; _result_shape_prop.fill = CompareUniFill(shapeProp1.fill, shapeProp2.fill); _result_shape_prop.IsLocked = shapeProp1.IsLocked === true || shapeProp2.IsLocked === true; if (isRealObject(shapeProp1.paddings) && isRealObject(shapeProp2.paddings)) { _result_shape_prop.paddings = new Asc.asc_CPaddings(); _result_shape_prop.paddings.Left = isRealNumber(shapeProp1.paddings.Left) ? (shapeProp1.paddings.Left === shapeProp2.paddings.Left ? shapeProp1.paddings.Left : undefined) : undefined; _result_shape_prop.paddings.Top = isRealNumber(shapeProp1.paddings.Top) ? (shapeProp1.paddings.Top === shapeProp2.paddings.Top ? shapeProp1.paddings.Top : undefined) : undefined; _result_shape_prop.paddings.Right = isRealNumber(shapeProp1.paddings.Right) ? (shapeProp1.paddings.Right === shapeProp2.paddings.Right ? shapeProp1.paddings.Right : undefined) : undefined; _result_shape_prop.paddings.Bottom = isRealNumber(shapeProp1.paddings.Bottom) ? (shapeProp1.paddings.Bottom === shapeProp2.paddings.Bottom ? shapeProp1.paddings.Bottom : undefined) : undefined; } _result_shape_prop.canFill = shapeProp1.canFill === true || shapeProp2.canFill === true; if (shapeProp1.bFromChart || shapeProp2.bFromChart) { _result_shape_prop.bFromChart = true; } else { _result_shape_prop.bFromChart = false; } if (shapeProp1.bFromSmartArt || shapeProp2.bFromSmartArt) { _result_shape_prop.bFromSmartArt = true; } else { _result_shape_prop.bFromSmartArt = false; } if (shapeProp1.bFromSmartArtInternal || shapeProp2.bFromSmartArtInternal) { _result_shape_prop.bFromSmartArtInternal = true; } else { _result_shape_prop.bFromSmartArtInternal = false; } if (shapeProp1.bFromGroup || shapeProp2.bFromGroup) { _result_shape_prop.bFromGroup = true; } else { _result_shape_prop.bFromGroup = false; } if (!shapeProp1.bFromImage || !shapeProp2.bFromImage) { _result_shape_prop.bFromImage = false; } else { _result_shape_prop.bFromImage = true; } if (shapeProp1.locked || shapeProp2.locked) { _result_shape_prop.locked = true; } _result_shape_prop.lockAspect = !!(shapeProp1.lockAspect && shapeProp2.lockAspect); _result_shape_prop.textArtProperties = CompareTextArtProperties(shapeProp1.textArtProperties, shapeProp2.textArtProperties); if (shapeProp1.bFromSmartArtInternal && !shapeProp2.bFromSmartArtInternal || !shapeProp1.bFromSmartArtInternal && shapeProp2.bFromSmartArtInternal) { _result_shape_prop.textArtProperties = null; } if (shapeProp1.title === shapeProp2.title) { _result_shape_prop.title = shapeProp1.title; } if (shapeProp1.description === shapeProp2.description) { _result_shape_prop.description = shapeProp1.description; } if (shapeProp1.columnNumber === shapeProp2.columnNumber) { _result_shape_prop.columnNumber = shapeProp1.columnNumber; } if (shapeProp1.columnSpace === shapeProp2.columnSpace) { _result_shape_prop.columnSpace = shapeProp1.columnSpace; } if (shapeProp1.textFitType === shapeProp2.textFitType) { _result_shape_prop.textFitType = shapeProp1.textFitType; } if (shapeProp1.vertOverflowType === shapeProp2.vertOverflowType) { _result_shape_prop.vertOverflowType = shapeProp1.vertOverflowType; } if (!shapeProp1.shadow && !shapeProp2.shadow) { _result_shape_prop.shadow = null; } else if (shapeProp1.shadow && !shapeProp2.shadow) { _result_shape_prop.shadow = null; } else if (!shapeProp1.shadow && shapeProp2.shadow) { _result_shape_prop.shadow = null; } else if (shapeProp1.shadow.IsIdentical(shapeProp2.shadow)) { _result_shape_prop.shadow = shapeProp1.shadow.createDuplicate(); } else { _result_shape_prop.shadow = null; } _result_shape_prop.protectionLockText = CompareProtectionFlags(shapeProp1.protectionLockText, shapeProp2.protectionLockText); _result_shape_prop.protectionLocked = CompareProtectionFlags(shapeProp1.protectionLocked, shapeProp2.protectionLocked); _result_shape_prop.protectionPrint = CompareProtectionFlags(shapeProp1.protectionPrint, shapeProp2.protectionPrint); return _result_shape_prop; } function CompareProtectionFlags(bFlag1, bFlag2) { if (bFlag1 === null || bFlag2 === null) { return null; } else if (bFlag1 === bFlag2) { return bFlag1; } return undefined; } function CompareTextArtProperties(oProps1, oProps2) { if (!oProps1 || !oProps2) return null; var oRet = {Fill: undefined, Line: undefined, Form: undefined}; if (oProps1.Form === oProps2.Form) { oRet.From = oProps1.Form; } if (oProps1.Fill && oProps2.Fill) { oRet.Fill = CompareUniFill(oProps1.Fill, oProps2.Fill); } if (oProps1.Line && oProps2.Line) { oRet.Line = oProps1.Line.compare(oProps2.Line); } return oRet; } // LN -------------------------- // ั€ะฐะทะผะตั€ั‹ ัั‚ั€ะตะปะพะบ; var lg = 500, mid = 300, sm = 200; //ั‚ะธะฟั‹ ัั‚ั€ะตะปะพะบ var ar_arrow = 0, ar_diamond = 1, ar_none = 2, ar_oval = 3, ar_stealth = 4, ar_triangle = 5; var LineEndType = { None: 0, Arrow: 1, Diamond: 2, Oval: 3, Stealth: 4, Triangle: 5 }; var LineEndSize = { Large: 0, Mid: 1, Small: 2 }; var LineJoinType = { Empty: 0, Round: 1, Bevel: 2, Miter: 3 }; function EndArrow() { CBaseNoIdObject.call(this); this.type = null; this.len = null; this.w = null; } InitClass(EndArrow, CBaseNoIdObject, 0); EndArrow.prototype.compare = function (end_arrow) { if (end_arrow == null) { return null; } var _ret = new EndArrow(); if (this.type === end_arrow.type) { _ret.type = this.type; } if (this.len === end_arrow.len) { _ret.len = this.len; } if (this.w === end_arrow) { _ret.w = this.w; } return _ret; }; EndArrow.prototype.createDuplicate = function () { var duplicate = new EndArrow(); duplicate.type = this.type; duplicate.len = this.len; duplicate.w = this.w; return duplicate; }; EndArrow.prototype.IsIdentical = function (arrow) { return arrow && arrow.type === this.type && arrow.len === this.len && arrow.w === this.w; }; EndArrow.prototype.GetWidth = function (_size, _max) { var size = Math.max(_size, _max ? _max : 2); var _ret = 3 * size; if (null != this.w) { switch (this.w) { case LineEndSize.Large: _ret = 5 * size; break; case LineEndSize.Small: _ret = 2 * size; break; default: break; } } return _ret; }; EndArrow.prototype.GetLen = function (_size, _max) { var size = Math.max(_size, _max ? _max : 2); var _ret = 3 * size; if (null != this.len) { switch (this.len) { case LineEndSize.Large: _ret = 5 * size; break; case LineEndSize.Small: _ret = 2 * size; break; default: break; } } return _ret; }; EndArrow.prototype.setType = function (type) { this.type = type; }; EndArrow.prototype.setLen = function (len) { this.len = len; }; EndArrow.prototype.setW = function (w) { this.w = w; }; EndArrow.prototype.Write_ToBinary = function (w) { writeLong(w, this.type); writeLong(w, this.len); writeLong(w, this.w); }; EndArrow.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.len = readLong(r); this.w = readLong(r); }; EndArrow.prototype.GetSizeCode = function (sVal) { switch (sVal) { case "lg": { return LineEndSize.Large; } case "med": { return LineEndSize.Mid; } case "sm": { return LineEndSize.Small; } } return LineEndSize.Mid; }; EndArrow.prototype.GetSizeByCode = function (nCode) { switch (nCode) { case LineEndSize.Large: { return "lg"; } case LineEndSize.Mid: { return "med"; } case LineEndSize.Small: { return "sm"; } } return "med"; }; EndArrow.prototype.GetTypeCode = function (sVal) { switch (sVal) { case "arrow": { return LineEndType.Arrow; } case "diamond": { return LineEndType.Diamond; } case "none": { return LineEndType.None; } case "oval": { return LineEndType.Oval; } case "stealth": { return LineEndType.Stealth; } case "triangle": { return LineEndType.Triangle; } } return LineEndType.Arrow; }; EndArrow.prototype.GetTypeByCode = function (nCode) { switch (nCode) { case LineEndType.Arrow : { return "arrow"; } case LineEndType.Diamond: { return "diamond"; } case LineEndType.None: { return "none"; } case LineEndType.Oval: { return "oval"; } case LineEndType.Stealth: { return "stealth"; } case LineEndType.Triangle: { return "triangle"; } } return "arrow"; }; EndArrow.prototype.readAttrXml = function (name, reader) { switch (name) { case "len": { let sVal = reader.GetValue(); this.len = this.GetSizeCode(sVal); break; } case "type": { let sVal = reader.GetValue(); this.type = this.GetTypeCode(sVal); break; } case "w": { let sVal = reader.GetValue(); this.w = this.GetSizeCode(sVal); break; } } }; EndArrow.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlNullableAttributeString("type", this.GetTypeByCode(this.type)); writer.WriteXmlNullableAttributeString("w", this.GetSizeByCode(this.w)); writer.WriteXmlNullableAttributeString("len", this.GetSizeByCode(this.len)); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd(sName); }; function ConvertJoinAggType(_type) { switch (_type) { case LineJoinType.Round: return 2; case LineJoinType.Bevel: return 1; case LineJoinType.Miter: return 0; default: break; } return 2; } function LineJoin(type) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(type) ? type : null; this.limit = null; } InitClass(LineJoin, CBaseNoIdObject, 0); LineJoin.prototype.IsIdentical = function (oJoin) { if (!oJoin) return false; if (this.type !== oJoin.type) { return false; } if (this.limit !== oJoin.limit) return false; return true; }; LineJoin.prototype.createDuplicate = function () { var duplicate = new LineJoin(); duplicate.type = this.type; duplicate.limit = this.limit; return duplicate; }; LineJoin.prototype.setType = function (type) { this.type = type; }; LineJoin.prototype.setLimit = function (limit) { this.limit = limit; }; LineJoin.prototype.Write_ToBinary = function (w) { writeLong(w, this.type); writeLong(w, this.limit); }; LineJoin.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.limit = readLong(r); }; LineJoin.prototype.readAttrXml = function (name, reader) { switch (name) { case "lim": { this.limit = reader.GetValueInt(); break; } } }; LineJoin.prototype.toXml = function (writer) { let sNodeNamespace = ""; let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { sNodeNamespace = "w14:"; sAttrNamespace = sNodeNamespace; } else sNodeNamespace = "a:"; if (this.type === LineJoinType.Round) { writer.WriteXmlString("<" + sNodeNamespace + "round/>"); } else if (this.type === LineJoinType.Bevel) { writer.WriteXmlString("<" + sNodeNamespace + "bevel/>"); } else if (this.type === LineJoinType.Miter) { writer.WriteXmlNodeStart(sNodeNamespace + "miter"); writer.WriteXmlNullableAttributeInt(sAttrNamespace + "lim", this.limit); writer.WriteXmlAttributesEnd(true); } }; function CLn() { CBaseNoIdObject.call(this); this.Fill = null;//new CUniFill(); this.prstDash = null; this.Join = null; this.headEnd = null; this.tailEnd = null; this.algn = null; this.cap = null; this.cmpd = null; this.w = null; } InitClass(CLn, CBaseNoIdObject, 0); CLn.prototype.compare = function (line) { if (line == null) { return null; } var _ret = new CLn(); if (this.Fill != null) { _ret.Fill = CompareUniFill(this.Fill, line.Fill); } if (this.prstDash === line.prstDash) { _ret.prstDash = this.prstDash; } else { _ret.prstDash = undefined; } if (this.Join === line.Join) { _ret.Join = this.Join; } if (this.tailEnd != null) { _ret.tailEnd = this.tailEnd.compare(line.tailEnd); } if (this.headEnd != null) { _ret.headEnd = this.headEnd.compare(line.headEnd); } if (this.algn === line.algn) { _ret.algn = this.algn; } if (this.cap === line.cap) { _ret.cap = this.cap; } if (this.cmpd === line.cmpd) { _ret.cmpd = this.cmpd; } if (this.w === line.w) { _ret.w = this.w; } return _ret; }; CLn.prototype.merge = function (ln) { if (ln == null) { return; } if (ln.Fill != null && ln.Fill.fill != null) { this.Fill = ln.Fill.createDuplicate(); } if (ln.prstDash != null) { this.prstDash = ln.prstDash; } if (ln.Join != null) { this.Join = ln.Join.createDuplicate(); } if (ln.headEnd != null) { this.headEnd = ln.headEnd.createDuplicate(); } if (ln.tailEnd != null) { this.tailEnd = ln.tailEnd.createDuplicate(); } if (ln.algn != null) { this.algn = ln.algn; } if (ln.cap != null) { this.cap = ln.cap; } if (ln.cmpd != null) { this.cmpd = ln.cmpd; } if (ln.w != null) { this.w = ln.w; } }; CLn.prototype.calculate = function (theme, slide, layout, master, RGBA, colorMap) { if (isRealObject(this.Fill)) { this.Fill.calculate(theme, slide, layout, master, RGBA, colorMap); } }; CLn.prototype.createDuplicate = function (bSaveFormatting) { var duplicate = new CLn(); if (null != this.Fill) { if (bSaveFormatting === true) { duplicate.Fill = this.Fill.saveSourceFormatting(); } else { duplicate.Fill = this.Fill.createDuplicate(); } } duplicate.prstDash = this.prstDash; duplicate.Join = this.Join; if (this.headEnd != null) { duplicate.headEnd = this.headEnd.createDuplicate(); } if (this.tailEnd != null) { duplicate.tailEnd = this.tailEnd.createDuplicate(); } duplicate.algn = this.algn; duplicate.cap = this.cap; duplicate.cmpd = this.cmpd; duplicate.w = this.w; return duplicate; }; CLn.prototype.IsIdentical = function (ln) { return ln && (this.Fill == null ? ln.Fill == null : this.Fill.IsIdentical(ln.Fill)) && (this.Join == null ? ln.Join == null : this.Join.IsIdentical(ln.Join)) && (this.headEnd == null ? ln.headEnd == null : this.headEnd.IsIdentical(ln.headEnd)) && (this.tailEnd == null ? ln.tailEnd == null : this.tailEnd.IsIdentical(ln.headEnd)) && this.algn == ln.algn && this.cap == ln.cap && this.cmpd == ln.cmpd && this.w == ln.w && this.prstDash === ln.prstDash; }; CLn.prototype.setFill = function (fill) { this.Fill = fill; }; CLn.prototype.setPrstDash = function (prstDash) { this.prstDash = prstDash; }; CLn.prototype.setJoin = function (join) { this.Join = join; }; CLn.prototype.setHeadEnd = function (headEnd) { this.headEnd = headEnd; }; CLn.prototype.setTailEnd = function (tailEnd) { this.tailEnd = tailEnd; }; CLn.prototype.setAlgn = function (algn) { this.algn = algn; }; CLn.prototype.setCap = function (cap) { this.cap = cap; }; CLn.prototype.setCmpd = function (cmpd) { this.cmpd = cmpd; }; CLn.prototype.setW = function (w) { this.w = w; }; CLn.prototype.isVisible = function () { return this.Fill && this.Fill.isVisible(); }; CLn.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.Fill)); if (isRealObject(this.Fill)) { this.Fill.Write_ToBinary(w); } writeLong(w, this.prstDash); w.WriteBool(isRealObject(this.Join)); if (isRealObject(this.Join)) { this.Join.Write_ToBinary(w); } w.WriteBool(isRealObject(this.headEnd)); if (isRealObject(this.headEnd)) { this.headEnd.Write_ToBinary(w); } w.WriteBool(isRealObject(this.tailEnd)); if (isRealObject(this.tailEnd)) { this.tailEnd.Write_ToBinary(w); } writeLong(w, this.algn); writeLong(w, this.cap); writeLong(w, this.cmpd); writeLong(w, this.w); }; CLn.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.Fill = new CUniFill(); this.Fill.Read_FromBinary(r); } else { this.Fill = null; } this.prstDash = readLong(r); if (r.GetBool()) { this.Join = new LineJoin(); this.Join.Read_FromBinary(r); } if (r.GetBool()) { this.headEnd = new EndArrow(); this.headEnd.Read_FromBinary(r); } if (r.GetBool()) { this.tailEnd = new EndArrow(); this.tailEnd.Read_FromBinary(r); } this.algn = readLong(r); this.cap = readLong(r); this.cmpd = readLong(r); this.w = readLong(r); }; CLn.prototype.isNoFillLine = function () { if (this.Fill) { return this.Fill.isNoFill(); } return false; }; CLn.prototype.GetCapCode = function (sVal) { switch (sVal) { case "flat": { return 0; } case "rnd": { return 1; } case "sq": { return 2; } } return 0; }; CLn.prototype.GetCapByCode = function (nCode) { switch (nCode) { case 0: { return "flat"; } case 1: { return "rnd"; } case 2: { return "sq"; } } return null; }; CLn.prototype.GetAlgnCode = function (sVal) { switch (sVal) { case "ctr": { return 0; } case "in": { return 1; } } return 0; }; CLn.prototype.GetAlgnByCode = function (sVal) { switch (sVal) { case 0: { return "ctr"; } case 1: { return "in"; } } return null; }; CLn.prototype.GetCmpdCode = function (sVal) { switch (sVal) { case "dbl": { return 0; } case "sng": { return 1; } case "thickThin": { return 2; } case "thinThick": { return 3; } case "tri": { return 4; } } return 1; }; CLn.prototype.GetCmpdByCode = function (sVal) { switch (sVal) { case 0: { return "dbl"; } case 1: { return "sng"; } case 2: { return "thickThin"; } case 3: { return "thinThick"; } case 4: { return "tri"; } } return null; }; CLn.prototype.GetDashCode = function (sVal) { switch (sVal) { case "dash": { return 0; } case "dashDot": { return 1; } case "dot": { return 2; } case "lgDash": { return 3; } case "lgDashDot": { return 4; } case "lgDashDotDot": { return 5; } case "solid": { return 6; } case "sysDash": { return 7; } case "sysDashDot": { return 8; } case "sysDashDotDot": { return 9; } case "sysDot": { return 10; } } return 6; }; CLn.prototype.GetDashByCode = function (sVal) { switch (sVal) { case 0: { return "dash"; } case 1 : { return "dashDot"; } case 2 : { return "dot"; } case 3 : { return "lgDash"; } case 4 : { return "lgDashDot"; } case 5 : { return "lgDashDotDot"; } case 6 : { return "solid"; } case 7 : { return "sysDash"; } case 8: { return "sysDashDot"; } case 9 : { return "sysDashDotDot"; } case 10 : { return "sysDot"; } } return null; }; CLn.prototype.readAttrXml = function (name, reader) { switch (name) { case "algn": { let sVal = reader.GetValue(); this.algn = this.GetAlgnCode(sVal); break; } case "cap": { let sVal = reader.GetValue(); this.cap = this.GetCapCode(sVal); break; } case "cmpd": { let sVal = reader.GetValue(); this.cmpd = this.GetCmpdCode(sVal); break; } case "w": { this.w = reader.GetValueInt(); break; } } }; CLn.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.Fill = new CUniFill(); this.Fill.fromXml(reader, name); } else if (name === "headEnd") { this.headEnd = new EndArrow(); this.headEnd.fromXml(reader); } else if (name === "tailEnd") { this.tailEnd = new EndArrow(); this.tailEnd.fromXml(reader); } else if (name === "prstDash") { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); let sVal = oNode.attributes["val"]; this.prstDash = this.GetDashCode(sVal); } else if (name === "bevel") { this.Join = new LineJoin(LineJoinType.Bevel); this.Join.fromXml(reader); } else if (name === "miter") { this.Join = new LineJoin(LineJoinType.Miter); this.Join.fromXml(reader); } else if (name === "round") { this.Join = new LineJoin(LineJoinType.Round); this.Join.fromXml(reader); } }; CLn.prototype.toXml = function (writer, sName) { let _name = sName; if (!_name || _name.length === 0) _name = ("a:ln"); let sAttrNamespace = ""; if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { _name = ("w14:textOutline"); sAttrNamespace = ("w14:"); } writer.WriteXmlNodeStart(_name); writer.WriteXmlNullableAttributeUInt(sAttrNamespace + "w", this.w); writer.WriteXmlNullableAttributeString(sAttrNamespace + "cap", this.GetCapByCode(this.cap)); writer.WriteXmlNullableAttributeString(sAttrNamespace + "cmpd", this.GetCmpdByCode(this.cmpd)); writer.WriteXmlNullableAttributeString(sAttrNamespace + "algn", this.GetAlgnByCode(this.algn)); writer.WriteXmlAttributesEnd(); if(this.Fill) { this.Fill.toXml(writer); } let nDashCode = this.GetDashByCode(this.prstDash); if(nDashCode !== null) { if (AscFormat.XMLWRITER_DOC_TYPE_WORDART === writer.context.docType) { writer.WriteXmlNodeStart("w14:prstDash"); writer.WriteXmlNullableAttributeString("w14:val", this.GetDashByCode(this.prstDash)); writer.WriteXmlAttributesEnd(true); } else { writer.WriteXmlNodeStart("a:prstDash"); writer.WriteXmlNullableAttributeString("val", this.GetDashByCode(this.prstDash)); writer.WriteXmlAttributesEnd(true); } } if (this.Join) { this.Join.toXml(writer); } if (this.headEnd) { this.headEnd.toXml(writer, "a:headEnd"); } if (this.tailEnd) { this.tailEnd.toXml(writer, "a:tailEnd"); } writer.WriteXmlNodeEnd(_name); }; CLn.prototype.fillDocumentBorder = function(oBorder) { if(this.Fill) { oBorder.Unifill = this.Fill; } oBorder.Size = (this.w === null) ? 12700 : ((this.w) >> 0); oBorder.Size /= 36000; oBorder.Value = AscCommonWord.border_Single; }; CLn.prototype.fromDocumentBorder = function(oBorder) { this.Fill = oBorder.Unifill; this.w = null; if(AscFormat.isRealNumber(oBorder.Size)) { this.w = oBorder.Size * 36000 >> 0; } this.cmpd = 1; }; // ----------------------------- // SHAPE ---------------------------- function DefaultShapeDefinition() { CBaseFormatObject.call(this); this.spPr = new CSpPr(); this.bodyPr = new CBodyPr(); this.lstStyle = new TextListStyle(); this.style = null; } InitClass(DefaultShapeDefinition, CBaseFormatObject, AscDFH.historyitem_type_DefaultShapeDefinition); DefaultShapeDefinition.prototype.setSpPr = function (spPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_DefaultShapeDefinition_SetSpPr, this.spPr, spPr)); this.spPr = spPr; }; DefaultShapeDefinition.prototype.setBodyPr = function (bodyPr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_DefaultShapeDefinition_SetBodyPr, this.bodyPr, bodyPr)); this.bodyPr = bodyPr; }; DefaultShapeDefinition.prototype.setLstStyle = function (lstStyle) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_DefaultShapeDefinition_SetLstStyle, this.lstStyle, lstStyle)); this.lstStyle = lstStyle; }; DefaultShapeDefinition.prototype.setStyle = function (style) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_DefaultShapeDefinition_SetStyle, this.style, style)); this.style = style; }; DefaultShapeDefinition.prototype.createDuplicate = function () { var ret = new DefaultShapeDefinition(); if (this.spPr) { ret.setSpPr(this.spPr.createDuplicate()); } if (this.bodyPr) { ret.setBodyPr(this.bodyPr.createDuplicate()); } if (this.lstStyle) { ret.setLstStyle(this.lstStyle.createDuplicate()); } if (this.style) { ret.setStyle(this.style.createDuplicate()); } return ret; }; DefaultShapeDefinition.prototype.readChildXml = function (name, reader) { switch (name) { case "bodyPr": { let oBodyPr = new AscFormat.CBodyPr(); oBodyPr.fromXml(reader); this.setBodyPr(oBodyPr); break; } case "lstStyle": { let oPr = new AscFormat.TextListStyle(); oPr.fromXml(reader); this.setLstStyle(oPr); break; } case "spPr": { let oPr = new AscFormat.CSpPr(); oPr.fromXml(reader); this.setSpPr(oPr); break; } case "style": { let oPr = new AscFormat.CShapeStyle(); oPr.fromXml(reader); this.setStyle(oPr); break; } case "extLst": { break; } } }; DefaultShapeDefinition.prototype.toXml = function (writer, sName) { let oContext = writer.context; let nOldDocType = oContext.docType; oContext.docType = AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS; writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); if (this.spPr) { writer.context.flag = 0x04; this.spPr.toXml(writer); writer.context.flag = 0; } if (this.bodyPr) this.bodyPr.toXml(writer); if (this.lstStyle) { this.lstStyle.toXml(writer, "a:lstStyle"); } if (this.style) { this.style.toXml(writer); } writer.WriteXmlNodeEnd(sName); oContext.docType = nOldDocType; }; function CNvPr() { CBaseFormatObject.call(this); this.id = 0; this.name = ""; this.isHidden = null; this.descr = null; this.title = null; this.hlinkClick = null; this.hlinkHover = null; this.form = null; this.setId(AscCommon.CreateDurableId()); } InitClass(CNvPr, CBaseFormatObject, AscDFH.historyitem_type_CNvPr); CNvPr.prototype.createDuplicate = function () { var duplicate = new CNvPr(); duplicate.setName(this.name); duplicate.setIsHidden(this.isHidden); duplicate.setDescr(this.descr); duplicate.setTitle(this.title); if (this.hlinkClick) { duplicate.setHlinkClick(this.hlinkClick.createDuplicate()); } if (this.hlinkHover) { duplicate.setHlinkHover(this.hlinkHover.createDuplicate()); } return duplicate; }; CNvPr.prototype.setId = function (id) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_CNvPr_SetId, this.id, id)); this.id = id; }; CNvPr.prototype.setName = function (name) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_CNvPr_SetName, this.name, name)); this.name = name; }; CNvPr.prototype.setIsHidden = function (isHidden) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_CNvPr_SetIsHidden, this.isHidden, isHidden)); this.isHidden = isHidden; }; CNvPr.prototype.setDescr = function (descr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_CNvPr_SetDescr, this.descr, descr)); this.descr = descr; }; CNvPr.prototype.setHlinkClick = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_CNvPr_SetHlinkClick, this.hlinkClick, pr)); this.hlinkClick = pr; }; CNvPr.prototype.setHlinkHover = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_CNvPr_SetHlinkHover, this.hlinkHover, pr)); this.hlinkHover = pr; }; CNvPr.prototype.setTitle = function (title) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_CNvPr_SetTitle, this.title, title)); this.title = title; }; CNvPr.prototype.setFromOther = function (oOther) { if (!oOther) { return; } if (oOther.name) { this.setName(oOther.name); } if (oOther.descr) { this.setDescr(oOther.descr); } if (oOther.title) { this.setTitle(oOther.title); } }; CNvPr.prototype.hasSameNameAndId = function (oPr) { if (!oPr) { return false; } return this.id === oPr.id && this.name === oPr.name; }; CNvPr.prototype.toXml = function (writer, name) { writer.WriteXmlNodeStart(name); writer.WriteXmlNullableAttributeUInt("id", this.id); writer.WriteXmlNullableAttributeStringEncode("name", this.name); writer.WriteXmlNullableAttributeStringEncode("descr", this.descr); writer.WriteXmlNullableAttributeBool("hidden", this.isHidden); writer.WriteXmlNullableAttributeBool("form", this.form); writer.WriteXmlNullableAttributeStringEncode("title", this.title); //writer.WriteXmlNullableAttributeBool("title", this.form); if(this.hlinkClick || this.hlinkHover) { let sNS = AscCommon.StaxParser.prototype.GetNSFromNodeName(name); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.hlinkClick, sNS + ":hlinkClick"); writer.WriteXmlNullable(this.hlinkHover, sNS + ":hlinkHover"); //writer.WriteXmlNullable(this.ExtLst, "w:extLst"); writer.WriteXmlNodeEnd(name); } else { writer.WriteXmlAttributesEnd(true); } }; CNvPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "id": { this.setId(reader.GetValueUInt()); break; } case "name": { this.setName(reader.GetValueDecodeXml()); break; } case "descr": { this.setDescr(reader.GetValueDecodeXml()); break; } case "hidden": { this.setIsHidden(reader.GetValueBool()); break; } case "title": { this.setTitle(reader.GetValueDecodeXml()); break; } case "form": { this.form = reader.GetValueBool(); break; } } }; CNvPr.prototype.readChildXml = function (name, reader) { switch (name) { case "hlinkClick": { let oPr = new CT_Hyperlink(); oPr.fromXml(reader); this.setHlinkClick(oPr); break; } case "hlinkHover": { let oPr = new CT_Hyperlink(); oPr.fromXml(reader); this.setHlinkHover(oPr); break; } } }; CNvPr.prototype.toXml = function (writer, sName) { if (sName) { this.toXml3(sName, writer); return; } let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; this.toXml2(namespace_, writer); }; CNvPr.prototype.toXml2 = function (namespace_, writer) { this.toXml3(namespace_ + (":cNvPr"), writer); }; CNvPr.prototype.toXml3 = function (sName, writer) { writer.WriteXmlNodeStart(sName); let _id = this.id; if (_id < 0) { _id = writer.context.objectId; ++writer.context.objectId; } else { if (writer.context.objectId <= _id) { writer.context.objectId = _id + 1; } } writer.WriteXmlNullableAttributeString("id", _id); writer.WriteXmlNullableAttributeStringEncode("name", this.name); if (this.descr) { let d = this.descr; d = d.replace(new RegExp("\n", 'g'), "&#xA;"); writer.WriteXmlNullableAttributeString("descr", d); } writer.WriteXmlNullableAttributeBool("hidden", this.isHidden); writer.WriteXmlNullableAttributeBool("form", this.form); if (this.title) writer.WriteXmlNullableAttributeStringEncode("title", this.title); if(this.hlinkClick || this.hlinkHover) { writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.hlinkClick, "a:hlinkClick"); writer.WriteXmlNullable(this.hlinkHover, "a:hlinkHover"); writer.WriteXmlNodeEnd(sName); } else { writer.WriteXmlAttributesEnd(true); } }; var AUDIO_CD = 0; var WAV_AUDIO_FILE = 1; var AUDIO_FILE = 2; var VIDEO_FILE = 3; var QUICK_TIME_FILE = 4; function UniMedia() { CBaseNoIdObject.call(this); this.type = null; this.media = null; } InitClass(UniMedia, CBaseNoIdObject, 0); UniMedia.prototype.Write_ToBinary = function (w) { var bType = this.type !== null && this.type !== undefined; var bMedia = typeof this.media === 'string'; var nFlags = 0; bType && (nFlags |= 1); bMedia && (nFlags |= 2); w.WriteLong(nFlags); bType && w.WriteLong(this.type); bMedia && w.WriteString2(this.media); }; UniMedia.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.type = r.GetLong(); } if (nFlags & 2) { this.media = r.GetString2(); } }; UniMedia.prototype.createDuplicate = function () { var _ret = new UniMedia(); _ret.type = this.type; _ret.media = this.media; return _ret; }; UniMedia.prototype.fromXml = function (reader, name) { //TODO:Implement in children // if (name === ("audioCd")) // // this.type = null; // else if (name === ("wavAudioFile")) // Media.reset(new Logic::WavAudioFile(oReader)); // else if (name === ("audioFile")) // Media.reset(new Logic::MediaFile(oReader)); // else if (name === ("videoFile")) // Media.reset(new Logic::MediaFile(oReader)); // else if (name === ("quickTimeFile")) // Media.reset(new Logic::MediaFile(oReader)); // else Media.reset(); }; UniMedia.prototype.toXml = function (writer) { //TODO:Implement in children }; drawingConstructorsMap[AscDFH.historyitem_NvPr_SetUniMedia] = UniMedia; function NvPr() { CBaseFormatObject.call(this); this.isPhoto = null; this.userDrawn = null; this.ph = null; this.unimedia = null; } InitClass(NvPr, CBaseFormatObject, AscDFH.historyitem_type_NvPr); NvPr.prototype.setIsPhoto = function (isPhoto) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_NvPr_SetIsPhoto, this.isPhoto, isPhoto)); this.isPhoto = isPhoto; }; NvPr.prototype.setUserDrawn = function (userDrawn) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_NvPr_SetUserDrawn, this.userDrawn, userDrawn)); this.userDrawn = userDrawn; }; NvPr.prototype.setPh = function (ph) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_NvPr_SetPh, this.ph, ph)); this.ph = ph; }; NvPr.prototype.setUniMedia = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_NvPr_SetUniMedia, this.unimedia, pr)); this.unimedia = pr; }; NvPr.prototype.createDuplicate = function () { var duplicate = new NvPr(); duplicate.setIsPhoto(this.isPhoto); duplicate.setUserDrawn(this.userDrawn); if (this.ph != null) { duplicate.setPh(this.ph.createDuplicate()); } if (this.unimedia != null) { duplicate.setUniMedia(this.unimedia.createDuplicate()); } return duplicate; }; NvPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "isPhoto": { this.isPhoto = reader.GetValueBool(); break; } case "userDrawn": { this.userDrawn = reader.GetValueBool(); break; } } }; NvPr.prototype.readChildXml = function (name, reader) { switch (name) { case "ph": { let oPr = new Ph(); oPr.fromXml(reader); this.setPh(oPr); break; } } }; NvPr.prototype.toXml = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; this.toXml2(namespace_, writer); }; NvPr.prototype.toXml2 = function (strNS, writer) { writer.WriteXmlNodeStart(strNS + ":nvPr"); writer.WriteXmlNullableAttributeBool("isPhoto", this.isPhoto); writer.WriteXmlNullableAttributeBool("userDrawn", this.userDrawn); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.ph); //media.toXml(writer); // let namespace_extLst = "a"; // if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_extLst = "p"; // // writer.WriteArray(namespace_extLst + ":extLst", extLst); writer.WriteXmlNodeEnd(strNS + ":nvPr"); }; var szPh_full = 0, szPh_half = 1, szPh_quarter = 2; var orientPh_horz = 0, orientPh_vert = 1; function Ph() { CBaseFormatObject.call(this); this.hasCustomPrompt = null; this.idx = null; this.orient = null; this.sz = null; this.type = null; } InitClass(Ph, CBaseFormatObject, AscDFH.historyitem_type_Ph); Ph.prototype.createDuplicate = function () { var duplicate = new Ph(); duplicate.setHasCustomPrompt(this.hasCustomPrompt); duplicate.setIdx(this.idx); duplicate.setOrient(this.orient); duplicate.setSz(this.sz); duplicate.setType(this.type); return duplicate; }; Ph.prototype.setHasCustomPrompt = function (hasCustomPrompt) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Ph_SetHasCustomPrompt, this.hasCustomPrompt, hasCustomPrompt)); this.hasCustomPrompt = hasCustomPrompt; }; Ph.prototype.setIdx = function (idx) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_Ph_SetIdx, this.idx, idx)); this.idx = idx; }; Ph.prototype.setOrient = function (orient) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_Ph_SetOrient, this.orient, orient)); this.orient = orient; }; Ph.prototype.setSz = function (sz) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_Ph_SetSz, this.sz, sz)); this.sz = sz; }; Ph.prototype.setType = function (type) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_Ph_SetType, this.type, type)); this.type = type; }; Ph.prototype.GetOrientCode = function(sVal) { switch (sVal) { case "horz": { return orientPh_horz; } case "vert": { return orientPh_vert; } } return null; }; Ph.prototype.GetOrientByCode = function(nVal) { switch (nVal) { case orientPh_horz: { return "horz"; } case orientPh_vert: { return "vert"; } } return null; }; Ph.prototype.GetSzCode = function(sVal) { switch (sVal) { case "full": { return szPh_full; } case "half": { return szPh_half; } case "quarter": { return szPh_quarter; } } return null; }; Ph.prototype.GetSzByCode = function(nVal) { switch (nVal) { case szPh_full: { return "full"; } case szPh_half: { return "half"; } case szPh_quarter: { return "quarter"; } } return null; }; Ph.prototype.GetTypeCode = function(sVal) { switch (sVal) { case "body": { return AscFormat.phType_body; } case "chart": { return AscFormat.phType_chart; } case "clipArt": { return AscFormat.phType_clipArt; } case "ctrTitle": { return AscFormat.phType_ctrTitle; } case "dgm": { return AscFormat.phType_dgm; } case "dt": { return AscFormat.phType_dt; } case "ftr": { return AscFormat.phType_ftr; } case "hdr": { return AscFormat.phType_hdr; } case "media": { return AscFormat.phType_media; } case "obj": { return AscFormat.phType_obj; } case "pic": { return AscFormat.phType_pic; } case "sldImg": { return AscFormat.phType_sldImg; } case "sldNum": { return AscFormat.phType_sldNum; } case "subTitle": { return AscFormat.phType_subTitle; } case "tbl": { return AscFormat.phType_tbl; } case "title": { return AscFormat.phType_title; } } return null; }; Ph.prototype.GetTypeByCode = function(nVal) { switch (nVal) { case AscFormat.phType_body: { return "body"; } case AscFormat.phType_chart: { return "chart"; } case AscFormat.phType_clipArt: { return "clipArt"; } case AscFormat.phType_ctrTitle: { return "ctrTitle"; } case AscFormat.phType_dgm: { return "dgm"; } case AscFormat.phType_dt: { return "dt"; } case AscFormat.phType_ftr: { return "ftr"; } case AscFormat.phType_hdr: { return "hdr"; } case AscFormat.phType_media: { return "media"; } case AscFormat.phType_obj: { return "obj"; } case AscFormat.phType_pic: { return "pic"; } case AscFormat.phType_sldImg: { return "sldImg"; } case AscFormat.phType_sldNum: { return "sldNum"; } case AscFormat.phType_subTitle: { return "subTitle"; } case AscFormat.phType_tbl: { return "tbl"; } case AscFormat.phType_title: { return "title"; } } return null; }; Ph.prototype.readAttrXml = function (name, reader) { switch (name) { case "hasCustomPrompt": { this.setHasCustomPrompt(reader.GetValueBool()); break; } case "idx": { this.setIdx(reader.GetValue()); break; } case "orient": { let sVal = reader.GetValue(); let nVal = this.GetOrientCode(sVal); if(nVal !== null) { this.setOrient(nVal); } break; } case "sz": { let sVal = reader.GetValue(); let nVal = this.GetSzCode(sVal); if(nVal !== null) { this.setSz(nVal); } break; } case "type": { let sVal = reader.GetValue(); let nVal = this.GetTypeCode(sVal); if(nVal !== null) { this.setType(nVal); } break; } } }; Ph.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:ph"); writer.WriteXmlNullableAttributeString("type", this.GetTypeByCode(this.type)); writer.WriteXmlNullableAttributeString("orient", this.GetOrientByCode(this.orient)); writer.WriteXmlNullableAttributeString("sz", this.GetSzByCode(this.sz)); writer.WriteXmlNullableAttributeString("idx", this.idx); writer.WriteXmlNullableAttributeBool("hasCustomPrompt", this.hasCustomPrompt); writer.WriteXmlAttributesEnd(true); }; function fUpdateLocksValue(nLocks, nMask, bValue) { nLocks |= nMask; if (bValue) { nLocks |= (nMask << 1) } else { nLocks &= ~(nMask << 1) } return nLocks; } function fGetLockValue(nLocks, nMask) { if (nLocks & nMask) { return !!(nLocks & (nMask << 1)); } return undefined; } window['AscFormat'] = window['AscFormat'] || {}; window['AscFormat'].fUpdateLocksValue = fUpdateLocksValue; window['AscFormat'].fGetLockValue = fGetLockValue; function CNvUniSpPr() { CBaseNoIdObject.call(this); this.locks = null; this.stCnxIdx = null; this.stCnxId = null; this.endCnxIdx = null; this.endCnxId = null; } InitClass(CNvUniSpPr, CBaseNoIdObject, 0); CNvUniSpPr.prototype.Write_ToBinary = function (w) { if (AscFormat.isRealNumber(this.locks)) { w.WriteBool(true); w.WriteLong(this.locks); } else { w.WriteBool(false); } if (AscFormat.isRealNumber(this.stCnxIdx) && typeof (this.stCnxId) === "string" && this.stCnxId.length > 0) { w.WriteBool(true); w.WriteLong(this.stCnxIdx); w.WriteString2(this.stCnxId); } else { w.WriteBool(false); } if (AscFormat.isRealNumber(this.endCnxIdx) && typeof (this.endCnxId) === "string" && this.endCnxId.length > 0) { w.WriteBool(true); w.WriteLong(this.endCnxIdx); w.WriteString2(this.endCnxId); } else { w.WriteBool(false); } }; CNvUniSpPr.prototype.Read_FromBinary = function (r) { var bCnx = r.GetBool(); if (bCnx) { this.locks = r.GetLong(); } else { this.locks = null; } bCnx = r.GetBool(); if (bCnx) { this.stCnxIdx = r.GetLong(); this.stCnxId = r.GetString2(); } else { this.stCnxIdx = null; this.stCnxId = null; } bCnx = r.GetBool(); if (bCnx) { this.endCnxIdx = r.GetLong(); this.endCnxId = r.GetString2(); } else { this.endCnxIdx = null; this.endCnxId = null; } }; CNvUniSpPr.prototype.assignConnectors = function(aSpTree) { let bNeedSetStart = AscFormat.isRealNumber(this.stCnxIdFormat); let bNeedSetEnd = AscFormat.isRealNumber(this.endCnxIdFormat); if(bNeedSetStart || bNeedSetEnd) { for(let nSp = 0; nSp < aSpTree.length && (bNeedSetEnd || bNeedSetStart); ++nSp) { let oSp = aSpTree[nSp]; if(bNeedSetStart && oSp.getFormatId() === this.stCnxIdFormat) { this.stCnxId = oSp.Get_Id(); this.stCnxIdFormat = undefined; bNeedSetStart = false; } if(bNeedSetEnd && oSp.getFormatId() === this.endCnxIdFormat) { this.endCnxId = oSp.Get_Id(); this.endCnxIdFormat = undefined; bNeedSetEnd = false; } } } }; CNvUniSpPr.prototype.copy = function () { var _ret = new CNvUniSpPr(); _ret.locks = this.locks; _ret.stCnxId = this.stCnxId; _ret.stCnxIdx = this.stCnxIdx; _ret.endCnxId = this.endCnxId; _ret.endCnxIdx = this.endCnxIdx; return _ret; }; CNvUniSpPr.prototype.readChildXml = function (name, reader) { if (name.toLowerCase().indexOf("locks") > -1) { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); this.locks = 0; let oAttr = oNode.attributes; for (let sAttr in oAttr) { if (oAttr.hasOwnProperty(sAttr)) { let sVal = oAttr[sAttr]; if (sVal) { let bBoolVal = reader.GetBool(sVal); switch (sAttr) { case "txBox": { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.txBox, bBoolVal); break; } case "noAdjustHandles" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles, bBoolVal); break; } case "noChangeArrowheads" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads, bBoolVal); break; } case "noChangeAspect" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect, bBoolVal); break; } case "noChangeShapeType" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType, bBoolVal); break; } case "noEditPoints" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints, bBoolVal); break; } case "noGrp" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noGrp, bBoolVal); break; } case "noMove" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noMove, bBoolVal); break; } case "noResize" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noResize, bBoolVal); break; } case "noRot" : { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noRot, bBoolVal); break; } case "noSelect": { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noSelect, bBoolVal); break; } case "noTextEdit": { this.locks = fUpdateLocksValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit, bBoolVal); break; } } } } } } else if (name === "stCxn" || name === "endCxn") { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); if(name === "stCxn") { this.stCnxIdx = parseInt(oNode.attributes["idx"]); this.stCnxIdFormat = parseInt(oNode.attributes["id"]); } if(name === "endCxn") { this.endCnxIdx = parseInt(oNode.attributes["idx"]); this.endCnxIdFormat = parseInt(oNode.attributes["id"]); } reader.context.addConnectorsPr(this); //TODO: connections } }; CNvUniSpPr.prototype.toXmlCxn = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvCxnSpPr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:cxnSpLocks"); writer.WriteXmlNullableAttributeBool("txBox", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.txBox)); writer.WriteXmlNullableAttributeBool("noAdjustHandles", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles)); writer.WriteXmlNullableAttributeBool("noChangeArrowheads", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads)); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noChangeShapeType", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType)); writer.WriteXmlNullableAttributeBool("noEditPoints", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noTextEdit", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit)); writer.WriteXmlAttributesEnd(true); if (AscFormat.isRealNumber(this.stCnxIdx) && this.stCnxId) { let nId = null; let oSp = AscCommon.g_oTableId.Get_ById(this.stCnxId); if(oSp) { nId = oSp.getFormatId && oSp.getFormatId(); } if(AscFormat.isRealNumber(nId)) { writer.WriteXmlNodeStart("a:stCxn"); writer.WriteXmlAttributeUInt("id", nId); writer.WriteXmlAttributeUInt("idx", this.stCnxIdx); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:stCxn"); } } if (AscFormat.isRealNumber(this.endCnxIdx) && this.endCnxId) { let nId = null; let oSp = AscCommon.g_oTableId.Get_ById(this.endCnxId); if(oSp) { nId = oSp.getFormatId && oSp.getFormatId(); } if(AscFormat.isRealNumber(nId)) { writer.WriteXmlNodeStart("a:endCxn"); writer.WriteXmlAttributeUInt("id", nId); writer.WriteXmlAttributeUInt("idx", this.endCnxIdx); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:endCxn"); } } writer.WriteXmlNodeEnd(namespace_ + ":cNvCxnSpPr"); }; CNvUniSpPr.prototype.toXmlGrFrame = function (writer) { let namespace_ = "a"; let namespaceLock_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { namespaceLock_ = "a"; namespace_ = "wp"; } else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvGraphicFramePr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart(namespaceLock_ + ":graphicFrameLocks"); writer.WriteXmlAttributeString("xmlns:a", "http://schemas.openxmlformats.org/drawingml/2006/main"); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noDrilldown", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noDrilldown)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlAttributesEnd(true); writer.WriteXmlNodeEnd(namespace_ + ":cNvGraphicFramePr"); }; CNvUniSpPr.prototype.toXmlGrSp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; if (!fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp) === undefined) { writer.WriteXmlString("<" + namespace_ + ":cNvGrpSpPr/>"); return; } writer.WriteXmlString("<" + namespace_ + ":cNvGrpSpPr>"); writer.WriteXmlNodeStart("a:grpSpLocks"); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noUngrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp)); writer.WriteXmlAttributesEnd(true); writer.WriteXmlString("</" + namespace_ + ":cNvGrpSpPr>"); }; CNvUniSpPr.prototype.toXmlGrSp2 = function (writer, strNS) { if (fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) === undefined && fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp) === undefined) { writer.WriteXmlString("<" + strNS + ":cNvGrpSpPr/>"); return; } writer.WriteXmlNodeStart(strNS + ":cNvGrpSpPr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("a:grpSpLocks"); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noUngrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noUngrp)); writer.WriteXmlAttributesEnd(true); writer.WriteXmlNodeEnd(strNS + ":cNvGrpSpPr"); }; CNvUniSpPr.prototype.toXmlPic = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvPicPr"); //writer.WriteXmlNullableAttributeString("preferRelativeResize", preferRelativeResize); writer.WriteXmlAttributesEnd(); if (fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noCrop) !== undefined) { writer.WriteXmlNodeStart("a:picLocks"); writer.WriteXmlNullableAttributeBool("noAdjustHandles", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles)); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noChangeArrowheads", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads)); writer.WriteXmlNullableAttributeBool("noChangeShapeType", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType)); writer.WriteXmlNullableAttributeBool("noEditPoints", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noCrop", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noCrop)); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(namespace_ + ":cNvPicPr"); }; CNvUniSpPr.prototype.toXmlSp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":cNvSpPr"); //writer.WriteXmlAttributeBool("txBox", this.txBox); writer.WriteXmlAttributesEnd(); if (fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect) !== undefined || fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit) !== undefined) { writer.WriteXmlNodeStart("a:spLocks"); writer.WriteXmlNullableAttributeBool("noAdjustHandles", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noAdjustHandles)); writer.WriteXmlNullableAttributeBool("noChangeArrowheads", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeArrowheads)); writer.WriteXmlNullableAttributeBool("noChangeAspect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeAspect)); writer.WriteXmlNullableAttributeBool("noChangeShapeType", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noChangeShapeType)); writer.WriteXmlNullableAttributeBool("noEditPoints", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noEditPoints)); writer.WriteXmlNullableAttributeBool("noGrp", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noGrp)); writer.WriteXmlNullableAttributeBool("noMove", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noMove)); writer.WriteXmlNullableAttributeBool("noResize", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noResize)); writer.WriteXmlNullableAttributeBool("noRot", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noRot)); writer.WriteXmlNullableAttributeBool("noSelect", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noSelect)); writer.WriteXmlNullableAttributeBool("noTextEdit", fGetLockValue(this.locks, AscFormat.LOCKS_MASKS.noTextEdit)); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(namespace_ + ":cNvSpPr"); }; CNvUniSpPr.prototype.getLocks = function() { if(!AscFormat.isRealNumber(this.locks)) { return 0; } return this.locks; }; function UniNvPr() { CBaseFormatObject.call(this); this.cNvPr = null; this.UniPr = null; this.nvPr = null; this.nvUniSpPr = null; this.setCNvPr(new CNvPr()); this.setNvPr(new NvPr()); this.setUniSpPr(new CNvUniSpPr()); } InitClass(UniNvPr, CBaseFormatObject, AscDFH.historyitem_type_UniNvPr); UniNvPr.prototype.setCNvPr = function (cNvPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_UniNvPr_SetCNvPr, this.cNvPr, cNvPr)); this.cNvPr = cNvPr; }; UniNvPr.prototype.setUniSpPr = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_UniNvPr_SetUniSpPr, this.nvUniSpPr, pr)); this.nvUniSpPr = pr; }; UniNvPr.prototype.setUniPr = function (uniPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_UniNvPr_SetUniPr, this.UniPr, uniPr)); this.UniPr = uniPr; }; UniNvPr.prototype.setNvPr = function (nvPr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_UniNvPr_SetNvPr, this.nvPr, nvPr)); this.nvPr = nvPr; }; UniNvPr.prototype.createDuplicate = function () { var duplicate = new UniNvPr(); this.cNvPr && duplicate.setCNvPr(this.cNvPr.createDuplicate()); this.nvPr && duplicate.setNvPr(this.nvPr.createDuplicate()); this.nvUniSpPr && duplicate.setUniSpPr(this.nvUniSpPr.copy()); return duplicate; }; UniNvPr.prototype.Write_ToBinary2 = function (w) { w.WriteLong(this.getObjectType()); w.WriteString2(this.Id); writeObject(w, this.cNvPr); writeObject(w, this.nvPr); }; UniNvPr.prototype.Read_FromBinary2 = function (r) { this.Id = r.GetString2(); this.cNvPr = readObject(r); this.nvPr = readObject(r); }; UniNvPr.prototype.readChildXml = function (name, reader) { switch (name) { case "cNvPr": { this.cNvPr.fromXml(reader); break; } case "cNvCxnSpPr": case "cNvGraphicFramePr": case "cNvGrpSpPr": case "cNvPicPr": case "cNvSpPr": { this.nvUniSpPr.fromXml(reader); break; } case "nvPr": { this.nvPr.fromXml(reader); break; } } }; UniNvPr.prototype.getLocks = function() { if(this.nvUniSpPr) { return this.nvUniSpPr.getLocks(); } return 0; }; UniNvPr.prototype.toXmlGrFrame = function (writer) { let namespace_ = "a"; if ((writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) && writer.context.groupIndex >= 0) { this.cNvPr.toXml2("wpg", writer); writer.WriteXmlString("<wpg:cNvFrPr/>"); return; } else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX && writer.context.groupIndex >= 0) { writer.WriteXmlNodeStart("xdr:nvGraphicFramePr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, "xdr:cNvPr"); this.nvUniSpPr.toXmlGrFrame(writer); writer.WriteXmlNodeEnd("xdr:nvGraphicFramePr"); return; } if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvGraphicFramePr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); this.nvUniSpPr.toXmlGrFrame(writer); this.nvPr.toXml(writer); writer.WriteXmlNodeEnd(namespace_ + ":nvGraphicFramePr"); }; UniNvPr.prototype.toXmlCxn = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvCxnSpPr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml2(namespace_, writer); this.nvUniSpPr.toXmlCxn(writer); if (writer.context.docType !== AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS && writer.context.docType !== AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) { this.nvPr.toXml2(namespace_, writer); } writer.WriteXmlNodeEnd(namespace_ + ":nvCxnSpPr"); }; UniNvPr.prototype.toXmlSp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wps"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvSpPr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); this.nvUniSpPr.toXmlSp(writer); if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) this.nvPr.toXml(writer); writer.WriteXmlNodeEnd(namespace_ + ":nvSpPr"); }; UniNvPr.prototype.toXmlPic = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "pic"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvPicPr"); writer.WriteXmlAttributesEnd(); if (this.cNvPr) { this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); } if (this.nvUniSpPr) { this.nvUniSpPr.toXmlPic(writer); } if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) { if (this.nvPr) { this.nvPr.toXml(writer); } } writer.WriteXmlNodeEnd(namespace_ + ":nvPicPr"); }; UniNvPr.prototype.toXmlGrp = function (writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wpg"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":nvGrpSpPr"); writer.WriteXmlAttributesEnd(); this.cNvPr.toXml(writer, namespace_ + ":cNvPr"); this.nvUniSpPr.toXmlGrSp(writer); if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) { this.nvPr.toXml(writer); } writer.WriteXmlNodeEnd(namespace_ + ":nvGrpSpPr"); }; function StyleRef() { CBaseNoIdObject.call(this); this.idx = 0; this.Color = new CUniColor(); } InitClass(StyleRef, CBaseNoIdObject, 0); StyleRef.prototype.isIdentical = function (styleRef) { if (styleRef == null) { return false; } if (this.idx !== styleRef.idx) { return false; } if(this.Color && !styleRef.Color || !this.Color && styleRef.Color) { return false; } if (!this.Color.IsIdentical(styleRef.Color)) { return false; } return true; }; StyleRef.prototype.getObjectType = function () { return AscDFH.historyitem_type_StyleRef; }; StyleRef.prototype.setIdx = function (idx) { this.idx = idx; }; StyleRef.prototype.setColor = function (color) { this.Color = color; }; StyleRef.prototype.createDuplicate = function () { var duplicate = new StyleRef(); duplicate.setIdx(this.idx); if (this.Color) duplicate.setColor(this.Color.createDuplicate()); return duplicate; }; StyleRef.prototype.Refresh_RecalcData = function () { }; StyleRef.prototype.Write_ToBinary = function (w) { writeLong(w, this.idx); w.WriteBool(isRealObject(this.Color)); if (isRealObject(this.Color)) { this.Color.Write_ToBinary(w); } }; StyleRef.prototype.Read_FromBinary = function (r) { this.idx = readLong(r); if (r.GetBool()) { this.Color = new CUniColor(); this.Color.Read_FromBinary(r); } }; StyleRef.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (this.Color && this.Color.isCorrect()) { return this.Color.getNoStyleUnicolor(nIdx, aColors); } return null; }; StyleRef.prototype.readAttrXml = function (name, reader) { switch (name) { case "idx": { this.idx = reader.GetValueInt(); break; } } }; StyleRef.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { this.Color.fromXml(reader, name); } }; StyleRef.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlNullableAttributeUInt("idx", this.idx); writer.WriteXmlAttributesEnd(); if (this.Color) { this.Color.toXml(writer); } writer.WriteXmlNodeEnd(sName); }; function FontRef() { CBaseNoIdObject.call(this); this.idx = AscFormat.fntStyleInd_none; this.Color = null; } InitClass(FontRef, CBaseNoIdObject, 0); FontRef.prototype.setIdx = function (idx) { this.idx = idx; }; FontRef.prototype.setColor = function (color) { this.Color = color; }; FontRef.prototype.createDuplicate = function () { var duplicate = new FontRef(); duplicate.setIdx(this.idx); if (this.Color) duplicate.setColor(this.Color.createDuplicate()); return duplicate; }; FontRef.prototype.Write_ToBinary = function (w) { writeLong(w, this.idx); w.WriteBool(isRealObject(this.Color)); if (isRealObject(this.Color)) { this.Color.Write_ToBinary(w); } }; FontRef.prototype.Read_FromBinary = function (r) { this.idx = readLong(r); if (r.GetBool()) { this.Color = new CUniColor(); this.Color.Read_FromBinary(r); } }; FontRef.prototype.getNoStyleUnicolor = function (nIdx, aColors) { if (this.Color && this.Color.isCorrect()) { return this.Color.getNoStyleUnicolor(nIdx, aColors); } return null; }; FontRef.prototype.getFirstPartThemeName = function () { if (this.idx === AscFormat.fntStyleInd_major) { return "+mj-"; } return "+mn-"; }; FontRef.prototype.readAttrXml = function (name, reader) { switch (name) { case "idx": { let sVal = reader.GetValue(); if (sVal === "major") { this.idx = AscFormat.fntStyleInd_major; } else if (sVal === "minor") { this.idx = AscFormat.fntStyleInd_minor; } else if (sVal === "none") { this.idx = AscFormat.fntStyleInd_none; } break; } } }; FontRef.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { let oColor = new CUniColor(); oColor.fromXml(reader, name); this.Color = oColor; } }; FontRef.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); let sVal; switch (this.idx) { case AscFormat.fntStyleInd_major: { sVal = "major"; break; } case AscFormat.fntStyleInd_minor: { sVal = "minor"; break; } case AscFormat.fntStyleInd_none: { sVal = "none"; break; } } writer.WriteXmlAttributeString("idx", sVal); writer.WriteXmlAttributesEnd(); if (this.Color) { this.Color.toXml(writer); } writer.WriteXmlNodeEnd(sName); }; function CShapeStyle() { CBaseFormatObject.call(this); this.lnRef = null; this.fillRef = null; this.effectRef = null; this.fontRef = null; } InitClass(CShapeStyle, CBaseFormatObject, AscDFH.historyitem_type_ShapeStyle); CShapeStyle.prototype.merge = function (style) { if (style != null) { if (style.lnRef != null) { this.lnRef = style.lnRef.createDuplicate(); } if (style.fillRef != null) { this.fillRef = style.fillRef.createDuplicate(); } if (style.effectRef != null) { this.effectRef = style.effectRef.createDuplicate(); } if (style.fontRef != null) { this.fontRef = style.fontRef.createDuplicate(); } } }; CShapeStyle.prototype.createDuplicate = function () { var duplicate = new CShapeStyle(); if (this.lnRef != null) { duplicate.setLnRef(this.lnRef.createDuplicate()); } if (this.fillRef != null) { duplicate.setFillRef(this.fillRef.createDuplicate()); } if (this.effectRef != null) { duplicate.setEffectRef(this.effectRef.createDuplicate()); } if (this.fontRef != null) { duplicate.setFontRef(this.fontRef.createDuplicate()); } return duplicate; }; CShapeStyle.prototype.setLnRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetLnRef, this.lnRef, pr)); this.lnRef = pr; }; CShapeStyle.prototype.setFillRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetFillRef, this.fillRef, pr)); this.fillRef = pr; }; CShapeStyle.prototype.setFontRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetFontRef, this.fontRef, pr)); this.fontRef = pr; }; CShapeStyle.prototype.setEffectRef = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ShapeStyle_SetEffectRef, this.effectRef, pr)); this.effectRef = pr; }; CShapeStyle.prototype.readChildXml = function (name, reader) { switch (name) { case "effectRef": { let oStyleRef = new StyleRef(); oStyleRef.fromXml(reader); this.setEffectRef(oStyleRef); break; } case "fillRef": { let oStyleRef = new StyleRef(); oStyleRef.fromXml(reader); this.setFillRef(oStyleRef); break; } case "fontRef": { let oStyleRef = new FontRef(); oStyleRef.fromXml(reader); this.setFontRef(oStyleRef); break; } case "lnRef": { let oStyleRef = new StyleRef(); oStyleRef.fromXml(reader); this.setLnRef(oStyleRef); break; } } }; CShapeStyle.prototype.toXml = function (writer) { let sNS = "a"; let oContext = writer.context; if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) sNS = "wps"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) sNS = "xdr"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) sNS = "a"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) sNS = "cdr"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) sNS = "dgm"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) sNS = "p"; else if (oContext.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) sNS = "dsp"; let sName = sNS + ":style"; writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); this.lnRef.toXml(writer, "a:lnRef"); this.fillRef.toXml(writer, "a:fillRef"); this.effectRef.toXml(writer, "a:effectRef"); this.fontRef.toXml(writer, "a:fontRef"); writer.WriteXmlNodeEnd(sName); }; var LINE_PRESETS_MAP = {}; LINE_PRESETS_MAP["line"] = true; LINE_PRESETS_MAP["bracePair"] = true; LINE_PRESETS_MAP["leftBrace"] = true; LINE_PRESETS_MAP["rightBrace"] = true; LINE_PRESETS_MAP["bracketPair"] = true; LINE_PRESETS_MAP["leftBracket"] = true; LINE_PRESETS_MAP["rightBracket"] = true; LINE_PRESETS_MAP["bentConnector2"] = true; LINE_PRESETS_MAP["bentConnector3"] = true; LINE_PRESETS_MAP["bentConnector4"] = true; LINE_PRESETS_MAP["bentConnector5"] = true; LINE_PRESETS_MAP["curvedConnector2"] = true; LINE_PRESETS_MAP["curvedConnector3"] = true; LINE_PRESETS_MAP["curvedConnector4"] = true; LINE_PRESETS_MAP["curvedConnector5"] = true; LINE_PRESETS_MAP["straightConnector1"] = true; LINE_PRESETS_MAP["arc"] = true; function CreateDefaultShapeStyle(preset) { var b_line = typeof preset === "string" && LINE_PRESETS_MAP[preset]; var tx_color = b_line; var unicolor; var style = new CShapeStyle(); var lnRef = new StyleRef(); lnRef.setIdx(b_line ? 1 : 2); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); var mod = new CColorMod(); mod.setName("shade"); mod.setVal(50000); unicolor.setMods(new CColorModifiers()); unicolor.Mods.addMod(mod); lnRef.setColor(unicolor); style.setLnRef(lnRef); var fillRef = new StyleRef(); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); fillRef.setIdx(b_line ? 0 : 1); fillRef.setColor(unicolor); style.setFillRef(fillRef); var effectRef = new StyleRef(); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); effectRef.setIdx(0); effectRef.setColor(unicolor); style.setEffectRef(effectRef); var fontRef = new FontRef(); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(tx_color ? 15 : 12); fontRef.setIdx(AscFormat.fntStyleInd_minor); fontRef.setColor(unicolor); style.setFontRef(fontRef); return style; } function CXfrm() { CBaseFormatObject.call(this); this.offX = null; this.offY = null; this.extX = null; this.extY = null; this.chOffX = null; this.chOffY = null; this.chExtX = null; this.chExtY = null; this.flipH = null; this.flipV = null; this.rot = null; } InitClass(CXfrm, CBaseFormatObject, AscDFH.historyitem_type_Xfrm); CXfrm.prototype.isNotNull = function () { return isRealNumber(this.offX) && isRealNumber(this.offY) && isRealNumber(this.extX) && isRealNumber(this.extY); }; CXfrm.prototype.isNotNullForGroup = function () { return isRealNumber(this.offX) && isRealNumber(this.offY) && isRealNumber(this.chOffX) && isRealNumber(this.chOffY) && isRealNumber(this.extX) && isRealNumber(this.extY) && isRealNumber(this.chExtX) && isRealNumber(this.chExtY); }; CXfrm.prototype.isZero = function () { return ( this.offX === 0 && this.offY === 0 && this.extX === 0 && this.extY === 0 ); }; CXfrm.prototype.isZeroCh = function () { return ( this.chOffX === 0 && this.chOffY === 0 && this.chExtX === 0 && this.chExtY === 0 ); }; CXfrm.prototype.isZeroInGroup = function () { return this.isZero() && this.isZeroCh(); }; CXfrm.prototype.isEqual = function (xfrm) { return xfrm && this.offX === xfrm.offX && this.offY === xfrm.offY && this.extX === xfrm.extX && this.extY === xfrm.extY && this.chOffX === xfrm.chOffX && this.chOffY === xfrm.chOffY && this.chExtX === xfrm.chExtX && this.chExtY === xfrm.chExtY; }; CXfrm.prototype.merge = function (xfrm) { if (xfrm.offX != null) { this.offX = xfrm.offX; } if (xfrm.offY != null) { this.offY = xfrm.offY; } if (xfrm.extX != null) { this.extX = xfrm.extX; } if (xfrm.extY != null) { this.extY = xfrm.extY; } if (xfrm.chOffX != null) { this.chOffX = xfrm.chOffX; } if (xfrm.chOffY != null) { this.chOffY = xfrm.chOffY; } if (xfrm.chExtX != null) { this.chExtX = xfrm.chExtX; } if (xfrm.chExtY != null) { this.chExtY = xfrm.chExtY; } if (xfrm.flipH != null) { this.flipH = xfrm.flipH; } if (xfrm.flipV != null) { this.flipV = xfrm.flipV; } if (xfrm.rot != null) { this.rot = xfrm.rot; } }; CXfrm.prototype.createDuplicate = function () { var duplicate = new CXfrm(); duplicate.setOffX(this.offX); duplicate.setOffY(this.offY); duplicate.setExtX(this.extX); duplicate.setExtY(this.extY); duplicate.setChOffX(this.chOffX); duplicate.setChOffY(this.chOffY); duplicate.setChExtX(this.chExtX); duplicate.setChExtY(this.chExtY); duplicate.setFlipH(this.flipH); duplicate.setFlipV(this.flipV); duplicate.setRot(this.rot); return duplicate; }; CXfrm.prototype.setParent = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_Xfrm_SetParent, this.parent, pr)); this.parent = pr; }; CXfrm.prototype.setOffX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetOffX, this.offX, pr)); this.offX = pr; this.handleUpdatePosition(); }; CXfrm.prototype.setOffY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetOffY, this.offY, pr)); this.offY = pr; this.handleUpdatePosition(); }; CXfrm.prototype.setExtX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetExtX, this.extX, pr)); this.extX = pr; this.handleUpdateExtents(true); }; CXfrm.prototype.setExtY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetExtY, this.extY, pr)); this.extY = pr; this.handleUpdateExtents(false); }; CXfrm.prototype.setChOffX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChOffX, this.chOffX, pr)); this.chOffX = pr; this.handleUpdateChildOffset(); }; CXfrm.prototype.setChOffY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChOffY, this.chOffY, pr)); this.chOffY = pr; this.handleUpdateChildOffset(); }; CXfrm.prototype.setChExtX = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChExtX, this.chExtX, pr)); this.chExtX = pr; this.handleUpdateChildExtents(); }; CXfrm.prototype.setChExtY = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetChExtY, this.chExtY, pr)); this.chExtY = pr; this.handleUpdateChildExtents(); }; CXfrm.prototype.setFlipH = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Xfrm_SetFlipH, this.flipH, pr)); this.flipH = pr; this.handleUpdateFlip(); }; CXfrm.prototype.setFlipV = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_Xfrm_SetFlipV, this.flipV, pr)); this.flipV = pr; this.handleUpdateFlip(); }; CXfrm.prototype.setRot = function (pr) { History.CanAddChanges() && History.Add(new CChangesDrawingsDouble(this, AscDFH.historyitem_Xfrm_SetRot, this.rot, pr)); this.rot = pr; this.handleUpdateRot(); }; CXfrm.prototype.handleUpdatePosition = function () { if (this.parent && this.parent.handleUpdatePosition) { this.parent.handleUpdatePosition(); } }; CXfrm.prototype.handleUpdateExtents = function (bExtX) { if (this.parent && this.parent.handleUpdateExtents) { this.parent.handleUpdateExtents(bExtX); } }; CXfrm.prototype.handleUpdateChildOffset = function () { if (this.parent && this.parent.handleUpdateChildOffset) { this.parent.handleUpdateChildOffset(); } }; CXfrm.prototype.handleUpdateChildExtents = function () { if (this.parent && this.parent.handleUpdateChildExtents) { this.parent.handleUpdateChildExtents(); } }; CXfrm.prototype.handleUpdateFlip = function () { if (this.parent && this.parent.handleUpdateFlip) { this.parent.handleUpdateFlip(); } }; CXfrm.prototype.handleUpdateRot = function () { if (this.parent && this.parent.handleUpdateRot) { this.parent.handleUpdateRot(); } }; CXfrm.prototype.Refresh_RecalcData = function (data) { switch (data.Type) { case AscDFH.historyitem_Xfrm_SetOffX: { this.handleUpdatePosition(); break; } case AscDFH.historyitem_Xfrm_SetOffY: { this.handleUpdatePosition(); break; } case AscDFH.historyitem_Xfrm_SetExtX: { this.handleUpdateExtents(); break; } case AscDFH.historyitem_Xfrm_SetExtY: { this.handleUpdateExtents(); break; } case AscDFH.historyitem_Xfrm_SetChOffX: { this.handleUpdateChildOffset(); break; } case AscDFH.historyitem_Xfrm_SetChOffY: { this.handleUpdateChildOffset(); break; } case AscDFH.historyitem_Xfrm_SetChExtX: { this.handleUpdateChildExtents(); break; } case AscDFH.historyitem_Xfrm_SetChExtY: { this.handleUpdateChildExtents(); break; } case AscDFH.historyitem_Xfrm_SetFlipH: { this.handleUpdateFlip(); break; } case AscDFH.historyitem_Xfrm_SetFlipV: { this.handleUpdateFlip(); break; } case AscDFH.historyitem_Xfrm_SetRot: { this.handleUpdateRot(); break; } } }; CXfrm.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { break; } } //TODO:Implement in children }; CXfrm.prototype.fromXml = function (reader) { this.readAttr(reader); var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { if ("off" === reader.GetNameNoNS()) { this.readAttrOff(reader, this.setOffX, this.setOffY); } else if ("ext" === reader.GetNameNoNS()) { this.readAttrExt(reader, this.setExtX, this.setExtY); } else if ("chOff" === reader.GetNameNoNS()) { this.readAttrOff(reader, this.setChOffX, this.setChOffY); } else if ("chExt" === reader.GetNameNoNS()) { this.readAttrExt(reader, this.setChExtX, this.setChExtY); } } }; CXfrm.prototype.toXml = function (writer, name) { writer.WriteXmlNodeStart(name); if (null !== this.rot) { writer.WriteXmlAttributeNumber("rot", Math.round(this.rot * 180 * 60000 / Math.PI)); } writer.WriteXmlNullableAttributeBool("flipH", this.flipH); writer.WriteXmlNullableAttributeBool("flipV", this.flipV); writer.WriteXmlAttributesEnd(); if (null !== this.offX || null !== this.offY) { writer.WriteXmlNodeStart("a:off"); if (null !== this.offX) { writer.WriteXmlAttributeNumber("x", Math.round(this.offX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.offY) { writer.WriteXmlAttributeNumber("y", Math.round(this.offY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } if (null !== this.extX || null !== this.extY) { writer.WriteXmlNodeStart("a:ext"); if (null !== this.extX) { writer.WriteXmlAttributeNumber("cx", Math.round(this.extX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.extY) { writer.WriteXmlAttributeNumber("cy", Math.round(this.extY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } if (null !== this.chOffX || null !== this.chOffY) { writer.WriteXmlNodeStart("a:chOff"); if (null !== this.chOffX) { writer.WriteXmlAttributeNumber("x", Math.round(this.chOffX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.chOffY) { writer.WriteXmlAttributeNumber("y", Math.round(this.chOffY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } if (null !== this.chExtX || null !== this.chExtY) { writer.WriteXmlNodeStart("a:chExt"); if (null !== this.chExtX) { writer.WriteXmlAttributeNumber("cx", Math.round(this.chExtX * AscCommon.c_dScalePPTXSizes)); } if (null !== this.chExtY) { writer.WriteXmlAttributeNumber("cy", Math.round(this.chExtY * AscCommon.c_dScalePPTXSizes)); } writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(name); }; CXfrm.prototype.readAttr = function (reader) { while (reader.MoveToNextAttribute()) { if ("flipH" === reader.GetName()) { this.setFlipH(reader.GetValueBool()); } else if ("flipV" === reader.GetName()) { this.setFlipV(reader.GetValueBool()); } else if ("rot" === reader.GetName()) { this.setRot((reader.GetValueInt() / 60000) * Math.PI / 180); } } }; CXfrm.prototype.readAttrOff = function (reader, fSetX, fSetY) { while (reader.MoveToNextAttribute()) { if ("x" === reader.GetName()) { fSetX.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } else if ("y" === reader.GetName()) { fSetY.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } } }; CXfrm.prototype.readAttrExt = function (reader, fSetCX, fSetCY) { while (reader.MoveToNextAttribute()) { if ("cx" === reader.GetName()) { fSetCX.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } else if ("cy" === reader.GetName()) { fSetCY.call(this, reader.GetValueInt() / AscCommon.c_dScalePPTXSizes); } } }; function CEffectProperties() { CBaseNoIdObject.call(this); this.EffectDag = null; this.EffectLst = null; } InitClass(CEffectProperties, CBaseNoIdObject, 0); CEffectProperties.prototype.createDuplicate = function () { var oCopy = new CEffectProperties(); if (this.EffectDag) { oCopy.EffectDag = this.EffectDag.createDuplicate(); } if (this.EffectLst) { oCopy.EffectLst = this.EffectLst.createDuplicate(); } return oCopy; }; CEffectProperties.prototype.Write_ToBinary = function (w) { var nFlags = 0; if (this.EffectDag) { nFlags |= 1; } if (this.EffectLst) { nFlags |= 2; } w.WriteLong(nFlags); if (this.EffectDag) { this.EffectDag.Write_ToBinary(w); } if (this.EffectLst) { this.EffectLst.Write_ToBinary(w); } }; CEffectProperties.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.EffectDag = new CEffectContainer(); this.EffectDag.Read_FromBinary(r); } if (nFlags & 2) { this.EffectLst = new CEffectLst(); this.EffectLst.Read_FromBinary(r); } }; CEffectProperties.prototype.fromXml = function (reader, name) { if (name === "effectLst") { this.EffectLst = new CEffectLst(); this.EffectLst.fromXml(reader); } else if (name === "effectDag") { this.EffectDag = new CEffectContainer(); this.EffectDag.fromXml(reader); } }; CEffectProperties.prototype.toXml = function (writer) { if (this.EffectLst) { this.EffectLst.toXml(writer, "effectLst"); } else if (this.EffectDag) { this.EffectDag.toXml(writer, "effectDag"); } }; function CEffectLst() { CBaseNoIdObject.call(this); this.blur = null; this.fillOverlay = null; this.glow = null; this.innerShdw = null; this.outerShdw = null; this.prstShdw = null; this.reflection = null; this.softEdge = null; } InitClass(CEffectLst, CBaseNoIdObject, 0); CEffectLst.prototype.createDuplicate = function () { var oCopy = new CEffectLst(); if (this.blur) { oCopy.blur = this.blur.createDuplicate(); } if (this.fillOverlay) { oCopy.fillOverlay = this.fillOverlay.createDuplicate(); } if (this.glow) { oCopy.glow = this.glow.createDuplicate(); } if (this.innerShdw) { oCopy.innerShdw = this.innerShdw.createDuplicate(); } if (this.outerShdw) { oCopy.outerShdw = this.outerShdw.createDuplicate(); } if (this.prstShdw) { oCopy.prstShdw = this.prstShdw.createDuplicate(); } if (this.reflection) { oCopy.reflection = this.reflection.createDuplicate(); } if (this.softEdge) { oCopy.softEdge = this.softEdge.createDuplicate(); } return oCopy; }; CEffectLst.prototype.Write_ToBinary = function (w) { var nFlags = 0; if (this.blur) { nFlags |= 1; } if (this.fillOverlay) { nFlags |= 2; } if (this.glow) { nFlags |= 4; } if (this.innerShdw) { nFlags |= 8; } if (this.outerShdw) { nFlags |= 16; } if (this.prstShdw) { nFlags |= 32; } if (this.reflection) { nFlags |= 64; } if (this.softEdge) { nFlags |= 128; } w.WriteLong(nFlags); if (this.blur) { this.blur.Write_ToBinary(w); } if (this.fillOverlay) { this.fillOverlay.Write_ToBinary(w); } if (this.glow) { this.glow.Write_ToBinary(w); } if (this.innerShdw) { this.innerShdw.Write_ToBinary(w); } if (this.outerShdw) { this.outerShdw.Write_ToBinary(w); } if (this.prstShdw) { this.prstShdw.Write_ToBinary(w); } if (this.reflection) { this.reflection.Write_ToBinary(w); } if (this.softEdge) { this.softEdge.Write_ToBinary(w); } }; CEffectLst.prototype.Read_FromBinary = function (r) { var nFlags = r.GetLong(); if (nFlags & 1) { this.blur = new CBlur(); r.GetLong(); this.blur.Read_FromBinary(r); } if (nFlags & 2) { this.fillOverlay = new CFillOverlay(); r.GetLong(); this.fillOverlay.Read_FromBinary(r); } if (nFlags & 4) { this.glow = new CGlow(); r.GetLong(); this.glow.Read_FromBinary(r); } if (nFlags & 8) { this.innerShdw = new CInnerShdw(); r.GetLong(); this.innerShdw.Read_FromBinary(r); } if (nFlags & 16) { this.outerShdw = new COuterShdw(); r.GetLong(); this.outerShdw.Read_FromBinary(r); } if (nFlags & 32) { this.prstShdw = new CPrstShdw(); r.GetLong(); this.prstShdw.Read_FromBinary(r); } if (nFlags & 64) { this.reflection = new CReflection(); r.GetLong(); this.reflection.Read_FromBinary(r); } if (nFlags & 128) { this.softEdge = new CSoftEdge(); r.GetLong(); this.softEdge.Read_FromBinary(r); } }; CEffectLst.prototype.readChildXml = function (name, reader) { if (name === "blur") { this.blur = new CBlur(); this.blur.fromXml(reader); } else if (name === "fillOverlay") { this.fillOverlay = new CFillOverlay(); this.fillOverlay.fromXml(reader); } else if (name === "glow") { this.glow = new CGlow(); this.glow.fromXml(reader); } else if (name === "innerShdw") { this.innerShdw = new CInnerShdw(); this.innerShdw.fromXml(reader); } else if (name === "outerShdw") { this.outerShdw = new COuterShdw(); this.outerShdw.fromXml(reader); } else if (name === "prstShdw") { this.prstShdw = new CPrstShdw(); this.prstShdw.fromXml(reader); } else if (name === "reflection") { this.reflection = new CReflection(); this.reflection.fromXml(reader); } else if (name === "softEdge") { this.softEdge = new CSoftEdge(); this.softEdge.fromXml(reader); } }; CEffectLst.prototype.toXml = function (writer) { if (!this.blur && !this.fillOverlay && !this.glow && !this.innerShdw && !this.outerShdw && !this.prstShdw && !this.reflection && !this.softEdge) { writer.WriteXmlString("<a:effectLst/>"); return; } writer.WriteXmlNodeStart("a:effectLst"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.blur); writer.WriteXmlNullable(this.fillOverlay); writer.WriteXmlNullable(this.glow); writer.WriteXmlNullable(this.innerShdw); writer.WriteXmlNullable(this.outerShdw); writer.WriteXmlNullable(this.prstShdw); writer.WriteXmlNullable(this.reflection); writer.WriteXmlNullable(this.softEdge); writer.WriteXmlNodeEnd("a:effectLst"); }; function CSpPr() { CBaseFormatObject.call(this); this.bwMode = 0; this.xfrm = null; this.geometry = null; this.Fill = null; this.ln = null; this.parent = null; this.effectProps = null; } InitClass(CSpPr, CBaseFormatObject, AscDFH.historyitem_type_SpPr); CSpPr.prototype.Refresh_RecalcData = function (data) { switch (data.Type) { case AscDFH.historyitem_SpPr_SetParent: { break; } case AscDFH.historyitem_SpPr_SetBwMode: { break; } case AscDFH.historyitem_SpPr_SetXfrm: { this.handleUpdateExtents(); break; } case AscDFH.historyitem_SpPr_SetGeometry: case AscDFH.historyitem_SpPr_SetEffectPr: { this.handleUpdateGeometry(); break; } case AscDFH.historyitem_SpPr_SetFill: { this.handleUpdateFill(); break; } case AscDFH.historyitem_SpPr_SetLn: { this.handleUpdateLn(); break; } } }; CSpPr.prototype.Refresh_RecalcData2 = function (data) { }; CSpPr.prototype.createDuplicate = function () { var duplicate = new CSpPr(); duplicate.setBwMode(this.bwMode); if (this.xfrm) { duplicate.setXfrm(this.xfrm.createDuplicate()); duplicate.xfrm.setParent(duplicate); } if (this.geometry != null) { duplicate.setGeometry(this.geometry.createDuplicate()); } if (this.Fill != null) { duplicate.setFill(this.Fill.createDuplicate()); } if (this.ln != null) { duplicate.setLn(this.ln.createDuplicate()); } if (this.effectProps) { duplicate.setEffectPr(this.effectProps.createDuplicate()); } return duplicate; }; CSpPr.prototype.createDuplicateForSmartArt = function () { var duplicate = new CSpPr(); if (this.Fill != null) { duplicate.setFill(this.Fill.createDuplicate()); } return duplicate; }; CSpPr.prototype.hasRGBFill = function () { return this.Fill && this.Fill.fill && this.Fill.fill.color && this.Fill.fill.color.color && this.Fill.fill.color.color.type === c_oAscColor.COLOR_TYPE_SRGB; }; CSpPr.prototype.hasNoFill = function () { if (this.Fill) { return this.Fill.isNoFill(); } return false; }; CSpPr.prototype.hasNoFillLine = function () { if (this.ln) { return this.ln.isNoFillLine(); } return false; }; CSpPr.prototype.checkUniFillRasterImageId = function (unifill) { if (unifill && unifill.fill && typeof unifill.fill.RasterImageId === "string" && unifill.fill.RasterImageId.length > 0) return unifill.fill.RasterImageId; return null; }; CSpPr.prototype.checkBlipFillRasterImage = function (images) { var fill_image_id = this.checkUniFillRasterImageId(this.Fill); if (fill_image_id !== null) images.push(fill_image_id); if (this.ln) { var line_image_id = this.checkUniFillRasterImageId(this.ln.Fill); if (line_image_id) images.push(line_image_id); } }; CSpPr.prototype.changeShadow = function (oShadow) { if (oShadow) { var oEffectProps = this.effectProps ? this.effectProps.createDuplicate() : new AscFormat.CEffectProperties(); if (!oEffectProps.EffectLst) { oEffectProps.EffectLst = new CEffectLst(); } oEffectProps.EffectLst.outerShdw = oShadow.createDuplicate(); this.setEffectPr(oEffectProps); } else { if (this.effectProps) { if (this.effectProps.EffectLst) { if (this.effectProps.EffectLst.outerShdw) { var oEffectProps = this.effectProps.createDuplicate(); oEffectProps.EffectLst.outerShdw = null; this.setEffectPr(oEffectProps); } } } } }; CSpPr.prototype.merge = function (spPr) { /*if(spPr.xfrm != null) { this.xfrm.merge(spPr.xfrm); } */ if (spPr.geometry != null) { this.geometry = spPr.geometry.createDuplicate(); } if (spPr.Fill != null && spPr.Fill.fill != null) { //this.Fill = spPr.Fill.createDuplicate(); } /*if(spPr.ln!=null) { if(this.ln == null) this.ln = new CLn(); this.ln.merge(spPr.ln); } */ }; CSpPr.prototype.setParent = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_SpPr_SetParent, this.parent, pr)); this.parent = pr; }; CSpPr.prototype.setBwMode = function (pr) { History.Add(new CChangesDrawingsLong(this, AscDFH.historyitem_SpPr_SetBwMode, this.bwMode, pr)); this.bwMode = pr; }; CSpPr.prototype.setXfrm = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_SpPr_SetXfrm, this.xfrm, pr)); this.xfrm = pr; if(pr) { pr.setParent(this); } }; CSpPr.prototype.setGeometry = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_SpPr_SetGeometry, this.geometry, pr)); this.geometry = pr; if (this.geometry) { this.geometry.setParent(this); } this.handleUpdateGeometry(); }; CSpPr.prototype.setFill = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_SpPr_SetFill, this.Fill, pr)); this.Fill = pr; if (this.parent && this.parent.handleUpdateFill) { this.parent.handleUpdateFill(); } }; CSpPr.prototype.setLn = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_SpPr_SetLn, this.ln, pr)); this.ln = pr; if (this.parent && this.parent.handleUpdateLn) { this.parent.handleUpdateLn(); } }; CSpPr.prototype.setEffectPr = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_SpPr_SetEffectPr, this.effectProps, pr)); this.effectProps = pr; }; CSpPr.prototype.handleUpdatePosition = function () { if (this.parent && this.parent.handleUpdatePosition) { this.parent.handleUpdatePosition(); } }; CSpPr.prototype.handleUpdateExtents = function (bExtX) { if (this.parent && this.parent.handleUpdateExtents) { this.parent.handleUpdateExtents(bExtX); } }; CSpPr.prototype.handleUpdateChildOffset = function () { if (this.parent && this.parent.handleUpdateChildOffset) { this.parent.handleUpdateChildOffset(); } }; CSpPr.prototype.handleUpdateChildExtents = function () { if (this.parent && this.parent.handleUpdateChildExtents) { this.parent.handleUpdateChildExtents(); } }; CSpPr.prototype.handleUpdateFlip = function () { if (this.parent && this.parent.handleUpdateFlip) { this.parent.handleUpdateFlip(); } }; CSpPr.prototype.handleUpdateRot = function () { if (this.parent && this.parent.handleUpdateRot) { this.parent.handleUpdateRot(); } }; CSpPr.prototype.handleUpdateGeometry = function () { if (this.parent && this.parent.handleUpdateGeometry) { this.parent.handleUpdateGeometry(); } }; CSpPr.prototype.handleUpdateFill = function () { if (this.parent && this.parent.handleUpdateFill) { this.parent.handleUpdateFill(); } }; CSpPr.prototype.handleUpdateLn = function () { if (this.parent && this.parent.handleUpdateLn) { this.parent.handleUpdateLn(); } }; CSpPr.prototype.setLineFill = function () { if (this.ln && this.ln.Fill) { this.setFill(this.ln.Fill.createDuplicate()); } }; CSpPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "bwMode": { break; } } }; CSpPr.prototype.readChildXml = function (name, reader) { let oPr; if (name === "xfrm") { oPr = new AscFormat.CXfrm(); oPr.fromXml(reader); this.setXfrm(oPr); } else if (name === "prstGeom" || name === "custGeom") { let oPr = new AscFormat.Geometry(); oPr.fromXml(reader); this.setGeometry(oPr); } else if (CUniFill.prototype.isFillName(name)) { let oFill = new CUniFill(); oFill.fromXml(reader, name); this.setFill(oFill); } else if (name === "ln") { let oLn = new CLn(); oLn.fromXml(reader); this.setLn(oLn); } else if (name === "effectDag" || name === "effectLst") { let oEffectProps = new CEffectProperties(); oEffectProps.fromXml(reader, name); this.setEffectPr(oEffectProps); } }; CSpPr.prototype.toXml = function (writer, name) { let name_ = "a:spPr"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { if (0 === (writer.context.flag & 0x01)) name_ = "wps:spPr"; else name_ = "pic:spPr"; } else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) name_ = "xdr:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) name_ = "cdr:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) name_ = "dgm:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) name_ = "dsp:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART) name_ = "c:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) name_ = "a:spPr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_STYLE) name_ = "cs:spPr"; else {//theme if (0 !== (writer.context.flag & 0x04)) name_ = "a:spPr"; else name_ = "p:spPr"; } writer.WriteXmlNodeStart(name_); writer.WriteXmlAttributeString("bwMode", "auto"); if(this.xfrm || this.geometry || ((writer.context.flag & 0x02) !== 0 && !this.Fill) || this.Fill || this.ln || this.effectProps) { writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.xfrm, "a:xfrm"); writer.WriteXmlNullable(this.geometry); if ((writer.context.flag & 0x02) !== 0 && !this.Fill) { writer.WriteXmlString("<a:grpFill/>"); } writer.WriteXmlNullable(this.Fill); writer.WriteXmlNullable(this.ln); writer.WriteXmlNullable(this.effectProps); //writer.WriteXmlNullable(scene3d); //writer.WriteXmlNullable(sp3d); writer.WriteXmlNodeEnd(name_); } else { writer.WriteXmlAttributesEnd(true); } }; CSpPr.prototype.toXmlGroup = function(writer) { let namespace_ = "a"; if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) namespace_ = "wpg"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) namespace_ = "xdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) namespace_ = "a"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) namespace_ = "cdr"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DIAGRAM) namespace_ = "dgm"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) namespace_ = "dsp"; else if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_PPTX) namespace_ = "p"; writer.WriteXmlNodeStart(namespace_ + ":grpSpPr"); writer.WriteXmlAttributeString("bwMode", "auto"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.xfrm, "a:xfrm"); writer.WriteXmlNullable(this.Fill); writer.WriteXmlNullable(this.effectProps); //writer.Write(scene3d); writer.WriteXmlNodeEnd(namespace_ + ":grpSpPr"); }; // ---------------------------------- // THEME ---------------------------- var g_clr_MIN = 0; var g_clr_accent1 = 0; var g_clr_accent2 = 1; var g_clr_accent3 = 2; var g_clr_accent4 = 3; var g_clr_accent5 = 4; var g_clr_accent6 = 5; var g_clr_dk1 = 6; var g_clr_dk2 = 7; var g_clr_folHlink = 8; var g_clr_hlink = 9; var g_clr_lt1 = 10; var g_clr_lt2 = 11; var g_clr_MAX = 11; var g_clr_bg1 = g_clr_lt1; var g_clr_bg2 = g_clr_lt2; var g_clr_tx1 = g_clr_dk1; var g_clr_tx2 = g_clr_dk2; var phClr = 14; var tx1 = 15; var tx2 = 16; let CLR_IDX_MAP = {}; CLR_IDX_MAP["dk1"] = 8; CLR_IDX_MAP["lt1"] = 12; CLR_IDX_MAP["dk2"] = 9; CLR_IDX_MAP["lt2"] = 13; CLR_IDX_MAP["accent1"] = 0; CLR_IDX_MAP["accent2"] = 1; CLR_IDX_MAP["accent3"] = 2; CLR_IDX_MAP["accent4"] = 3; CLR_IDX_MAP["accent5"] = 4; CLR_IDX_MAP["accent6"] = 5; CLR_IDX_MAP["hlink"] = 11; CLR_IDX_MAP["folHlink"] = 10; let CLR_NAME_MAP = {}; CLR_NAME_MAP[8] = "dk1"; CLR_NAME_MAP[12] = "lt1"; CLR_NAME_MAP[9] = "dk2"; CLR_NAME_MAP[13] = "lt2"; CLR_NAME_MAP[0] = "accent1"; CLR_NAME_MAP[1] = "accent2"; CLR_NAME_MAP[2] = "accent3"; CLR_NAME_MAP[3] = "accent4"; CLR_NAME_MAP[4] = "accent5"; CLR_NAME_MAP[5] = "accent6"; CLR_NAME_MAP[11] = "hlink"; CLR_NAME_MAP[10] = "folHlink"; function ClrScheme() { CBaseNoIdObject.call(this); this.name = ""; this.colors = []; for (var i = g_clr_MIN; i <= g_clr_MAX; i++) this.colors[i] = null; } InitClass(ClrScheme, CBaseNoIdObject, 0); ClrScheme.prototype.isIdentical = function (clrScheme) { if (!(clrScheme instanceof ClrScheme)) { return false; } if (clrScheme.name !== this.name) { return false; } for (var _clr_index = g_clr_MIN; _clr_index <= g_clr_MAX; ++_clr_index) { if (this.colors[_clr_index]) { if (!this.colors[_clr_index].IsIdentical(clrScheme.colors[_clr_index])) { return false; } } else { if (clrScheme.colors[_clr_index]) { return false; } } } return true; }; ClrScheme.prototype.createDuplicate = function () { var _duplicate = new ClrScheme(); _duplicate.name = this.name; for (var _clr_index = 0; _clr_index <= this.colors.length; ++_clr_index) { if (this.colors[_clr_index]) { _duplicate.colors[_clr_index] = this.colors[_clr_index].createDuplicate(); } } return _duplicate; }; ClrScheme.prototype.Write_ToBinary = function (w) { w.WriteLong(this.colors.length); w.WriteString2(this.name); for (var i = 0; i < this.colors.length; ++i) { w.WriteBool(isRealObject(this.colors[i])); if (isRealObject(this.colors[i])) { this.colors[i].Write_ToBinary(w); } } }; ClrScheme.prototype.Read_FromBinary = function (r) { var len = r.GetLong(); this.name = r.GetString2(); for (var i = 0; i < len; ++i) { if (r.GetBool()) { this.colors[i] = new CUniColor(); this.colors[i].Read_FromBinary(r); } else { this.colors[i] = null; } } }; ClrScheme.prototype.setName = function (name) { this.name = name; }; ClrScheme.prototype.addColor = function (index, color) { this.colors[index] = color; }; ClrScheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.name = reader.GetValue(); break; } } }; ClrScheme.prototype.readChildXml = function (name, reader) { let nClrIdx = CLR_IDX_MAP[name]; if (AscFormat.isRealNumber(nClrIdx)) { this.colors[nClrIdx] = new CUniColor(); var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { var sClrName = reader.GetNameNoNS(); if (CUniColor.prototype.isUnicolor(sClrName)) { this.colors[nClrIdx].fromXml(reader, sClrName); } } } }; ClrScheme.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNullableAttributeStringEncode("name", this.name); }; ClrScheme.prototype.writeChildrenXml = function (writer) { let aIdx = [8, 12, 9, 13, 0, 1, 2, 3, 4, 5, 11, 10]; for (let nIdx = 0; nIdx < aIdx.length; ++nIdx) { let oColor = this.colors[aIdx[nIdx]]; if (oColor) { let sName = CLR_NAME_MAP[aIdx[nIdx]]; if (sName) { let sNodeName = "a:" + sName; writer.WriteXmlNodeStart(sNodeName); writer.WriteXmlAttributesEnd(); oColor.toXml(writer); writer.WriteXmlNodeEnd(sNodeName); } } } }; function ClrMap() { CBaseFormatObject.call(this); this.color_map = []; for (var i = g_clr_MIN; i <= g_clr_MAX; i++) this.color_map[i] = null; } InitClass(ClrMap, CBaseFormatObject, AscDFH.historyitem_type_ClrMap); ClrMap.prototype.Refresh_RecalcData = function () { }; ClrMap.prototype.notAllowedWithoutId = function () { return false; }; ClrMap.prototype.createDuplicate = function () { var _copy = new ClrMap(); for (var _color_index = g_clr_MIN; _color_index <= this.color_map.length; ++_color_index) { _copy.setClr(_color_index, this.color_map[_color_index]); } return _copy; }; ClrMap.prototype.compare = function (other) { if (!other) return false; for (var i = g_clr_MIN; i < this.color_map.length; ++i) { if (this.color_map[i] !== other.color_map[i]) { return false; } } return true; }; ClrMap.prototype.setClr = function (index, clr) { History.Add(new CChangesDrawingsContentLongMap(this, AscDFH.historyitem_ClrMap_SetClr, index, [clr], true)); this.color_map[index] = clr; }; ClrMap.prototype.SchemeClr_GetBYTECode = function (sValue) { if ("accent1" === sValue) return 0; if ("accent2" === sValue) return 1; if ("accent3" === sValue) return 2; if ("accent4" === sValue) return 3; if ("accent5" === sValue) return 4; if ("accent6" === sValue) return 5; if ("bg1" === sValue) return 6; if ("bg2" === sValue) return 7; if ("dk1" === sValue) return 8; if ("dk2" === sValue) return 9; if ("folHlink" === sValue) return 10; if ("hlink" === sValue) return 11; if ("lt1" === sValue) return 12; if ("lt2" === sValue) return 13; if ("phClr" === sValue) return 14; if ("tx1" === sValue) return 15; if ("tx2" === sValue) return 16; return 0; }; ClrMap.prototype.SchemeClr_GetStringCode = function (val) { switch (val) { case 0: return ("accent1"); case 1: return ("accent2"); case 2: return ("accent3"); case 3: return ("accent4"); case 4: return ("accent5"); case 5: return ("accent6"); case 6: return ("bg1"); case 7: return ("bg2"); case 8: return ("dk1"); case 9: return ("dk2"); case 10: return ("folHlink"); case 11: return ("hlink"); case 12: return ("lt1"); case 13: return ("lt2"); case 14: return ("phClr"); case 15: return ("tx1"); case 16: return ("tx2"); } return ("accent1"); } ClrMap.prototype.getColorIdx = function (name) { if ("accent1" === name) return 0; if ("accent2" === name) return 1; if ("accent3" === name) return 2; if ("accent4" === name) return 3; if ("accent5" === name) return 4; if ("accent6" === name) return 5; if ("bg1" === name) return 6; if ("bg2" === name) return 7; if ("dk1" === name) return 8; if ("dk2" === name) return 9; if ("folHlink" === name) return 10; if ("hlink" === name) return 11; if ("lt1" === name) return 12; if ("lt2" === name) return 13; if ("phClr" === name) return 14; if ("tx1" === name) return 15; if ("tx2" === name) return 16; return null; }; ClrMap.prototype.getColorName = function (nIdx) { if (0 === nIdx) return "accent1"; if (1 === nIdx) return "accent2"; if (2 === nIdx) return "accent3"; if (3 === nIdx) return "accent4"; if (4 === nIdx) return "accent5"; if (5 === nIdx) return "accent6"; if (6 === nIdx) return "bg1"; if (7 === nIdx) return "bg2"; if (8 === nIdx) return "dk1"; if (9 === nIdx) return "dk2"; if (10 === nIdx) return "folHlink"; if (11 === nIdx) return "hlink"; if (12 === nIdx) return "lt1"; if (13 === nIdx) return "lt2"; if (14 === nIdx) return "phClr"; if (15 === nIdx) return "tx1"; if (16 === nIdx) return "tx2"; return null; }; ClrMap.prototype.readAttrXml = function (name, reader) { let nIdx = this.SchemeClr_GetBYTECode(name); let sVal = reader.GetValue(); let nVal = this.getColorIdx(sVal); if (nVal !== null) { this.color_map[nIdx] = nVal } }; ClrMap.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); let aIdx = [6, 15, 7, 16, 0, 1, 2, 3, 4, 5, 11, 10]; for (let i = 0; i < aIdx.length; ++i) { if (AscFormat.isRealNumber(this.color_map[aIdx[i]])) { writer.WriteXmlNullableAttributeString(this.SchemeClr_GetStringCode(aIdx[i]), this.getColorName(this.color_map[aIdx[i]])); } } writer.WriteXmlAttributesEnd(true); }; ClrMap.prototype.SchemeClr_GetBYTECodeWord = function (sValue) { if ("accent1" === sValue) return 0; if ("accent2" === sValue) return 1; if ("accent3" === sValue) return 2; if ("accent4" === sValue) return 3; if ("accent5" === sValue) return 4; if ("accent6" === sValue) return 5; if ("bg1" === sValue) return 6; if ("bg2" === sValue) return 7; if ("followedHyperlink" === sValue) return 10; if ("hyperlink" === sValue) return 11; if ("t1" === sValue) return 15; if ("t2" === sValue) return 16; return null; }; ClrMap.prototype.SchemeClr_GetStringCodeWord = function (val) { switch (val) { case 0: return ("accent1"); case 1: return ("accent2"); case 2: return ("accent3"); case 3: return ("accent4"); case 4: return ("accent5"); case 5: return ("accent6"); case 6: return ("bg1"); case 7: return ("bg2"); case 10: return ("followedHyperlink"); case 11: return ("hyperlink"); case 15: return ("t1"); case 16: return ("t2"); } return (""); } ClrMap.prototype.getColorIdxWord = function (name) { if ("accent1" === name) return 0; if ("accent2" === name) return 1; if ("accent3" === name) return 2; if ("accent4" === name) return 3; if ("accent5" === name) return 4; if ("accent6" === name) return 5; if ("dark1" === name) return 8; if ("dark2" === name) return 9; if ("followedHyperlink" === name) return 10; if ("hyperlink" === name) return 11; if ("light1" === name) return 12; if ("light2" === name) return 13; return null; }; ClrMap.prototype.getColorNameWord = function (val) { switch (val) { case 0: return ("accent1"); case 1: return ("accent2"); case 2: return ("accent3"); case 3: return ("accent4"); case 4: return ("accent5"); case 5: return ("accent6"); case 8: return ("dark1"); case 9: return ("dark2"); case 10: return ("followedHyperlink"); case 11: return ("hyperlink"); case 12: return ("light1"); case 13: return ("light2"); } return (""); }; ClrMap.prototype.fromXmlWord = function (reader) { while (reader.MoveToNextAttribute()) { let nIdx = this.SchemeClr_GetBYTECodeWord(reader.GetNameNoNS()); let sVal = reader.GetValue(); let nVal = this.getColorIdxWord(sVal); if (nIdx !== null && nVal !== null) { this.color_map[nIdx] = nVal } } reader.ReadTillEnd(); }; ClrMap.prototype.toXmlWord = function (writer, name) { writer.WriteXmlNodeStart(name); let ns = AscCommon.StaxParser.prototype.GetNSFromNodeName(name); for (let i in this.color_map) { if (this.color_map.hasOwnProperty(i)) { let name = this.SchemeClr_GetStringCodeWord(parseInt(i)); let val = this.getColorNameWord(this.color_map[i]); if (name && val) { writer.WriteXmlNullableAttributeString(ns + name, val); } } } writer.WriteXmlAttributesEnd(true); }; function ExtraClrScheme() { CBaseFormatObject.call(this); this.clrScheme = null; this.clrMap = null; } InitClass(ExtraClrScheme, CBaseFormatObject, AscDFH.historyitem_type_ExtraClrScheme); ExtraClrScheme.prototype.Refresh_RecalcData = function () { }; ExtraClrScheme.prototype.setClrScheme = function (pr) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ExtraClrScheme_SetClrScheme, this.clrScheme, pr)); this.clrScheme = pr; }; ExtraClrScheme.prototype.setClrMap = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ExtraClrScheme_SetClrMap, this.clrMap, pr)); this.clrMap = pr; }; ExtraClrScheme.prototype.createDuplicate = function () { var ret = new ExtraClrScheme(); if (this.clrScheme) { ret.setClrScheme(this.clrScheme.createDuplicate()) } if (this.clrMap) { ret.setClrMap(this.clrMap.createDuplicate()); } return ret; }; ExtraClrScheme.prototype.readChildXml = function (name, reader) { switch (name) { case "clrMap": { let oPr = new ClrMap(); oPr.fromXml(reader); this.setClrMap(oPr); break; } case "clrScheme": { let oPr = new ClrScheme(); oPr.fromXml(reader); this.setClrScheme(oPr); break; } } }; ExtraClrScheme.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("a:extraClrScheme"); writer.WriteXmlAttributesEnd(); if (this.clrScheme) { this.clrScheme.toXml(writer, "a:clrScheme"); } if (this.clrMap) { this.clrMap.toXml(writer, "a:clrMap") } writer.WriteXmlNodeEnd("a:extraClrScheme"); }; drawingConstructorsMap[AscDFH.historyitem_ExtraClrScheme_SetClrScheme] = ClrScheme; function FontCollection(fontScheme) { CBaseNoIdObject.call(this); this.latin = null; this.ea = null; this.cs = null; if (fontScheme) { this.setFontScheme(fontScheme); } } InitClass(FontCollection, CBaseNoIdObject, 0); FontCollection.prototype.Refresh_RecalcData = function () { }; FontCollection.prototype.setFontScheme = function (fontScheme) { this.fontScheme = fontScheme; }; FontCollection.prototype.setLatin = function (pr) { this.latin = pr; if (this.fontScheme) this.fontScheme.checkFromFontCollection(pr, this, FONT_REGION_LT); }; FontCollection.prototype.setEA = function (pr) { this.ea = pr; if (this.fontScheme) this.fontScheme.checkFromFontCollection(pr, this, FONT_REGION_EA); }; FontCollection.prototype.setCS = function (pr) { this.cs = pr; if (this.fontScheme) this.fontScheme.checkFromFontCollection(pr, this, FONT_REGION_CS); }; FontCollection.prototype.Write_ToBinary = function (w) { writeString(w, this.latin); writeString(w, this.ea); writeString(w, this.cs); }; FontCollection.prototype.Read_FromBinary = function (r) { this.latin = readString(r); this.ea = readString(r); this.cs = readString(r); if (this.fontScheme) { this.fontScheme.checkFromFontCollection(this.latin, this, FONT_REGION_LT); this.fontScheme.checkFromFontCollection(this.ea, this, FONT_REGION_EA); this.fontScheme.checkFromFontCollection(this.cs, this, FONT_REGION_CS); } }; FontCollection.prototype.readFont = function (reader) { let oNode = new CT_XmlNode(function (reader, name) { return true; }); oNode.fromXml(reader); return oNode.attributes["typeface"]; }; FontCollection.prototype.writeFont = function (writer, sNodeName, sFont) { writer.WriteXmlNodeStart(sNodeName); writer.WriteXmlAttributeString("typeface", sFont || ""); writer.WriteXmlAttributesEnd(true); }; FontCollection.prototype.readChildXml = function (name, reader) { switch (name) { case "cs": { this.setCS(this.readFont(reader)); break; } case "ea": { this.setEA(this.readFont(reader)); break; } case "latin": { this.setLatin(this.readFont(reader)); break; } } }; FontCollection.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); this.writeFont(writer, "a:latin", this.latin); this.writeFont(writer, "a:ea", this.ea); this.writeFont(writer, "a:cs", this.cs); // let nCount = Fonts.length; // for (let i = 0; // i < nCount; // ++i // ) // Fonts[i].toXml(writer); writer.WriteXmlNodeEnd(sName); }; var FONT_REGION_LT = 0x00; var FONT_REGION_EA = 0x01; var FONT_REGION_CS = 0x02; function FontScheme() { CBaseNoIdObject.call(this) this.name = ""; this.majorFont = new FontCollection(this); this.minorFont = new FontCollection(this); this.fontMap = { "+mj-lt": undefined, "+mj-ea": undefined, "+mj-cs": undefined, "+mn-lt": undefined, "+mn-ea": undefined, "+mn-cs": undefined, "majorAscii": undefined, "majorBidi": undefined, "majorEastAsia": undefined, "majorHAnsi": undefined, "minorAscii": undefined, "minorBidi": undefined, "minorEastAsia": undefined, "minorHAnsi": undefined }; } InitClass(FontScheme, CBaseNoIdObject, 0); FontScheme.prototype.createDuplicate = function () { var oCopy = new FontScheme(); oCopy.majorFont.setLatin(this.majorFont.latin); oCopy.majorFont.setEA(this.majorFont.ea); oCopy.majorFont.setCS(this.majorFont.cs); oCopy.minorFont.setLatin(this.minorFont.latin); oCopy.minorFont.setEA(this.minorFont.ea); oCopy.minorFont.setCS(this.minorFont.cs); return oCopy; }; FontScheme.prototype.Refresh_RecalcData = function () { }; FontScheme.prototype.Write_ToBinary = function (w) { this.majorFont.Write_ToBinary(w); this.minorFont.Write_ToBinary(w); writeString(w, this.name); }; FontScheme.prototype.Read_FromBinary = function (r) { this.majorFont.Read_FromBinary(r); this.minorFont.Read_FromBinary(r); this.name = readString(r); }; FontScheme.prototype.checkFromFontCollection = function (font, fontCollection, region) { if (fontCollection === this.majorFont) { switch (region) { case FONT_REGION_LT: { this.fontMap["+mj-lt"] = font; this.fontMap["majorAscii"] = font; this.fontMap["majorHAnsi"] = font; break; } case FONT_REGION_EA: { this.fontMap["+mj-ea"] = font; this.fontMap["majorEastAsia"] = font; break; } case FONT_REGION_CS: { this.fontMap["+mj-cs"] = font; this.fontMap["majorBidi"] = font; break; } } } else if (fontCollection === this.minorFont) { switch (region) { case FONT_REGION_LT: { this.fontMap["+mn-lt"] = font; this.fontMap["minorAscii"] = font; this.fontMap["minorHAnsi"] = font; break; } case FONT_REGION_EA: { this.fontMap["+mn-ea"] = font; this.fontMap["minorEastAsia"] = font; break; } case FONT_REGION_CS: { this.fontMap["+mn-cs"] = font; this.fontMap["minorBidi"] = font; break; } } } }; FontScheme.prototype.checkFont = function (font) { if (g_oThemeFontsName[font]) { if (this.fontMap[font]) { return this.fontMap[font]; } else if (this.fontMap["+mn-lt"]) { return this.fontMap["+mn-lt"]; } else { return "Arial"; } } return font; }; FontScheme.prototype.getObjectType = function () { return AscDFH.historyitem_type_FontScheme; }; FontScheme.prototype.setName = function (pr) { this.name = pr; }; FontScheme.prototype.setMajorFont = function (pr) { this.majorFont = pr; }; FontScheme.prototype.setMinorFont = function (pr) { this.minorFont = pr; }; FontScheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.name = reader.GetValue(); break; } } }; FontScheme.prototype.readChildXml = function (name, reader) { switch (name) { case "majorFont": { this.majorFont.fromXml(reader); break; } case "minorFont": { this.minorFont.fromXml(reader); break; } } }; FontScheme.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNullableAttributeStringEncode("name", this.name); }; FontScheme.prototype.writeChildrenXml = function (writer) { this.majorFont.toXml(writer, "a:majorFont"); this.minorFont.toXml(writer, "a:minorFont"); }; function FmtScheme() { CBaseNoIdObject.call(this); this.name = ""; this.fillStyleLst = []; this.lnStyleLst = []; this.effectStyleLst = null; this.bgFillStyleLst = []; } InitClass(FmtScheme, CBaseNoIdObject, 0); FmtScheme.prototype.GetFillStyle = function (number, unicolor) { if (number >= 1 && number <= 999) { var ret = this.fillStyleLst[number - 1]; if (!ret) return null; var ret2 = ret.createDuplicate(); ret2.checkPhColor(unicolor, false); return ret2; } else if (number >= 1001) { var ret = this.bgFillStyleLst[number - 1001]; if (!ret) return null; var ret2 = ret.createDuplicate(); ret2.checkPhColor(unicolor, false); return ret2; } return null; }; FmtScheme.prototype.Write_ToBinary = function (w) { writeString(w, this.name); var i; w.WriteLong(this.fillStyleLst.length); for (i = 0; i < this.fillStyleLst.length; ++i) { this.fillStyleLst[i].Write_ToBinary(w); } w.WriteLong(this.lnStyleLst.length); for (i = 0; i < this.lnStyleLst.length; ++i) { this.lnStyleLst[i].Write_ToBinary(w); } w.WriteLong(this.bgFillStyleLst.length); for (i = 0; i < this.bgFillStyleLst.length; ++i) { this.bgFillStyleLst[i].Write_ToBinary(w); } }; FmtScheme.prototype.Read_FromBinary = function (r) { this.name = readString(r); var _len = r.GetLong(), i; for (i = 0; i < _len; ++i) { this.fillStyleLst[i] = new CUniFill(); this.fillStyleLst[i].Read_FromBinary(r); } _len = r.GetLong(); for (i = 0; i < _len; ++i) { this.lnStyleLst[i] = new CLn(); this.lnStyleLst[i].Read_FromBinary(r); } _len = r.GetLong(); for (i = 0; i < _len; ++i) { this.bgFillStyleLst[i] = new CUniFill(); this.bgFillStyleLst[i].Read_FromBinary(r); } }; FmtScheme.prototype.createDuplicate = function () { var oCopy = new FmtScheme(); oCopy.name = this.name; var i; for (i = 0; i < this.fillStyleLst.length; ++i) { oCopy.fillStyleLst[i] = this.fillStyleLst[i].createDuplicate(); } for (i = 0; i < this.lnStyleLst.length; ++i) { oCopy.lnStyleLst[i] = this.lnStyleLst[i].createDuplicate(); } for (i = 0; i < this.bgFillStyleLst.length; ++i) { oCopy.bgFillStyleLst[i] = this.bgFillStyleLst[i].createDuplicate(); } return oCopy; }; FmtScheme.prototype.setName = function (pr) { this.name = pr; }; FmtScheme.prototype.addFillToStyleLst = function (pr) { this.fillStyleLst.push(pr); }; FmtScheme.prototype.addLnToStyleLst = function (pr) { this.lnStyleLst.push(pr); }; FmtScheme.prototype.addEffectToStyleLst = function (pr) { this.effectStyleLst.push(pr); }; FmtScheme.prototype.addBgFillToStyleLst = function (pr) { this.bgFillStyleLst.push(pr); }; FmtScheme.prototype.getImageFromBulletsMap = function(oImages) {}; FmtScheme.prototype.getDocContentsWithImageBullets = function (arrContents) {}; FmtScheme.prototype.getAllRasterImages = function(aImages) { for(let nIdx = 0; nIdx < this.fillStyleLst.length; ++nIdx) { let oUnifill = this.fillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId) { aImages.push(sRasterImageId); } } for(let nIdx = 0; nIdx < this.bgFillStyleLst.length; ++nIdx) { let oUnifill = this.bgFillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId) { aImages.push(sRasterImageId); } } }; FmtScheme.prototype.Reassign_ImageUrls = function(oImageMap) { for(let nIdx = 0; nIdx < this.fillStyleLst.length; ++nIdx) { let oUnifill = this.fillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId && oImageMap[sRasterImageId]) { oUnifill.fill.RasterImageId = oImageMap[sRasterImageId] } } for(let nIdx = 0; nIdx < this.bgFillStyleLst.length; ++nIdx) { let oUnifill = this.bgFillStyleLst[nIdx]; let sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if(sRasterImageId && oImageMap[sRasterImageId]) { oUnifill.fill.RasterImageId = oImageMap[sRasterImageId] } } }; FmtScheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.name = reader.GetValue(); break; } } }; FmtScheme.prototype.readList = function (reader, aArray, fConstructor) { var depth = reader.GetDepth(); while (reader.ReadNextSiblingNode(depth)) { let name = reader.GetNameNoNS(); let oObj = new fConstructor(); oObj.fromXml(reader, name === "ln" ? undefined : name); aArray.push(oObj); } }; FmtScheme.prototype.writeList = function (writer, aArray, sName, sChildName) { writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributesEnd(); for (let nIdx = 0; nIdx < aArray.length; ++nIdx) { aArray[nIdx].toXml(writer, sChildName) } writer.WriteXmlNodeEnd(sName); }; FmtScheme.prototype.readChildXml = function (name, reader) { switch (name) { case "bgFillStyleLst": { this.readList(reader, this.bgFillStyleLst, CUniFill); break; } case "effectStyleLst": { break; } case "fillStyleLst": { this.readList(reader, this.fillStyleLst, CUniFill); break; } case "lnStyleLst": { this.readList(reader, this.lnStyleLst, CLn); break; } } }; FmtScheme.prototype.writeAttrXmlImpl = function (writer) { writer.WriteXmlNullableAttributeStringEncode("name", this.name); }; FmtScheme.prototype.writeChildrenXml = function (writer) { this.writeList(writer, this.fillStyleLst, "a:fillStyleLst"); this.writeList(writer, this.lnStyleLst, "a:lnStyleLst", "a:ln"); writer.WriteXmlString("<a:effectStyleLst><a:effectStyle><a:effectLst>\ <a:outerShdw blurRad=\"40000\" dist=\"20000\" dir=\"5400000\" rotWithShape=\"0\"><a:srgbClr val=\"000000\"><a:alpha val=\"38000\"/></a:srgbClr></a:outerShdw>\ </a:effectLst></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=\"40000\" dist=\"23000\" dir=\"5400000\" rotWithShape=\"0\">\ <a:srgbClr val=\"000000\"><a:alpha val=\"35000\"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle><a:effectStyle><a:effectLst>\ <a:outerShdw blurRad=\"40000\" dist=\"23000\" dir=\"5400000\" rotWithShape=\"0\"><a:srgbClr val=\"000000\"><a:alpha val=\"35000\"/></a:srgbClr>\ </a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst>"); this.writeList(writer, this.bgFillStyleLst, "a:bgFillStyleLst"); }; function ThemeElements(oTheme) { CBaseNoIdObject.call(this); this.theme = oTheme; this.clrScheme = new ClrScheme(); this.fontScheme = new FontScheme(); this.fmtScheme = new FmtScheme(); } InitClass(ThemeElements, CBaseNoIdObject, 0); ThemeElements.prototype.readAttrXml = function (name, reader) { }; ThemeElements.prototype.readChildXml = function (name, reader) { switch (name) { case "clrScheme": { let oClrScheme = new ClrScheme(); oClrScheme.fromXml(reader); this.theme.setColorScheme(oClrScheme); break; } case "extLst": { break; } case "fmtScheme": { let oFmtScheme = new FmtScheme(); oFmtScheme.fromXml(reader); this.theme.setFormatScheme(oFmtScheme); break; } case "fontScheme": { let oFontScheme = new FontScheme(); oFontScheme.fromXml(reader); this.theme.setFontScheme(oFontScheme); break; } } }; ThemeElements.prototype.writeAttrXmlImpl = function (writer) { }; ThemeElements.prototype.writeChildrenXml = function (writer) { writer.WriteXmlNullable(this.clrScheme, "a:clrScheme"); writer.WriteXmlNullable(this.fontScheme, "a:fontScheme"); writer.WriteXmlNullable(this.fmtScheme, "a:fmtScheme"); }; function CTheme() { CBaseFormatObject.call(this); this.name = ""; this.themeElements = new ThemeElements(this); this.spDef = null; this.lnDef = null; this.txDef = null; this.extraClrSchemeLst = []; this.isThemeOverride = false; // pointers this.presentation = null; this.clrMap = null; } InitClass(CTheme, CBaseFormatObject, 0); CTheme.prototype.notAllowedWithoutId = function () { return false; }; CTheme.prototype.createDuplicate = function () { var oTheme = new CTheme(); oTheme.setName(this.name); oTheme.setColorScheme(this.themeElements.clrScheme.createDuplicate()); oTheme.setFontScheme(this.themeElements.fontScheme.createDuplicate()); oTheme.setFormatScheme(this.themeElements.fmtScheme.createDuplicate()); if (this.spDef) { oTheme.setSpDef(this.spDef.createDuplicate()); } if (this.lnDef) { oTheme.setLnDef(this.lnDef.createDuplicate()); } if (this.txDef) { oTheme.setTxDef(this.txDef.createDuplicate()); } for (var i = 0; i < this.extraClrSchemeLst.length; ++i) { oTheme.addExtraClrSceme(this.extraClrSchemeLst[i].createDuplicate()); } return oTheme; }; CTheme.prototype.Document_Get_AllFontNames = function (AllFonts) { var font_scheme = this.themeElements.fontScheme; var major_font = font_scheme.majorFont; typeof major_font.latin === "string" && major_font.latin.length > 0 && (AllFonts[major_font.latin] = 1); typeof major_font.ea === "string" && major_font.ea.length > 0 && (AllFonts[major_font.ea] = 1); typeof major_font.cs === "string" && major_font.latin.length > 0 && (AllFonts[major_font.cs] = 1); var minor_font = font_scheme.minorFont; typeof minor_font.latin === "string" && minor_font.latin.length > 0 && (AllFonts[minor_font.latin] = 1); typeof minor_font.ea === "string" && minor_font.ea.length > 0 && (AllFonts[minor_font.ea] = 1); typeof minor_font.cs === "string" && minor_font.latin.length > 0 && (AllFonts[minor_font.cs] = 1); }; CTheme.prototype.getFillStyle = function (idx, unicolor) { if (idx === 0 || idx === 1000) { return AscFormat.CreateNoFillUniFill(); } var ret; if (idx >= 1 && idx <= 999) { if (this.themeElements.fmtScheme.fillStyleLst[idx - 1]) { ret = this.themeElements.fmtScheme.fillStyleLst[idx - 1].createDuplicate(); if (ret) { ret.checkPhColor(unicolor, false); return ret; } } } else if (idx >= 1001) { if (this.themeElements.fmtScheme.bgFillStyleLst[idx - 1001]) { ret = this.themeElements.fmtScheme.bgFillStyleLst[idx - 1001].createDuplicate(); if (ret) { ret.checkPhColor(unicolor, false); return ret; } } } return CreateSolidFillRGBA(0, 0, 0, 255); }; CTheme.prototype.getLnStyle = function (idx, unicolor) { if (idx === 0) { return AscFormat.CreateNoFillLine(); } if (this.themeElements.fmtScheme.lnStyleLst[idx - 1]) { var ret = this.themeElements.fmtScheme.lnStyleLst[idx - 1].createDuplicate(); if (ret.Fill) { ret.Fill.checkPhColor(unicolor, false); } return ret; } return new CLn(); }; CTheme.prototype.getExtraClrScheme = function (sName) { for (var i = 0; i < this.extraClrSchemeLst.length; ++i) { if (this.extraClrSchemeLst[i].clrScheme && this.extraClrSchemeLst[i].clrScheme.name === sName) { return this.extraClrSchemeLst[i].clrScheme.createDuplicate(); } } return null; }; CTheme.prototype.changeColorScheme = function (clrScheme) { var oCurClrScheme = this.themeElements.clrScheme; this.setColorScheme(clrScheme); var oOldAscColorScheme = AscCommon.getAscColorScheme(oCurClrScheme, this), aExtraAscClrSchemes = this.getExtraAscColorSchemes(); var oNewAscColorScheme = AscCommon.getAscColorScheme(clrScheme, this); if (AscCommon.getIndexColorSchemeInArray(AscCommon.g_oUserColorScheme, oOldAscColorScheme) === -1) { if (AscCommon.getIndexColorSchemeInArray(aExtraAscClrSchemes, oOldAscColorScheme) === -1) { var oExtraClrScheme = new ExtraClrScheme(); if (this.clrMap) { oExtraClrScheme.setClrMap(this.clrMap.createDuplicate()); } oExtraClrScheme.setClrScheme(oCurClrScheme.createDuplicate()); this.addExtraClrSceme(oExtraClrScheme, 0); aExtraAscClrSchemes = this.getExtraAscColorSchemes(); } } var nIndex = AscCommon.getIndexColorSchemeInArray(aExtraAscClrSchemes, oNewAscColorScheme); if (nIndex > -1) { this.removeExtraClrScheme(nIndex); } }; CTheme.prototype.getExtraAscColorSchemes = function () { var asc_color_scheme; var aCustomSchemes = []; var _extra = this.extraClrSchemeLst; var _count = _extra.length; for (var i = 0; i < _count; ++i) { var _scheme = _extra[i].clrScheme; asc_color_scheme = AscCommon.getAscColorScheme(_scheme, this); aCustomSchemes.push(asc_color_scheme); } return aCustomSchemes; }; CTheme.prototype.setColorScheme = function (clrScheme) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ThemeSetColorScheme, this.themeElements.clrScheme, clrScheme)); this.themeElements.clrScheme = clrScheme; }; CTheme.prototype.setFontScheme = function (fontScheme) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ThemeSetFontScheme, this.themeElements.fontScheme, fontScheme)); this.themeElements.fontScheme = fontScheme; }; CTheme.prototype.changeFontScheme = function (fontScheme) { this.setFontScheme(fontScheme); let aIndexes = this.GetAllSlideIndexes(); let aSlides = this.GetPresentationSlides(); if(aIndexes && aSlides) { for (let i = 0; i < aIndexes.length; ++i) { aSlides[aIndexes[i]] && aSlides[aIndexes[i]].checkSlideTheme(); } } }; CTheme.prototype.setFormatScheme = function (fmtScheme) { History.Add(new CChangesDrawingsObjectNoId(this, AscDFH.historyitem_ThemeSetFmtScheme, this.themeElements.fmtScheme, fmtScheme)); this.themeElements.fmtScheme = fmtScheme; }; CTheme.prototype.setName = function (pr) { History.Add(new CChangesDrawingsString(this, AscDFH.historyitem_ThemeSetName, this.name, pr)); this.name = pr; }; CTheme.prototype.setIsThemeOverride = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_ThemeSetIsThemeOverride, this.isThemeOverride, pr)); this.isThemeOverride = pr; }; CTheme.prototype.setSpDef = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ThemeSetSpDef, this.spDef, pr)); this.spDef = pr; }; CTheme.prototype.setLnDef = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ThemeSetLnDef, this.lnDef, pr)); this.lnDef = pr; }; CTheme.prototype.setTxDef = function (pr) { History.Add(new CChangesDrawingsObject(this, AscDFH.historyitem_ThemeSetTxDef, this.txDef, pr)); this.txDef = pr; }; CTheme.prototype.addExtraClrSceme = function (pr, idx) { var pos; if (AscFormat.isRealNumber(idx)) pos = idx; else pos = this.extraClrSchemeLst.length; History.Add(new CChangesDrawingsContent(this, AscDFH.historyitem_ThemeAddExtraClrScheme, pos, [pr], true)); this.extraClrSchemeLst.splice(pos, 0, pr); }; CTheme.prototype.removeExtraClrScheme = function (idx) { if (idx > -1 && idx < this.extraClrSchemeLst.length) { History.Add(new CChangesDrawingsContent(this, AscDFH.historyitem_ThemeRemoveExtraClrScheme, idx, this.extraClrSchemeLst.splice(idx, 1), false)); } }; CTheme.prototype.GetLogicDocument = function() { let oRet = typeof editor !== "undefined" && editor.WordControl && editor.WordControl.m_oLogicDocument; return AscCommon.isRealObject(oRet) ? oRet : null; }; CTheme.prototype.GetWordDrawingObjects = function () { let oLogicDocument = this.GetLogicDocument(); let oRet = oLogicDocument && oLogicDocument.DrawingObjects; return AscCommon.isRealObject(oRet) ? oRet : null; }; CTheme.prototype.GetPresentationSlides = function () { let oLogicDocument = this.GetLogicDocument(); if(oLogicDocument && Array.isArray(oLogicDocument.Slides)) { return oLogicDocument.Slides; } return null; }; CTheme.prototype.GetAllSlideIndexes = function () { let oPresentation = this.GetLogicDocument(); let aSlides = this.GetPresentationSlides(); if(oPresentation && aSlides) { let aIndexes = []; for(let nSlide = 0; nSlide < aSlides.length; ++nSlide) { let oSlide = aSlides[nSlide]; let oTheme = oSlide.getTheme(); if(oTheme === this) { aIndexes.push(nSlide); } } return aIndexes; } return null; }; CTheme.prototype.Refresh_RecalcData = function (oData) { if (oData) { if (oData.Type === AscDFH.historyitem_ThemeSetColorScheme) { let oWordGraphicObject = this.GetWordDrawingObjects(); if (oWordGraphicObject) { History.RecalcData_Add({All: true}); let aDrawings = oWordGraphicObject.drawingObjects; for (let nDrawing = 0; nDrawing < aDrawings.length; ++nDrawing) { let oGrObject = aDrawings[nDrawing].GraphicObj; if (oGrObject) { oGrObject.handleUpdateFill(); oGrObject.handleUpdateLn(); } } let oApi = oWordGraphicObject.document.Api; oApi.chartPreviewManager.clearPreviews(); oApi.textArtPreviewManager.clear(); } } else if(oData.Type === AscDFH.historyitem_ThemeSetFontScheme) { let oPresentation = this.GetLogicDocument(); let aSlideIndexes = this.GetAllSlideIndexes(); if(oPresentation) { oPresentation.Refresh_RecalcData({Type: AscDFH.historyitem_Presentation_ChangeTheme, aIndexes: aSlideIndexes}); } } } }; CTheme.prototype.getAllRasterImages = function(aImages) { if(this.themeElements && this.themeElements.fmtScheme) { this.themeElements.fmtScheme.getAllRasterImages(aImages); } }; CTheme.prototype.getImageFromBulletsMap = function(oImages) {}; CTheme.prototype.getDocContentsWithImageBullets = function (arrContents) {}; CTheme.prototype.Reassign_ImageUrls = function(images_rename) { if(this.themeElements && this.themeElements.fmtScheme) { let aImages = []; this.themeElements.fmtScheme.getAllRasterImages(aImages); let bReassign = false; for(let nImage = 0; nImage < aImages.length; ++nImage) { if(images_rename[aImages[nImage]]) { bReassign = true; break; } } if(bReassign) { let oNewFmtScheme = this.themeElements.fmtScheme.createDuplicate(); oNewFmtScheme.Reassign_ImageUrls(images_rename); this.setFormatScheme(oNewFmtScheme); } } }; CTheme.prototype.getObjectType = function () { return AscDFH.historyitem_type_Theme; }; CTheme.prototype.Write_ToBinary2 = function (w) { w.WriteLong(AscDFH.historyitem_type_Theme); w.WriteString2(this.Id); }; CTheme.prototype.Read_FromBinary2 = function (r) { this.Id = r.GetString2(); }; CTheme.prototype.readAttrXml = function (name, reader) { switch (name) { case "name": { this.setName(reader.GetValue()); break; } } }; CTheme.prototype.readChildXml = function (name, reader) { switch (name) { case "custClrLst": { break; } case "extLst": { break; } case "extraClrSchemeLst": { let oTheme = this; let oNode = new CT_XmlNode(function (reader, name) { if (name === "extraClrScheme") { let oExtraClrScheme = new ExtraClrScheme(); oExtraClrScheme.fromXml(reader); return oTheme.addExtraClrSceme(oExtraClrScheme, oTheme.extraClrSchemeLst.length); } return true; }); oNode.fromXml(reader); break; } case "objectDefaults": { let oTheme = this; let oNode = new CT_XmlNode(function (reader, name) { if (name === "lnDef") { oTheme.setLnDef(new DefaultShapeDefinition()); oTheme.lnDef.fromXml(reader); return oTheme.lnDef; } if (name === "spDef") { oTheme.setSpDef(new DefaultShapeDefinition()); oTheme.spDef.fromXml(reader); return oTheme.spDef; } if (name === "txDef") { oTheme.setTxDef(new DefaultShapeDefinition()); oTheme.txDef.fromXml(reader); return oTheme.txDef; } }); oNode.fromXml(reader); break; } case "themeElements": { this.themeElements.fromXml(reader); break; } } }; CTheme.prototype.toXml = function (writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); let sName = "a:theme"; writer.WriteXmlNodeStart(sName); writer.WriteXmlString(" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\""); writer.WriteXmlNullableAttributeStringEncode("name", this.name); writer.WriteXmlAttributesEnd(); this.themeElements.toXml(writer, "a:themeElements"); if(this.lnDef || this.spDef || this.txDef) { let oNode = new CT_XmlNode(); if (this.lnDef) oNode.members["a:lnDef"] = this.lnDef; if (this.spDef) oNode.members["a:spDef"] = this.spDef; if (this.txDef) oNode.members["a:txDef"] = this.txDef; oNode.toXml(writer, "a:objectDefaults"); } else { writer.WriteXmlNodeStart("a:objectDefaults"); writer.WriteXmlAttributesEnd(true); } if(this.extraClrSchemeLst.length > 0) { let oNode = new CT_XmlNode(); oNode.members["a:extraClrScheme"] = this.extraClrSchemeLst; writer.WriteXmlNullable(oNode, "a:extraClrSchemeLst"); } else { writer.WriteXmlNodeStart("a:extraClrSchemeLst"); writer.WriteXmlAttributesEnd(true); } writer.WriteXmlNodeEnd(sName); } // ---------------------------------- // CSLD ----------------------------- function HF() { CBaseFormatObject.call(this); this.dt = null; this.ftr = null; this.hdr = null; this.sldNum = null; } InitClass(HF, CBaseFormatObject, AscDFH.historyitem_type_HF); HF.prototype.Refresh_RecalcData = function () { }; HF.prototype.createDuplicate = function () { var ret = new HF(); if (ret.dt !== this.dt) { ret.setDt(this.dt); } if (ret.ftr !== this.ftr) { ret.setFtr(this.ftr); } if (ret.hdr !== this.hdr) { ret.setHdr(this.hdr); } if (ret.sldNum !== this.sldNum) { ret.setSldNum(this.sldNum); } return ret; }; HF.prototype.setDt = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetDt, this.dt, pr)); this.dt = pr; }; HF.prototype.setFtr = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetFtr, this.ftr, pr)); this.ftr = pr; }; HF.prototype.setHdr = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetHdr, this.hdr, pr)); this.hdr = pr; }; HF.prototype.setSldNum = function (pr) { History.Add(new CChangesDrawingsBool(this, AscDFH.historyitem_HF_SetSldNum, this.sldNum, pr)); this.sldNum = pr; }; HF.prototype.readAttrXml = function (name, reader) { switch (name) { case "dt": { this.setDt(reader.GetValueBool()); break; } case "ftr": { this.setFtr(reader.GetValueBool()); break; } case "hdr": { this.setHdr(reader.GetValueBool()); break; } case "sldNum": { this.setSldNum(reader.GetValueBool()); break; } } }; HF.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:hf"); writer.WriteXmlNullableAttributeString("dt", this.dt); writer.WriteXmlNullableAttributeString("ftr", this.ftr); writer.WriteXmlNullableAttributeString("hdr", this.hdr); writer.WriteXmlNullableAttributeString("sldNum", this.sldNum); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("p:hf"); }; function CBgPr() { CBaseNoIdObject.call(this) this.Fill = null; this.shadeToTitle = false; this.EffectProperties = null; } InitClass(CBgPr, CBaseNoIdObject, 0); CBgPr.prototype.merge = function (bgPr) { if (this.Fill == null) { this.Fill = new CUniFill(); if (bgPr.Fill != null) { this.Fill.merge(bgPr.Fill) } } }; CBgPr.prototype.createFullCopy = function () { var _copy = new CBgPr(); if (this.Fill != null) { _copy.Fill = this.Fill.createDuplicate(); } _copy.shadeToTitle = this.shadeToTitle; return _copy; }; CBgPr.prototype.setFill = function (pr) { this.Fill = pr; }; CBgPr.prototype.setShadeToTitle = function (pr) { this.shadeToTitle = pr; }; CBgPr.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.Fill)); if (isRealObject(this.Fill)) { this.Fill.Write_ToBinary(w); } w.WriteBool(this.shadeToTitle); }; CBgPr.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.Fill = new CUniFill(); this.Fill.Read_FromBinary(r); } this.shadeToTitle = r.GetBool(); }; CBgPr.prototype.readAttrXml = function (name, reader) { if (name === "shadeToTitle") { this.shadeToTitle = reader.GetValueBool(); } }; CBgPr.prototype.readChildXml = function (name, reader) { if (CUniFill.prototype.isFillName(name)) { this.Fill = new CUniFill(); this.Fill.fromXml(reader, name); } else if (name === "effectDag" || name === "effectLst") { this.EffectProperties = new CEffectProperties(); this.EffectProperties.fromXml(reader); } }; CBgPr.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:bgPr"); writer.WriteXmlNullableAttributeBool("shadeToTitle", this.shadeToTitle); writer.WriteXmlAttributesEnd(); if (this.Fill) { this.Fill.toXml(writer); } if (this.EffectProperties) { this.EffectProperties.toXml(writer); } writer.WriteXmlNodeEnd("p:bgPr"); }; function CBg() { CBaseNoIdObject.call(this); this.bwMode = null; this.bgPr = null; this.bgRef = null; } InitClass(CBg, CBaseNoIdObject, 0); CBg.prototype.setBwMode = function (pr) { this.bwMode = pr; }; CBg.prototype.setBgPr = function (pr) { this.bgPr = pr; }; CBg.prototype.setBgRef = function (pr) { this.bgRef = pr; }; CBg.prototype.merge = function (bg) { if (this.bgPr == null) { this.bgPr = new CBgPr(); if (bg.bgPr != null) { this.bgPr.merge(bg.bgPr); } } }; CBg.prototype.createFullCopy = function () { var _copy = new CBg(); _copy.bwMode = this.bwMode; if (this.bgPr != null) { _copy.bgPr = this.bgPr.createFullCopy(); } if (this.bgRef != null) { _copy.bgRef = this.bgRef.createDuplicate(); } return _copy; }; CBg.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.bgPr)); if (isRealObject(this.bgPr)) { this.bgPr.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bgRef)); if (isRealObject(this.bgRef)) { this.bgRef.Write_ToBinary(w); } }; CBg.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.bgPr = new CBgPr(); this.bgPr.Read_FromBinary(r); } if (r.GetBool()) { this.bgRef = new StyleRef(); this.bgRef.Read_FromBinary(r); } }; CBg.prototype.readAttrXml = function (name, reader) { if (name === "bwMode") { this.bwMode = reader.GetValue(); } }; CBg.prototype.readChildXml = function (name, reader) { switch (name) { case "bgPr": { var oBgPr = new CBgPr(); oBgPr.fromXml(reader); this.bgPr = oBgPr; break; } case "bgRef": { var oBgRef = new StyleRef(); oBgRef.fromXml(reader); this.bgRef = oBgRef; break; } } }; CBg.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:bg"); writer.WriteXmlNullableAttributeString("bwMode", this.bwMode); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.bgPr); writer.WriteXmlNullable(this.bgRef, "p:bgRef"); writer.WriteXmlNodeEnd("p:bg"); }; function CSld(parent) { CBaseNoIdObject.call(this); this.name = ""; this.Bg = null; this.spTree = [];//new GroupShape(); this.parent = parent; } InitClass(CSld, CBaseNoIdObject, 0); CSld.prototype.getObjectsNamesPairs = function () { var aPairs = []; var aSpTree = this.spTree; for (var nSp = 0; nSp < aSpTree.length; ++nSp) { var oSp = aSpTree[nSp]; if (!oSp.isEmptyPlaceholder()) { aPairs.push({object: oSp, name: oSp.getObjectName()}); } } return aPairs; }; CSld.prototype.getObjectsNames = function () { var aPairs = this.getObjectsNamesPairs(); var aNames = []; for (var nPair = 0; nPair < aPairs.length; ++nPair) { var oPair = aPairs[nPair]; aNames.push(oPair.name); } return aNames; }; CSld.prototype.getObjectByName = function (sName) { var aSpTree = this.spTree; for (var nSp = 0; nSp < aSpTree.length; ++nSp) { var oSp = aSpTree[nSp]; if (oSp.getObjectName() === sName) { return oSp; } } return null; }; CSld.prototype.readAttrXml = function (name, reader) { if (name === "name") { this.name = reader.GetValue(); } }; CSld.prototype.readChildXml = function (name, reader) { switch (name) { case "bg": { var oBg = new AscFormat.CBg(); oBg.fromXml(reader); this.Bg = oBg; break; } case "controls": { break; } case "custDataLst": { break; } case "extLst": { break; } case "spTree": { var oSpTree = new CSpTree(this.parent); oSpTree.fromXml(reader); this.spTree = oSpTree.spTree; break; } } }; CSld.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("p:cSld"); if(typeof this.name === "string" && this.name.length > 0) { writer.WriteXmlNullableAttributeString("name", this.name); } writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.Bg); let oSpTree = new CSpTree(null); oSpTree.spTree = this.spTree; oSpTree.toXml(writer); // this.spTree.toXml(writer); writer.WriteXmlNodeEnd("p:cSld"); }; function CSpTree(oSlideObject) { CBaseNoIdObject.call(this); this.spTree = []; this.slideObject = oSlideObject; } InitClass(CSpTree, CBaseNoIdObject, 0); CSpTree.prototype.fromXml = function(reader) { CBaseNoIdObject.prototype.fromXml.call(this, reader); if(!(this instanceof AscFormat.CGroupShape)) { reader.context.assignConnectors(this.spTree); } }; CSpTree.prototype.readSpTreeElement = function(name, reader) { let oSp = null; switch (name) { case "contentPart": { break; } case "cxnSp": { oSp = new AscFormat.CConnectionShape(); oSp.fromXml(reader); break; } case "extLst": { break; } case "graphicFrame": { oSp = new AscFormat.CGraphicFrame(); oSp.fromXml(reader); break; } case "grpSp": { oSp = new AscFormat.CGroupShape(); oSp.fromXml(reader); break; } case "grpSpPr": { break; } case "nvGrpSpPr": { break; } case "pic": { oSp = new AscFormat.CImageShape(); oSp.fromXml(reader); break; } case "sp": { oSp = new AscFormat.CShape(); oSp.fromXml(reader); break; } case "AlternateContent": { let oThis = this; let oNode = new CT_XmlNode(function (reader, name) { if(!oSp) { if(name === "Choice") { let oChoiceNode = new CT_XmlNode(function(reader, name) { oSp = CSpTree.prototype.readSpTreeElement.call(oThis, name, reader); return true; }); oChoiceNode.fromXml(reader); } else if(name === "Fallback") { let oFallbackNode = new CT_XmlNode(function(reader, name) { oSp = CSpTree.prototype.readSpTreeElement.call(oThis, name, reader); return true; }); oFallbackNode.fromXml(reader); } } return true; }); oNode.fromXml(reader); break; } } if (oSp) { if (name === "graphicFrame" && !(oSp.graphicObject instanceof AscCommonWord.CTable)) { let _xfrm = oSp.spPr && oSp.spPr.xfrm; let _nvGraphicFramePr = oSp.nvGraphicFramePr; oSp = oSp.graphicObject; if (oSp) { if (!oSp.spPr) { oSp.setSpPr(new AscFormat.CSpPr()); oSp.spPr.setParent(oSp); } if (!_xfrm) { _xfrm = new AscFormat.CXfrm(); _xfrm.setOffX(0); _xfrm.setOffY(0); _xfrm.setExtX(0); _xfrm.setExtY(0); } if (AscCommon.isRealObject(_nvGraphicFramePr)) { oSp.setNvSpPr(_nvGraphicFramePr); if (AscFormat.isRealNumber(_nvGraphicFramePr.locks)) { oSp.setLocks(_nvGraphicFramePr.locks); } if (oSp.cNvPr) {//TODO: connect objects //this.map_shapes_by_id[_nvGraphicFramePr.cNvPr.id] = oSp; } } oSp.spPr.setXfrm(_xfrm); _xfrm.setParent(oSp.spPr); } } } return oSp; }; CSpTree.prototype.readChildXml = function (name, reader) { let oSp = CSpTree.prototype.readSpTreeElement.call(this, name, reader); if (oSp) { oSp.setBDeleted(false); if(this.slideObject) { oSp.setParent(this.slideObject); } this.spTree.push(oSp); } return oSp; }; CSpTree.prototype.toXml = function (writer, bGroup) { let name_; let nDocType = writer.context.docType; if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || nDocType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { if (writer.context.groupIndex === 0) name_ = "wpg:wgp"; else name_ = "wpg:grpSp"; } else if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_XLSX) name_ = "xdr:grpSp"; else if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_CHART_DRAWING) name_ = "cdr:grpSp"; else if (nDocType === AscFormat.XMLWRITER_DOC_TYPE_GRAPHICS) name_ = "a:grpSp"; else if(nDocType === AscFormat.XMLWRITER_DOC_TYPE_DSP_DRAWING) name_ = "dsp:spTree"; else { if (writer.context.groupIndex === 0) name_ = "p:spTree"; else name_ = "p:grpSp"; } writer.WriteXmlNodeStart(name_); writer.WriteXmlAttributesEnd(); if (this.nvGrpSpPr) { if (writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX || writer.context.docType === AscFormat.XMLWRITER_DOC_TYPE_DOCX_GLOSSARY) { if (this.nvGrpSpPr.cNvGrpSpPr) { this.nvGrpSpPr.cNvGrpSpPr.toXmlGrSp2(writer, "wpg"); } } else this.nvGrpSpPr.toXmlGrp(writer); } else { if(writer.context.groupIndex === 0) { writer.WriteXmlString("<p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr /></p:nvGrpSpPr><p:grpSpPr bwMode=\"auto\"><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"0\" cy=\"0\"/></a:xfrm></p:grpSpPr>") } } if (this.spPr) { if(bGroup) { this.spPr.toXmlGroup(writer); } else { this.spPr.toXml(writer); } } writer.context.groupIndex++; for (let i = 0; i < this.spTree.length; ++i) { let oSp = this.spTree[i]; let nType = oSp.getObjectType(); let oElement = oSp; if(nType === AscDFH.historyitem_type_ChartSpace || nType === AscDFH.historyitem_type_SmartArt) { oElement = AscFormat.CGraphicFrame.prototype.static_CreateGraphicFrameFromDrawing(oSp); } oElement.toXml(writer); } writer.context.groupIndex--; writer.WriteXmlNodeEnd(name_); }; // ---------------------------------- // MASTERSLIDE ---------------------- function CTextStyles() { CBaseNoIdObject.call(this); this.titleStyle = null; this.bodyStyle = null; this.otherStyle = null; } InitClass(CTextStyles, CBaseNoIdObject, 0); CTextStyles.prototype.getStyleByPhType = function (phType) { switch (phType) { case AscFormat.phType_ctrTitle: case AscFormat.phType_title: { return this.titleStyle; } case AscFormat.phType_body: case AscFormat.phType_subTitle: case AscFormat.phType_obj: case null: { return this.bodyStyle; } default: { break; } } return this.otherStyle; }; CTextStyles.prototype.createDuplicate = function () { var ret = new CTextStyles(); if (isRealObject(this.titleStyle)) { ret.titleStyle = this.titleStyle.createDuplicate(); } if (isRealObject(this.bodyStyle)) { ret.bodyStyle = this.bodyStyle.createDuplicate(); } if (isRealObject(this.otherStyle)) { ret.otherStyle = this.otherStyle.createDuplicate(); } return ret; }; CTextStyles.prototype.Refresh_RecalcData = function () { }; CTextStyles.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.titleStyle)); if (isRealObject(this.titleStyle)) { this.titleStyle.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bodyStyle)); if (isRealObject(this.bodyStyle)) { this.bodyStyle.Write_ToBinary(w); } w.WriteBool(isRealObject(this.otherStyle)); if (isRealObject(this.otherStyle)) { this.otherStyle.Write_ToBinary(w); } }; CTextStyles.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.titleStyle = new TextListStyle(); this.titleStyle.Read_FromBinary(r); } else { this.titleStyle = null; } if (r.GetBool()) { this.bodyStyle = new TextListStyle(); this.bodyStyle.Read_FromBinary(r); } else { this.bodyStyle = null; } if (r.GetBool()) { this.otherStyle = new TextListStyle(); this.otherStyle.Read_FromBinary(r); } else { this.otherStyle = null; } }; CTextStyles.prototype.Document_Get_AllFontNames = function (AllFonts) { if (this.titleStyle) { this.titleStyle.Document_Get_AllFontNames(AllFonts); } if (this.bodyStyle) { this.bodyStyle.Document_Get_AllFontNames(AllFonts); } if (this.otherStyle) { this.otherStyle.Document_Get_AllFontNames(AllFonts); } }; CTextStyles.prototype.readChildXml = function (name, reader) { switch (name) { case "bodyStyle": { this.bodyStyle = new TextListStyle(); this.bodyStyle.fromXml(reader); break; } case "otherStyle": { this.otherStyle = new TextListStyle(); this.otherStyle.fromXml(reader); break; } case "titleStyle": { this.titleStyle = new TextListStyle(); this.titleStyle.fromXml(reader); break; } } }; CTextStyles.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart("p:txStyles"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.titleStyle, "p:titleStyle"); writer.WriteXmlNullable(this.bodyStyle, "p:bodyStyle"); writer.WriteXmlNullable(this.otherStyle, "p:otherStyle"); writer.WriteXmlNodeEnd("p:txStyles"); }; //--------------------------- // SLIDELAYOUT ---------------------- //Layout types var nSldLtTBlank = 0; // Blank )) var nSldLtTChart = 1; //Chart) var nSldLtTChartAndTx = 2; //( Chart and Text )) var nSldLtTClipArtAndTx = 3; //Clip Art and Text) var nSldLtTClipArtAndVertTx = 4; //Clip Art and Vertical Text) var nSldLtTCust = 5; // Custom )) var nSldLtTDgm = 6; //Diagram )) var nSldLtTFourObj = 7; //Four Objects) var nSldLtTMediaAndTx = 8; // ( Media and Text )) var nSldLtTObj = 9; //Title and Object) var nSldLtTObjAndTwoObj = 10; //Object and Two Object) var nSldLtTObjAndTx = 11; // ( Object and Text )) var nSldLtTObjOnly = 12; //Object) var nSldLtTObjOverTx = 13; // ( Object over Text)) var nSldLtTObjTx = 14; //Title, Object, and Caption) var nSldLtTPicTx = 15; //Picture and Caption) var nSldLtTSecHead = 16; //Section Header) var nSldLtTTbl = 17; // ( Table )) var nSldLtTTitle = 18; // ( Title )) var nSldLtTTitleOnly = 19; // ( Title Only )) var nSldLtTTwoColTx = 20; // ( Two Column Text )) var nSldLtTTwoObj = 21; //Two Objects) var nSldLtTTwoObjAndObj = 22; //Two Objects and Object) var nSldLtTTwoObjAndTx = 23; //Two Objects and Text) var nSldLtTTwoObjOverTx = 24; //Two Objects over Text) var nSldLtTTwoTxTwoObj = 25; //Two Text and Two Objects) var nSldLtTTx = 26; // ( Text )) var nSldLtTTxAndChart = 27; // ( Text and Chart )) var nSldLtTTxAndClipArt = 28; //Text and Clip Art) var nSldLtTTxAndMedia = 29; // ( Text and Media )) var nSldLtTTxAndObj = 30; // ( Text and Object )) var nSldLtTTxAndTwoObj = 31; //Text and Two Objects) var nSldLtTTxOverObj = 32; // ( Text over Object)) var nSldLtTVertTitleAndTx = 33; //Vertical Title and Text) var nSldLtTVertTitleAndTxOverChart = 34; //Vertical Title and Text Over Chart) var nSldLtTVertTx = 35; //Vertical Text) AscFormat.nSldLtTBlank = nSldLtTBlank; // Blank )) AscFormat.nSldLtTChart = nSldLtTChart; //Chart) AscFormat.nSldLtTChartAndTx = nSldLtTChartAndTx; //( Chart and Text )) AscFormat.nSldLtTClipArtAndTx = nSldLtTClipArtAndTx; //Clip Art and Text) AscFormat.nSldLtTClipArtAndVertTx = nSldLtTClipArtAndVertTx; //Clip Art and Vertical Text) AscFormat.nSldLtTCust = nSldLtTCust; // Custom )) AscFormat.nSldLtTDgm = nSldLtTDgm; //Diagram )) AscFormat.nSldLtTFourObj = nSldLtTFourObj; //Four Objects) AscFormat.nSldLtTMediaAndTx = nSldLtTMediaAndTx; // ( Media and Text )) AscFormat.nSldLtTObj = nSldLtTObj; //Title and Object) AscFormat.nSldLtTObjAndTwoObj = nSldLtTObjAndTwoObj; //Object and Two Object) AscFormat.nSldLtTObjAndTx = nSldLtTObjAndTx; // ( Object and Text )) AscFormat.nSldLtTObjOnly = nSldLtTObjOnly; //Object) AscFormat.nSldLtTObjOverTx = nSldLtTObjOverTx; // ( Object over Text)) AscFormat.nSldLtTObjTx = nSldLtTObjTx; //Title, Object, and Caption) AscFormat.nSldLtTPicTx = nSldLtTPicTx; //Picture and Caption) AscFormat.nSldLtTSecHead = nSldLtTSecHead; //Section Header) AscFormat.nSldLtTTbl = nSldLtTTbl; // ( Table )) AscFormat.nSldLtTTitle = nSldLtTTitle; // ( Title )) AscFormat.nSldLtTTitleOnly = nSldLtTTitleOnly; // ( Title Only )) AscFormat.nSldLtTTwoColTx = nSldLtTTwoColTx; // ( Two Column Text )) AscFormat.nSldLtTTwoObj = nSldLtTTwoObj; //Two Objects) AscFormat.nSldLtTTwoObjAndObj = nSldLtTTwoObjAndObj; //Two Objects and Object) AscFormat.nSldLtTTwoObjAndTx = nSldLtTTwoObjAndTx; //Two Objects and Text) AscFormat.nSldLtTTwoObjOverTx = nSldLtTTwoObjOverTx; //Two Objects over Text) AscFormat.nSldLtTTwoTxTwoObj = nSldLtTTwoTxTwoObj; //Two Text and Two Objects) AscFormat.nSldLtTTx = nSldLtTTx; // ( Text )) AscFormat.nSldLtTTxAndChart = nSldLtTTxAndChart; // ( Text and Chart )) AscFormat.nSldLtTTxAndClipArt = nSldLtTTxAndClipArt; //Text and Clip Art) AscFormat.nSldLtTTxAndMedia = nSldLtTTxAndMedia; // ( Text and Media )) AscFormat.nSldLtTTxAndObj = nSldLtTTxAndObj; // ( Text and Object )) AscFormat.nSldLtTTxAndTwoObj = nSldLtTTxAndTwoObj; //Text and Two Objects) AscFormat.nSldLtTTxOverObj = nSldLtTTxOverObj; // ( Text over Object)) AscFormat.nSldLtTVertTitleAndTx = nSldLtTVertTitleAndTx; //Vertical Title and Text) AscFormat.nSldLtTVertTitleAndTxOverChart = nSldLtTVertTitleAndTxOverChart; //Vertical Title and Text Over Chart) AscFormat.nSldLtTVertTx = nSldLtTVertTx; //Vertical Text) var _ph_multiplier = 4; var _weight_body = 9; var _weight_chart = 5; var _weight_clipArt = 2; var _weight_ctrTitle = 11; var _weight_dgm = 4; var _weight_media = 3; var _weight_obj = 8; var _weight_pic = 7; var _weight_subTitle = 10; var _weight_tbl = 6; var _weight_title = 11; var _ph_summ_blank = 0; var _ph_summ_chart = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_chart); var _ph_summ_chart_and_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_chart) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ_dgm = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_dgm); var _ph_summ_four_obj = Math.pow(_ph_multiplier, _weight_title) + 4 * Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__media_and_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_media) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__obj = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__obj_and_two_obj = Math.pow(_ph_multiplier, _weight_title) + 3 * Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__obj_and_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_obj) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__obj_only = Math.pow(_ph_multiplier, _weight_obj); var _ph_summ__pic_tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_pic) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__sec_head = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_subTitle); var _ph_summ__tbl = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_tbl); var _ph_summ__title_only = Math.pow(_ph_multiplier, _weight_title); var _ph_summ__two_col_tx = Math.pow(_ph_multiplier, _weight_title) + 2 * Math.pow(_ph_multiplier, _weight_body); var _ph_summ__two_obj_and_tx = Math.pow(_ph_multiplier, _weight_title) + 2 * Math.pow(_ph_multiplier, _weight_obj) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__two_obj_and_two_tx = Math.pow(_ph_multiplier, _weight_title) + 2 * Math.pow(_ph_multiplier, _weight_obj) + 2 * Math.pow(_ph_multiplier, _weight_body); var _ph_summ__tx = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_body); var _ph_summ__tx_and_clip_art = Math.pow(_ph_multiplier, _weight_title) + Math.pow(_ph_multiplier, _weight_body) + +Math.pow(_ph_multiplier, _weight_clipArt); var _arr_lt_types_weight = []; _arr_lt_types_weight[0] = _ph_summ_blank; _arr_lt_types_weight[1] = _ph_summ_chart; _arr_lt_types_weight[2] = _ph_summ_chart_and_tx; _arr_lt_types_weight[3] = _ph_summ_dgm; _arr_lt_types_weight[4] = _ph_summ_four_obj; _arr_lt_types_weight[5] = _ph_summ__media_and_tx; _arr_lt_types_weight[6] = _ph_summ__obj; _arr_lt_types_weight[7] = _ph_summ__obj_and_two_obj; _arr_lt_types_weight[8] = _ph_summ__obj_and_tx; _arr_lt_types_weight[9] = _ph_summ__obj_only; _arr_lt_types_weight[10] = _ph_summ__pic_tx; _arr_lt_types_weight[11] = _ph_summ__sec_head; _arr_lt_types_weight[12] = _ph_summ__tbl; _arr_lt_types_weight[13] = _ph_summ__title_only; _arr_lt_types_weight[14] = _ph_summ__two_col_tx; _arr_lt_types_weight[15] = _ph_summ__two_obj_and_tx; _arr_lt_types_weight[16] = _ph_summ__two_obj_and_two_tx; _arr_lt_types_weight[17] = _ph_summ__tx; _arr_lt_types_weight[18] = _ph_summ__tx_and_clip_art; _arr_lt_types_weight.sort(AscCommon.fSortAscending); var _global_layout_summs_array = {}; _global_layout_summs_array["_" + _ph_summ_blank] = nSldLtTBlank; _global_layout_summs_array["_" + _ph_summ_chart] = nSldLtTChart; _global_layout_summs_array["_" + _ph_summ_chart_and_tx] = nSldLtTChartAndTx; _global_layout_summs_array["_" + _ph_summ_dgm] = nSldLtTDgm; _global_layout_summs_array["_" + _ph_summ_four_obj] = nSldLtTFourObj; _global_layout_summs_array["_" + _ph_summ__media_and_tx] = nSldLtTMediaAndTx; _global_layout_summs_array["_" + _ph_summ__obj] = nSldLtTObj; _global_layout_summs_array["_" + _ph_summ__obj_and_two_obj] = nSldLtTObjAndTwoObj; _global_layout_summs_array["_" + _ph_summ__obj_and_tx] = nSldLtTObjAndTx; _global_layout_summs_array["_" + _ph_summ__obj_only] = nSldLtTObjOnly; _global_layout_summs_array["_" + _ph_summ__pic_tx] = nSldLtTPicTx; _global_layout_summs_array["_" + _ph_summ__sec_head] = nSldLtTSecHead; _global_layout_summs_array["_" + _ph_summ__tbl] = nSldLtTTbl; _global_layout_summs_array["_" + _ph_summ__title_only] = nSldLtTTitleOnly; _global_layout_summs_array["_" + _ph_summ__two_col_tx] = nSldLtTTwoColTx; _global_layout_summs_array["_" + _ph_summ__two_obj_and_tx] = nSldLtTTwoObjAndTx; _global_layout_summs_array["_" + _ph_summ__two_obj_and_two_tx] = nSldLtTTwoTxTwoObj; _global_layout_summs_array["_" + _ph_summ__tx] = nSldLtTTx; _global_layout_summs_array["_" + _ph_summ__tx_and_clip_art] = nSldLtTTxAndClipArt; // SLIDE ---------------------------- function redrawSlide(slide, presentation, arrInd, pos, direction, arr_slides) { if (slide) { slide.recalculate(); presentation.DrawingDocument.OnRecalculatePage(slide.num, slide); } if (direction === 0) { if (pos > 0) { presentation.backChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos - 1]], presentation, arrInd, pos - 1, -1, arr_slides) }, recalcSlideInterval); } else { presentation.backChangeThemeTimeOutId = null; } if (pos < arrInd.length - 1) { presentation.forwardChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos + 1]], presentation, arrInd, pos + 1, +1, arr_slides) }, recalcSlideInterval); } else { presentation.forwardChangeThemeTimeOutId = null; } presentation.startChangeThemeTimeOutId = null; } if (direction > 0) { if (pos < arrInd.length - 1) { presentation.forwardChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos + 1]], presentation, arrInd, pos + 1, +1, arr_slides) }, recalcSlideInterval); } else { presentation.forwardChangeThemeTimeOutId = null; } } if (direction < 0) { if (pos > 0) { presentation.backChangeThemeTimeOutId = setTimeout(function () { redrawSlide(arr_slides[arrInd[pos - 1]], presentation, arrInd, pos - 1, -1, arr_slides) }, recalcSlideInterval); } else { presentation.backChangeThemeTimeOutId = null; } } } function CTextFit(nType) { CBaseNoIdObject.call(this); this.type = nType !== undefined && nType !== null ? nType : 0; this.fontScale = null; this.lnSpcReduction = null; } InitClass(CTextFit, CBaseNoIdObject, 0); CTextFit.prototype.CreateDublicate = function () { var d = new CTextFit(); d.type = this.type; d.fontScale = this.fontScale; d.lnSpcReduction = this.lnSpcReduction; return d; }; CTextFit.prototype.Write_ToBinary = function (w) { writeLong(w, this.type); writeLong(w, this.fontScale); writeLong(w, this.lnSpcReduction); }; CTextFit.prototype.Read_FromBinary = function (r) { this.type = readLong(r); this.fontScale = readLong(r); this.lnSpcReduction = readLong(r); }; CTextFit.prototype.Get_Id = function () { return this.Id; }; CTextFit.prototype.Refresh_RecalcData = function () { }; CTextFit.prototype.readAttrXml = function (name, reader) { switch (name) { case "fontScale": { this.fontScale = reader.GetValueInt(); break; } case "lnSpcReduction": { this.lnSpcReduction = reader.GetValueInt(); break; } } }; CTextFit.prototype.toXml = function (writer) { if (this.type === AscFormat.text_fit_No) { writer.WriteXmlString("<a:noAutofit/>"); return; } if (this.type === AscFormat.text_fit_Auto) { writer.WriteXmlString("<a:spAutoFit/>"); return; } if (this.type === AscFormat.text_fit_NormAuto) { writer.WriteXmlNodeStart("a:normAutofit"); writer.WriteXmlNullableAttributeString("fontScale", this.fontScale); writer.WriteXmlNullableAttributeString("lnSpcReduction", this.lnSpcReduction); writer.WriteXmlAttributesEnd(true); } }; //----------------------------- //Text Anchoring Types var nTextATB = 0;// (Text Anchor Enum ( Bottom )) var nTextATCtr = 1;// (Text Anchor Enum ( Center )) var nTextATDist = 2;// (Text Anchor Enum ( Distributed )) var nTextATJust = 3;// (Text Anchor Enum ( Justified )) var nTextATT = 4;// Top function CBodyPr() { CBaseNoIdObject.call(this); this.flatTx = null; this.anchor = null; this.anchorCtr = null; this.bIns = null; this.compatLnSpc = null; this.forceAA = null; this.fromWordArt = null; this.horzOverflow = null; this.lIns = null; this.numCol = null; this.rIns = null; this.rot = null; this.rtlCol = null; this.spcCol = null; this.spcFirstLastPara = null; this.tIns = null; this.upright = null; this.vert = null; this.vertOverflow = null; this.wrap = null; this.textFit = null; this.prstTxWarp = null; this.parent = null; } InitClass(CBodyPr, CBaseNoIdObject, 0); CBodyPr.prototype.Get_Id = function () { return this.Id; }; CBodyPr.prototype.Refresh_RecalcData = function () { }; CBodyPr.prototype.setVertOpen = function (nVert) { let nVert_ = nVert; if(nVert === AscFormat.nVertTTwordArtVert) { nVert_ = AscFormat.nVertTTvert; } this.vert = nVert_; }; CBodyPr.prototype.getLnSpcReduction = function () { if (this.textFit && this.textFit.type === AscFormat.text_fit_NormAuto && AscFormat.isRealNumber(this.textFit.lnSpcReduction)) { return this.textFit.lnSpcReduction / 100000.0; } return undefined; }; CBodyPr.prototype.getFontScale = function () { if (this.textFit && this.textFit.type === AscFormat.text_fit_NormAuto && AscFormat.isRealNumber(this.textFit.fontScale)) { return this.textFit.fontScale / 100000.0; } return undefined; }; CBodyPr.prototype.isNotNull = function () { return this.flatTx !== null || this.anchor !== null || this.anchorCtr !== null || this.bIns !== null || this.compatLnSpc !== null || this.forceAA !== null || this.fromWordArt !== null || this.horzOverflow !== null || this.lIns !== null || this.numCol !== null || this.rIns !== null || this.rot !== null || this.rtlCol !== null || this.spcCol !== null || this.spcFirstLastPara !== null || this.tIns !== null || this.upright !== null || this.vert !== null || this.vertOverflow !== null || this.wrap !== null || this.textFit !== null || this.prstTxWarp !== null; }; CBodyPr.prototype.setAnchor = function (val) { this.anchor = val; }; CBodyPr.prototype.setVert = function (val) { this.vert = val; }; CBodyPr.prototype.setRot = function (val) { this.rot = val; }; CBodyPr.prototype.reset = function () { this.flatTx = null; this.anchor = null; this.anchorCtr = null; this.bIns = null; this.compatLnSpc = null; this.forceAA = null; this.fromWordArt = null; this.horzOverflow = null; this.lIns = null; this.numCol = null; this.rIns = null; this.rot = null; this.rtlCol = null; this.spcCol = null; this.spcFirstLastPara = null; this.tIns = null; this.upright = null; this.vert = null; this.vertOverflow = null; this.wrap = null; this.textFit = null; this.prstTxWarp = null; }; CBodyPr.prototype.WritePrstTxWarp = function (w) { w.WriteBool(isRealObject(this.prstTxWarp)); if (isRealObject(this.prstTxWarp)) { writeString(w, this.prstTxWarp.preset); var startPos = w.GetCurPosition(), countAv = 0; w.Skip(4); for (var key in this.prstTxWarp.avLst) { if (this.prstTxWarp.avLst.hasOwnProperty(key)) { ++countAv; w.WriteString2(key); w.WriteLong(this.prstTxWarp.gdLst[key]); } } var endPos = w.GetCurPosition(); w.Seek(startPos); w.WriteLong(countAv); w.Seek(endPos); } }; CBodyPr.prototype.ReadPrstTxWarp = function (r) { ExecuteNoHistory(function () { if (r.GetBool()) { this.prstTxWarp = AscFormat.CreatePrstTxWarpGeometry(readString(r)); var count = r.GetLong(); for (var i = 0; i < count; ++i) { var sAdj = r.GetString2(); var nVal = r.GetLong(); this.prstTxWarp.AddAdj(sAdj, 15, nVal + "", undefined, undefined); } } }, this, []); }; CBodyPr.prototype.Write_ToBinary2 = function (w) { var flag = this.flatTx != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.flatTx); } flag = this.anchor != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.anchor); } flag = this.anchorCtr != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.anchorCtr); } flag = this.bIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.bIns); } flag = this.compatLnSpc != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.compatLnSpc); } flag = this.forceAA != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.forceAA); } flag = this.fromWordArt != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.fromWordArt); } flag = this.horzOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.horzOverflow); } flag = this.lIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.lIns); } flag = this.numCol != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.numCol); } flag = this.rIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.rIns); } flag = this.rot != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.rot); } flag = this.rtlCol != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.rtlCol); } flag = this.spcCol != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.spcCol); } flag = this.spcFirstLastPara != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.spcFirstLastPara); } flag = this.tIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.tIns); } flag = this.upright != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.upright); } flag = this.vert != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vert); } flag = this.vertOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vertOverflow); } flag = this.wrap != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.wrap); } this.WritePrstTxWarp(w); w.WriteBool(isRealObject(this.textFit)); if (this.textFit) { this.textFit.Write_ToBinary(w); } }; CBodyPr.prototype.Read_FromBinary2 = function (r) { var flag = r.GetBool(); if (flag) { this.flatTx = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchor = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchorCtr = r.GetBool(); } flag = r.GetBool(); if (flag) { this.bIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.compatLnSpc = r.GetBool(); } flag = r.GetBool(); if (flag) { this.forceAA = r.GetBool(); } flag = r.GetBool(); if (flag) { this.fromWordArt = r.GetBool(); } flag = r.GetBool(); if (flag) { this.horzOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.lIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.numCol = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.rot = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rtlCol = r.GetBool(); } flag = r.GetBool(); if (flag) { this.spcCol = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.spcFirstLastPara = r.GetBool(); } flag = r.GetBool(); if (flag) { this.tIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.upright = r.GetBool(); } flag = r.GetBool(); if (flag) { this.vert = r.GetLong(); } flag = r.GetBool(); if (flag) { this.vertOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.wrap = r.GetLong(); } this.ReadPrstTxWarp(r); if (r.GetBool()) { this.textFit = new CTextFit(); this.textFit.Read_FromBinary(r); } }; CBodyPr.prototype.setDefault = function () { this.flatTx = null; this.anchor = 4; this.anchorCtr = false; this.bIns = 45720 / 36000; this.compatLnSpc = false; this.forceAA = false; this.fromWordArt = false; this.horzOverflow = AscFormat.nHOTOverflow; this.lIns = 91440 / 36000; this.numCol = 1; this.rIns = 91440 / 36000; this.rot = null; this.rtlCol = false; this.spcCol = false; this.spcFirstLastPara = null; this.tIns = 45720 / 36000; this.upright = false; this.vert = AscFormat.nVertTThorz; this.vertOverflow = AscFormat.nVOTOverflow; this.wrap = AscFormat.nTWTSquare; this.prstTxWarp = null; this.textFit = null; }; CBodyPr.prototype.createDuplicate = function () { var duplicate = new CBodyPr(); duplicate.flatTx = this.flatTx; duplicate.anchor = this.anchor; duplicate.anchorCtr = this.anchorCtr; duplicate.bIns = this.bIns; duplicate.compatLnSpc = this.compatLnSpc; duplicate.forceAA = this.forceAA; duplicate.fromWordArt = this.fromWordArt; duplicate.horzOverflow = this.horzOverflow; duplicate.lIns = this.lIns; duplicate.numCol = this.numCol; duplicate.rIns = this.rIns; duplicate.rot = this.rot; duplicate.rtlCol = this.rtlCol; duplicate.spcCol = this.spcCol; duplicate.spcFirstLastPara = this.spcFirstLastPara; duplicate.tIns = this.tIns; duplicate.upright = this.upright; duplicate.vert = this.vert; duplicate.vertOverflow = this.vertOverflow; duplicate.wrap = this.wrap; if (this.prstTxWarp) { duplicate.prstTxWarp = ExecuteNoHistory(function () { return this.prstTxWarp.createDuplicate(); }, this, []); } if (this.textFit) { duplicate.textFit = this.textFit.CreateDublicate(); } return duplicate; }; CBodyPr.prototype.createDuplicateForSmartArt = function (oPr) { var duplicate = new CBodyPr(); duplicate.anchor = this.anchor; duplicate.vert = this.vert; duplicate.rot = this.rot; duplicate.vertOverflow = this.vertOverflow; duplicate.horzOverflow = this.horzOverflow; duplicate.upright = this.upright; duplicate.rtlCol = this.rtlCol; duplicate.fromWordArt = this.fromWordArt; duplicate.compatLnSpc = this.compatLnSpc; duplicate.forceAA = this.forceAA; if (oPr.lIns) { duplicate.lIns = this.lIns; } if (oPr.rIns) { duplicate.rIns = this.rIns; } if (oPr.tIns) { duplicate.tIns = this.tIns; } if (oPr.bIns) { duplicate.bIns = this.bIns; } return duplicate; }; CBodyPr.prototype.merge = function (bodyPr) { if (!bodyPr) return; if (bodyPr.flatTx != null) { this.flatTx = bodyPr.flatTx; } if (bodyPr.anchor != null) { this.anchor = bodyPr.anchor; } if (bodyPr.anchorCtr != null) { this.anchorCtr = bodyPr.anchorCtr; } if (bodyPr.bIns != null) { this.bIns = bodyPr.bIns; } if (bodyPr.compatLnSpc != null) { this.compatLnSpc = bodyPr.compatLnSpc; } if (bodyPr.forceAA != null) { this.forceAA = bodyPr.forceAA; } if (bodyPr.fromWordArt != null) { this.fromWordArt = bodyPr.fromWordArt; } if (bodyPr.horzOverflow != null) { this.horzOverflow = bodyPr.horzOverflow; } if (bodyPr.lIns != null) { this.lIns = bodyPr.lIns; } if (bodyPr.numCol != null) { this.numCol = bodyPr.numCol; } if (bodyPr.rIns != null) { this.rIns = bodyPr.rIns; } if (bodyPr.rot != null) { this.rot = bodyPr.rot; } if (bodyPr.rtlCol != null) { this.rtlCol = bodyPr.rtlCol; } if (bodyPr.spcCol != null) { this.spcCol = bodyPr.spcCol; } if (bodyPr.spcFirstLastPara != null) { this.spcFirstLastPara = bodyPr.spcFirstLastPara; } if (bodyPr.tIns != null) { this.tIns = bodyPr.tIns; } if (bodyPr.upright != null) { this.upright = bodyPr.upright; } if (bodyPr.vert != null) { this.vert = bodyPr.vert; } if (bodyPr.vertOverflow != null) { this.vertOverflow = bodyPr.vertOverflow; } if (bodyPr.wrap != null) { this.wrap = bodyPr.wrap; } if (bodyPr.prstTxWarp) { this.prstTxWarp = ExecuteNoHistory(function () { return bodyPr.prstTxWarp.createDuplicate(); }, this, []); } if (bodyPr.textFit) { this.textFit = bodyPr.textFit.CreateDublicate(); } if (bodyPr.numCol != null) { this.numCol = bodyPr.numCol; } return this; }; CBodyPr.prototype.Write_ToBinary = function (w) { var flag = this.flatTx != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.flatTx); } flag = this.anchor != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.anchor); } flag = this.anchorCtr != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.anchorCtr); } flag = this.bIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.bIns); } flag = this.compatLnSpc != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.compatLnSpc); } flag = this.forceAA != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.forceAA); } flag = this.fromWordArt != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.fromWordArt); } flag = this.horzOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.horzOverflow); } flag = this.lIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.lIns); } flag = this.numCol != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.numCol); } flag = this.rIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.rIns); } flag = this.rot != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.rot); } flag = this.rtlCol != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.rtlCol); } flag = this.spcCol != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.spcCol); } flag = this.spcFirstLastPara != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.spcFirstLastPara); } flag = this.tIns != null; w.WriteBool(flag); if (flag) { w.WriteDouble(this.tIns); } flag = this.upright != null; w.WriteBool(flag); if (flag) { w.WriteBool(this.upright); } flag = this.vert != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vert); } flag = this.vertOverflow != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.vertOverflow); } flag = this.wrap != null; w.WriteBool(flag); if (flag) { w.WriteLong(this.wrap); } this.WritePrstTxWarp(w); w.WriteBool(isRealObject(this.textFit)); if (this.textFit) { this.textFit.Write_ToBinary(w); } }; CBodyPr.prototype.Read_FromBinary = function (r) { var flag = r.GetBool(); if (flag) { this.flatTx = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchor = r.GetLong(); } flag = r.GetBool(); if (flag) { this.anchorCtr = r.GetBool(); } flag = r.GetBool(); if (flag) { this.bIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.compatLnSpc = r.GetBool(); } flag = r.GetBool(); if (flag) { this.forceAA = r.GetBool(); } flag = r.GetBool(); if (flag) { this.fromWordArt = r.GetBool(); } flag = r.GetBool(); if (flag) { this.horzOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.lIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.numCol = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.rot = r.GetLong(); } flag = r.GetBool(); if (flag) { this.rtlCol = r.GetBool(); } flag = r.GetBool(); if (flag) { this.spcCol = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.spcFirstLastPara = r.GetBool(); } flag = r.GetBool(); if (flag) { this.tIns = r.GetDouble(); } flag = r.GetBool(); if (flag) { this.upright = r.GetBool(); } flag = r.GetBool(); if (flag) { this.vert = r.GetLong(); } flag = r.GetBool(); if (flag) { this.vertOverflow = r.GetLong(); } flag = r.GetBool(); if (flag) { this.wrap = r.GetLong(); } this.ReadPrstTxWarp(r); if (r.GetBool()) { this.textFit = new CTextFit(); this.textFit.Read_FromBinary(r) } }; CBodyPr.prototype.readXmlInset = function (reader) { return reader.GetValueInt() / 36000; }; CBodyPr.prototype.getXmlInset = function (dVal) { if (!AscFormat.isRealNumber(dVal)) { return null; } return dVal * 36000 + 0.5 >> 0; }; CBodyPr.prototype.GetAnchorCode = function (sVal) { switch (sVal) { case "b": { return AscFormat.VERTICAL_ANCHOR_TYPE_BOTTOM; } case "ctr": { return AscFormat.VERTICAL_ANCHOR_TYPE_CENTER; } case "dist": { return AscFormat.VERTICAL_ANCHOR_TYPE_DISTRIBUTED; } case "just": { return AscFormat.VERTICAL_ANCHOR_TYPE_JUSTIFIED; } case "t": { return AscFormat.VERTICAL_ANCHOR_TYPE_TOP; } } }; CBodyPr.prototype.GetAnchorByCode = function (nCode) { switch (nCode) { case AscFormat.VERTICAL_ANCHOR_TYPE_BOTTOM: { return "b"; } case AscFormat.VERTICAL_ANCHOR_TYPE_CENTER: { return "ctr"; } case AscFormat.VERTICAL_ANCHOR_TYPE_DISTRIBUTED: { return "dist"; } case AscFormat.VERTICAL_ANCHOR_TYPE_JUSTIFIED: { return "just"; } case AscFormat.VERTICAL_ANCHOR_TYPE_TOP: { return "t" } } return null; }; CBodyPr.prototype.GetVertOverFlowCode = function (sVal) { switch (sVal) { case "clip": { return AscFormat.nVOTClip; } case "ellipsis": { return AscFormat.nVOTEllipsis; } case "overflow": { return AscFormat.nVOTOverflow; } } }; CBodyPr.prototype.GetHorOverFlowCode = function (sVal) { switch (sVal) { case "clip": { return AscFormat.nHOTClip; } case "overflow": { return AscFormat.nHOTOverflow; } } }; CBodyPr.prototype.GetVertOverFlowByCode = function (nCode) { switch (nCode) { case AscFormat.nVOTClip: { return "clip"; } case AscFormat.nVOTEllipsis : { return "ellipsis"; } case AscFormat.nVOTOverflow: { return "overflow"; } } }; CBodyPr.prototype.GetHorOverFlowByCode = function (nCode) { switch (nCode) { case AscFormat.nHOTClip: { return "clip"; } case AscFormat.nHOTOverflow: { return "overflow"; } } }; CBodyPr.prototype.GetVertCode = function (sVal) { switch (sVal) { case "eaVert": { return AscFormat.nVertTTeaVert; } case "horz": { return AscFormat.nVertTThorz; } case "mongolianVert": { return AscFormat.nVertTTmongolianVert; } case "vert": { return AscFormat.nVertTTvert; } case "vert270": { return AscFormat.nVertTTvert270; } case "wordArtVert": { return AscFormat.nVertTTwordArtVert; } case "wordArtVertRtl": { return AscFormat.nVertTTwordArtVertRtl; } } }; CBodyPr.prototype.GetVertByCode = function (nCode) { switch (nCode) { case AscFormat.nVertTTeaVert: { return "eaVert"; } case AscFormat.nVertTThorz: { return "horz"; } case AscFormat.nVertTTmongolianVert: { return "mongolianVert"; } case AscFormat.nVertTTvert: { return "vert"; } case AscFormat.nVertTTvert270: { return "vert270"; } case AscFormat.nVertTTwordArtVert: { return "wordArtVert"; } case AscFormat.nVertTTwordArtVertRtl: { return "wordArtVertRtl"; } } }; CBodyPr.prototype.GetWrapCode = function (sVal) { switch (sVal) { case "none": { return AscFormat.nTWTNone; } case "square": { return AscFormat.nTWTSquare; } } }; CBodyPr.prototype.GetWrapByCode = function (nCode) { switch (nCode) { case AscFormat.nTWTNone: { return "none"; } case AscFormat.nTWTSquare: { return "square"; } } }; CBodyPr.prototype.readAttrXml = function (name, reader) { switch (name) { case "anchor": { let sVal = reader.GetValue(); this.anchor = this.GetAnchorCode(sVal); break; } case "anchorCtr": { this.anchorCtr = reader.GetValueBool(); break; } case "bIns": { this.bIns = this.readXmlInset(reader); break; } case "compatLnSpc": { this.compatLnSpc = reader.GetValueBool(); break; } case "forceAA": { this.forceAA = reader.GetValueBool(); break; } case "fromWordArt": { this.fromWordArt = reader.GetValueBool(); break; } case "horzOverflow": { let sVal = reader.GetValue(); this.horzOverflow = this.GetHorOverFlowCode(sVal); break; } case "lIns": { this.lIns = this.readXmlInset(reader); break; } case "numCol": { this.numCol = reader.GetValueInt(); break; } case "rIns": { this.rIns = this.readXmlInset(reader); break; } case "rot": { this.rot = reader.GetValueInt(); break; } case "rtlCol": { this.rtlCol = reader.GetValueBool(); break; } case "spcCol": { this.spcCol = this.readXmlInset(reader); break; } case "spcFirstLastPara": { this.spcFirstLastPara = reader.GetValueBool(); break; } case "tIns": { this.tIns = this.readXmlInset(reader); break; } case "upright": { this.upright = reader.GetValueBool(); break; } case "vert": { let sVal = reader.GetValue(); this.setVertOpen(this.GetVertCode(sVal)); break; } case "vertOverflow": { let sVal = reader.GetValue(); this.vertOverflow = this.GetVertOverFlowCode(sVal); break; } case "wrap": { let sVal = reader.GetValue(); this.wrap = this.GetWrapCode(sVal); break; } } }; CBodyPr.prototype.readChildXml = function (name, reader) { switch (name) { case "flatTx": { this.flatTx = AscCommon.CT_Int.prototype.toVal(reader, null); break; } case "noAutofit": { this.textFit = new CTextFit(AscFormat.text_fit_No); break; } case "normAutofit": { this.textFit = new CTextFit(AscFormat.text_fit_NormAuto); this.textFit.fromXml(reader); break; } case "prstTxWarp": { this.prstTxWarp = AscFormat.ExecuteNoHistory(function () { let oGeometry = new AscFormat.Geometry(); oGeometry.bWrap = true; oGeometry.fromXml(reader); return oGeometry; }, this, []); break; } case "scene3d": { //TODO: break; } case "sp3d": { //TODO break; } case "spAutoFit": { this.textFit = new CTextFit(AscFormat.text_fit_Auto); break; } } }; CBodyPr.prototype.toXml = function (writer, sNamespace) { let sNamespace_ = sNamespace || "a"; writer.WriteXmlNodeStart(sNamespace_ + ":bodyPr"); writer.WriteXmlNullableAttributeString("rot", this.rot); writer.WriteXmlNullableAttributeBool("spcFirstLastPara", this.spcFirstLastPara); writer.WriteXmlNullableAttributeString("vertOverflow", this.GetVertOverFlowByCode(this.vertOverflow)); writer.WriteXmlNullableAttributeString("horzOverflow", this.GetHorOverFlowByCode(this.horzOverflow)); writer.WriteXmlNullableAttributeString("vert", this.GetVertByCode(this.vert)); writer.WriteXmlNullableAttributeString("wrap", this.GetWrapByCode(this.wrap)); writer.WriteXmlNullableAttributeInt("lIns", this.getXmlInset(this.lIns)); writer.WriteXmlNullableAttributeInt("tIns", this.getXmlInset(this.tIns)); writer.WriteXmlNullableAttributeInt("rIns", this.getXmlInset(this.rIns)); writer.WriteXmlNullableAttributeInt("bIns", this.getXmlInset(this.bIns)); writer.WriteXmlNullableAttributeUInt("numCol", this.numCol); writer.WriteXmlNullableAttributeInt("spcCol", this.getXmlInset(this.spcCol)); writer.WriteXmlNullableAttributeBool("rtlCol", this.rtlCol); writer.WriteXmlNullableAttributeBool("fromWordArt", this.fromWordArt); writer.WriteXmlNullableAttributeString("anchor", this.GetAnchorByCode(this.anchor)); writer.WriteXmlNullableAttributeBool("anchorCtr", this.anchorCtr); writer.WriteXmlNullableAttributeBool("forceAA", this.forceAA); writer.WriteXmlNullableAttributeBool("upright", this.upright); writer.WriteXmlNullableAttributeBool("compatLnSpc", this.compatLnSpc); if(this.prstTxWarp || this.textFit || AscFormat.isRealNumber(this.flatTx)) { writer.WriteXmlAttributesEnd(); writer.WriteXmlNullable(this.prstTxWarp, "a:prstTxWarp"); writer.WriteXmlNullable(this.textFit); //writer.WriteXmlNullable(this.scene3d); //writer.WriteXmlNullable(this.sp3d); if (AscFormat.isRealNumber(this.flatTx)) { writer.WriteXmlNodeStart(sNamespace_ + ":flatTx"); writer.WriteXmlNullableAttributeString("z", this.flatTx); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd(sNamespace_ + ":flatTx"); } writer.WriteXmlNodeEnd(sNamespace_ + ":bodyPr"); } else { writer.WriteXmlAttributesEnd(true); } }; function CTextParagraphPr() { this.bullet = new CBullet(); this.lvl = null; this.pPr = new CParaPr(); this.rPr = new CTextPr(); } function CreateNoneBullet() { var ret = new CBullet(); ret.bulletType = new CBulletType(); ret.bulletType.type = AscFormat.BULLET_TYPE_BULLET_NONE; return ret; } function CompareBullets(bullet1, bullet2) { //TODO: ะฟะพะบะฐ ะฑัƒะดะตะผ ัั€ะฐะฒะฝะธะฒะฐั‚ัŒ ั‚ะพะปัŒะบะพ bulletType, ั‚. ะบ. ัั‚ะฐ ั„ัƒะฝะบั†ะธั ะธัะฟะพะปัŒะทัƒะตั‚ัั ะดะปั ะผะตั€ะถะฐ ัะฒะพะนัั‚ะฒ ะฟั€ะธ ะพั‚ะดะฐั‡ะต ะฒ ะธะฝั‚ะตั€ั„ะตะนั, ะฐ ะดะปั ะธะฝั‚ะตั€ั„ะตะนัะฐ bulletTyp'a ะดะพัั‚ะฐั‚ะพั‡ะฝะพ. ะ•ัะปะธ ะฟะพะฝะฐะดะพะฑะธั‚ัั ะฝัƒะถะฝะพ ัะดะตะปะฐั‚ัŒ ะฟะพะปะฝะพะต ัั€ะฐะฒะฝะตะฝะธะต. // if (bullet1.bulletType && bullet2.bulletType && bullet1.bulletType.type === bullet2.bulletType.type) { var ret = new CBullet(); ret.bulletType = new CBulletType(); switch (bullet1.bulletType.type) { case AscFormat.BULLET_TYPE_BULLET_CHAR: { ret.bulletType.type = AscFormat.BULLET_TYPE_BULLET_CHAR; if (bullet1.bulletType.Char === bullet2.bulletType.Char) { ret.bulletType.Char = bullet1.bulletType.Char; } break; } case AscFormat.BULLET_TYPE_BULLET_BLIP: { ret.bulletType.type = AscFormat.BULLET_TYPE_BULLET_BLIP; var compareBlip = bullet1.bulletType.Blip && bullet2.bulletType.Blip && bullet1.bulletType.Blip.compare(bullet2.bulletType.Blip); ret.bulletType.Blip = compareBlip; break; } case AscFormat.BULLET_TYPE_BULLET_AUTONUM: { if (bullet1.bulletType.AutoNumType === bullet2.bulletType.AutoNumType) { ret.bulletType.AutoNumType = bullet1.bulletType.AutoNumType; } if (bullet1.bulletType.startAt === bullet2.bulletType.startAt) { ret.bulletType.startAt = bullet1.bulletType.startAt; } else { ret.bulletType.startAt = undefined; } if (bullet1.bulletType.type === bullet2.bulletType.type) { ret.bulletType.type = bullet1.bulletType.type; } break; } } if (bullet1.bulletSize && bullet2.bulletSize && bullet1.bulletSize.val === bullet2.bulletSize.val && bullet1.bulletSize.type === bullet2.bulletSize.type) { ret.bulletSize = bullet1.bulletSize; } if (bullet1.bulletColor && bullet2.bulletColor && bullet1.bulletColor.type === bullet2.bulletColor.type) { ret.bulletColor = new CBulletColor(); ret.bulletColor.type = bullet2.bulletColor.type; if (bullet1.bulletColor.UniColor) { ret.bulletColor.UniColor = bullet1.bulletColor.UniColor.compare(bullet2.bulletColor.UniColor); } if (!ret.bulletColor.UniColor || !ret.bulletColor.UniColor.color) { ret.bulletColor = null; } } return ret; } else { return undefined; } } function CBullet() { CBaseNoIdObject.call(this) this.bulletColor = null; this.bulletSize = null; this.bulletTypeface = null; this.bulletType = null; this.Bullet = null; //used to get properties for interface this.FirstTextPr = null; } InitClass(CBullet, CBaseNoIdObject, 0); CBullet.prototype.Set_FromObject = function (obj) { if (obj) { if (obj.bulletColor) { this.bulletColor = new CBulletColor(); this.bulletColor.Set_FromObject(obj.bulletColor); } else this.bulletColor = null; if (obj.bulletSize) { this.bulletSize = new CBulletSize(); this.bulletSize.Set_FromObject(obj.bulletSize); } else this.bulletSize = null; if (obj.bulletTypeface) { this.bulletTypeface = new CBulletTypeface(); this.bulletTypeface.Set_FromObject(obj.bulletTypeface); } else this.bulletTypeface = null; } }; CBullet.prototype.merge = function (oBullet) { if (!oBullet) { return; } if (oBullet.bulletColor) { if (!this.bulletColor) { this.bulletColor = oBullet.bulletColor.createDuplicate(); } else { this.bulletColor.merge(oBullet.bulletColor); } } if (oBullet.bulletSize) { if (!this.bulletSize) { this.bulletSize = oBullet.bulletSize.createDuplicate(); } else { this.bulletSize.merge(oBullet.bulletSize); } } if (oBullet.bulletTypeface) { if (!this.bulletTypeface) { this.bulletTypeface = oBullet.bulletTypeface.createDuplicate(); } else { this.bulletTypeface.merge(oBullet.bulletTypeface); } } if (oBullet.bulletType) { if (!this.bulletType) { this.bulletType = oBullet.bulletType.createDuplicate(); } else { this.bulletType.merge(oBullet.bulletType); } } }; CBullet.prototype.createDuplicate = function () { var duplicate = new CBullet(); if (this.bulletColor) { duplicate.bulletColor = this.bulletColor.createDuplicate(); } if (this.bulletSize) { duplicate.bulletSize = this.bulletSize.createDuplicate(); } if (this.bulletTypeface) { duplicate.bulletTypeface = this.bulletTypeface.createDuplicate(); } if (this.bulletType) { duplicate.bulletType = this.bulletType.createDuplicate(); } duplicate.Bullet = this.Bullet; return duplicate; }; CBullet.prototype.isBullet = function () { return this.bulletType != null && this.bulletType.type != null; }; CBullet.prototype.getPresentationBullet = function (theme, color) { var para_pr = new CParaPr(); para_pr.Bullet = this; return para_pr.Get_PresentationBullet(theme, color); }; CBullet.prototype.getBulletType = function (theme, color) { return this.getPresentationBullet(theme, color).m_nType; }; CBullet.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealObject(this.bulletColor)); if (isRealObject(this.bulletColor)) { this.bulletColor.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bulletSize)); if (isRealObject(this.bulletSize)) { this.bulletSize.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bulletTypeface)); if (isRealObject(this.bulletTypeface)) { this.bulletTypeface.Write_ToBinary(w); } w.WriteBool(isRealObject(this.bulletType)); if (isRealObject(this.bulletType)) { this.bulletType.Write_ToBinary(w); } }; CBullet.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { this.bulletColor = new CBulletColor(); this.bulletColor.Read_FromBinary(r); } if (r.GetBool()) { this.bulletSize = new CBulletSize(); this.bulletSize.Read_FromBinary(r); } if (r.GetBool()) { this.bulletTypeface = new CBulletTypeface(); this.bulletTypeface.Read_FromBinary(r); } if (r.GetBool()) { this.bulletType = new CBulletType(); this.bulletType.Read_FromBinary(r); } }; CBullet.prototype.Get_AllFontNames = function (AllFonts) { if (this.bulletTypeface && typeof this.bulletTypeface.typeface === "string" && this.bulletTypeface.typeface.length > 0) { AllFonts[this.bulletTypeface.typeface] = true; } }; CBullet.prototype.putNumStartAt = function (NumStartAt) { if (!this.bulletType) { this.bulletType = new CBulletType(); } this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_AUTONUM; this.bulletType.startAt = NumStartAt; }; CBullet.prototype.getNumStartAt = function () { if (this.bulletType) { if (AscFormat.isRealNumber(this.bulletType.startAt)) { return Math.max(1, this.bulletType.startAt); } } return undefined; }; CBullet.prototype.isEqual = function (oBullet) { if (!oBullet) { return false; } if (!this.bulletColor && oBullet.bulletColor || !oBullet.bulletColor && this.bulletColor) { return false; } if (this.bulletColor && oBullet.bulletColor) { if (!this.bulletColor.IsIdentical(oBullet.bulletColor)) { return false; } } if (!this.bulletSize && oBullet.bulletSize || this.bulletSize && !oBullet.bulletSize) { return false; } if (this.bulletSize && oBullet.bulletSize) { if (!this.bulletSize.IsIdentical(oBullet.bulletSize)) { return false; } } if (!this.bulletTypeface && oBullet.bulletTypeface || this.bulletTypeface && !oBullet.bulletTypeface) { return false; } if (this.bulletTypeface && oBullet.bulletTypeface) { if (!this.bulletTypeface.IsIdentical(oBullet.bulletTypeface)) { return false; } } if (!this.bulletType && oBullet.bulletType || this.bulletType && !oBullet.bulletType) { return false; } if (this.bulletType && oBullet.bulletType) { if (!this.bulletType.IsIdentical(oBullet.bulletType)) { return false; } } return true; }; CBullet.prototype.fillBulletImage = function (url) { this.bulletType = new CBulletType(); this.bulletType.Blip = new AscFormat.CBuBlip(); this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_BLIP; this.bulletType.Blip.setBlip(AscFormat.CreateBlipFillUniFillFromUrl(url)); }; CBullet.prototype.fillBulletFromCharAndFont = function (char, font) { this.bulletType = new AscFormat.CBulletType(); this.bulletTypeface = new AscFormat.CBulletTypeface(); this.bulletTypeface.type = AscFormat.BULLET_TYPE_TYPEFACE_BUFONT; this.bulletTypeface.typeface = font || AscFonts.FontPickerByCharacter.getFontBySymbol(char.getUnicodeIterator().value()); this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_CHAR; this.bulletType.Char = char; }; CBullet.prototype.getImageBulletURL = function () { var res = (this.bulletType && this.bulletType.Blip && this.bulletType.Blip.blip && this.bulletType.Blip.blip.fill && this.bulletType.Blip.blip.fill.RasterImageId); return res ? res : null; }; CBullet.prototype.setImageBulletURL = function (url) { var blipFill = (this.bulletType && this.bulletType.Blip && this.bulletType.Blip.blip && this.bulletType.Blip.blip.fill); if (blipFill) { blipFill.setRasterImageId(url); } }; CBullet.prototype.drawSquareImage = function (divId, relativeIndent) { relativeIndent = relativeIndent || 0; var url = this.getImageBulletURL(); var Api = editor || Asc.editor; if (!url || !Api) { return; } var oDiv = document.getElementById(divId); if (!oDiv) { return; } var nWidth = oDiv.clientWidth; var nHeight = oDiv.clientHeight; var rPR = AscCommon.AscBrowser.retinaPixelRatio; var sideSize = nWidth < nHeight ? nWidth * rPR : nHeight * rPR; var oCanvas = oDiv.firstChild; if (!oCanvas) { oCanvas = document.createElement('canvas'); oCanvas.style.cssText = "padding:0;margin:0;user-select:none;"; oCanvas.style.width = oDiv.clientWidth + 'px'; oCanvas.style.height = oDiv.clientHeight + 'px'; oCanvas.width = sideSize; oCanvas.height = sideSize; oDiv.appendChild(oCanvas); } var oContext = oCanvas.getContext('2d'); oContext.fillStyle = "white"; oContext.fillRect(0, 0, oCanvas.width, oCanvas.height); var _img = Api.ImageLoader.map_image_index[AscCommon.getFullImageSrc2(url)]; if (_img && _img.Image && _img.Status !== AscFonts.ImageLoadStatus.Loading) { var absoluteIndent = sideSize * relativeIndent; var _x = absoluteIndent; var _y = absoluteIndent; var _w = sideSize - absoluteIndent * 2; var _h = sideSize - absoluteIndent * 2; oContext.drawImage(_img.Image, _x, _y, _w, _h); } }; CBullet.prototype.readChildXml = function (name, reader) { switch (name) { case "buAutoNum": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_AUTONUM); this.bulletType.fromXml(reader); break; } case "buBlip": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_BLIP); this.bulletType.fromXml(reader); break; } case "buChar": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_CHAR); this.bulletType.fromXml(reader); break; } case "buClr": { this.bulletColor = new CBulletColor(AscFormat.BULLET_TYPE_COLOR_CLR); this.bulletColor.fromXml(reader); break; } case "buClrTx": { this.bulletColor = new CBulletColor(AscFormat.BULLET_TYPE_COLOR_CLRTX); this.bulletColor.fromXml(reader); break; } case "buFont": { this.bulletTypeface = new CBulletTypeface(AscFormat.BULLET_TYPE_TYPEFACE_BUFONT); this.bulletTypeface.fromXml(reader); break; } case "buFontTx": { this.bulletTypeface = new CBulletTypeface(AscFormat.BULLET_TYPE_TYPEFACE_TX); this.bulletTypeface.fromXml(reader); break; } case "buNone": { this.bulletType = new CBulletType(AscFormat.BULLET_TYPE_BULLET_NONE); this.bulletType.fromXml(reader); break; } case "buSzPct": { this.bulletSize = new CBulletSize(AscFormat.BULLET_TYPE_SIZE_PCT); this.bulletSize.fromXml(reader); break; } case "buSzPts": { this.bulletSize = new CBulletSize(AscFormat.BULLET_TYPE_SIZE_PTS); this.bulletSize.fromXml(reader); break; } case "buSzTx": { this.bulletSize = new CBulletSize(AscFormat.BULLET_TYPE_SIZE_TX); this.bulletSize.fromXml(reader); break; } } }; CBullet.prototype.toXml = function (writer) { if (this.bulletColor) { this.bulletColor.toXml(writer); } if (this.bulletSize) { this.bulletSize.toXml(writer); } if (this.bulletTypeface) { this.bulletTypeface.toXml(writer); } if (this.bulletType) { this.bulletType.toXml(writer); } }; //interface methods var prot = CBullet.prototype; prot["fillBulletImage"] = prot["asc_fillBulletImage"] = CBullet.prototype.fillBulletImage; prot["fillBulletFromCharAndFont"] = prot["asc_fillBulletFromCharAndFont"] = CBullet.prototype.fillBulletFromCharAndFont; prot["drawSquareImage"] = prot["asc_drawSquareImage"] = CBullet.prototype.drawSquareImage; prot.getImageId = function () { return this.getImageBulletURL(); } prot["getImageId"] = prot["asc_getImageId"] = CBullet.prototype.getImageId; prot.put_ImageUrl = function (sUrl, token) { var _this = this; var Api = editor || Asc.editor; if (!Api) { return; } AscCommon.sendImgUrls(Api, [sUrl], function (data) { if (data && data[0] && data[0].url !== "error") { var url = AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path); Api.ImageLoader.LoadImagesWithCallback([AscCommon.getFullImageSrc2(url)], function () { _this.fillBulletImage(url); //_this.drawSquareImage(); Api.sendEvent("asc_onBulletImageLoaded", _this); }); } }, false, false, token); }; prot["put_ImageUrl"] = prot["asc_putImageUrl"] = CBullet.prototype.put_ImageUrl; prot.showFileDialog = function () { var Api = editor || Asc.editor; if (!Api) { return; } var _this = this; AscCommon.ShowImageFileDialog(Api.documentId, Api.documentUserId, Api.CoAuthoringApi.get_jwt(), function (error, files) { if (Asc.c_oAscError.ID.No !== error) { Api.sendEvent("asc_onError", error, Asc.c_oAscError.Level.NoCritical); } else { Api.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); AscCommon.UploadImageFiles(files, Api.documentId, Api.documentUserId, Api.CoAuthoringApi.get_jwt(), function (error, urls) { if (Asc.c_oAscError.ID.No !== error) { Api.sendEvent("asc_onError", error, Asc.c_oAscError.Level.NoCritical); Api.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); } else { Api.ImageLoader.LoadImagesWithCallback(urls, function () { if (urls.length > 0) { _this.fillBulletImage(urls[0]); //_this.drawSquareImage(); Api.sendEvent("asc_onBulletImageLoaded", _this); } Api.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); }); } }); } }, function (error) { if (Asc.c_oAscError.ID.No !== error) { Api.sendEvent("asc_onError", error, Asc.c_oAscError.Level.NoCritical); } Api.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage); }); }; prot["showFileDialog"] = prot["asc_showFileDialog"] = CBullet.prototype.showFileDialog; prot.asc_getSize = function () { var nRet = 100; if (this.bulletSize) { switch (this.bulletSize.type) { case AscFormat.BULLET_TYPE_SIZE_NONE: { break; } case AscFormat.BULLET_TYPE_SIZE_TX: { break; } case AscFormat.BULLET_TYPE_SIZE_PCT: { nRet = this.bulletSize.val / 1000.0; break; } case AscFormat.BULLET_TYPE_SIZE_PTS: { break; } } } return nRet; }; prot["get_Size"] = prot["asc_getSize"] = CBullet.prototype.asc_getSize; prot.asc_putSize = function (Size) { if (AscFormat.isRealNumber(Size)) { this.bulletSize = new AscFormat.CBulletSize(); this.bulletSize.type = AscFormat.BULLET_TYPE_SIZE_PCT; this.bulletSize.val = (Size * 1000) >> 0; } }; prot["put_Size"] = prot["asc_putSize"] = CBullet.prototype.asc_putSize; prot.asc_getColor = function () { if (this.bulletColor) { if (this.bulletColor.UniColor) { return AscCommon.CreateAscColor(this.bulletColor.UniColor); } } else { var FirstTextPr = this.FirstTextPr; if (FirstTextPr && FirstTextPr.Unifill) { if (FirstTextPr.Unifill.fill instanceof AscFormat.CSolidFill && FirstTextPr.Unifill.fill.color) { return AscCommon.CreateAscColor(FirstTextPr.Unifill.fill.color); } else { var RGBA = FirstTextPr.Unifill.getRGBAColor(); return AscCommon.CreateAscColorCustom(RGBA.R, RGBA.G, RGBA.B); } } } return AscCommon.CreateAscColorCustom(0, 0, 0); }; prot["get_Color"] = prot["asc_getColor"] = prot.asc_getColor; prot.asc_putColor = function (color) { this.bulletColor = new AscFormat.CBulletColor(); this.bulletColor.type = AscFormat.BULLET_TYPE_COLOR_CLR; this.bulletColor.UniColor = AscFormat.CorrectUniColor(color, this.bulletColor.UniColor, 0); }; prot["put_Color"] = prot["asc_putColor"] = prot.asc_putColor; prot.asc_getFont = function () { var sRet = ""; if (this.bulletTypeface && this.bulletTypeface.type === AscFormat.BULLET_TYPE_TYPEFACE_BUFONT && typeof this.bulletTypeface.typeface === "string" && this.bulletTypeface.typeface.length > 0) { sRet = this.bulletTypeface.typeface; } else { var FirstTextPr = this.FirstTextPr; if (FirstTextPr && FirstTextPr.FontFamily && typeof FirstTextPr.FontFamily.Name === "string" && FirstTextPr.FontFamily.Name.length > 0) { sRet = FirstTextPr.FontFamily.Name; } } return sRet; }; prot["get_Font"] = prot["asc_getFont"] = prot.asc_getFont; prot.asc_putFont = function (val) { if (typeof val === "string" && val.length > 0) { this.bulletTypeface = new AscFormat.CBulletTypeface(); this.bulletTypeface.type = AscFormat.BULLET_TYPE_TYPEFACE_BUFONT; this.bulletTypeface.typeface = val; } }; prot["put_Font"] = prot["asc_putFont"] = prot.asc_putFont; prot.asc_putNumStartAt = function (NumStartAt) { this.putNumStartAt(NumStartAt); }; prot["put_NumStartAt"] = prot["asc_putNumStartAt"] = prot.asc_putNumStartAt; prot.asc_getNumStartAt = function () { return this.getNumStartAt(); }; prot["get_NumStartAt"] = prot["asc_getNumStartAt"] = prot.asc_getNumStartAt; prot.asc_getSymbol = function () { if (this.bulletType && this.bulletType.type === AscFormat.BULLET_TYPE_BULLET_CHAR) { return this.bulletType.Char; } return undefined; }; prot["get_Symbol"] = prot["asc_getSymbol"] = prot.asc_getSymbol; prot.asc_putSymbol = function (v) { if (!this.bulletType) { this.bulletType = new CBulletType(); } this.bulletType.AutoNumType = 0; this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_CHAR; this.bulletType.Char = v; }; prot["put_Symbol"] = prot["asc_putSymbol"] = prot.asc_putSymbol; prot.asc_putAutoNumType = function (val) { if (!this.bulletType) { this.bulletType = new CBulletType(); } this.bulletType.type = AscFormat.BULLET_TYPE_BULLET_AUTONUM; this.bulletType.AutoNumType = AscFormat.getNumberingType(val); }; prot["put_AutoNumType"] = prot["asc_putAutoNumType"] = prot.asc_putAutoNumType; prot.asc_getAutoNumType = function () { if (this.bulletType && this.bulletType.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { return AscFormat.fGetListTypeFromBullet(this).SubType; } return -1; }; prot["get_AutoNumType"] = prot["asc_getAutoNumType"] = prot.asc_getAutoNumType; prot.asc_putListType = function (type, subtype, custom) { var NumberInfo = { Type: type, SubType: subtype, Custom: custom }; AscFormat.fFillBullet(NumberInfo, this); }; prot["put_ListType"] = prot["asc_putListType"] = prot.asc_putListType; prot.asc_getListType = function () { return new AscCommon.asc_CListType(AscFormat.fGetListTypeFromBullet(this)); }; prot.asc_getType = function () { return this.bulletType && this.bulletType.type; }; prot["get_Type"] = prot["asc_getType"] = prot.asc_getType; window["Asc"]["asc_CBullet"] = window["Asc"].asc_CBullet = CBullet; function CBulletColor(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : AscFormat.BULLET_TYPE_COLOR_CLRTX; this.UniColor = null; } InitClass(CBulletColor, CBaseNoIdObject, 0); CBulletColor.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletColor.prototype.merge = function (oBulletColor) { if (!oBulletColor) { return; } if (oBulletColor.UniColor) { this.type = oBulletColor.type; this.UniColor = oBulletColor.UniColor.createDuplicate(); } }; CBulletColor.prototype.IsIdentical = function (oBulletColor) { if (!oBulletColor) { return false; } if (this.type !== oBulletColor.type) { return false; } if (this.UniColor && !oBulletColor.UniColor || oBulletColor.UniColor && !this.UniColor) { return false; } if (this.UniColor) { if (!this.UniColor.IsIdentical(oBulletColor.UniColor)) { return false; } } return true; }; CBulletColor.prototype.createDuplicate = function () { var duplicate = new CBulletColor(); duplicate.type = this.type; if (this.UniColor != null) { duplicate.UniColor = this.UniColor.createDuplicate(); } return duplicate; }; CBulletColor.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(isRealObject(this.UniColor)); if (isRealObject(this.UniColor)) { this.UniColor.Write_ToBinary(w); } }; CBulletColor.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { this.UniColor = new CUniColor(); this.UniColor.Read_FromBinary(r); } }; CBulletColor.prototype.readChildXml = function (name, reader) { if (CUniColor.prototype.isUnicolor(name)) { if (this.type === AscFormat.BULLET_TYPE_COLOR_CLR) { this.UniColor = new CUniColor(); this.UniColor.fromXml(reader, name); } } }; CBulletColor.prototype.toXml = function (writer) { if (this.type === AscFormat.BULLET_TYPE_COLOR_CLR) { writer.WriteXmlNodeStart("a:buClr"); writer.WriteXmlAttributesEnd(); if (this.UniColor) { this.UniColor.toXml(writer); } writer.WriteXmlNodeEnd("a:buClr"); } else { writer.WriteXmlString("<a:buClrTx/>"); } }; function CBulletSize(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : AscFormat.BULLET_TYPE_SIZE_NONE; this.val = 0; } InitClass(CBulletSize, CBaseNoIdObject, 0); CBulletSize.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletSize.prototype.merge = function (oBulletSize) { if (!oBulletSize) { return; } this.type = oBulletSize.type; this.val = oBulletSize.val; }; CBulletSize.prototype.createDuplicate = function () { var d = new CBulletSize(); d.type = this.type; d.val = this.val; return d; }; CBulletSize.prototype.IsIdentical = function (oBulletSize) { if (!oBulletSize) { return false; } return this.type === oBulletSize.type && this.val === oBulletSize.val; }; CBulletSize.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(isRealNumber(this.val)); if (isRealNumber(this.val)) { w.WriteLong(this.val); } }; CBulletSize.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { (this.val) = r.GetLong(); } }; CBulletSize.prototype.readAttrXml = function (name, reader) { switch (name) { case "val": { if (this.type === AscFormat.BULLET_TYPE_SIZE_PCT) { this.val = reader.GetValueInt(); } else if (this.type === AscFormat.BULLET_TYPE_SIZE_PTS) { this.val = reader.GetValueInt(); } break; } } }; CBulletSize.prototype.toXml = function (writer) { if (this.type === AscFormat.BULLET_TYPE_SIZE_PCT) { writer.WriteXmlNodeStart("a:buSzPct"); writer.WriteXmlNullableAttributeInt("val", this.val); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:buSzPct"); } else if (this.type === AscFormat.BULLET_TYPE_SIZE_PTS) { writer.WriteXmlNodeStart("a:buSzPts"); writer.WriteXmlNullableAttributeString("val", this.val); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd("a:buSzPts"); } else { writer.WriteXmlString("<a:buSzTx/>"); } }; function CBulletTypeface(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : AscFormat.BULLET_TYPE_TYPEFACE_NONE; this.typeface = ""; } InitClass(CBulletTypeface, CBaseNoIdObject, 0); CBulletTypeface.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletTypeface.prototype.createDuplicate = function () { var d = new CBulletTypeface(); d.type = this.type; d.typeface = this.typeface; return d; }; CBulletTypeface.prototype.merge = function (oBulletTypeface) { if (!oBulletTypeface) { return; } this.type = oBulletTypeface.type; this.typeface = oBulletTypeface.typeface; }; CBulletTypeface.prototype.IsIdentical = function (oBulletTypeface) { if (!oBulletTypeface) { return false; } return this.type === oBulletTypeface.type && this.typeface === oBulletTypeface.typeface; }; CBulletTypeface.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(typeof this.typeface === "string"); if (typeof this.typeface === "string") { w.WriteString2(this.typeface); } }; CBulletTypeface.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { (this.typeface) = r.GetString2(); } }; CBulletTypeface.prototype.readAttrXml = function (name, reader) { switch (name) { case "typeface": { if (this.type === AscFormat.BULLET_TYPE_TYPEFACE_BUFONT) { this.typeface = reader.GetValue(); } break; } } }; CBulletTypeface.prototype.toXml = function (writer) { if (this.type === AscFormat.BULLET_TYPE_TYPEFACE_BUFONT) { FontCollection.prototype.writeFont.call(this, writer, "a:buFont", this.typeface); } else { writer.WriteXmlString("<a:buFontTx/>"); } }; var numbering_presentationnumfrmt_AlphaLcParenBoth = 0; var numbering_presentationnumfrmt_AlphaLcParenR = 1; var numbering_presentationnumfrmt_AlphaLcPeriod = 2; var numbering_presentationnumfrmt_AlphaUcParenBoth = 3; var numbering_presentationnumfrmt_AlphaUcParenR = 4; var numbering_presentationnumfrmt_AlphaUcPeriod = 5; var numbering_presentationnumfrmt_Arabic1Minus = 6; var numbering_presentationnumfrmt_Arabic2Minus = 7; var numbering_presentationnumfrmt_ArabicDbPeriod = 8; var numbering_presentationnumfrmt_ArabicDbPlain = 9; var numbering_presentationnumfrmt_ArabicParenBoth = 10; var numbering_presentationnumfrmt_ArabicParenR = 11; var numbering_presentationnumfrmt_ArabicPeriod = 12; var numbering_presentationnumfrmt_ArabicPlain = 13; var numbering_presentationnumfrmt_CircleNumDbPlain = 14; var numbering_presentationnumfrmt_CircleNumWdBlackPlain = 15; var numbering_presentationnumfrmt_CircleNumWdWhitePlain = 16; var numbering_presentationnumfrmt_Ea1ChsPeriod = 17; var numbering_presentationnumfrmt_Ea1ChsPlain = 18; var numbering_presentationnumfrmt_Ea1ChtPeriod = 19; var numbering_presentationnumfrmt_Ea1ChtPlain = 20; var numbering_presentationnumfrmt_Ea1JpnChsDbPeriod = 21; var numbering_presentationnumfrmt_Ea1JpnKorPeriod = 22; var numbering_presentationnumfrmt_Ea1JpnKorPlain = 23; var numbering_presentationnumfrmt_Hebrew2Minus = 24; var numbering_presentationnumfrmt_HindiAlpha1Period = 25; var numbering_presentationnumfrmt_HindiAlphaPeriod = 26; var numbering_presentationnumfrmt_HindiNumParenR = 27; var numbering_presentationnumfrmt_HindiNumPeriod = 28; var numbering_presentationnumfrmt_RomanLcParenBoth = 29; var numbering_presentationnumfrmt_RomanLcParenR = 30; var numbering_presentationnumfrmt_RomanLcPeriod = 31; var numbering_presentationnumfrmt_RomanUcParenBoth = 32; var numbering_presentationnumfrmt_RomanUcParenR = 33; var numbering_presentationnumfrmt_RomanUcPeriod = 34; var numbering_presentationnumfrmt_ThaiAlphaParenBoth = 35; var numbering_presentationnumfrmt_ThaiAlphaParenR = 36; var numbering_presentationnumfrmt_ThaiAlphaPeriod = 37; var numbering_presentationnumfrmt_ThaiNumParenBoth = 38; var numbering_presentationnumfrmt_ThaiNumParenR = 39; var numbering_presentationnumfrmt_ThaiNumPeriod = 40; var numbering_presentationnumfrmt_None = 100; var numbering_presentationnumfrmt_Char = 101; var numbering_presentationnumfrmt_Blip = 102; AscFormat.numbering_presentationnumfrmt_AlphaLcParenBoth = numbering_presentationnumfrmt_AlphaLcParenBoth; AscFormat.numbering_presentationnumfrmt_AlphaLcParenR = numbering_presentationnumfrmt_AlphaLcParenR; AscFormat.numbering_presentationnumfrmt_AlphaLcPeriod = numbering_presentationnumfrmt_AlphaLcPeriod; AscFormat.numbering_presentationnumfrmt_AlphaUcParenBoth = numbering_presentationnumfrmt_AlphaUcParenBoth; AscFormat.numbering_presentationnumfrmt_AlphaUcParenR = numbering_presentationnumfrmt_AlphaUcParenR; AscFormat.numbering_presentationnumfrmt_AlphaUcPeriod = numbering_presentationnumfrmt_AlphaUcPeriod; AscFormat.numbering_presentationnumfrmt_Arabic1Minus = numbering_presentationnumfrmt_Arabic1Minus; AscFormat.numbering_presentationnumfrmt_Arabic2Minus = numbering_presentationnumfrmt_Arabic2Minus; AscFormat.numbering_presentationnumfrmt_ArabicDbPeriod = numbering_presentationnumfrmt_ArabicDbPeriod; AscFormat.numbering_presentationnumfrmt_ArabicDbPlain = numbering_presentationnumfrmt_ArabicDbPlain; AscFormat.numbering_presentationnumfrmt_ArabicParenBoth = numbering_presentationnumfrmt_ArabicParenBoth; AscFormat.numbering_presentationnumfrmt_ArabicParenR = numbering_presentationnumfrmt_ArabicParenR; AscFormat.numbering_presentationnumfrmt_ArabicPeriod = numbering_presentationnumfrmt_ArabicPeriod; AscFormat.numbering_presentationnumfrmt_ArabicPlain = numbering_presentationnumfrmt_ArabicPlain; AscFormat.numbering_presentationnumfrmt_CircleNumDbPlain = numbering_presentationnumfrmt_CircleNumDbPlain; AscFormat.numbering_presentationnumfrmt_CircleNumWdBlackPlain = numbering_presentationnumfrmt_CircleNumWdBlackPlain; AscFormat.numbering_presentationnumfrmt_CircleNumWdWhitePlain = numbering_presentationnumfrmt_CircleNumWdWhitePlain; AscFormat.numbering_presentationnumfrmt_Ea1ChsPeriod = numbering_presentationnumfrmt_Ea1ChsPeriod; AscFormat.numbering_presentationnumfrmt_Ea1ChsPlain = numbering_presentationnumfrmt_Ea1ChsPlain; AscFormat.numbering_presentationnumfrmt_Ea1ChtPeriod = numbering_presentationnumfrmt_Ea1ChtPeriod; AscFormat.numbering_presentationnumfrmt_Ea1ChtPlain = numbering_presentationnumfrmt_Ea1ChtPlain; AscFormat.numbering_presentationnumfrmt_Ea1JpnChsDbPeriod = numbering_presentationnumfrmt_Ea1JpnChsDbPeriod; AscFormat.numbering_presentationnumfrmt_Ea1JpnKorPeriod = numbering_presentationnumfrmt_Ea1JpnKorPeriod; AscFormat.numbering_presentationnumfrmt_Ea1JpnKorPlain = numbering_presentationnumfrmt_Ea1JpnKorPlain; AscFormat.numbering_presentationnumfrmt_Hebrew2Minus = numbering_presentationnumfrmt_Hebrew2Minus; AscFormat.numbering_presentationnumfrmt_HindiAlpha1Period = numbering_presentationnumfrmt_HindiAlpha1Period; AscFormat.numbering_presentationnumfrmt_HindiAlphaPeriod = numbering_presentationnumfrmt_HindiAlphaPeriod; AscFormat.numbering_presentationnumfrmt_HindiNumParenR = numbering_presentationnumfrmt_HindiNumParenR; AscFormat.numbering_presentationnumfrmt_HindiNumPeriod = numbering_presentationnumfrmt_HindiNumPeriod; AscFormat.numbering_presentationnumfrmt_RomanLcParenBoth = numbering_presentationnumfrmt_RomanLcParenBoth; AscFormat.numbering_presentationnumfrmt_RomanLcParenR = numbering_presentationnumfrmt_RomanLcParenR; AscFormat.numbering_presentationnumfrmt_RomanLcPeriod = numbering_presentationnumfrmt_RomanLcPeriod; AscFormat.numbering_presentationnumfrmt_RomanUcParenBoth = numbering_presentationnumfrmt_RomanUcParenBoth; AscFormat.numbering_presentationnumfrmt_RomanUcParenR = numbering_presentationnumfrmt_RomanUcParenR; AscFormat.numbering_presentationnumfrmt_RomanUcPeriod = numbering_presentationnumfrmt_RomanUcPeriod; AscFormat.numbering_presentationnumfrmt_ThaiAlphaParenBoth = numbering_presentationnumfrmt_ThaiAlphaParenBoth; AscFormat.numbering_presentationnumfrmt_ThaiAlphaParenR = numbering_presentationnumfrmt_ThaiAlphaParenR; AscFormat.numbering_presentationnumfrmt_ThaiAlphaPeriod = numbering_presentationnumfrmt_ThaiAlphaPeriod; AscFormat.numbering_presentationnumfrmt_ThaiNumParenBoth = numbering_presentationnumfrmt_ThaiNumParenBoth; AscFormat.numbering_presentationnumfrmt_ThaiNumParenR = numbering_presentationnumfrmt_ThaiNumParenR; AscFormat.numbering_presentationnumfrmt_ThaiNumPeriod = numbering_presentationnumfrmt_ThaiNumPeriod; AscFormat.numbering_presentationnumfrmt_None = numbering_presentationnumfrmt_None; AscFormat.numbering_presentationnumfrmt_Char = numbering_presentationnumfrmt_Char; AscFormat.numbering_presentationnumfrmt_Blip = numbering_presentationnumfrmt_Blip; var MAP_AUTONUM_TYPES = {}; MAP_AUTONUM_TYPES["alphaLcParenBot"] = numbering_presentationnumfrmt_AlphaLcParenBoth; MAP_AUTONUM_TYPES["alphaLcParen"] = numbering_presentationnumfrmt_AlphaLcParenR; MAP_AUTONUM_TYPES["alphaLcPerio"] = numbering_presentationnumfrmt_AlphaLcPeriod; MAP_AUTONUM_TYPES["alphaUcParenBot"] = numbering_presentationnumfrmt_AlphaUcParenBoth; MAP_AUTONUM_TYPES["alphaUcParen"] = numbering_presentationnumfrmt_AlphaUcParenR; MAP_AUTONUM_TYPES["alphaUcPerio"] = numbering_presentationnumfrmt_AlphaUcPeriod; MAP_AUTONUM_TYPES["arabic1Minu"] = numbering_presentationnumfrmt_Arabic1Minus; MAP_AUTONUM_TYPES["arabic2Minu"] = numbering_presentationnumfrmt_Arabic2Minus; MAP_AUTONUM_TYPES["arabicDbPerio"] = numbering_presentationnumfrmt_ArabicDbPeriod; MAP_AUTONUM_TYPES["arabicDbPlai"] = numbering_presentationnumfrmt_ArabicDbPlain; MAP_AUTONUM_TYPES["arabicParenBoth"] = numbering_presentationnumfrmt_ArabicParenBoth; MAP_AUTONUM_TYPES["arabicParenR"] = numbering_presentationnumfrmt_ArabicParenR; MAP_AUTONUM_TYPES["arabicPeriod"] = numbering_presentationnumfrmt_ArabicPeriod; MAP_AUTONUM_TYPES["arabicPlain"] = numbering_presentationnumfrmt_ArabicPlain; MAP_AUTONUM_TYPES["circleNumDbPlain"] = numbering_presentationnumfrmt_CircleNumDbPlain; MAP_AUTONUM_TYPES["circleNumWdBlackPlain"] = numbering_presentationnumfrmt_CircleNumWdBlackPlain; MAP_AUTONUM_TYPES["circleNumWdWhitePlain"] = numbering_presentationnumfrmt_CircleNumWdWhitePlain; MAP_AUTONUM_TYPES["ea1ChsPeriod"] = numbering_presentationnumfrmt_Ea1ChsPeriod; MAP_AUTONUM_TYPES["ea1ChsPlain"] = numbering_presentationnumfrmt_Ea1ChsPlain; MAP_AUTONUM_TYPES["ea1ChtPeriod"] = numbering_presentationnumfrmt_Ea1ChtPeriod; MAP_AUTONUM_TYPES["ea1ChtPlain"] = numbering_presentationnumfrmt_Ea1ChtPlain; MAP_AUTONUM_TYPES["ea1JpnChsDbPeriod"] = numbering_presentationnumfrmt_Ea1JpnChsDbPeriod; MAP_AUTONUM_TYPES["ea1JpnKorPeriod"] = numbering_presentationnumfrmt_Ea1JpnKorPeriod; MAP_AUTONUM_TYPES["ea1JpnKorPlain"] = numbering_presentationnumfrmt_Ea1JpnKorPlain; MAP_AUTONUM_TYPES["hebrew2Minus"] = numbering_presentationnumfrmt_Hebrew2Minus; MAP_AUTONUM_TYPES["hindiAlpha1Period"] = numbering_presentationnumfrmt_HindiAlpha1Period; MAP_AUTONUM_TYPES["hindiAlphaPeriod"] = numbering_presentationnumfrmt_HindiAlphaPeriod; MAP_AUTONUM_TYPES["hindiNumParenR"] = numbering_presentationnumfrmt_HindiNumParenR; MAP_AUTONUM_TYPES["hindiNumPeriod"] = numbering_presentationnumfrmt_HindiNumPeriod; MAP_AUTONUM_TYPES["romanLcParenBoth"] = numbering_presentationnumfrmt_RomanLcParenBoth; MAP_AUTONUM_TYPES["romanLcParenR"] = numbering_presentationnumfrmt_RomanLcParenR; MAP_AUTONUM_TYPES["romanLcPeriod"] = numbering_presentationnumfrmt_RomanLcPeriod; MAP_AUTONUM_TYPES["romanUcParenBoth"] = numbering_presentationnumfrmt_RomanUcParenBoth; MAP_AUTONUM_TYPES["romanUcParenR"] = numbering_presentationnumfrmt_RomanUcParenR; MAP_AUTONUM_TYPES["romanUcPeriod"] = numbering_presentationnumfrmt_RomanUcPeriod; MAP_AUTONUM_TYPES["thaiAlphaParenBoth"] = numbering_presentationnumfrmt_ThaiAlphaParenBoth; MAP_AUTONUM_TYPES["thaiAlphaParenR"] = numbering_presentationnumfrmt_ThaiAlphaParenR; MAP_AUTONUM_TYPES["thaiAlphaPeriod"] = numbering_presentationnumfrmt_ThaiAlphaPeriod; MAP_AUTONUM_TYPES["thaiNumParenBoth"] = numbering_presentationnumfrmt_ThaiNumParenBoth; MAP_AUTONUM_TYPES["thaiNumParenR"] = numbering_presentationnumfrmt_ThaiNumParenR; MAP_AUTONUM_TYPES["thaiNumPeriod"] = numbering_presentationnumfrmt_ThaiNumPeriod; function CBulletType(nType) { CBaseNoIdObject.call(this); this.type = AscFormat.isRealNumber(nType) ? nType : null;//BULLET_TYPE_BULLET_NONE; this.Char = null; this.AutoNumType = null; this.Blip = null; this.startAt = null; } InitClass(CBulletType, CBaseNoIdObject, 0); CBulletType.prototype.Set_FromObject = function (o) { this.merge(o); }; CBulletType.prototype.IsIdentical = function (oBulletType) { if (!oBulletType) { return false; } return this.type === oBulletType.type && this.Char === oBulletType.Char && this.AutoNumType === oBulletType.AutoNumType && this.startAt === oBulletType.startAt && ((this.Blip && this.Blip.isEqual(oBulletType.Blip)) || this.Blip === oBulletType.Blip); }; CBulletType.prototype.merge = function (oBulletType) { if (!oBulletType) { return; } if (oBulletType.type !== null && this.type !== oBulletType.type) { this.type = oBulletType.type; this.Char = oBulletType.Char; this.AutoNumType = oBulletType.AutoNumType; this.startAt = oBulletType.startAt; if (oBulletType.Blip) { this.Blip = oBulletType.Blip.createDuplicate(); } } else { if (this.type === AscFormat.BULLET_TYPE_BULLET_CHAR) { if (typeof oBulletType.Char === "string" && oBulletType.Char.length > 0) { if (this.Char !== oBulletType.Char) { this.Char = oBulletType.Char; } } } if (this.type === AscFormat.BULLET_TYPE_BULLET_BLIP) { if (this.Blip instanceof AscFormat.CBuBlip && this.Blip !== oBulletType.Blip) { this.Blip = oBulletType.Blip.createDuplicate(); } } if (this.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { if (oBulletType.AutoNumType !== null && this.AutoNumType !== oBulletType.AutoNumType) { this.AutoNumType = oBulletType.AutoNumType; } if (oBulletType.startAt !== null && this.startAt !== oBulletType.startAt) { this.startAt = oBulletType.startAt; } } } }; CBulletType.prototype.createDuplicate = function () { var d = new CBulletType(); d.type = this.type; d.Char = this.Char; d.AutoNumType = this.AutoNumType; d.startAt = this.startAt; if (this.Blip) { d.Blip = this.Blip.createDuplicate(); } return d; }; CBulletType.prototype.setBlip = function (oPr) { this.Blip = oPr; }; CBulletType.prototype.Write_ToBinary = function (w) { w.WriteBool(isRealNumber(this.type)); if (isRealNumber(this.type)) { w.WriteLong(this.type); } w.WriteBool(typeof this.Char === "string"); if (typeof this.Char === "string") { w.WriteString2(this.Char); } w.WriteBool(isRealNumber(this.AutoNumType)); if (isRealNumber(this.AutoNumType)) { w.WriteLong(this.AutoNumType); } w.WriteBool(isRealNumber(this.startAt)); if (isRealNumber(this.startAt)) { w.WriteLong(this.startAt); } w.WriteBool(isRealObject(this.Blip)); if (isRealObject(this.Blip)) { this.Blip.Write_ToBinary(w); } }; CBulletType.prototype.Read_FromBinary = function (r) { if (r.GetBool()) { (this.type) = r.GetLong(); } if (r.GetBool()) { (this.Char) = r.GetString2(); if (AscFonts.IsCheckSymbols) AscFonts.FontPickerByCharacter.getFontsByString(this.Char); } if (r.GetBool()) { (this.AutoNumType) = r.GetLong(); } if (r.GetBool()) { (this.startAt) = r.GetLong(); } if (r.GetBool()) { this.Blip = new CBuBlip(); this.Blip.Read_FromBinary(r); var oUnifill = this.Blip.blip; var sRasterImageId = oUnifill && oUnifill.fill && oUnifill.fill.RasterImageId; if (typeof AscCommon.CollaborativeEditing !== "undefined") { if (typeof sRasterImageId === "string" && sRasterImageId.length > 0) { AscCommon.CollaborativeEditing.Add_NewImage(sRasterImageId); } } } }; CBulletType.prototype.readAttrXml = function (name, reader) { switch (name) { case "startAt": { if (this.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { this.startAt = reader.GetValueInt(); } break; } case "type": { if (this.type === AscFormat.BULLET_TYPE_BULLET_AUTONUM) { let sVal = reader.GetValue(); let nType = MAP_AUTONUM_TYPES[sVal]; if (AscFormat.isRealNumber(nType)) { this.AutoNumType = nType; } } break; } case "char": { if (this.type === AscFormat.BULLET_TYPE_BULLET_CHAR) { this.Char = reader.GetValue(); } } } }; CBulletType.prototype.GetAutonumTypeByCode = function (nCode) { switch (nCode) { case numbering_presentationnumfrmt_AlphaLcParenBoth: { return "alphaLcParenBot"; } case numbering_presentationnumfrmt_AlphaLcParenR: { return "alphaLcParen"; } case numbering_presentationnumfrmt_AlphaLcPeriod: { return "alphaLcPerio"; } case numbering_presentationnumfrmt_AlphaUcParenBoth: { return "alphaUcParenBot"; } case numbering_presentationnumfrmt_AlphaUcParenR: { return "alphaUcParen"; } case numbering_presentationnumfrmt_AlphaUcPeriod: { return "alphaUcPerio"; } case numbering_presentationnumfrmt_Arabic1Minus: { return "arabic1Minu"; } case numbering_presentationnumfrmt_Arabic2Minus: { return "arabic2Minu"; } case numbering_presentationnumfrmt_ArabicDbPeriod: { return "arabicDbPerio"; } case numbering_presentationnumfrmt_ArabicDbPlain: { return "arabicDbPlai"; } case numbering_presentationnumfrmt_ArabicParenBoth: { return "arabicParenBoth"; } case numbering_presentationnumfrmt_ArabicParenR: { return "arabicParenR"; } case numbering_presentationnumfrmt_ArabicPeriod: { return "arabicPeriod"; } case numbering_presentationnumfrmt_ArabicPlain: { return "arabicPlain"; } case numbering_presentationnumfrmt_CircleNumDbPlain: { return "circleNumDbPlain"; } case numbering_presentationnumfrmt_CircleNumWdBlackPlain: { return "circleNumWdBlackPlain"; } case numbering_presentationnumfrmt_CircleNumWdWhitePlain: { return "circleNumWdWhitePlain"; } case numbering_presentationnumfrmt_Ea1ChsPeriod: { return "ea1ChsPeriod"; } case numbering_presentationnumfrmt_Ea1ChsPlain: { return "ea1ChsPlain"; } case numbering_presentationnumfrmt_Ea1ChtPeriod: { return "ea1ChtPeriod"; } case numbering_presentationnumfrmt_Ea1ChtPlain: { return "ea1ChtPlain"; } case numbering_presentationnumfrmt_Ea1JpnChsDbPeriod: { return "ea1JpnChsDbPeriod"; } case numbering_presentationnumfrmt_Ea1JpnKorPeriod: { return "ea1JpnKorPeriod"; } case numbering_presentationnumfrmt_Ea1JpnKorPlain: { return "ea1JpnKorPlain"; } case numbering_presentationnumfrmt_Hebrew2Minus: { return "hebrew2Minus"; } case numbering_presentationnumfrmt_HindiAlpha1Period: { return "hindiAlpha1Period"; } case numbering_presentationnumfrmt_HindiAlphaPeriod: { return "hindiAlphaPeriod"; } case numbering_presentationnumfrmt_HindiNumParenR: { return "hindiNumParenR"; } case numbering_presentationnumfrmt_HindiNumPeriod: { return "hindiNumPeriod"; } case numbering_presentationnumfrmt_RomanLcParenBoth: { return "romanLcParenBoth"; } case numbering_presentationnumfrmt_RomanLcParenR: { return "romanLcParenR"; } case numbering_presentationnumfrmt_RomanLcPeriod: { return "romanLcPeriod"; } case numbering_presentationnumfrmt_RomanUcParenBoth: { return "romanUcParenBoth"; } case numbering_presentationnumfrmt_RomanUcParenR: { return "romanUcParenR"; } case numbering_presentationnumfrmt_RomanUcPeriod: { return "romanUcPeriod"; } case numbering_presentationnumfrmt_ThaiAlphaParenBoth: { return "thaiAlphaParenBoth"; } case numbering_presentationnumfrmt_ThaiAlphaParenR: { return "thaiAlphaParenR"; } case numbering_presentationnumfrmt_ThaiAlphaPeriod: { return "thaiAlphaPeriod"; } case numbering_presentationnumfrmt_ThaiNumParenBoth: { return "thaiNumParenBoth"; } case numbering_presentationnumfrmt_ThaiNumParenR: { return "thaiNumParenR"; } case numbering_presentationnumfrmt_ThaiNumPeriod: { return "thaiNumPeriod"; } } }; CBulletType.prototype.readChildXml = function (name, reader) { switch (name) { case "blip": { if (this.type === AscFormat.BULLET_TYPE_BULLET_BLIP) { this.Blip = new CBuBlip(); this.Blip.blip = new CUniFill(); this.Blip.blip.fromXml(reader, "blipFill"); this.Blip.blip.readChildXml(reader, "blip"); } break; } } }; CBulletType.prototype.toXml = function (writer) { switch (this.type) { case AscFormat.BULLET_TYPE_BULLET_NONE: { writer.WriteXmlString("<a:buNone/>"); break; } case AscFormat.BULLET_TYPE_BULLET_CHAR: { writer.WriteXmlNodeStart("a:buChar"); writer.WriteXmlNullableAttributeString("char", this.Char); writer.WriteXmlAttributesEnd(true); break; } case AscFormat.BULLET_TYPE_BULLET_AUTONUM: { writer.WriteXmlNodeStart("a:buAutoNum"); writer.WriteXmlNullableAttributeString("type", this.GetAutonumTypeByCode(this.AutoNumType)); writer.WriteXmlNullableAttributeUInt("startAt", this.startAt); writer.WriteXmlAttributesEnd(true); break; } case AscFormat.BULLET_TYPE_BULLET_BLIP: { if(this.Blip) { writer.WriteXmlNodeStart("a:blip"); writer.WriteXmlAttributesEnd(); this.Blip.toXml(writer); writer.WriteXmlNodeEnd("a:blip"); } break; } } }; function TextListStyle() { CBaseNoIdObject.call(this); this.levels = new Array(10); for (var i = 0; i < 10; i++) this.levels[i] = null; } InitClass(TextListStyle, CBaseNoIdObject, 0); TextListStyle.prototype.Get_Id = function () { return this.Id; }; TextListStyle.prototype.Refresh_RecalcData = function () { }; TextListStyle.prototype.createDuplicate = function () { var duplicate = new TextListStyle(); for (var i = 0; i < 10; ++i) { if (this.levels[i] != null) { duplicate.levels[i] = this.levels[i].Copy(); } } return duplicate; }; TextListStyle.prototype.Write_ToBinary = function (w) { for (var i = 0; i < 10; ++i) { w.WriteBool(isRealObject(this.levels[i])); if (isRealObject(this.levels[i])) { this.levels[i].Write_ToBinary(w); } } }; TextListStyle.prototype.Read_FromBinary = function (r) { for (var i = 0; i < 10; ++i) { if (r.GetBool()) { this.levels[i] = new CParaPr(); this.levels[i].Read_FromBinary(r); } else { this.levels[i] = null; } } }; TextListStyle.prototype.merge = function (oTextListStyle) { if (!oTextListStyle) { return; } for (var i = 0; i < this.levels.length; ++i) { if (oTextListStyle.levels[i]) { if (this.levels[i]) { this.levels[i].Merge(oTextListStyle.levels[i]); } else { this.levels[i] = oTextListStyle.levels[i].Copy(); } } } }; TextListStyle.prototype.Document_Get_AllFontNames = function (AllFonts) { for (var i = 0; i < 10; ++i) { if (this.levels[i]) { if (this.levels[i].DefaultRunPr) { this.levels[i].DefaultRunPr.Document_Get_AllFontNames(AllFonts); } if (this.levels[i].Bullet) { this.levels[i].Bullet.Get_AllFontNames(AllFonts); } } } }; TextListStyle.prototype.readChildXml = function (name, reader) { let nIdx = null; if (name.indexOf("lvl") === 0) { nIdx = parseInt(name.charAt(3)) - 1; } else if (name === "defPPr") { nIdx = 9; } if (AscFormat.isRealNumber(nIdx)) { let oParaPr = new AscCommonWord.CParaPr(); oParaPr.fromDrawingML(reader); this.levels[nIdx] = oParaPr; } }; TextListStyle.prototype.toXml = function (writer, sName) { writer.WriteXmlNodeStart(sName); if(this.levels[9] || this.levels[0] || this.levels[1] || this.levels[2] || this.levels[3] || this.levels[4] || this.levels[5] || this.levels[6] || this.levels[7] || this.levels[8]) { writer.WriteXmlAttributesEnd(); this.levels[9] && this.levels[9].toDrawingML(writer,"a:defPPr"); this.levels[0] && this.levels[0].toDrawingML(writer,"a:lvl1pPr"); this.levels[1] && this.levels[1].toDrawingML(writer,"a:lvl2pPr"); this.levels[2] && this.levels[2].toDrawingML(writer,"a:lvl3pPr"); this.levels[3] && this.levels[3].toDrawingML(writer,"a:lvl4pPr"); this.levels[4] && this.levels[4].toDrawingML(writer,"a:lvl5pPr"); this.levels[5] && this.levels[5].toDrawingML(writer,"a:lvl6pPr"); this.levels[6] && this.levels[6].toDrawingML(writer,"a:lvl7pPr"); this.levels[7] && this.levels[7].toDrawingML(writer,"a:lvl8pPr"); this.levels[8] && this.levels[8].toDrawingML(writer,"a:lvl9pPr"); writer.WriteXmlNodeEnd(sName); } else { writer.WriteXmlAttributesEnd(true); } }; function CBaseAttrObject() { CBaseNoIdObject.call(this); this.attr = {}; } InitClass(CBaseAttrObject, CBaseNoIdObject, 0); CBaseAttrObject.prototype.readAttrXml = function (name, reader) { this.attr[name] = reader.GetValue(); }; CBaseAttrObject.prototype.readChildXml = function (name, reader) { }; CBaseAttrObject.prototype.toXml = function (writer) { //TODO:Implement in children }; AscFormat.CBaseAttrObject = CBaseAttrObject; function CChangesCorePr(Class, Old, New, Color) { AscDFH.CChangesBase.call(this, Class, Old, New, Color); if (Old && New) { this.OldTitle = Old.title; this.OldCreator = Old.creator; this.OldDescription = Old.description; this.OldSubject = Old.subject; this.NewTitle = New.title === Old.title ? undefined : New.title; this.NewCreator = New.creator === Old.creator ? undefined : New.creator; this.NewDescription = New.description === Old.description ? undefined : New.description; this.NewSubject = New.subject === Old.subject ? undefined : New.subject; } else { this.OldTitle = undefined; this.OldCreator = undefined; this.OldDescription = undefined; this.OldSubject = undefined; this.NewTitle = undefined; this.NewCreator = undefined; this.NewDescription = undefined; this.NewSubject = undefined; } } CChangesCorePr.prototype = Object.create(AscDFH.CChangesBase.prototype); CChangesCorePr.prototype.constructor = CChangesCorePr; CChangesCorePr.prototype.Type = AscDFH.historyitem_CoreProperties; CChangesCorePr.prototype.Undo = function () { if (!this.Class) { return; } this.Class.title = this.OldTitle; this.Class.creator = this.OldCreator; this.Class.description = this.OldDescription; this.Class.subject = this.OldSubject; }; CChangesCorePr.prototype.Redo = function () { if (!this.Class) { return; } if (this.NewTitle !== undefined) { this.Class.title = this.NewTitle; } if (this.NewCreator !== undefined) { this.Class.creator = this.NewCreator; } if (this.NewDescription !== undefined) { this.Class.description = this.NewDescription; } if (this.NewSubject !== undefined) { this.Class.subject = this.NewSubject; } }; CChangesCorePr.prototype.WriteToBinary = function (Writer) { var nFlags = 0; if (undefined !== this.NewTitle) { nFlags |= 1; } if (undefined !== this.NewCreator) { nFlags |= 2; } if (undefined !== this.NewDescription) { nFlags |= 4; } if (undefined !== this.NewSubject) { nFlags |= 8; } Writer.WriteLong(nFlags); var bIsField; if (nFlags & 1) { bIsField = typeof this.NewTitle === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewTitle); } } if (nFlags & 2) { bIsField = typeof this.NewCreator === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewCreator); } } if (nFlags & 4) { bIsField = typeof this.NewDescription === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewDescription); } } if (nFlags & 8) { bIsField = typeof this.NewSubject === "string"; Writer.WriteBool(bIsField); if (bIsField) { Writer.WriteString2(this.NewSubject); } } }; CChangesCorePr.prototype.ReadFromBinary = function (Reader) { var nFlags = Reader.GetLong(); var bIsField; if (nFlags & 1) { bIsField = Reader.GetBool(); if (bIsField) { this.NewTitle = Reader.GetString2(); } else { this.NewTitle = null; } } if (nFlags & 2) { bIsField = Reader.GetBool(); if (bIsField) { this.NewCreator = Reader.GetString2(); } else { this.NewCreator = null; } } if (nFlags & 4) { bIsField = Reader.GetBool(); if (bIsField) { this.NewDescription = Reader.GetString2(); } else { this.NewDescription = null; } } if (nFlags & 8) { bIsField = Reader.GetBool(); if (bIsField) { this.NewSubject = Reader.GetString2(); } else { this.NewSubject = null; } } }; CChangesCorePr.prototype.CreateReverseChange = function () { var ret = new CChangesCorePr(this.Class); ret.OldTitle = this.NewTitle; ret.OldCreator = this.NewCreator; ret.OldDescription = this.NewCreator; ret.OldSubject = this.NewSubject; ret.NewTitle = this.OldTitle; ret.NewCreator = this.OldCreator; ret.NewDescription = this.OldCreator; ret.NewSubject = this.OldSubject; return ret; }; AscDFH.changesFactory[AscDFH.historyitem_CoreProperties] = CChangesCorePr; function CCore() { AscFormat.CBaseFormatObject.call(this); this.category = null; this.contentStatus = null;//Status in menu this.created = null; this.creator = null;// Authors in menu this.description = null;//Comments in menu this.identifier = null; this.keywords = null; this.language = null; this.lastModifiedBy = null; this.lastPrinted = null; this.modified = null; this.revision = null; this.subject = null; this.title = null; this.version = null; this.Lock = new AscCommon.CLock(); this.lockType = AscCommon.c_oAscLockTypes.kLockTypeNone; } InitClass(CCore, CBaseFormatObject, AscDFH.historyitem_type_Core); CCore.prototype.fromStream = function (s) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.title = s.GetString2(); break; } case 1: { this.creator = s.GetString2(); break; } case 2: { this.lastModifiedBy = s.GetString2(); break; } case 3: { this.revision = s.GetString2(); break; } case 4: { this.created = this.readDate(s.GetString2()); break; } case 5: { this.modified = this.readDate(s.GetString2()); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { var _end_rec2 = s.cur + s.GetLong() + 4; s.Skip2(1); // start attributes while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 6: { this.category = s.GetString2(); break; } case 7: { this.contentStatus = s.GetString2(); break; } case 8: { this.description = s.GetString2(); break; } case 9: { this.identifier = s.GetString2(); break; } case 10: { this.keywords = s.GetString2(); break; } case 11: { this.language = s.GetString2(); break; } case 12: { this.lastPrinted = this.readDate(s.GetString2()); break; } case 13: { this.subject = s.GetString2(); break; } case 14: { this.version = s.GetString2(); break; } default: return; } } s.Seek2(_end_rec2); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CCore.prototype.readDate = function (val) { val = new Date(val); return val instanceof Date && !isNaN(val) ? val : null; }; CCore.prototype.toStream = function (s, api) { s.StartRecord(AscCommon.c_oMainTables.Core); s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.title); s._WriteString2(1, this.creator); if (api && api.DocInfo) { s._WriteString2(2, api.DocInfo.get_UserName()); } var revision = 0; if (this.revision) { var rev = parseInt(this.revision); if (!isNaN(rev)) { revision = rev; } } s._WriteString2(3, (revision + 1).toString()); if (this.created) { s._WriteString2(4, this.created.toISOString().slice(0, 19) + 'Z'); } s._WriteString2(5, new Date().toISOString().slice(0, 19) + 'Z'); s.WriteUChar(g_nodeAttributeEnd); s.StartRecord(0); s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(6, this.category); s._WriteString2(7, this.contentStatus); s._WriteString2(8, this.description); s._WriteString2(9, this.identifier); s._WriteString2(10, this.keywords); s._WriteString2(11, this.language); // we don't track it // if (this.lastPrinted) { // s._WriteString1(12, this.lastPrinted.toISOString().slice(0, 19) + 'Z'); // } s._WriteString2(13, this.subject); s._WriteString2(14, this.version); s.WriteUChar(g_nodeAttributeEnd); s.EndRecord(); s.EndRecord(); }; CCore.prototype.asc_getTitle = function () { return this.title; }; CCore.prototype.asc_getCreator = function () { return this.creator; }; CCore.prototype.asc_getLastModifiedBy = function () { return this.lastModifiedBy; }; CCore.prototype.asc_getRevision = function () { return this.revision; }; CCore.prototype.asc_getCreated = function () { return this.created; }; CCore.prototype.asc_getModified = function () { return this.modified; }; CCore.prototype.asc_getCategory = function () { return this.category; }; CCore.prototype.asc_getContentStatus = function () { return this.contentStatus; }; CCore.prototype.asc_getDescription = function () { return this.description; }; CCore.prototype.asc_getIdentifier = function () { return this.identifier; }; CCore.prototype.asc_getKeywords = function () { return this.keywords; }; CCore.prototype.asc_getLanguage = function () { return this.language; }; CCore.prototype.asc_getLastPrinted = function () { return this.lastPrinted; }; CCore.prototype.asc_getSubject = function () { return this.subject; }; CCore.prototype.asc_getVersion = function () { return this.version; }; CCore.prototype.asc_putTitle = function (v) { this.title = v; }; CCore.prototype.asc_putCreator = function (v) { this.creator = v; }; CCore.prototype.asc_putLastModifiedBy = function (v) { this.lastModifiedBy = v; }; CCore.prototype.asc_putRevision = function (v) { this.revision = v; }; CCore.prototype.asc_putCreated = function (v) { this.created = v; }; CCore.prototype.asc_putModified = function (v) { this.modified = v; }; CCore.prototype.asc_putCategory = function (v) { this.category = v; }; CCore.prototype.asc_putContentStatus = function (v) { this.contentStatus = v; }; CCore.prototype.asc_putDescription = function (v) { this.description = v; }; CCore.prototype.asc_putIdentifier = function (v) { this.identifier = v; }; CCore.prototype.asc_putKeywords = function (v) { this.keywords = v; }; CCore.prototype.asc_putLanguage = function (v) { this.language = v; }; CCore.prototype.asc_putLastPrinted = function (v) { this.lastPrinted = v; }; CCore.prototype.asc_putSubject = function (v) { this.subject = v; }; CCore.prototype.asc_putVersion = function (v) { this.version = v; }; CCore.prototype.setProps = function (oProps) { History.Add(new CChangesCorePr(this, this, oProps, null)); this.title = oProps.title; this.creator = oProps.creator; this.description = oProps.description; this.subject = oProps.subject; }; CCore.prototype.Refresh_RecalcData = function () { }; CCore.prototype.Refresh_RecalcData2 = function () { }; CCore.prototype.copy = function () { return AscFormat.ExecuteNoHistory(function () { var oCopy = new CCore(); oCopy.category = this.category; oCopy.contentStatus = this.contentStatus; oCopy.created = this.created; oCopy.creator = this.creator; oCopy.description = this.description; oCopy.identifier = this.identifier; oCopy.keywords = this.keywords; oCopy.language = this.language; oCopy.lastModifiedBy = this.lastModifiedBy; oCopy.lastPrinted = this.lastPrinted; oCopy.modified = this.modified; oCopy.revision = this.revision; oCopy.subject = this.subject; oCopy.title = this.title; oCopy.version = this.version; return oCopy; }, this, []); }; CCore.prototype.writeDate = function(writer, sName, oDate) { if (!oDate) { return; } let sToWrite = oDate.toISOString().slice(0, 19) + 'Z'; writer.WriteXmlNodeStart(sName); writer.WriteXmlAttributeString("xsi:type", "dcterms:W3CDTF"); writer.WriteXmlAttributesEnd(); writer.WriteXmlString(sToWrite); writer.WriteXmlNodeEnd(sName); } CCore.prototype.readChildXml = function (name, reader) { switch (name) { case "category": { this.category = reader.GetTextDecodeXml(); break; } case "contentStatus": { this.contentStatus = reader.GetTextDecodeXml(); break; } case "created": { this.created = this.readDate(reader.GetTextDecodeXml()); break; } case "creator": { this.creator = reader.GetTextDecodeXml(); break; } case "description": { this.description = reader.GetTextDecodeXml(); break; } case "identifier": { this.identifier = reader.GetTextDecodeXml(); break; } case "keywords": { this.keywords = reader.GetTextDecodeXml(); break; } case "language": { this.language = reader.GetTextDecodeXml(); break; } case "lastModifiedBy": { this.lastModifiedBy = reader.GetTextDecodeXml(); break; } case "lastPrinted": { this.lastPrinted = this.readDate(reader.GetTextDecodeXml()); break; } case "modified": { this.modified = this.readDate(reader.GetTextDecodeXml()); break; } case "revision": { this.revision = reader.GetTextDecodeXml(); break; } case "subject": { this.subject = reader.GetTextDecodeXml(); break; } case "title": { this.title = reader.GetTextDecodeXml(); break; } case "version": { this.version = reader.GetTextDecodeXml(); break; } } }; CCore.prototype.toXmlImpl = function(writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); writer.WriteXmlNodeStart("cp:coreProperties"); writer.WriteXmlNullableAttributeString("xmlns:cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); writer.WriteXmlNullableAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/"); writer.WriteXmlNullableAttributeString("xmlns:dcterms", "http://purl.org/dc/terms/"); writer.WriteXmlNullableAttributeString("xmlns:dcmitype", "http://purl.org/dc/dcmitype/"); writer.WriteXmlNullableAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullableValueStringEncode2("dc:title", this.title); writer.WriteXmlNullableValueStringEncode2("dc:subject", this.subject); writer.WriteXmlNullableValueStringEncode2("dc:creator", this.creator); writer.WriteXmlNullableValueStringEncode2("cp:keywords", this.keywords); writer.WriteXmlNullableValueStringEncode2("dc:description", this.description); writer.WriteXmlNullableValueStringEncode2("dc:identifier", this.identifier); writer.WriteXmlNullableValueStringEncode2("dc:language", this.language); writer.WriteXmlNullableValueStringEncode2("cp:lastModifiedBy", this.lastModifiedBy); writer.WriteXmlNullableValueStringEncode2("cp:revision", this.revision); if (this.lastPrinted && this.lastPrinted.length > 0) { writer.WriteXmlNullableValueStringEncode2("cp:lastPrinted", this.lastPrinted); } this.writeDate(writer, "dcterms:created", this.created); this.writeDate(writer, "dcterms:modified", this.modified); writer.WriteXmlNullableValueStringEncode2("cp:category", this.category); writer.WriteXmlNullableValueStringEncode2("cp:contentStatus", this.contentStatus); writer.WriteXmlNullableValueStringEncode2("cp:version", this.version); writer.WriteXmlNodeEnd("cp:coreProperties"); }; CCore.prototype.toXml = function (writer) { let oContext = writer.context; if(oContext.presentation) { let oCore = this.copy(); oCore.setRequiredDefaultsPresentationEditor(); oCore.toXmlImpl(writer); return; } this.toXmlImpl(writer); }; CCore.prototype.createDefaultPresentationEditor = function() { this.lastModifiedBy = ""; }; let DEFAULT_CREATOR = "CREATOR"; let DEFAULT_LAST_MODIFIED_BY = "CREATOR"; CCore.prototype.setRequiredDefaultsPresentationEditor = function() { if(!this.creator) { this.creator = DEFAULT_CREATOR; } if(!this.lastModifiedBy) { this.lastModifiedBy = DEFAULT_LAST_MODIFIED_BY; } }; window['AscCommon'].CCore = CCore; prot = CCore.prototype; prot["asc_getTitle"] = prot.asc_getTitle; prot["asc_getCreator"] = prot.asc_getCreator; prot["asc_getLastModifiedBy"] = prot.asc_getLastModifiedBy; prot["asc_getRevision"] = prot.asc_getRevision; prot["asc_getCreated"] = prot.asc_getCreated; prot["asc_getModified"] = prot.asc_getModified; prot["asc_getCategory"] = prot.asc_getCategory; prot["asc_getContentStatus"] = prot.asc_getContentStatus; prot["asc_getDescription"] = prot.asc_getDescription; prot["asc_getIdentifier"] = prot.asc_getIdentifier; prot["asc_getKeywords"] = prot.asc_getKeywords; prot["asc_getLanguage"] = prot.asc_getLanguage; prot["asc_getLastPrinted"] = prot.asc_getLastPrinted; prot["asc_getSubject"] = prot.asc_getSubject; prot["asc_getVersion"] = prot.asc_getVersion; prot["asc_putTitle"] = prot.asc_putTitle; prot["asc_putCreator"] = prot.asc_putCreator; prot["asc_putLastModifiedBy"] = prot.asc_putLastModifiedBy; prot["asc_putRevision"] = prot.asc_putRevision; prot["asc_putCreated"] = prot.asc_putCreated; prot["asc_putModified"] = prot.asc_putModified; prot["asc_putCategory"] = prot.asc_putCategory; prot["asc_putContentStatus"] = prot.asc_putContentStatus; prot["asc_putDescription"] = prot.asc_putDescription; prot["asc_putIdentifier"] = prot.asc_putIdentifier; prot["asc_putKeywords"] = prot.asc_putKeywords; prot["asc_putLanguage"] = prot.asc_putLanguage; prot["asc_putLastPrinted"] = prot.asc_putLastPrinted; prot["asc_putSubject"] = prot.asc_putSubject; prot["asc_putVersion"] = prot.asc_putVersion; function PartTitle() { CBaseNoIdObject.call(this); this.title = null; } InitClass(PartTitle, CBaseNoIdObject, 0); PartTitle.prototype.fromXml = function (reader) { this.title = reader.GetTextDecodeXml(); } PartTitle.prototype.toXml = function (writer) { if(this.title !== null) { writer.WriteXmlString("<vt:lpstr>"); writer.WriteXmlStringEncode(this.title); writer.WriteXmlString("</vt:lpstr>"); } } function CApp() { CBaseNoIdObject.call(this); this.Template = null; this.TotalTime = null; this.Words = null; this.Application = null; this.PresentationFormat = null; this.Paragraphs = null; this.Slides = null; this.Notes = null; this.HiddenSlides = null; this.MMClips = null; this.ScaleCrop = null; this.HeadingPairs = []; this.TitlesOfParts = []; this.Company = null; this.LinksUpToDate = null; this.SharedDoc = null; this.HyperlinksChanged = null; this.AppVersion = null; this.Characters = null; this.CharactersWithSpaces = null; this.DocSecurity = null; this.HyperlinkBase = null; this.Lines = null; this.Manager = null; this.Pages = null; } InitClass(CApp, CBaseNoIdObject, 0); CApp.prototype.getAppName = function() { return "@@AppName/@@Version"; }; CApp.prototype.setRequiredDefaults = function() { this.Application = this.getAppName(); }; CApp.prototype.merge = function(oOtherApp) { oOtherApp.Template !== null && (this.Template = oOtherApp.Template); oOtherApp.TotalTime !== null && (this.TotalTime = oOtherApp.TotalTime); oOtherApp.Words !== null && (this.Words = oOtherApp.Words); oOtherApp.Application !== null && (this.Application = oOtherApp.Application); oOtherApp.PresentationFormat !== null && (this.PresentationFormat = oOtherApp.PresentationFormat); oOtherApp.Paragraphs !== null && (this.Paragraphs = oOtherApp.Paragraphs); //oOtherApp.Slides !== null && (this.Slides = oOtherApp.Slides); //oOtherApp.Notes !== null && (this.Notes = oOtherApp.Notes); oOtherApp.HiddenSlides !== null && (this.HiddenSlides = oOtherApp.HiddenSlides); oOtherApp.MMClips !== null && (this.MMClips = oOtherApp.MMClips); oOtherApp.ScaleCrop !== null && (this.ScaleCrop = oOtherApp.ScaleCrop); oOtherApp.Company !== null && (this.Company = oOtherApp.Company); oOtherApp.LinksUpToDate !== null && (this.LinksUpToDate = oOtherApp.LinksUpToDate); oOtherApp.SharedDoc !== null && (this.SharedDoc = oOtherApp.SharedDoc); oOtherApp.HyperlinksChanged !== null && (this.HyperlinksChanged = oOtherApp.HyperlinksChanged); oOtherApp.AppVersion !== null && (this.AppVersion = oOtherApp.AppVersion); oOtherApp.Characters !== null && (this.Characters = oOtherApp.Characters); oOtherApp.CharactersWithSpaces !== null && (this.CharactersWithSpaces = oOtherApp.CharactersWithSpaces); oOtherApp.DocSecurity !== null && (this.DocSecurity = oOtherApp.DocSecurity); oOtherApp.HyperlinkBase !== null && (this.HyperlinkBase = oOtherApp.HyperlinkBase); oOtherApp.Lines !== null && (this.Lines = oOtherApp.Lines); oOtherApp.Manager !== null && (this.Manager = oOtherApp.Manager); oOtherApp.Pages !== null && (this.Pages = oOtherApp.Pages); }; CApp.prototype.createDefaultPresentationEditor = function(nCountSlides, nCountThemes) { this.TotalTime = 0; this.Words = 0; this.setRequiredDefaults(); this.PresentationFormat = "On-screen Show (4:3)"; this.Paragraphs = 0; this.Slides = nCountSlides; this.Notes = nCountSlides; this.HiddenSlides = 0; this.MMClips = 2; this.ScaleCrop = false; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[0].type = c_oVariantTypes.vtLpstr; this.HeadingPairs[0].strContent = "Theme"; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[1].type = c_oVariantTypes.vtI4; this.HeadingPairs[1].iContent = nCountThemes; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[2].type = c_oVariantTypes.vtLpstr; this.HeadingPairs[2].strContent = "Slide Titles"; this.HeadingPairs.push(new CVariant()); this.HeadingPairs[3].type = c_oVariantTypes.vtI4; this.HeadingPairs[3].iContent = nCountSlides; for (let i = 0; i < nCountThemes; ++i) { let s = "Theme " + ( i + 1); this.TitlesOfParts.push(new PartTitle()); this.TitlesOfParts[i].title = s; } for (let i = 0; i < nCountSlides; ++i) { let s = "Slide " + (i + 1); this.TitlesOfParts.push( new PartTitle()); this.TitlesOfParts[nCountThemes + i].title = s; } this.LinksUpToDate = false; this.SharedDoc = false; this.HyperlinksChanged = false; }; CApp.prototype.fromStream = function (s) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.Template = s.GetString2(); break; } case 1: { this.Application = s.GetString2(); break; } case 2: { this.PresentationFormat = s.GetString2(); break; } case 3: { this.Company = s.GetString2(); break; } case 4: { this.AppVersion = s.GetString2(); break; } case 5: { this.TotalTime = s.GetLong(); break; } case 6: { this.Words = s.GetLong(); break; } case 7: { this.Paragraphs = s.GetLong(); break; } case 8: { this.Slides = s.GetLong(); break; } case 9: { this.Notes = s.GetLong(); break; } case 10: { this.HiddenSlides = s.GetLong(); break; } case 11: { this.MMClips = s.GetLong(); break; } case 12: { this.ScaleCrop = s.GetBool(); break; } case 13: { this.LinksUpToDate = s.GetBool(); break; } case 14: { this.SharedDoc = s.GetBool(); break; } case 15: { this.HyperlinksChanged = s.GetBool(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { var _end_rec2 = s.cur + s.GetLong() + 4; s.Skip2(1); // start attributes while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 16: { this.Characters = s.GetLong(); break; } case 17: { this.CharactersWithSpaces = s.GetLong(); break; } case 18: { this.DocSecurity = s.GetLong(); break; } case 19: { this.HyperlinkBase = s.GetString2(); break; } case 20: { this.Lines = s.GetLong(); break; } case 21: { this.Manager = s.GetString2(); break; } case 22: { this.Pages = s.GetLong(); break; } default: return; } } s.Seek2(_end_rec2); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CApp.prototype.toStream = function (s) { s.StartRecord(AscCommon.c_oMainTables.App); s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.Template); // just in case // s._WriteString2(1, this.Application); s._WriteString2(2, this.PresentationFormat); s._WriteString2(3, this.Company); // just in case // s._WriteString2(4, this.AppVersion); //we don't count these stats // s._WriteInt2(5, this.TotalTime); // s._WriteInt2(6, this.Words); // s._WriteInt2(7, this.Paragraphs); // s._WriteInt2(8, this.Slides); // s._WriteInt2(9, this.Notes); // s._WriteInt2(10, this.HiddenSlides); // s._WriteInt2(11, this.MMClips); s._WriteBool2(12, this.ScaleCrop); s._WriteBool2(13, this.LinksUpToDate); s._WriteBool2(14, this.SharedDoc); s._WriteBool2(15, this.HyperlinksChanged); s.WriteUChar(g_nodeAttributeEnd); s.StartRecord(0); s.WriteUChar(AscCommon.g_nodeAttributeStart); // s._WriteInt2(16, this.Characters); // s._WriteInt2(17, this.CharactersWithSpaces); s._WriteInt2(18, this.DocSecurity); s._WriteString2(19, this.HyperlinkBase); // s._WriteInt2(20, this.Lines); s._WriteString2(21, this.Manager); // s._WriteInt2(22, this.Pages); s.WriteUChar(g_nodeAttributeEnd); s.EndRecord(); s.EndRecord(); }; CApp.prototype.asc_getTemplate = function () { return this.Template; }; CApp.prototype.asc_getTotalTime = function () { return this.TotalTime; }; CApp.prototype.asc_getWords = function () { return this.Words; }; CApp.prototype.asc_getApplication = function () { return this.Application; }; CApp.prototype.asc_getPresentationFormat = function () { return this.PresentationFormat; }; CApp.prototype.asc_getParagraphs = function () { return this.Paragraphs; }; CApp.prototype.asc_getSlides = function () { return this.Slides; }; CApp.prototype.asc_getNotes = function () { return this.Notes; }; CApp.prototype.asc_getHiddenSlides = function () { return this.HiddenSlides; }; CApp.prototype.asc_getMMClips = function () { return this.MMClips; }; CApp.prototype.asc_getScaleCrop = function () { return this.ScaleCrop; }; CApp.prototype.asc_getCompany = function () { return this.Company; }; CApp.prototype.asc_getLinksUpToDate = function () { return this.LinksUpToDate; }; CApp.prototype.asc_getSharedDoc = function () { return this.SharedDoc; }; CApp.prototype.asc_getHyperlinksChanged = function () { return this.HyperlinksChanged; }; CApp.prototype.asc_getAppVersion = function () { return this.AppVersion; }; CApp.prototype.asc_getCharacters = function () { return this.Characters; }; CApp.prototype.asc_getCharactersWithSpaces = function () { return this.CharactersWithSpaces; }; CApp.prototype.asc_getDocSecurity = function () { return this.DocSecurity; }; CApp.prototype.asc_getHyperlinkBase = function () { return this.HyperlinkBase; }; CApp.prototype.asc_getLines = function () { return this.Lines; }; CApp.prototype.asc_getManager = function () { return this.Manager; }; CApp.prototype.asc_getPages = function () { return this.Pages; }; CApp.prototype.readChildXml = function (name, reader) { switch (name) { case "Template": { this.Template = reader.GetTextDecodeXml(); break; } case "Application": { this.Application = reader.GetTextDecodeXml(); break; } case "PresentationFormat": { this.PresentationFormat = reader.GetTextDecodeXml(); break; } case "Company": { this.Company = reader.GetTextDecodeXml(); break; } case "AppVersion": { this.AppVersion = reader.GetTextDecodeXml(); break; } case "TotalTime": { this.TotalTime = reader.GetTextInt(null, 10); break; } case "Words": { this.Words = reader.GetTextInt(null, 10); break; } case "Paragraphs": { this.Paragraphs = reader.GetTextInt(null, 10); break; } case "Slides": { this.Slides = reader.GetTextInt(null, 10); break; } case "Notes": { this.Notes = reader.GetTextInt(null, 10); break; } case "HiddenSlides": { this.HiddenSlides = reader.GetTextInt(null, 10); break; } case "MMClips": { this.MMClips = reader.GetTextInt(null, 10); break; } case "ScaleCrop": { this.ScaleCrop = reader.GetTextBool(); break; } case "LinksUpToDate": { this.LinksUpToDate = reader.GetTextBool(); break; } case "SharedDoc": { this.SharedDoc = reader.GetTextBool(); break; } case "HyperlinksChanged": { this.HyperlinksChanged = reader.GetTextBool(); break; } case "Pages": { this.Pages = reader.GetTextUInt(); break; } } }; CApp.prototype.toXml = function (writer) { let oContext = writer.context; if(oContext.presentation) { let oAppToWrite = new CApp(); oAppToWrite.createDefaultPresentationEditor(oContext.getSlidesCount(), oContext.getSlideMastersCount()); oAppToWrite.merge(this); oAppToWrite.toDrawingML(writer); } else { this.toXmlInternal(writer); } }; CApp.prototype.toDrawingML = function(writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); writer.WriteXmlNodeStart("Properties"); writer.WriteXmlNullableAttributeString("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"); writer.WriteXmlNullableAttributeString("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullableValueStringEncode2("Template", this.Template); writer.WriteXmlNullableValueUInt("TotalTime", this.TotalTime); writer.WriteXmlNullableValueUInt("Pages", this.Pages); writer.WriteXmlNullableValueUInt("Words", this.Words); writer.WriteXmlNullableValueUInt("Characters", this.Characters); writer.WriteXmlNullableValueUInt("CharactersWithSpaces", this.CharactersWithSpaces); writer.WriteXmlNullableValueStringEncode2("Application", this.Application); writer.WriteXmlNullableValueInt("DocSecurity", this.DocSecurity); writer.WriteXmlNullableValueStringEncode2("PresentationFormat", this.PresentationFormat); writer.WriteXmlNullableValueUInt("Lines", this.Lines); writer.WriteXmlNullableValueUInt("Paragraphs", this.Paragraphs); writer.WriteXmlNullableValueUInt("Slides", this.Slides); writer.WriteXmlNullableValueUInt("Notes", this.Notes); writer.WriteXmlNullableValueUInt("HiddenSlides", this.HiddenSlides); writer.WriteXmlNullableValueInt("MMClips", this.MMClips); if (this.ScaleCrop !== null) { writer.WriteXmlString("<ScaleCrop>"); writer.WriteXmlString(this.ScaleCrop ? "true" : "false"); writer.WriteXmlString("</ScaleCrop>"); } writer.WriteXmlNodeStart("HeadingPairs"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("vt:vector"); writer.WriteXmlNullableAttributeUInt("size", this.HeadingPairs.length); writer.WriteXmlNullableAttributeString("baseType", "variant"); writer.WriteXmlAttributesEnd(); writer.WriteXmlArray(this.HeadingPairs, "vt:variant"); writer.WriteXmlNodeEnd("vt:vector"); writer.WriteXmlNodeEnd("HeadingPairs"); writer.WriteXmlNodeStart("TitlesOfParts"); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeStart("vt:vector"); writer.WriteXmlNullableAttributeUInt("size", this.TitlesOfParts.length); writer.WriteXmlNullableAttributeString("baseType", "lpstr"); writer.WriteXmlAttributesEnd(); writer.WriteXmlArray(this.TitlesOfParts, "vt:variant"); writer.WriteXmlNodeEnd("vt:vector"); writer.WriteXmlNodeEnd("TitlesOfParts"); writer.WriteXmlNullableValueStringEncode2("Manager", this.Manager); writer.WriteXmlNullableValueStringEncode2("Company", this.Company); writer.WriteXmlNullableValueStringEncode2("LinksUpToDate", this.LinksUpToDate); writer.WriteXmlNullableValueStringEncode2("SharedDoc", this.SharedDoc); writer.WriteXmlNullableValueStringEncode2("HyperlinkBase", this.HyperlinkBase); writer.WriteXmlNullableValueStringEncode2("HyperlinksChanged", this.HyperlinksChanged); writer.WriteXmlNullableValueStringEncode2("AppVersion", this.AppVersion); writer.WriteXmlNodeEnd("Properties"); }; CApp.prototype.toXmlInternal = function (writer) { writer.WriteXmlString(AscCommonWord.g_sXmlHeader); writer.WriteXmlNodeStart("Properties"); writer.WriteXmlNullableAttributeString("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"); writer.WriteXmlNullableAttributeString("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.WriteXmlAttributesEnd(); writer.WriteXmlString("<Application>"); writer.WriteXmlStringEncode(this.getAppName()); writer.WriteXmlString("</Application>"); if (this.Characters !== null) { writer.WriteXmlString("<Characters>"); writer.WriteXmlString(this.Characters + ""); writer.WriteXmlString("</Characters>"); } if (this.CharactersWithSpaces !== null) { writer.WriteXmlString("<CharactersWithSpaces>"); writer.WriteXmlString(this.CharactersWithSpaces + ""); writer.WriteXmlString("</CharactersWithSpaces>"); } if (this.Company !== null) { writer.WriteXmlString("<Company>"); writer.WriteXmlStringEncode(this.Company); writer.WriteXmlString("</Company>"); } if (this.DocSecurity !== null) { writer.WriteXmlString("<DocSecurity>"); writer.WriteXmlString(this.DocSecurity + ""); writer.WriteXmlString("</DocSecurity>"); } if (this.HiddenSlides !== null) { writer.WriteXmlString("<HiddenSlides>"); writer.WriteXmlString(this.HiddenSlides + ""); writer.WriteXmlString("</HiddenSlides>"); } if (this.HyperlinkBase !== null) { writer.WriteXmlString("<HyperlinkBase>"); writer.WriteXmlString(this.HyperlinkBase + ""); writer.WriteXmlString("</HyperlinkBase>"); } if (this.HyperlinksChanged !== null) { writer.WriteXmlString("<HyperlinksChanged>"); writer.WriteXmlString(this.HyperlinksChanged ? "true" : "false"); writer.WriteXmlString("</HyperlinksChanged>"); } if (this.Lines !== null) { writer.WriteXmlString("<Lines>"); writer.WriteXmlString(this.Lines + ""); writer.WriteXmlString("</Lines>"); } if (this.LinksUpToDate !== null) { writer.WriteXmlString("<LinksUpToDate>"); writer.WriteXmlString(this.LinksUpToDate ? "true" : "false"); writer.WriteXmlString("</LinksUpToDate>"); } if (this.Manager !== null) { writer.WriteXmlString("<Manager>"); writer.WriteXmlStringEncode(this.Manager); writer.WriteXmlString("</Manager>"); } if (this.MMClips !== null) { writer.WriteXmlString("<MMClips>"); writer.WriteXmlString(this.MMClips + ""); writer.WriteXmlString("</MMClips>"); } if (this.Notes !== null) { writer.WriteXmlString("<Notes>"); writer.WriteXmlString(this.Notes + ""); writer.WriteXmlString("</Notes>"); } if (this.Pages !== null) { writer.WriteXmlString("<Pages>"); writer.WriteXmlString(this.Pages + ""); writer.WriteXmlString("</Pages>"); } if (this.Paragraphs !== null) { writer.WriteXmlString("<Paragraphs>"); writer.WriteXmlString(this.Paragraphs + ""); writer.WriteXmlString("</Paragraphs>"); } if (this.ScaleCrop !== null) { writer.WriteXmlString("<ScaleCrop>"); writer.WriteXmlString(this.ScaleCrop ? "true" : "false"); writer.WriteXmlString("</ScaleCrop>"); } if (this.SharedDoc !== null) { writer.WriteXmlString("<SharedDoc>"); writer.WriteXmlString(this.SharedDoc ? "true" : "false"); writer.WriteXmlString("</SharedDoc>"); } if (this.Slides !== null) { writer.WriteXmlString("<Slides>"); writer.WriteXmlString(this.Slides + ""); writer.WriteXmlString("</Slides>"); } if (this.Template !== null) { writer.WriteXmlString("<Template>"); writer.WriteXmlStringEncode(this.Template); writer.WriteXmlString("</Template>"); } if (this.TotalTime !== null) { writer.WriteXmlString("<TotalTime>"); writer.WriteXmlString(this.TotalTime + ""); writer.WriteXmlString("</TotalTime>"); } if (this.Words !== null) { writer.WriteXmlString("<Words>"); writer.WriteXmlString(this.Words + ""); writer.WriteXmlString("</Words>"); } writer.WriteXmlNodeEnd("Properties"); }; window['AscCommon'].CApp = CApp; prot = CApp.prototype; prot["asc_getTemplate"] = prot.asc_getTemplate; prot["asc_getTotalTime"] = prot.asc_getTotalTime; prot["asc_getWords"] = prot.asc_getWords; prot["asc_getApplication"] = prot.asc_getApplication; prot["asc_getPresentationFormat"] = prot.asc_getPresentationFormat; prot["asc_getParagraphs"] = prot.asc_getParagraphs; prot["asc_getSlides"] = prot.asc_getSlides; prot["asc_getNotes"] = prot.asc_getNotes; prot["asc_getHiddenSlides"] = prot.asc_getHiddenSlides; prot["asc_getMMClips"] = prot.asc_getMMClips; prot["asc_getScaleCrop"] = prot.asc_getScaleCrop; prot["asc_getCompany"] = prot.asc_getCompany; prot["asc_getLinksUpToDate"] = prot.asc_getLinksUpToDate; prot["asc_getSharedDoc"] = prot.asc_getSharedDoc; prot["asc_getHyperlinksChanged"] = prot.asc_getHyperlinksChanged; prot["asc_getAppVersion"] = prot.asc_getAppVersion; prot["asc_getCharacters"] = prot.asc_getCharacters; prot["asc_getCharactersWithSpaces"] = prot.asc_getCharactersWithSpaces; prot["asc_getDocSecurity"] = prot.asc_getDocSecurity; prot["asc_getHyperlinkBase"] = prot.asc_getHyperlinkBase; prot["asc_getLines"] = prot.asc_getLines; prot["asc_getManager"] = prot.asc_getManager; prot["asc_getPages"] = prot.asc_getPages; function CCustomProperties() { CBaseNoIdObject.call(this); this.properties = []; } InitClass(CCustomProperties, CBaseNoIdObject, 0); CCustomProperties.prototype.fromStream = function (s) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { s.Skip2(4); var _c = s.GetULong(); for (var i = 0; i < _c; ++i) { s.Skip2(1); // type var tmp = new CCustomProperty(); tmp.fromStream(s); this.properties.push(tmp); } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CCustomProperties.prototype.toStream = function (s) { s.StartRecord(AscCommon.c_oMainTables.CustomProperties); s.WriteUChar(AscCommon.g_nodeAttributeStart); s.WriteUChar(g_nodeAttributeEnd); this.fillNewPid(); s.WriteRecordArray4(0, 0, this.properties); s.EndRecord(); }; CCustomProperties.prototype.fillNewPid = function (s) { var index = 2; this.properties.forEach(function (property) { property.pid = index++; }); }; CCustomProperties.prototype.add = function (name, variant, opt_linkTarget) { var newProperty = new CCustomProperty(); newProperty.fmtid = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProperty.pid = null; newProperty.name = name; newProperty.linkTarget = opt_linkTarget || null; newProperty.content = variant; this.properties.push(newProperty); }; CCustomProperties.prototype.readChildXml = function (name, reader) { switch (name) { case "property": { let oPr = new CCustomProperty(); oPr.fromXml(reader); this.properties.push(oPr); break; } } }; CCustomProperties.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("Properties"); writer.WriteXmlNullableAttributeString("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"); writer.WriteXmlNullableAttributeString("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.WriteXmlAttributesEnd(); for (let i = 0; i < m_arProperties.length; ++i) { this.properties[i].toXml(writer); } writer.WriteXmlNodeEnd("Properties"); }; window['AscCommon'].CCustomProperties = CCustomProperties; prot = CCustomProperties.prototype; prot["add"] = prot.add; function CCustomProperty() { CBaseNoIdObject.call(this); this.fmtid = null; this.pid = null; this.name = null; this.linkTarget = null; this.content = null; } InitClass(CCustomProperty, CBaseNoIdObject, 0); CCustomProperty.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.fmtid = s.GetString2(); break; } case 1: { this.pid = s.GetLong(); break; } case 2: { this.name = s.GetString2(); break; } case 3: { this.linkTarget = s.GetString2(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.content = new CVariant(this); this.content.fromStream(s); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CCustomProperty.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.fmtid); s._WriteInt2(1, this.pid); s._WriteString2(2, this.name); s._WriteString2(3, this.linkTarget); s.WriteUChar(g_nodeAttributeEnd); s.WriteRecord4(0, this.content); }; CCustomProperty.prototype.readAttrXml = function (name, reader) { switch (name) { case "fmtid": { this.fmtid = reader.GetValue(); break; } case "linkTarget": { this.linkTarget = reader.GetValue(); break; } case "name": { this.name = reader.GetValue(); break; } case "pid": { this.pid = reader.GetValueInt(); break; } } }; CCustomProperty.prototype.readChildXml = function (name, reader) { if (!this.content) { this.content = new CVariant(this); } this.content.readChildXml(name, reader); }; CCustomProperty.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("property"); writer.WriteXmlNullableAttributeString("fmtid", this.fmtid); writer.WriteXmlNullableAttributeInt("pid", this.pid); writer.WriteXmlNullableAttributeString("name", this.name); writer.WriteXmlNullableAttributeString("linkTarget", this.linkTarget); writer.WriteXmlAttributesEnd(); if (this.content) { this.content.toXmlWriterContent(writer); } writer.WriteXmlNodeEnd("property"); }; function CVariantVector() { CBaseNoIdObject.call(this); this.baseType = null; this.size = null; this.variants = []; } InitClass(CVariantVector, CBaseNoIdObject, 0); CVariantVector.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.baseType = s.GetUChar(); break; } case 1: { this.size = s.GetLong(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { s.Skip2(4); var _c = s.GetULong(); for (var i = 0; i < _c; ++i) { s.Skip2(1); // type var tmp = new CVariant(this); tmp.fromStream(s); this.variants.push(tmp); } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariantVector.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteUChar2(0, this.baseType); s._WriteInt2(1, this.size); s.WriteUChar(g_nodeAttributeEnd); s.WriteRecordArray4(0, 0, this.variants); }; CVariantVector.prototype.readAttrXml = function (name, reader) { switch (name) { case "baseType": { let sType = reader.GetValue(); this.baseTyep = CVariant.prototype.typeStrToEnum.call(this, sType); break; } case "size": { this.size = reader.GetValueInt(); break; } } }; CVariantVector.prototype.readChildXml = function (name, reader) { let oVar = new CVariant(this); oVar.readChildXml(name, reader); this.variants.push(oVar); }; CVariantVector.prototype.getVariantType = function () { return AscFormat.isRealNumber(this.baseType) ? this.baseType : c_oVariantTypes.vtEmpty; }; CVariantVector.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:vector"); writer.WriteXmlNullableAttributeString("baseType", CVariant.prototype.getStringByType.call(this, this.getVariantType())); writer.WriteXmlNullableAttributeInt("size", this.size); writer.WriteXmlAttributesEnd(); for (let i = 0; i < this.variants.length; ++i) { this.variants[i].toXmlWriterContent(writer); } writer.WriteXmlNodeEnd("vt:vector"); }; function CVariantArray() { CBaseNoIdObject.call(this); this.baseType = null; this.lBounds = null; this.uBounds = null; this.variants = []; } InitClass(CVariantArray, CBaseNoIdObject, 0); CVariantArray.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.baseType = s.GetUChar(); break; } case 1: { this.lBounds = s.GetString2(); break; } case 2: { this.uBounds = s.GetString2(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { s.Skip2(4); var _c = s.GetULong(); for (var i = 0; i < _c; ++i) { s.Skip2(1); // type var tmp = new CVariant(); tmp.fromStream(s); this.variants.push(tmp); } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariantArray.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteUChar2(0, this.baseType); s._WriteString2(1, this.lBounds); s._WriteString2(2, this.uBounds); s.WriteUChar(g_nodeAttributeEnd); s.WriteRecordArray4(0, 0, this.variants); }; CVariantArray.prototype.getVariantType = function () { return AscFormat.isRealNumber(this.baseType) ? this.baseType : c_oVariantTypes.vtEmpty; }; CVariantArray.prototype.readAttrXml = function (name, reader) { switch (name) { case "baseType": { let sType = reader.GetValue(); this.baseTyep = CVariant.prototype.typeStrToEnum.call(this, sType); break; } case "lBounds": { this.lBounds = reader.GetValueInt(); break; } case "uBounds": { this.uBounds = reader.GetValueInt(); break; } } }; CVariantArray.prototype.readChildXml = function (name, reader) { let oVar = new CVariant(this); oVar.readChildXml(name, reader); this.variants.push(oVar); }; CVariantArray.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:array"); writer.WriteXmlNullableAttributeInt("lBounds", this.lBounds); writer.WriteXmlNullableAttributeInt("uBounds", this.uBounds); writer.WriteXmlNullableAttributeString("baseType", CVariant.prototype.getStringByType.call(this, this.getVariantType())); writer.WriteXmlAttributesEnd(); for (let i = 0; i < this.variants.length; ++i) { this.variants[i].toXmlWriterContent(writer); } writer.WriteXmlNodeEnd("vt:array"); }; function CVariantVStream() { CBaseNoIdObject.call(this); this.version = null; this.strContent = null; } InitClass(CVariantVStream, CBaseNoIdObject, 0); CVariantVStream.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.version = s.GetString2(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.strContent = s.GetString2(); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariantVStream.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteString2(0, this.version); s.WriteUChar(g_nodeAttributeEnd); s._WriteString2(0, this.strContent); }; CVariantVStream.prototype.fromXml = function (reader, bSkipFirstNode) { this.strContent = reader.GetValueDecodeXml(); CBaseNoIdObject.prototype.fromXml.call(this, reader, bSkipFirstNode); }; CVariantVStream.prototype.readAttrXml = function (name, reader) { switch (name) { case "version": { this.version = reader.GetValue(); break; } } }; CVariantVStream.prototype.readChildXml = function (name, reader) { let oVar = new CVariant(this); oVar.readChildXml(name, reader); this.variants.push(oVar); }; CVariantVStream.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:vstream"); writer.WriteXmlNullableAttributeString("version", this.version); writer.WriteXmlAttributesEnd(); writer.WriteXmlNullableValueStringEncode2(this.content); writer.WriteXmlNodeEnd("vt:vstream"); }; function CVariant(parent) { CBaseNoIdObject.call(this); this.type = null; this.strContent = null; this.iContent = null; this.uContent = null; this.dContent = null; this.bContent = null; this.variant = null; this.vector = null; this.array = null; this.vStream = null; this.parent = parent; } InitClass(CVariant, CBaseNoIdObject, 0); CVariant.prototype.fromStream = function (s) { var _type; var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; var _at; // attributes var _sa = s.GetUChar(); while (true) { _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.type = s.GetUChar(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.strContent = s.GetString2(); break; } case 1: { this.iContent = s.GetLong(); break; } case 2: { this.iContent = s.GetULong(); break; } case 3: { this.dContent = s.GetDouble(); break; } case 4: { this.bContent = s.GetBool(); break; } case 5: { this.variant = new CVariant(this); this.variant.fromStream(s); break; } case 6: { this.vector = new CVariantVector(); this.vector.fromStream(s); break; } case 7: { this.array = new CVariantArray(); this.array.fromStream(s); break; } case 8: { this.vStream = new CVariantVStream(); this.vStream.fromStream(s); break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_pos); }; CVariant.prototype.toStream = function (s) { s.WriteUChar(AscCommon.g_nodeAttributeStart); s._WriteUChar2(0, this.type); s.WriteUChar(g_nodeAttributeEnd); s._WriteString2(0, this.strContent); s._WriteInt2(1, this.iContent); s._WriteUInt2(2, this.uContent); s._WriteDoubleReal2(3, this.dContent); s._WriteBool2(4, this.bContent); s.WriteRecord4(5, this.variant); s.WriteRecord4(6, this.vector); s.WriteRecord4(7, this.array); s.WriteRecord4(8, this.vStream); }; CVariant.prototype.setText = function (val) { this.type = c_oVariantTypes.vtLpwstr; this.strContent = val; }; CVariant.prototype.setNumber = function (val) { this.type = c_oVariantTypes.vtI4; this.iContent = val; }; CVariant.prototype.setDate = function (val) { this.type = c_oVariantTypes.vtFiletime; this.strContent = val.toISOString().slice(0, 19) + 'Z'; }; CVariant.prototype.setBool = function (val) { this.type = c_oVariantTypes.vtBool; this.bContent = val; }; CVariant.prototype.readAttrXml = function (name, reader) { switch (name) { case "fmtid": { this.fmtid = reader.GetValue(); break; } case "linkTarget": { this.linkTarget = reader.GetValue(); break; } case "name": { this.name = reader.GetValue(); break; } case "pid": { this.name = reader.GetValueInt(); break; } } }; CVariant.prototype.typeStrToEnum = function (name) { switch (name) { case "vector": { return c_oVariantTypes.vtVector; break; } case "array": { return c_oVariantTypes.vtArray; break; } case "blob": { return c_oVariantTypes.vtBlob; break; } case "oblob": { return c_oVariantTypes.vtOBlob; break; } case "empty": { return c_oVariantTypes.vtEmpty; break; } case "null": { return c_oVariantTypes.vtNull; break; } case "i1": { return c_oVariantTypes.vtI1; break; } case "i2": { return c_oVariantTypes.vtI2; break; } case "i4": { return c_oVariantTypes.vtI4; break; } case "i8": { return c_oVariantTypes.vtI8; break; } case "int": { return c_oVariantTypes.vtInt; break; } case "ui1": { return c_oVariantTypes.vtUi1; break; } case "ui2": { return c_oVariantTypes.vtUi2; break; } case "ui4": { return c_oVariantTypes.vtUi4; break; } case "ui8": { return c_oVariantTypes.vtUi8; break; } case "uint": { return c_oVariantTypes.vtUint; break; } case "r4": { return c_oVariantTypes.vtR4; break; } case "r8": { return c_oVariantTypes.vtR8; break; } case "decimal": { return c_oVariantTypes.vtDecimal; break; } case "lpstr": { return c_oVariantTypes.vtLpstr; break; } case "lpwstr": { return c_oVariantTypes.vtLpwstr; break; } case "bstr": { return c_oVariantTypes.vtBstr; break; } case "date": { return c_oVariantTypes.vtDate; break; } case "filetime": { return c_oVariantTypes.vtFiletime; break; } case "bool": { return c_oVariantTypes.vtBool; break; } case "cy": { return c_oVariantTypes.vtCy; break; } case "error": { return c_oVariantTypes.vtError; break; } case "stream": { return c_oVariantTypes.vtStream; break; } case "ostream": { return c_oVariantTypes.vtOStream; break; } case "storage": { return c_oVariantTypes.vtStorage; break; } case "ostorage": { return c_oVariantTypes.vtOStorage; break; } case "vstream": { return c_oVariantTypes.vtVStream; break; } case "clsid": { return c_oVariantTypes.vtClsid; break; } } return null; }; CVariant.prototype.getStringByType = function (eType) { if (c_oVariantTypes.vtEmpty === eType) return "empty"; else if (c_oVariantTypes.vtNull === eType) return "null"; else if (c_oVariantTypes.vtVariant === eType) return "variant"; else if (c_oVariantTypes.vtVector === eType) return "vector"; else if (c_oVariantTypes.vtArray === eType) return "array"; else if (c_oVariantTypes.vtVStream === eType) return "vstream"; else if (c_oVariantTypes.vtBlob === eType) return "blob"; else if (c_oVariantTypes.vtOBlob === eType) return "oblob"; else if (c_oVariantTypes.vtI1 === eType) return "i1"; else if (c_oVariantTypes.vtI2 === eType) return "i2"; else if (c_oVariantTypes.vtI4 === eType) return "i4"; else if (c_oVariantTypes.vtI8 === eType) return "i8"; else if (c_oVariantTypes.vtInt === eType) return "int"; else if (c_oVariantTypes.vtUi1 === eType) return "ui1"; else if (c_oVariantTypes.vtUi2 === eType) return "ui2"; else if (c_oVariantTypes.vtUi4 === eType) return "ui4"; else if (c_oVariantTypes.vtUi8 === eType) return "ui8"; else if (c_oVariantTypes.vtUint === eType) return "uint"; else if (c_oVariantTypes.vtR4 === eType) return "r4"; else if (c_oVariantTypes.vtR8 === eType) return "r8"; else if (c_oVariantTypes.vtDecimal === eType) return "decimal"; else if (c_oVariantTypes.vtLpstr === eType) return "lpstr"; else if (c_oVariantTypes.vtLpwstr === eType) return "lpwstr"; else if (c_oVariantTypes.vtBstr === eType) return "bstr"; else if (c_oVariantTypes.vtDate === eType) return "date"; else if (c_oVariantTypes.vtFiletime === eType) return "filetime"; else if (c_oVariantTypes.vtBool === eType) return "bool"; else if (c_oVariantTypes.vtCy === eType) return "cy"; else if (c_oVariantTypes.vtError === eType) return "error"; else if (c_oVariantTypes.vtStream === eType) return "stream"; else if (c_oVariantTypes.vtOStream === eType) return "ostream"; else if (c_oVariantTypes.vtStorage === eType) return "storage"; else if (c_oVariantTypes.vtOStorage === eType) return "ostorage"; else if (c_oVariantTypes.vtClsid === eType) return "clsid"; return ""; } CVariant.prototype.readChildXml = function (name, reader) { this.type = this.typeStrToEnum(name); switch (name) { case "vector": { this.vector = new CVariantVector(); this.vector.fromXml(reader); break; } case "array": { this.array = new CVariantArray(); this.array.fromXml(reader); break; } case "blob": { this.strContent = reader.GetValue(); break; } case "oblob": { this.strContent = reader.GetValue(); break; } case "empty": { break; } case "null": { break; } case "i1": { this.iContent = reader.GetValueInt(); break; } case "i2": { this.iContent = reader.GetValueInt(); break; } case "i4": { this.iContent = reader.GetValueInt(); break; } case "i8": { this.iContent = reader.GetValueInt(); break; } case "int": { this.iContent = reader.GetValueInt(); break; } case "ui1": { this.uContent = reader.GetValueUInt(); break; } case "ui2": { this.uContent = reader.GetValueUInt(); break; } case "ui4": { this.uContent = reader.GetValueUInt(); break; } case "ui8": { this.uContent = reader.GetValueUInt(); break; } case "uint": { this.uContent = reader.GetValueUInt(); break; } case "r4": { this.dContent = reader.GetValueDouble(); break; } case "r8": { this.dContent = reader.GetValueDouble(); break; } case "decimal": { this.dContent = reader.GetValueDouble(); break; } case "lpstr": { this.strContent = reader.GetValue(); break; } case "lpwstr": { this.strContent = reader.GetValue(); break; } case "bstr": { this.strContent = reader.GetValue(); break; } case "date": { this.strContent = reader.GetValue(); break; } case "filetime": { this.strContent = reader.GetValue(); break; } case "bool": { this.bContent = reader.GetValueBool(); break; } case "cy": { this.strContent = reader.GetValue(); break; } case "error": { this.strContent = reader.GetValue(); break; } case "stream": { this.strContent = reader.GetValue(); break; } case "ostream": { this.strContent = reader.GetValue(); break; } case "storage": { this.strContent = reader.GetValue(); break; } case "ostorage": { this.strContent = reader.GetValue(); break; } case "vstream": { this.vStream = new CVariantVStream(); break; } case "clsid": { this.strContent = reader.GetValue(); break; } } }; CVariant.prototype.toXml = function (writer) { writer.WriteXmlNodeStart("vt:variant"); writer.WriteXmlAttributesEnd(); this.toXmlWriterContent(writer); writer.WriteXmlNodeEnd("vt:variant"); }; CVariant.prototype.getVariantType = function () { return AscFormat.isRealNumber(this.type) ? this.type : c_oVariantTypes.vtEmpty; }; CVariant.prototype.toXmlWriterContent = function (writer) { let eType = this.getVariantType(); let strNodeName = "vt:" + this.getStringByType(eType); if (c_oVariantTypes.vtEmpty === eType || c_oVariantTypes.vtNull === eType) { writer.WriteXmlNodeStart(strNodeName); writer.WriteXmlAttributesEnd(); writer.WriteXmlNodeEnd(strNodeName); } writer.WriteXmlNullableValueStringEncode2(strNodeName, this.strContent); writer.WriteXmlNullableValueStringEncode2(strNodeName, this.iContent); writer.WriteXmlNullableValueStringEncode2(strNodeName, this.uContent); writer.WriteXmlNullableValueStringEncode2(strNodeName, this.dContent); if (this.bContent) { writer.WriteXmlNodeStart(strNodeName); writer.WriteXmlAttributesEnd(); if (this.bContent) writer.WriteXmlString("true"); else writer.WriteXmlString("false"); writer.WriteXmlNodeEnd(strNodeName); } if (this.variant) { this.variant.toXml(writer); } if (this.vector) { this.vector.toXml(writer); } if (this.array) { this.array.toXml(writer); } if (this.vStream) { this.vStream.toXml(writer); } }; window['AscCommon'].CVariant = CVariant; prot = CVariant.prototype; prot["setText"] = prot.setText; prot["setNumber"] = prot.setNumber; prot["setDate"] = prot.setDate; prot["setBool"] = prot.setBool; var c_oVariantTypes = { vtEmpty: 0, vtNull: 1, vtVariant: 2, vtVector: 3, vtArray: 4, vtVStream: 5, vtBlob: 6, vtOBlob: 7, vtI1: 8, vtI2: 9, vtI4: 10, vtI8: 11, vtInt: 12, vtUi1: 13, vtUi2: 14, vtUi4: 15, vtUi8: 16, vtUint: 17, vtR4: 18, vtR8: 19, vtDecimal: 20, vtLpstr: 21, vtLpwstr: 22, vtBstr: 23, vtDate: 24, vtFiletime: 25, vtBool: 26, vtCy: 27, vtError: 28, vtStream: 29, vtOStream: 30, vtStorage: 31, vtOStorage: 32, vtClsid: 33 }; window['AscCommon'].c_oVariantTypes = c_oVariantTypes; function CPres() { CBaseNoIdObject.call(this); this.defaultTextStyle = null; this.NotesSz = null; this.attrAutoCompressPictures = null; this.attrBookmarkIdSeed = null; this.attrCompatMode = null; this.attrConformance = null; this.attrEmbedTrueTypeFonts = null; this.attrFirstSlideNum = null; this.attrRemovePersonalInfoOnSave = null; this.attrRtl = null; this.attrSaveSubsetFonts = null; this.attrServerZoom = null; this.attrShowSpecialPlsOnTitleSld = null; this.attrStrictFirstAndLastChars = null; } InitClass(CPres, CBaseNoIdObject, 0); CPres.prototype.fromStream = function (s, reader) { var _type = s.GetUChar(); var _len = s.GetULong(); var _start_pos = s.cur; var _end_pos = _len + _start_pos; // attributes var _sa = s.GetUChar(); var oPresentattion = reader.presentation; while (true) { var _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { this.attrAutoCompressPictures = s.GetBool(); break; } case 1: { this.attrBookmarkIdSeed = s.GetLong(); break; } case 2: { this.attrCompatMode = s.GetBool(); break; } case 3: { this.attrConformance = s.GetUChar(); break; } case 4: { this.attrEmbedTrueTypeFonts = s.GetBool(); break; } case 5: { this.attrFirstSlideNum = s.GetLong(); break; } case 6: { this.attrRemovePersonalInfoOnSave = s.GetBool(); break; } case 7: { this.attrRtl = s.GetBool(); break; } case 8: { this.attrSaveSubsetFonts = s.GetBool(); break; } case 9: { this.attrServerZoom = s.GetString2(); break; } case 10: { this.attrShowSpecialPlsOnTitleSld = s.GetBool(); break; } case 11: { this.attrStrictFirstAndLastChars = s.GetBool(); break; } default: return; } } while (true) { if (s.cur >= _end_pos) break; _type = s.GetUChar(); switch (_type) { case 0: { this.defaultTextStyle = reader.ReadTextListStyle(); break; } case 1: { s.SkipRecord(); break; } case 2: { s.SkipRecord(); break; } case 3: { s.SkipRecord(); break; } case 4: { s.SkipRecord(); break; } case 5: { var oSldSize = new AscCommonSlide.CSlideSize(); s.Skip2(5); // len + start attributes while (true) { var _at = s.GetUChar(); if (_at === g_nodeAttributeEnd) break; switch (_at) { case 0: { oSldSize.setCX(s.GetLong()); break; } case 1: { oSldSize.setCY(s.GetLong()); break; } case 2: { oSldSize.setType(s.GetUChar()); break; } default: return; } } if (oPresentattion.setSldSz) { oPresentattion.setSldSz(oSldSize); } break; } case 6: { var _end_rec2 = s.cur + s.GetULong() + 4; while (s.cur < _end_rec2) { var _rec = s.GetUChar(); switch (_rec) { case 0: { s.Skip2(4); // len var lCount = s.GetULong(); for (var i = 0; i < lCount; i++) { s.Skip2(1); var _author = new AscCommon.CCommentAuthor(); var _end_rec3 = s.cur + s.GetLong() + 4; s.Skip2(1); // start attributes while (true) { var _at2 = s.GetUChar(); if (_at2 === g_nodeAttributeEnd) break; switch (_at2) { case 0: _author.Id = s.GetLong(); break; case 1: _author.LastId = s.GetLong(); break; case 2: var _clr_idx = s.GetLong(); break; case 3: _author.Name = s.GetString2(); break; case 4: _author.Initials = s.GetString2(); break; default: break; } } s.Seek2(_end_rec3); oPresentattion.CommentAuthors[_author.Name] = _author; } break; } default: { s.SkipRecord(); break; } } } s.Seek2(_end_rec2); break; } case 8: { var _length = s.GetULong(); var _end_rec2 = s.cur + _length; oPresentattion.Api.vbaMacros = s.GetBuffer(_length); s.Seek2(_end_rec2); break; } case 9: { var _length = s.GetULong(); var _end_rec2 = s.cur + _length; oPresentattion.Api.macros.SetData(AscCommon.GetStringUtf8(s, _length)); s.Seek2(_end_rec2); break; } case 10: { reader.ReadComments(oPresentattion.writecomments); break; } default: { s.SkipRecord(); break; } } } if (oPresentattion.Load_Comments) { oPresentattion.Load_Comments(oPresentattion.CommentAuthors); } s.Seek2(_end_pos); }; window['AscCommon'].CPres = CPres; function CClrMapOvr() { CBaseNoIdObject.call(this); this.overrideClrMapping = null; } InitClass(CClrMapOvr, CBaseNoIdObject, 0); CClrMapOvr.prototype.readChildXml = function (name, reader) { if ( "overrideClrMapping" === name) { this.overrideClrMapping = new ClrMap(); this.overrideClrMapping.fromXml(reader); } }; CClrMapOvr.prototype.toXml = function (writer) { if (this.overrideClrMapping) { writer.WriteXmlString("<p:clrMapOvr>"); this.overrideClrMapping.toXml(writer, "a:overrideClrMapping"); writer.WriteXmlString("</p:clrMapOvr>"); } else { writer.WriteXmlString("<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>"); } }; CClrMapOvr.prototype.static_WriteCrlMapAsOvr = function(writer, oClrMap) { let oClrMapOvr = new CClrMapOvr(); oClrMapOvr.overrideClrMapping = oClrMap; oClrMapOvr.toXml(writer); }; function IdEntry(name) { AscFormat.CBaseNoIdObject.call(this); this.name = name; this.id = null; this.rId = null; } InitClass(IdEntry, CBaseNoIdObject, undefined); IdEntry.prototype.readAttrXml = function(name, reader) { switch (reader.GetName()) { case "id": { this.id = reader.GetValue(); break; } case "r:id": { this.rId = reader.GetValue(); break; } } }; IdEntry.prototype.toXml = function(writer) { writer.WriteXmlNodeStart(this.name); writer.WriteXmlNullableAttributeString("id", this.id); writer.WriteXmlNullableAttributeString("r:id", this.rId); writer.WriteXmlAttributesEnd(true); }; IdEntry.prototype.readItem = function(reader, fConstructor) { let oRel = reader.rels.getRelationship(this.rId); let oRelPart = reader.rels.pkg.getPartByUri(oRel.targetFullName); let oContent = oRelPart.getDocumentContent(); let oReader = new AscCommon.StaxParser(oContent, oRelPart, reader.context); let oElement = fConstructor(oReader); if(oElement) { oElement.fromXml(oReader, true); } return oElement; }; // DEFAULT OBJECTS function GenerateDefaultTheme(presentation, opt_fontName) { return ExecuteNoHistory(function () { if (!opt_fontName) { opt_fontName = "Arial"; } var theme = new CTheme(); theme.presentation = presentation; theme.setFontScheme(new FontScheme()); theme.themeElements.fontScheme.setMajorFont(new FontCollection(theme.themeElements.fontScheme)); theme.themeElements.fontScheme.setMinorFont(new FontCollection(theme.themeElements.fontScheme)); theme.themeElements.fontScheme.majorFont.setLatin(opt_fontName); theme.themeElements.fontScheme.minorFont.setLatin(opt_fontName); var scheme = theme.themeElements.clrScheme; scheme.colors[8] = CreateUniColorRGB(0, 0, 0); scheme.colors[12] = CreateUniColorRGB(255, 255, 255); scheme.colors[9] = CreateUniColorRGB(0x1F, 0x49, 0x7D); scheme.colors[13] = CreateUniColorRGB(0xEE, 0xEC, 0xE1); scheme.colors[0] = CreateUniColorRGB(0x4F, 0x81, 0xBD); //CreateUniColorRGB(0xFF, 0x81, 0xBD);// scheme.colors[1] = CreateUniColorRGB(0xC0, 0x50, 0x4D); scheme.colors[2] = CreateUniColorRGB(0x9B, 0xBB, 0x59); scheme.colors[3] = CreateUniColorRGB(0x80, 0x64, 0xA2); scheme.colors[4] = CreateUniColorRGB(0x4B, 0xAC, 0xC6); scheme.colors[5] = CreateUniColorRGB(0xF7, 0x96, 0x46); scheme.colors[11] = CreateUniColorRGB(0x00, 0x00, 0xFF); scheme.colors[10] = CreateUniColorRGB(0x80, 0x00, 0x80); // -------------- fill styles ------------------------- var brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(new CSchemeColor()); brush.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.fillStyleLst.push(brush); brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.fillStyleLst.push(brush); brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.fillStyleLst.push(brush); // ---------------------------------------------------- // -------------- back styles ------------------------- brush = new CUniFill(); brush.setFill(new CSolidFill()); brush.fill.setColor(new CUniColor()); brush.fill.color.setColor(new CSchemeColor()); brush.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.bgFillStyleLst.push(brush); brush = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.bgFillStyleLst.push(brush); brush = AscFormat.CreateUniFillByUniColor(AscFormat.CreateUniColorRGB(0, 0, 0)); theme.themeElements.fmtScheme.bgFillStyleLst.push(brush); // ---------------------------------------------------- var pen = new CLn(); pen.setW(9525); pen.setFill(new CUniFill()); pen.Fill.setFill(new CSolidFill()); pen.Fill.fill.setColor(new CUniColor()); pen.Fill.fill.color.setColor(new CSchemeColor()); pen.Fill.fill.color.color.setId(phClr); pen.Fill.fill.color.setMods(new CColorModifiers()); var mod = new CColorMod(); mod.setName("shade"); mod.setVal(95000); pen.Fill.fill.color.Mods.addMod(mod); mod = new CColorMod(); mod.setName("satMod"); mod.setVal(105000); pen.Fill.fill.color.Mods.addMod(mod); theme.themeElements.fmtScheme.lnStyleLst.push(pen); pen = new CLn(); pen.setW(25400); pen.setFill(new CUniFill()); pen.Fill.setFill(new CSolidFill()); pen.Fill.fill.setColor(new CUniColor()); pen.Fill.fill.color.setColor(new CSchemeColor()); pen.Fill.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.lnStyleLst.push(pen); pen = new CLn(); pen.setW(38100); pen.setFill(new CUniFill()); pen.Fill.setFill(new CSolidFill()); pen.Fill.fill.setColor(new CUniColor()); pen.Fill.fill.color.setColor(new CSchemeColor()); pen.Fill.fill.color.color.setId(phClr); theme.themeElements.fmtScheme.lnStyleLst.push(pen); theme.extraClrSchemeLst = []; return theme; }, this, []); } function GetDefaultTheme() { if(!AscFormat.DEFAULT_THEME) { AscFormat.DEFAULT_THEME = GenerateDefaultTheme(null); } return AscFormat.DEFAULT_THEME; } function GenerateDefaultMasterSlide(theme) { var master = new MasterSlide(theme.presentation, theme); master.Theme = theme; master.sldLayoutLst[0] = GenerateDefaultSlideLayout(master); return master; } function GenerateDefaultSlideLayout(master) { var layout = new SlideLayout(); layout.Theme = master.Theme; layout.Master = master; return layout; } function GenerateDefaultSlide(layout) { var slide = new Slide(layout.Master.presentation, layout, 0); slide.Master = layout.Master; slide.Theme = layout.Master.Theme; slide.setNotes(AscCommonSlide.CreateNotes()); slide.notes.setNotesMaster(layout.Master.presentation.notesMasters[0]); slide.notes.setSlide(slide); return slide; } function CreateDefaultTextRectStyle() { var style = new CShapeStyle(); var lnRef = new StyleRef(); lnRef.setIdx(0); var unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); var mod = new CColorMod(); mod.setName("shade"); mod.setVal(50000); unicolor.setMods(new CColorModifiers()); unicolor.Mods.addMod(mod); lnRef.setColor(unicolor); style.setLnRef(lnRef); var fillRef = new StyleRef(); fillRef.setIdx(0); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); fillRef.setColor(unicolor); style.setFillRef(fillRef); var effectRef = new StyleRef(); effectRef.setIdx(0); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(g_clr_accent1); effectRef.setColor(unicolor); style.setEffectRef(effectRef); var fontRef = new FontRef(); fontRef.setIdx(AscFormat.fntStyleInd_minor); unicolor = new CUniColor(); unicolor.setColor(new CSchemeColor()); unicolor.color.setId(8); fontRef.setColor(unicolor); style.setFontRef(fontRef); return style; } function GenerateDefaultColorMap() { return AscFormat.ExecuteNoHistory(function () { var clrMap = new ClrMap(); clrMap.color_map[0] = 0; clrMap.color_map[1] = 1; clrMap.color_map[2] = 2; clrMap.color_map[3] = 3; clrMap.color_map[4] = 4; clrMap.color_map[5] = 5; clrMap.color_map[10] = 10; clrMap.color_map[11] = 11; clrMap.color_map[6] = 12; clrMap.color_map[7] = 13; clrMap.color_map[15] = 8; clrMap.color_map[16] = 9; return clrMap; }, [], null); } function GetDefaultColorMap() { if(!AscFormat.DEFAULT_COLOR_MAP) { AscFormat.DEFAULT_COLOR_MAP = GenerateDefaultColorMap(); } return AscFormat.DEFAULT_COLOR_MAP; } function CreateAscFill(unifill) { if (null == unifill || null == unifill.fill) return new asc_CShapeFill(); var ret = new asc_CShapeFill(); var _fill = unifill.fill; switch (_fill.type) { case c_oAscFill.FILL_TYPE_SOLID: { ret.type = c_oAscFill.FILL_TYPE_SOLID; ret.fill = new Asc.asc_CFillSolid(); ret.fill.color = CreateAscColor(_fill.color); break; } case c_oAscFill.FILL_TYPE_PATT: { ret.type = c_oAscFill.FILL_TYPE_PATT; ret.fill = new Asc.asc_CFillHatch(); ret.fill.PatternType = _fill.ftype; ret.fill.fgClr = CreateAscColor(_fill.fgClr); ret.fill.bgClr = CreateAscColor(_fill.bgClr); break; } case c_oAscFill.FILL_TYPE_GRAD: { ret.type = c_oAscFill.FILL_TYPE_GRAD; ret.fill = new Asc.asc_CFillGrad(); var bCheckTransparent = true, nLastTransparent = null, nLastTempTransparent, j, aMods; for (var i = 0; i < _fill.colors.length; i++) { if (0 == i) { ret.fill.Colors = []; ret.fill.Positions = []; } if (bCheckTransparent) { if (_fill.colors[i].color.Mods) { aMods = _fill.colors[i].color.Mods.Mods; nLastTempTransparent = null; for (j = 0; j < aMods.length; ++j) { if (aMods[j].name === "alpha") { if (nLastTempTransparent === null) { nLastTempTransparent = aMods[j].val; if (nLastTransparent === null) { nLastTransparent = nLastTempTransparent; } else { if (nLastTransparent !== nLastTempTransparent) { bCheckTransparent = false; break; } } } else { bCheckTransparent = false; break; } } } } else { bCheckTransparent = false; } } ret.fill.Colors.push(CreateAscColor(_fill.colors[i].color)); ret.fill.Positions.push(_fill.colors[i].pos); } if (bCheckTransparent && nLastTransparent !== null) { ret.transparent = (nLastTransparent / 100000) * 255; } if (_fill.lin) { ret.fill.GradType = c_oAscFillGradType.GRAD_LINEAR; ret.fill.LinearAngle = _fill.lin.angle; ret.fill.LinearScale = _fill.lin.scale; } else if (_fill.path) { ret.fill.GradType = c_oAscFillGradType.GRAD_PATH; ret.fill.PathType = 0; } else { ret.fill.GradType = c_oAscFillGradType.GRAD_LINEAR; ret.fill.LinearAngle = 0; ret.fill.LinearScale = false; } break; } case c_oAscFill.FILL_TYPE_BLIP: { ret.type = c_oAscFill.FILL_TYPE_BLIP; ret.fill = new Asc.asc_CFillBlip(); ret.fill.url = _fill.RasterImageId; ret.fill.type = (_fill.tile == null) ? c_oAscFillBlipType.STRETCH : c_oAscFillBlipType.TILE; break; } case c_oAscFill.FILL_TYPE_NOFILL: { ret.type = c_oAscFill.FILL_TYPE_NOFILL; break; } default: break; } if (isRealNumber(unifill.transparent)) { ret.transparent = unifill.transparent; } return ret; } function CorrectUniFill(asc_fill, unifill, editorId) { if (asc_fill instanceof CUniFill) { return asc_fill; } if (null == asc_fill) return unifill; var ret = unifill; if (null == ret) ret = new CUniFill(); var _fill = asc_fill.fill; var _type = asc_fill.type; if (null != _type) { switch (_type) { case c_oAscFill.FILL_TYPE_NOFILL: { ret.fill = new CNoFill(); break; } case c_oAscFill.FILL_TYPE_GRP: { ret.fill = new CGrpFill(); break; } case c_oAscFill.FILL_TYPE_BLIP: { var _url = _fill.url; var _tx_id = _fill.texture_id; if (null != _tx_id && (0 <= _tx_id) && (_tx_id < AscCommon.g_oUserTexturePresets.length)) { _url = AscCommon.g_oUserTexturePresets[_tx_id]; } if (ret.fill == null) { ret.fill = new CBlipFill(); } if (ret.fill.type !== c_oAscFill.FILL_TYPE_BLIP) { if (!(typeof (_url) === "string" && _url.length > 0) || !isRealNumber(_fill.type)) { break; } ret.fill = new CBlipFill(); } if (_url != null && _url !== undefined && _url != "") ret.fill.setRasterImageId(_url); if (ret.fill.RasterImageId == null) ret.fill.RasterImageId = ""; var tile = _fill.type; if (tile === c_oAscFillBlipType.STRETCH) { ret.fill.tile = null; ret.fill.srcRect = null; ret.fill.stretch = true; } else if (tile === c_oAscFillBlipType.TILE) { ret.fill.tile = new CBlipFillTile(); ret.fill.stretch = false; ret.fill.srcRect = null; } break; } case c_oAscFill.FILL_TYPE_PATT: { if (ret.fill == null) { ret.fill = new CPattFill(); } if (ret.fill.type != c_oAscFill.FILL_TYPE_PATT) { if (undefined != _fill.PatternType && undefined != _fill.fgClr && undefined != _fill.bgClr) { ret.fill = new CPattFill(); } else { break; } } if (undefined != _fill.PatternType) { ret.fill.ftype = _fill.PatternType; } if (undefined != _fill.fgClr) { ret.fill.fgClr = CorrectUniColor(_fill.fgClr, ret.fill.fgClr, editorId); } if (!ret.fill.fgClr) { ret.fill.fgClr = CreateUniColorRGB(0, 0, 0); } if (undefined != _fill.bgClr) { ret.fill.bgClr = CorrectUniColor(_fill.bgClr, ret.fill.bgClr, editorId); } if (!ret.fill.bgClr) { ret.fill.bgClr = CreateUniColorRGB(0, 0, 0); } break; } case c_oAscFill.FILL_TYPE_GRAD: { if (ret.fill == null) { ret.fill = new CGradFill(); } var _colors = _fill.Colors; var _positions = _fill.Positions; if (ret.fill.type != c_oAscFill.FILL_TYPE_GRAD) { if (undefined != _colors && undefined != _positions) { ret.fill = new CGradFill(); } else { break; } } if (undefined != _colors && undefined != _positions) { if (_colors.length === _positions.length) { if (ret.fill.colors.length === _colors.length) { for (var i = 0; i < _colors.length; i++) { var _gs = ret.fill.colors[i] ? ret.fill.colors[i] : new CGs(); _gs.color = CorrectUniColor(_colors[i], _gs.color, editorId); _gs.pos = _positions[i]; ret.fill.colors[i] = _gs; } } else { ret.fill.colors.length = 0; for (var i = 0; i < _colors.length; i++) { var _gs = new CGs(); _gs.color = CorrectUniColor(_colors[i], _gs.color, editorId); _gs.pos = _positions[i]; ret.fill.colors.push(_gs); } } } } else if (undefined != _colors) { if (_colors.length === ret.fill.colors.length) { for (var i = 0; i < _colors.length; i++) { ret.fill.colors[i].color = CorrectUniColor(_colors[i], ret.fill.colors[i].color, editorId); } } } else if (undefined != _positions) { if (_positions.length <= ret.fill.colors.length) { if (_positions.length < ret.fill.colors.length) { ret.fill.colors.splice(_positions.length, ret.fill.colors.length - _positions.length); } for (var i = 0; i < _positions.length; i++) { ret.fill.colors[i].pos = _positions[i]; } } } var _grad_type = _fill.GradType; if (c_oAscFillGradType.GRAD_LINEAR === _grad_type) { var _angle = _fill.LinearAngle; var _scale = _fill.LinearScale; if (!ret.fill.lin) { ret.fill.lin = new GradLin(); ret.fill.lin.angle = 0; ret.fill.lin.scale = false; } if (undefined != _angle) ret.fill.lin.angle = _angle; if (undefined != _scale) ret.fill.lin.scale = _scale; ret.fill.path = null; } else if (c_oAscFillGradType.GRAD_PATH === _grad_type) { ret.fill.lin = null; ret.fill.path = new GradPath(); } break; } default: { if (ret.fill == null || ret.fill.type !== c_oAscFill.FILL_TYPE_SOLID) { ret.fill = new CSolidFill(); } ret.fill.color = CorrectUniColor(_fill.color, ret.fill.color, editorId); } } } var _alpha = asc_fill.transparent; if (null != _alpha) { ret.transparent = _alpha; } if (ret.transparent != null) { if (ret.fill && ret.fill.type === c_oAscFill.FILL_TYPE_BLIP) { for (var i = 0; i < ret.fill.Effects.length; ++i) { if (ret.fill.Effects[i].Type === EFFECT_TYPE_ALPHAMODFIX) { ret.fill.Effects[i].amt = ((ret.transparent * 100000 / 255) >> 0); break; } } if (i === ret.fill.Effects.length) { var oEffect = new CAlphaModFix(); oEffect.amt = ((ret.transparent * 100000 / 255) >> 0); ret.fill.Effects.push(oEffect); } } } return ret; } // ัั‚ะฐ ั„ัƒะฝะบั†ะธั ะ”ะžะ›ะ–ะะ ะผะธะฝะธะผะธะทะธั€ะพะฒะฐั‚ัŒัั function CreateAscStroke(ln, _canChangeArrows) { if (null == ln || null == ln.Fill || ln.Fill.fill == null) return new Asc.asc_CStroke(); var ret = new Asc.asc_CStroke(); var _fill = ln.Fill.fill; if (_fill != null) { switch (_fill.type) { case c_oAscFill.FILL_TYPE_BLIP: { break; } case c_oAscFill.FILL_TYPE_SOLID: { ret.color = CreateAscColor(_fill.color); ret.type = c_oAscStrokeType.STROKE_COLOR; break; } case c_oAscFill.FILL_TYPE_GRAD: { var _c = _fill.colors; if (_c != 0) { ret.color = CreateAscColor(_fill.colors[0].color); ret.type = c_oAscStrokeType.STROKE_COLOR; } break; } case c_oAscFill.FILL_TYPE_PATT: { ret.color = CreateAscColor(_fill.fgClr); ret.type = c_oAscStrokeType.STROKE_COLOR; break; } case c_oAscFill.FILL_TYPE_NOFILL: { ret.color = null; ret.type = c_oAscStrokeType.STROKE_NONE; break; } default: { break; } } } ret.width = (ln.w == null) ? 12700 : (ln.w >> 0); ret.width /= 36000.0; if (ln.cap != null) ret.asc_putLinecap(ln.cap); if (ln.Join != null) ret.asc_putLinejoin(ln.Join.type); if (ln.headEnd != null) { ret.asc_putLinebeginstyle((ln.headEnd.type == null) ? LineEndType.None : ln.headEnd.type); var _len = (null == ln.headEnd.len) ? 1 : (2 - ln.headEnd.len); var _w = (null == ln.headEnd.w) ? 1 : (2 - ln.headEnd.w); ret.asc_putLinebeginsize(_w * 3 + _len); } else { ret.asc_putLinebeginstyle(LineEndType.None); } if (ln.tailEnd != null) { ret.asc_putLineendstyle((ln.tailEnd.type == null) ? LineEndType.None : ln.tailEnd.type); var _len = (null == ln.tailEnd.len) ? 1 : (2 - ln.tailEnd.len); var _w = (null == ln.tailEnd.w) ? 1 : (2 - ln.tailEnd.w); ret.asc_putLineendsize(_w * 3 + _len); } else { ret.asc_putLineendstyle(LineEndType.None); } if (AscFormat.isRealNumber(ln.prstDash)) { ret.prstDash = ln.prstDash; } else if (ln.prstDash === null) { ret.prstDash = Asc.c_oDashType.solid; } if (true === _canChangeArrows) ret.canChangeArrows = true; return ret; } function CorrectUniStroke(asc_stroke, unistroke, flag) { if (null == asc_stroke) return unistroke; var ret = unistroke; if (null == ret) ret = new CLn(); var _type = asc_stroke.type; var _w = asc_stroke.width; if (_w !== null && _w !== undefined) ret.w = _w * 36000.0; var _color = asc_stroke.color; if (_type === c_oAscStrokeType.STROKE_NONE) { ret.Fill = new CUniFill(); ret.Fill.fill = new CNoFill(); } else if (_type != null) { if (null !== _color && undefined !== _color) { ret.Fill = new CUniFill(); ret.Fill.type = c_oAscFill.FILL_TYPE_SOLID; ret.Fill.fill = new CSolidFill(); ret.Fill.fill.color = CorrectUniColor(_color, ret.Fill.fill.color, flag); } } var _join = asc_stroke.LineJoin; if (null != _join) { ret.Join = new LineJoin(); ret.Join.type = _join; } var _cap = asc_stroke.LineCap; if (null != _cap) { ret.cap = _cap; } var _begin_style = asc_stroke.LineBeginStyle; if (null != _begin_style) { if (ret.headEnd == null) ret.headEnd = new EndArrow(); ret.headEnd.type = _begin_style; } var _end_style = asc_stroke.LineEndStyle; if (null != _end_style) { if (ret.tailEnd == null) ret.tailEnd = new EndArrow(); ret.tailEnd.type = _end_style; } var _begin_size = asc_stroke.LineBeginSize; if (null != _begin_size) { if (ret.headEnd == null) ret.headEnd = new EndArrow(); ret.headEnd.w = 2 - ((_begin_size / 3) >> 0); ret.headEnd.len = 2 - (_begin_size % 3); } var _end_size = asc_stroke.LineEndSize; if (null != _end_size) { if (ret.tailEnd == null) ret.tailEnd = new EndArrow(); ret.tailEnd.w = 2 - ((_end_size / 3) >> 0); ret.tailEnd.len = 2 - (_end_size % 3); } if (AscFormat.isRealNumber(asc_stroke.prstDash)) { ret.prstDash = asc_stroke.prstDash; } return ret; } // ัั‚ะฐ ั„ัƒะฝะบั†ะธั ะ”ะžะ›ะ–ะะ ะผะธะฝะธะผะธะทะธั€ะพะฒะฐั‚ัŒัั function CreateAscShapeProp(shape) { if (null == shape) return new asc_CShapeProperty(); var ret = new asc_CShapeProperty(); ret.fill = CreateAscFill(shape.brush); ret.stroke = CreateAscStroke(shape.pen); ret.lockAspect = shape.getNoChangeAspect(); var paddings = null; if (shape.textBoxContent) { var body_pr = shape.bodyPr; paddings = new Asc.asc_CPaddings(); if (typeof body_pr.lIns === "number") paddings.Left = body_pr.lIns; else paddings.Left = 2.54; if (typeof body_pr.tIns === "number") paddings.Top = body_pr.tIns; else paddings.Top = 1.27; if (typeof body_pr.rIns === "number") paddings.Right = body_pr.rIns; else paddings.Right = 2.54; if (typeof body_pr.bIns === "number") paddings.Bottom = body_pr.bIns; else paddings.Bottom = 1.27; } return ret; } function CreateAscShapePropFromProp(shapeProp) { var obj = new asc_CShapeProperty(); if (!isRealObject(shapeProp)) return obj; if (isRealBool(shapeProp.locked)) { obj.Locked = shapeProp.locked; } obj.lockAspect = shapeProp.lockAspect; if (typeof shapeProp.type === "string") obj.type = shapeProp.type; if (isRealObject(shapeProp.fill)) obj.fill = CreateAscFill(shapeProp.fill); if (isRealObject(shapeProp.stroke)) obj.stroke = CreateAscStroke(shapeProp.stroke, shapeProp.canChangeArrows); if (isRealObject(shapeProp.paddings)) obj.paddings = shapeProp.paddings; if (shapeProp.canFill === true || shapeProp.canFill === false) { obj.canFill = shapeProp.canFill; } obj.bFromChart = shapeProp.bFromChart; obj.bFromSmartArt = shapeProp.bFromSmartArt; obj.bFromSmartArtInternal = shapeProp.bFromSmartArtInternal; obj.bFromGroup = shapeProp.bFromGroup; obj.bFromImage = shapeProp.bFromImage; obj.w = shapeProp.w; obj.h = shapeProp.h; obj.rot = shapeProp.rot; obj.flipH = shapeProp.flipH; obj.flipV = shapeProp.flipV; obj.vert = shapeProp.vert; obj.verticalTextAlign = shapeProp.verticalTextAlign; if (shapeProp.textArtProperties) { obj.textArtProperties = CreateAscTextArtProps(shapeProp.textArtProperties); } obj.title = shapeProp.title; obj.description = shapeProp.description; obj.columnNumber = shapeProp.columnNumber; obj.columnSpace = shapeProp.columnSpace; obj.textFitType = shapeProp.textFitType; obj.vertOverflowType = shapeProp.vertOverflowType; obj.shadow = shapeProp.shadow; if (shapeProp.signatureId) { obj.signatureId = shapeProp.signatureId; } if (shapeProp.signatureId) { obj.signatureId = shapeProp.signatureId; } obj.Position = new Asc.CPosition({X: shapeProp.x, Y: shapeProp.y}); return obj; } function CorrectShapeProp(asc_shape_prop, shape) { if (null == shape || null == asc_shape_prop) return; shape.spPr.Fill = CorrectUniFill(asc_shape_prop.asc_getFill(), shape.spPr.Fill); shape.spPr.ln = CorrectUniFill(asc_shape_prop.asc_getStroke(), shape.spPr.ln); } function CreateAscTextArtProps(oTextArtProps) { if (!oTextArtProps) { return undefined; } var oRet = new Asc.asc_TextArtProperties(); if (oTextArtProps.Fill) { oRet.asc_putFill(CreateAscFill(oTextArtProps.Fill)); } if (oTextArtProps.Line) { oRet.asc_putLine(CreateAscStroke(oTextArtProps.Line, false)); } oRet.asc_putForm(oTextArtProps.Form); return oRet; } function CreateUnifillFromAscColor(asc_color, editorId) { var Unifill = new CUniFill(); Unifill.fill = new CSolidFill(); Unifill.fill.color = CorrectUniColor(asc_color, Unifill.fill.color, editorId); return Unifill; } function CorrectUniColor(asc_color, unicolor, flag) { if (null == asc_color) return unicolor; var ret = unicolor; if (null == ret) ret = new CUniColor(); var _type = asc_color.asc_getType(); switch (_type) { case c_oAscColor.COLOR_TYPE_PRST: { if (ret.color == null || ret.color.type !== c_oAscColor.COLOR_TYPE_PRST) { ret.color = new CPrstColor(); } ret.color.id = asc_color.value; if (ret.Mods.Mods.length != 0) ret.Mods.Mods.splice(0, ret.Mods.Mods.length); break; } case c_oAscColor.COLOR_TYPE_SCHEME: { if (ret.color == null || ret.color.type !== c_oAscColor.COLOR_TYPE_SCHEME) { ret.color = new CSchemeColor(); } // ั‚ัƒั‚ ะฒั‹ัั‚ะฐะฒะปัะตั‚ัั ะขะžะ›ะฌะšะž ะธะท ะผะตะฝัŽ. ะฟะพัั‚ะพะผัƒ: var _index = parseInt(asc_color.value); if (isNaN(_index)) break; var _id = (_index / 6) >> 0; var _pos = _index - _id * 6; var array_colors_types = [6, 15, 7, 16, 0, 1, 2, 3, 4, 5]; ret.color.id = array_colors_types[_id]; if (!ret.Mods) { ret.setMods(new CColorModifiers()); } if (ret.Mods.Mods.length != 0) ret.Mods.Mods.splice(0, ret.Mods.Mods.length); var __mods = null; var _flag; if (editor && editor.WordControl && editor.WordControl.m_oDrawingDocument && editor.WordControl.m_oDrawingDocument.GuiControlColorsMap) { var _map = editor.WordControl.m_oDrawingDocument.GuiControlColorsMap; _flag = isRealNumber(flag) ? flag : 1; __mods = AscCommon.GetDefaultMods(_map[_id].r, _map[_id].g, _map[_id].b, _pos, _flag); } else { var _editor = window["Asc"] && window["Asc"]["editor"]; if (_editor && _editor.wbModel) { var _theme = _editor.wbModel.theme; var _clrMap = _editor.wbModel.clrSchemeMap; if (_theme && _clrMap) { var _schemeClr = new CSchemeColor(); _schemeClr.id = array_colors_types[_id]; var _rgba = {R: 0, G: 0, B: 0, A: 255}; _schemeClr.Calculate(_theme, _clrMap.color_map, _rgba); _flag = isRealNumber(flag) ? flag : 0; __mods = AscCommon.GetDefaultMods(_schemeClr.RGBA.R, _schemeClr.RGBA.G, _schemeClr.RGBA.B, _pos, _flag); } } } if (null != __mods) { ret.Mods.Mods = __mods; } break; } default: { if (ret.color == null || ret.color.type !== c_oAscColor.COLOR_TYPE_SRGB) { ret.color = new CRGBColor(); } ret.color.RGBA.R = asc_color.r; ret.color.RGBA.G = asc_color.g; ret.color.RGBA.B = asc_color.b; ret.color.RGBA.A = asc_color.a; if (ret.Mods && ret.Mods.Mods.length !== 0) ret.Mods.Mods.splice(0, ret.Mods.Mods.length); } } return ret; } function deleteDrawingBase(aObjects, graphicId) { var position = null; for (var i = 0; i < aObjects.length; i++) { if (aObjects[i].graphicObject.Get_Id() == graphicId) { aObjects.splice(i, 1); position = i; break; } } return position; } /* Common Functions For Builder*/ function builder_CreateShape(sType, nWidth, nHeight, oFill, oStroke, oParent, oTheme, oDrawingDocument, bWord, worksheet) { var oShapeTrack = new AscFormat.NewShapeTrack(sType, 0, 0, oTheme, null, null, null, 0); oShapeTrack.track({}, nWidth, nHeight); var oShape = oShapeTrack.getShape(bWord === true, oDrawingDocument, null); oShape.setParent(oParent); if (worksheet) { oShape.setWorksheet(worksheet); } if (bWord) { oShape.createTextBoxContent(); } else { oShape.createTextBody(); } oShape.spPr.setFill(oFill); oShape.spPr.setLn(oStroke); return oShape; } function ChartBuilderTypeToInternal(sType) { switch (sType) { case "bar" : { return Asc.c_oAscChartTypeSettings.barNormal; } case "barStacked": { return Asc.c_oAscChartTypeSettings.barStacked; } case "barStackedPercent": { return Asc.c_oAscChartTypeSettings.barStackedPer; } case "bar3D": { return Asc.c_oAscChartTypeSettings.barNormal3d; } case "barStacked3D": { return Asc.c_oAscChartTypeSettings.barStacked3d; } case "barStackedPercent3D": { return Asc.c_oAscChartTypeSettings.barStackedPer3d; } case "barStackedPercent3DPerspective": { return Asc.c_oAscChartTypeSettings.barNormal3dPerspective; } case "horizontalBar": { return Asc.c_oAscChartTypeSettings.hBarNormal; } case "horizontalBarStacked": { return Asc.c_oAscChartTypeSettings.hBarStacked; } case "horizontalBarStackedPercent": { return Asc.c_oAscChartTypeSettings.hBarStackedPer; } case "horizontalBar3D": { return Asc.c_oAscChartTypeSettings.hBarNormal3d; } case "horizontalBarStacked3D": { return Asc.c_oAscChartTypeSettings.hBarStacked3d; } case "horizontalBarStackedPercent3D": { return Asc.c_oAscChartTypeSettings.hBarStackedPer3d; } case "lineNormal": { return Asc.c_oAscChartTypeSettings.lineNormal; } case "lineStacked": { return Asc.c_oAscChartTypeSettings.lineStacked; } case "lineStackedPercent": { return Asc.c_oAscChartTypeSettings.lineStackedPer; } case "line3D": { return Asc.c_oAscChartTypeSettings.line3d; } case "pie": { return Asc.c_oAscChartTypeSettings.pie; } case "pie3D": { return Asc.c_oAscChartTypeSettings.pie3d; } case "doughnut": { return Asc.c_oAscChartTypeSettings.doughnut; } case "scatter": { return Asc.c_oAscChartTypeSettings.scatter; } case "stock": { return Asc.c_oAscChartTypeSettings.stock; } case "area": { return Asc.c_oAscChartTypeSettings.areaNormal; } case "areaStacked": { return Asc.c_oAscChartTypeSettings.areaStacked; } case "areaStackedPercent": { return Asc.c_oAscChartTypeSettings.areaStackedPer; } } return null; } function builder_CreateChart(nW, nH, sType, aCatNames, aSeriesNames, aSeries, nStyleIndex, aNumFormats) { var settings = new Asc.asc_ChartSettings(); settings.type = ChartBuilderTypeToInternal(sType); var aAscSeries = []; var aAlphaBet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; var oCat, i; if (aCatNames.length > 0) { var aNumCache = []; for (i = 0; i < aCatNames.length; ++i) { aNumCache.push({val: aCatNames[i] + ""}); } oCat = { Formula: "Sheet1!$B$1:$" + AscFormat.CalcLiterByLength(aAlphaBet, aCatNames.length) + "$1", NumCache: aNumCache }; } for (i = 0; i < aSeries.length; ++i) { var oAscSeries = new AscFormat.asc_CChartSeria(); oAscSeries.Val.NumCache = []; var aData = aSeries[i]; var sEndLiter = AscFormat.CalcLiterByLength(aAlphaBet, aData.length); oAscSeries.Val.Formula = 'Sheet1!' + '$B$' + (i + 2) + ':$' + sEndLiter + '$' + (i + 2); if (aSeriesNames[i]) { oAscSeries.TxCache.Formula = 'Sheet1!' + '$A$' + (i + 2); oAscSeries.TxCache.NumCache = [{ numFormatStr: "General", isDateTimeFormat: false, val: aSeriesNames[i], isHidden: false }]; } if (oCat) { oAscSeries.Cat = oCat; } if (Array.isArray(aNumFormats) && typeof (aNumFormats[i]) === "string") oAscSeries.FormatCode = aNumFormats[i]; for (var j = 0; j < aData.length; ++j) { oAscSeries.Val.NumCache.push({ numFormatStr: oAscSeries.FormatCode !== "" ? null : "General", isDateTimeFormat: false, val: aData[j], isHidden: false }); } aAscSeries.push(oAscSeries); } var oChartSpace = AscFormat.DrawingObjectsController.prototype._getChartSpace(aAscSeries, settings, true); if (!oChartSpace) { return null; } oChartSpace.setBDeleted(false); oChartSpace.extX = nW; oChartSpace.extY = nH; if (AscFormat.isRealNumber(nStyleIndex)) { oChartSpace.setStyle(nStyleIndex); } AscFormat.CheckSpPrXfrm(oChartSpace); return oChartSpace; } function builder_CreateGroup(aDrawings, oController) { if (!oController) { return null; } var aForGroup = []; for (var i = 0; i < aDrawings.length; ++i) { if (!aDrawings[i].Drawing || !aDrawings[i].Drawing.canGroup()) { return null; } aForGroup.push(aDrawings[i].Drawing); } return oController.getGroup(aForGroup); } function builder_CreateSchemeColor(sColorId) { var oUniColor = new AscFormat.CUniColor(); oUniColor.setColor(new AscFormat.CSchemeColor()); switch (sColorId) { case "accent1": { oUniColor.color.id = 0; break; } case "accent2": { oUniColor.color.id = 1; break; } case "accent3": { oUniColor.color.id = 2; break; } case "accent4": { oUniColor.color.id = 3; break; } case "accent5": { oUniColor.color.id = 4; break; } case "accent6": { oUniColor.color.id = 5; break; } case "bg1": { oUniColor.color.id = 6; break; } case "bg2": { oUniColor.color.id = 7; break; } case "dk1": { oUniColor.color.id = 8; break; } case "dk2": { oUniColor.color.id = 9; break; } case "lt1": { oUniColor.color.id = 12; break; } case "lt2": { oUniColor.color.id = 13; break; } case "tx1": { oUniColor.color.id = 15; break; } case "tx2": { oUniColor.color.id = 16; break; } default: { oUniColor.color.id = 16; break; } } return oUniColor; } function builder_CreatePresetColor(sPresetColor) { var oUniColor = new AscFormat.CUniColor(); oUniColor.setColor(new AscFormat.CPrstColor()); oUniColor.color.id = sPresetColor; return oUniColor; } function builder_CreateGradientStop(oUniColor, nPos) { var Gs = new AscFormat.CGs(); Gs.pos = nPos; Gs.color = oUniColor; return Gs; } function builder_CreateGradient(aGradientStop) { var oUniFill = new AscFormat.CUniFill(); oUniFill.fill = new AscFormat.CGradFill(); for (var i = 0; i < aGradientStop.length; ++i) { oUniFill.fill.colors.push(aGradientStop[i].Gs); } return oUniFill; } function builder_CreateLinearGradient(aGradientStop, Angle) { var oUniFill = builder_CreateGradient(aGradientStop); oUniFill.fill.lin = new AscFormat.GradLin(); if (!AscFormat.isRealNumber(Angle)) { oUniFill.fill.lin.angle = 0; } else { oUniFill.fill.lin.angle = Angle; } return oUniFill; } function builder_CreateRadialGradient(aGradientStop) { var oUniFill = builder_CreateGradient(aGradientStop); oUniFill.fill.path = new AscFormat.GradPath(); return oUniFill; } function builder_CreatePatternFill(sPatternType, BgColor, FgColor) { var oUniFill = new AscFormat.CUniFill(); oUniFill.fill = new AscFormat.CPattFill(); oUniFill.fill.ftype = AscCommon.global_hatch_offsets[sPatternType]; oUniFill.fill.fgClr = FgColor && FgColor.Unicolor; oUniFill.fill.bgClr = BgColor && BgColor.Unicolor; return oUniFill; } function builder_CreateBlipFill(sImageUrl, sBlipFillType) { var oUniFill = new AscFormat.CUniFill(); oUniFill.fill = new AscFormat.CBlipFill(); oUniFill.fill.RasterImageId = sImageUrl; if (sBlipFillType === "tile") { oUniFill.fill.tile = new AscFormat.CBlipFillTile(); } else if (sBlipFillType === "stretch") { oUniFill.fill.stretch = true; } return oUniFill; } function builder_CreateLine(nWidth, oFill) { if (nWidth === 0) { return new AscFormat.CreateNoFillLine(); } var oLn = new AscFormat.CLn(); oLn.w = nWidth; oLn.Fill = oFill.UniFill; return oLn; } function builder_CreateChartTitle(sTitle, nFontSize, bIsBold, oDrawingDocument) { if (typeof sTitle === "string" && sTitle.length > 0) { var oTitle = new AscFormat.CTitle(); oTitle.setOverlay(false); oTitle.setTx(new AscFormat.CChartText()); var oTextBody = AscFormat.CreateTextBodyFromString(sTitle, oDrawingDocument, oTitle.tx); if (AscFormat.isRealNumber(nFontSize)) { oTextBody.content.SetApplyToAll(true); oTextBody.content.AddToParagraph(new ParaTextPr({FontSize: nFontSize, Bold: bIsBold})); oTextBody.content.SetApplyToAll(false); } oTitle.tx.setRich(oTextBody); return oTitle; } return null; } function builder_CreateTitle(sTitle, nFontSize, bIsBold, oChartSpace) { if (typeof sTitle === "string" && sTitle.length > 0) { var oTitle = new AscFormat.CTitle(); oTitle.setOverlay(false); oTitle.setTx(new AscFormat.CChartText()); var oTextBody = AscFormat.CreateTextBodyFromString(sTitle, oChartSpace.getDrawingDocument(), oTitle.tx); if (AscFormat.isRealNumber(nFontSize)) { oTextBody.content.SetApplyToAll(true); oTextBody.content.AddToParagraph(new ParaTextPr({FontSize: nFontSize, Bold: bIsBold})); oTextBody.content.SetApplyToAll(false); } oTitle.tx.setRich(oTextBody); return oTitle; } return null; } function builder_SetChartTitle(oChartSpace, sTitle, nFontSize, bIsBold) { if (oChartSpace) { oChartSpace.chart.setTitle(builder_CreateChartTitle(sTitle, nFontSize, bIsBold, oChartSpace.getDrawingDocument())); } } function builder_SetChartHorAxisTitle(oChartSpace, sTitle, nFontSize, bIsBold) { if (oChartSpace) { var horAxis = oChartSpace.chart.plotArea.getHorizontalAxis(); if (horAxis) { horAxis.setTitle(builder_CreateTitle(sTitle, nFontSize, bIsBold, oChartSpace)); } } } function builder_SetChartVertAxisTitle(oChartSpace, sTitle, nFontSize, bIsBold) { if (oChartSpace) { var verAxis = oChartSpace.chart.plotArea.getVerticalAxis(); if (verAxis) { if (typeof sTitle === "string" && sTitle.length > 0) { verAxis.setTitle(builder_CreateTitle(sTitle, nFontSize, bIsBold, oChartSpace)); if (verAxis.title) { var _body_pr = new AscFormat.CBodyPr(); _body_pr.reset(); if (!verAxis.title.txPr) { verAxis.title.setTxPr(AscFormat.CreateTextBodyFromString("", oChartSpace.getDrawingDocument(), verAxis.title)); } var _text_body = verAxis.title.txPr; _text_body.setBodyPr(_body_pr); verAxis.title.setOverlay(false); } } else { verAxis.setTitle(null); } } } } function builder_SetChartVertAxisOrientation(oChartSpace, bIsMinMax) { if (oChartSpace) { var verAxis = oChartSpace.chart.plotArea.getVerticalAxis(); if (verAxis) { if (!verAxis.scaling) verAxis.setScaling(new AscFormat.CScaling()); var scaling = verAxis.scaling; if (bIsMinMax) { scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); } else { scaling.setOrientation(AscFormat.ORIENTATION_MAX_MIN); } } } } function builder_SetChartHorAxisOrientation(oChartSpace, bIsMinMax) { if (oChartSpace) { var horAxis = oChartSpace.chart.plotArea.getHorizontalAxis(); if (horAxis) { if (!horAxis.scaling) horAxis.setScaling(new AscFormat.CScaling()); var scaling = horAxis.scaling; if (bIsMinMax) { scaling.setOrientation(AscFormat.ORIENTATION_MIN_MAX); } else { scaling.setOrientation(AscFormat.ORIENTATION_MAX_MIN); } } } } function builder_SetChartLegendPos(oChartSpace, sLegendPos) { if (oChartSpace && oChartSpace.chart) { if (sLegendPos === "none") { if (oChartSpace.chart.legend) { oChartSpace.chart.setLegend(null); } } else { var nLegendPos = null; switch (sLegendPos) { case "left": { nLegendPos = Asc.c_oAscChartLegendShowSettings.left; break; } case "top": { nLegendPos = Asc.c_oAscChartLegendShowSettings.top; break; } case "right": { nLegendPos = Asc.c_oAscChartLegendShowSettings.right; break; } case "bottom": { nLegendPos = Asc.c_oAscChartLegendShowSettings.bottom; break; } } if (null !== nLegendPos) { if (!oChartSpace.chart.legend) { oChartSpace.chart.setLegend(new AscFormat.CLegend()); } if (oChartSpace.chart.legend.legendPos !== nLegendPos) oChartSpace.chart.legend.setLegendPos(nLegendPos); if (oChartSpace.chart.legend.overlay !== false) { oChartSpace.chart.legend.setOverlay(false); } } } } } function builder_SetObjectFontSize(oObject, nFontSize, oDrawingDocument) { if (!oObject) { return; } if (!oObject.txPr) { oObject.setTxPr(new AscFormat.CTextBody()); } if (!oObject.txPr.bodyPr) { oObject.txPr.setBodyPr(new AscFormat.CBodyPr()); } if (!oObject.txPr.content) { oObject.txPr.setContent(new AscFormat.CDrawingDocContent(oObject.txPr, oDrawingDocument, 0, 0, 100, 500, false, false, true)); } var oPr = oObject.txPr.content.Content[0].Pr.Copy(); if (!oPr.DefaultRunPr) { oPr.DefaultRunPr = new AscCommonWord.CTextPr(); } oPr.DefaultRunPr.FontSize = nFontSize; oObject.txPr.content.Content[0].Set_Pr(oPr); } function builder_SetLegendFontSize(oChartSpace, nFontSize) { builder_SetObjectFontSize(oChartSpace.chart.legend, nFontSize, oChartSpace.getDrawingDocument()); } function builder_SetHorAxisFontSize(oChartSpace, nFontSize) { builder_SetObjectFontSize(oChartSpace.chart.plotArea.getHorizontalAxis(), nFontSize, oChartSpace.getDrawingDocument()); } function builder_SetVerAxisFontSize(oChartSpace, nFontSize) { builder_SetObjectFontSize(oChartSpace.chart.plotArea.getVerticalAxis(), nFontSize, oChartSpace.getDrawingDocument()); } function builder_SetShowPointDataLabel(oChartSpace, nSeriesIndex, nPointIndex, bShowSerName, bShowCatName, bShowVal, bShowPerecent) { if (oChartSpace && oChartSpace.chart && oChartSpace.chart.plotArea && oChartSpace.chart.plotArea.charts[0]) { var oChart = oChartSpace.chart.plotArea.charts[0]; var bPieChart = oChart.getObjectType() === AscDFH.historyitem_type_PieChart || oChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart; var ser = oChart.series[nSeriesIndex]; if (ser) { { if (!ser.dLbls) { if (oChart.dLbls) { ser.setDLbls(oChart.dLbls.createDuplicate()); } else { ser.setDLbls(new AscFormat.CDLbls()); ser.dLbls.setSeparator(","); ser.dLbls.setShowSerName(false); ser.dLbls.setShowCatName(false); ser.dLbls.setShowVal(false); ser.dLbls.setShowLegendKey(false); if (bPieChart) { ser.dLbls.setShowPercent(false); } ser.dLbls.setShowBubbleSize(false); } } var dLbl = ser.dLbls && ser.dLbls.findDLblByIdx(nPointIndex); if (!dLbl) { dLbl = new AscFormat.CDLbl(); dLbl.setIdx(nPointIndex); if (ser.dLbls.txPr) { dLbl.merge(ser.dLbls); } ser.dLbls.addDLbl(dLbl); } dLbl.setSeparator(","); dLbl.setShowSerName(true == bShowSerName); dLbl.setShowCatName(true == bShowCatName); dLbl.setShowVal(true == bShowVal); dLbl.setShowLegendKey(false); if (bPieChart) { dLbl.setShowPercent(true === bShowPerecent); } dLbl.setShowBubbleSize(false); } } } } function builder_SetShowDataLabels(oChartSpace, bShowSerName, bShowCatName, bShowVal, bShowPerecent) { if (oChartSpace && oChartSpace.chart && oChartSpace.chart.plotArea && oChartSpace.chart.plotArea.charts[0]) { var oChart = oChartSpace.chart.plotArea.charts[0]; var bPieChart = oChart.getObjectType() === AscDFH.historyitem_type_PieChart || oChart.getObjectType() === AscDFH.historyitem_type_DoughnutChart; if (false == bShowSerName && false == bShowCatName && false == bShowVal && (bPieChart && bShowPerecent === false)) { if (oChart.dLbls) { oChart.setDLbls(null); } } if (!oChart.dLbls) { oChart.setDLbls(new AscFormat.CDLbls()); } oChart.dLbls.setSeparator(","); oChart.dLbls.setShowSerName(true == bShowSerName); oChart.dLbls.setShowCatName(true == bShowCatName); oChart.dLbls.setShowVal(true == bShowVal); oChart.dLbls.setShowLegendKey(false); if (bPieChart) { oChart.dLbls.setShowPercent(true === bShowPerecent); } oChart.dLbls.setShowBubbleSize(false); } } function builder_SetChartAxisLabelsPos(oAxis, sPosition) { if (!oAxis || !oAxis.setTickLblPos) { return; } var nPositionType = null; var c_oAscTickLabelsPos = window['Asc'].c_oAscTickLabelsPos; switch (sPosition) { case "high": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_HIGH; break; } case "low": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_LOW; break; } case "nextTo": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO; break; } case "none": { nPositionType = c_oAscTickLabelsPos.TICK_LABEL_POSITION_NONE; break; } } if (nPositionType !== null) { oAxis.setTickLblPos(nPositionType); } } function builder_SetChartVertAxisTickLablePosition(oChartSpace, sPosition) { if (oChartSpace) { builder_SetChartAxisLabelsPos(oChartSpace.chart.plotArea.getVerticalAxis(), sPosition); } } function builder_SetChartHorAxisTickLablePosition(oChartSpace, sPosition) { if (oChartSpace) { builder_SetChartAxisLabelsPos(oChartSpace.chart.plotArea.getHorizontalAxis(), sPosition); } } function builder_GetTickMark(sTickMark) { var nNewTickMark = null; switch (sTickMark) { case 'cross': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_CROSS; break; } case 'in': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_IN; break; } case 'none': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_NONE; break; } case 'out': { nNewTickMark = Asc.c_oAscTickMark.TICK_MARK_OUT; break; } } return nNewTickMark; } function builder_SetChartAxisMajorTickMark(oAxis, sTickMark) { if (!oAxis) { return; } var nNewTickMark = builder_GetTickMark(sTickMark); if (nNewTickMark !== null) { oAxis.setMajorTickMark(nNewTickMark); } } function builder_SetChartAxisMinorTickMark(oAxis, sTickMark) { if (!oAxis) { return; } var nNewTickMark = builder_GetTickMark(sTickMark); if (nNewTickMark !== null) { oAxis.setMinorTickMark(nNewTickMark); } } function builder_SetChartHorAxisMajorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMajorTickMark(oChartSpace.chart.plotArea.getHorizontalAxis(), sTickMark); } } function builder_SetChartHorAxisMinorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMinorTickMark(oChartSpace.chart.plotArea.getHorizontalAxis(), sTickMark); } } function builder_SetChartVerAxisMajorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMajorTickMark(oChartSpace.chart.plotArea.getVerticalAxis(), sTickMark); } } function builder_SetChartVerAxisMinorTickMark(oChartSpace, sTickMark) { if (oChartSpace) { builder_SetChartAxisMinorTickMark(oChartSpace.chart.plotArea.getVerticalAxis(), sTickMark); } } function builder_SetAxisMajorGridlines(oAxis, oLn) { if (oAxis) { if (!oAxis.majorGridlines) { oAxis.setMajorGridlines(new AscFormat.CSpPr()); } oAxis.majorGridlines.setLn(oLn); if (!oAxis.majorGridlines.Fill && !oAxis.majorGridlines.ln) { oAxis.setMajorGridlines(null); } } } function builder_SetAxisMinorGridlines(oAxis, oLn) { if (oAxis) { if (!oAxis.minorGridlines) { oAxis.setMinorGridlines(new AscFormat.CSpPr()); } oAxis.minorGridlines.setLn(oLn); if (!oAxis.minorGridlines.Fill && !oAxis.minorGridlines.ln) { oAxis.setMinorGridlines(null); } } } function builder_SetHorAxisMajorGridlines(oChartSpace, oLn) { builder_SetAxisMajorGridlines(oChartSpace.chart.plotArea.getVerticalAxis(), oLn); } function builder_SetHorAxisMinorGridlines(oChartSpace, oLn) { builder_SetAxisMinorGridlines(oChartSpace.chart.plotArea.getVerticalAxis(), oLn); } function builder_SetVerAxisMajorGridlines(oChartSpace, oLn) { builder_SetAxisMajorGridlines(oChartSpace.chart.plotArea.getHorizontalAxis(), oLn); } function builder_SetVerAxisMinorGridlines(oChartSpace, oLn) { builder_SetAxisMinorGridlines(oChartSpace.chart.plotArea.getHorizontalAxis(), oLn); } //----------------------------------------------------------export---------------------------------------------------- window['AscFormat'] = window['AscFormat'] || {}; window['AscFormat'].CreateFontRef = CreateFontRef; window['AscFormat'].CreatePresetColor = CreatePresetColor; window['AscFormat'].isRealNumber = isRealNumber; window['AscFormat'].isRealBool = isRealBool; window['AscFormat'].writeLong = writeLong; window['AscFormat'].readLong = readLong; window['AscFormat'].writeDouble = writeDouble; window['AscFormat'].readDouble = readDouble; window['AscFormat'].writeBool = writeBool; window['AscFormat'].readBool = readBool; window['AscFormat'].writeString = writeString; window['AscFormat'].readString = readString; window['AscFormat'].writeObject = writeObject; window['AscFormat'].readObject = readObject; window['AscFormat'].checkThemeFonts = checkThemeFonts; window['AscFormat'].ExecuteNoHistory = ExecuteNoHistory; window['AscFormat'].checkTableCellPr = checkTableCellPr; window['AscFormat'].CColorMod = CColorMod; window['AscFormat'].CColorModifiers = CColorModifiers; window['AscFormat'].CSysColor = CSysColor; window['AscFormat'].CPrstColor = CPrstColor; window['AscFormat'].CRGBColor = CRGBColor; window['AscFormat'].CSchemeColor = CSchemeColor; window['AscFormat'].CStyleColor = CStyleColor; window['AscFormat'].CUniColor = CUniColor; window['AscFormat'].CreateUniColorRGB = CreateUniColorRGB; window['AscFormat'].CreateUniColorRGB2 = CreateUniColorRGB2; window['AscFormat'].CreateSolidFillRGB = CreateSolidFillRGB; window['AscFormat'].CreateSolidFillRGBA = CreateSolidFillRGBA; window['AscFormat'].CSrcRect = CSrcRect; window['AscFormat'].CBlipFillTile = CBlipFillTile; window['AscFormat'].CBlipFill = CBlipFill; window['AscFormat'].CSolidFill = CSolidFill; window['AscFormat'].CGs = CGs; window['AscFormat'].GradLin = GradLin; window['AscFormat'].GradPath = GradPath; window['AscFormat'].CGradFill = CGradFill; window['AscFormat'].CPattFill = CPattFill; window['AscFormat'].CNoFill = CNoFill; window['AscFormat'].CGrpFill = CGrpFill; window['AscFormat'].CUniFill = CUniFill; window['AscFormat'].CompareUniFill = CompareUniFill; window['AscFormat'].CompareUnifillBool = CompareUnifillBool; window['AscFormat'].CompareShapeProperties = CompareShapeProperties; window['AscFormat'].CompareProtectionFlags = CompareProtectionFlags; window['AscFormat'].EndArrow = EndArrow; window['AscFormat'].ConvertJoinAggType = ConvertJoinAggType; window['AscFormat'].LineJoin = LineJoin; window['AscFormat'].CLn = CLn; window['AscFormat'].DefaultShapeDefinition = DefaultShapeDefinition; window['AscFormat'].CNvPr = CNvPr; window['AscFormat'].NvPr = NvPr; window['AscFormat'].Ph = Ph; window['AscFormat'].UniNvPr = UniNvPr; window['AscFormat'].StyleRef = StyleRef; window['AscFormat'].FontRef = FontRef; window['AscFormat'].CShapeStyle = CShapeStyle; window['AscFormat'].CreateDefaultShapeStyle = CreateDefaultShapeStyle; window['AscFormat'].CXfrm = CXfrm; window['AscFormat'].CEffectProperties = CEffectProperties; window['AscFormat'].CEffectLst = CEffectLst; window['AscFormat'].CSpPr = CSpPr; window['AscFormat'].ClrScheme = ClrScheme; window['AscFormat'].ClrMap = ClrMap; window['AscFormat'].ExtraClrScheme = ExtraClrScheme; window['AscFormat'].FontCollection = FontCollection; window['AscFormat'].FontScheme = FontScheme; window['AscFormat'].FmtScheme = FmtScheme; window['AscFormat'].ThemeElements = ThemeElements; window['AscFormat'].CTheme = CTheme; window['AscFormat'].HF = HF; window['AscFormat'].CBgPr = CBgPr; window['AscFormat'].CBg = CBg; window['AscFormat'].CSld = CSld; window['AscFormat'].CTextStyles = CTextStyles; window['AscFormat'].redrawSlide = redrawSlide; window['AscFormat'].CTextFit = CTextFit; window['AscFormat'].CBodyPr = CBodyPr; window['AscFormat'].CTextParagraphPr = CTextParagraphPr; window['AscFormat'].CompareBullets = CompareBullets; window['AscFormat'].CBuBlip = CBuBlip; window['AscFormat'].CBullet = CBullet; window['AscFormat'].CBulletColor = CBulletColor; window['AscFormat'].CBulletSize = CBulletSize; window['AscFormat'].CBulletTypeface = CBulletTypeface; window['AscFormat'].CBulletType = CBulletType; window['AscFormat'].TextListStyle = TextListStyle; window['AscFormat'].GenerateDefaultTheme = GenerateDefaultTheme; window['AscFormat'].GenerateDefaultMasterSlide = GenerateDefaultMasterSlide; window['AscFormat'].GenerateDefaultSlideLayout = GenerateDefaultSlideLayout; window['AscFormat'].GenerateDefaultSlide = GenerateDefaultSlide; window['AscFormat'].CreateDefaultTextRectStyle = CreateDefaultTextRectStyle; window['AscFormat'].GenerateDefaultColorMap = GenerateDefaultColorMap; window['AscFormat'].CreateAscFill = CreateAscFill; window['AscFormat'].CorrectUniFill = CorrectUniFill; window['AscFormat'].CreateAscStroke = CreateAscStroke; window['AscFormat'].CorrectUniStroke = CorrectUniStroke; window['AscFormat'].CreateAscShapePropFromProp = CreateAscShapePropFromProp; window['AscFormat'].CreateAscTextArtProps = CreateAscTextArtProps; window['AscFormat'].CreateUnifillFromAscColor = CreateUnifillFromAscColor; window['AscFormat'].CorrectUniColor = CorrectUniColor; window['AscFormat'].deleteDrawingBase = deleteDrawingBase; window['AscFormat'].CNvUniSpPr = CNvUniSpPr; window['AscFormat'].UniMedia = UniMedia; window['AscFormat'].CT_Hyperlink = CT_Hyperlink; window['AscFormat'].builder_CreateShape = builder_CreateShape; window['AscFormat'].builder_CreateChart = builder_CreateChart; window['AscFormat'].builder_CreateGroup = builder_CreateGroup; window['AscFormat'].builder_CreateSchemeColor = builder_CreateSchemeColor; window['AscFormat'].builder_CreatePresetColor = builder_CreatePresetColor; window['AscFormat'].builder_CreateGradientStop = builder_CreateGradientStop; window['AscFormat'].builder_CreateLinearGradient = builder_CreateLinearGradient; window['AscFormat'].builder_CreateRadialGradient = builder_CreateRadialGradient; window['AscFormat'].builder_CreatePatternFill = builder_CreatePatternFill; window['AscFormat'].builder_CreateBlipFill = builder_CreateBlipFill; window['AscFormat'].builder_CreateLine = builder_CreateLine; window['AscFormat'].builder_SetChartTitle = builder_SetChartTitle; window['AscFormat'].builder_SetChartHorAxisTitle = builder_SetChartHorAxisTitle; window['AscFormat'].builder_SetChartVertAxisTitle = builder_SetChartVertAxisTitle; window['AscFormat'].builder_SetChartLegendPos = builder_SetChartLegendPos; window['AscFormat'].builder_SetShowDataLabels = builder_SetShowDataLabels; window['AscFormat'].builder_SetChartVertAxisOrientation = builder_SetChartVertAxisOrientation; window['AscFormat'].builder_SetChartHorAxisOrientation = builder_SetChartHorAxisOrientation; window['AscFormat'].builder_SetChartVertAxisTickLablePosition = builder_SetChartVertAxisTickLablePosition; window['AscFormat'].builder_SetChartHorAxisTickLablePosition = builder_SetChartHorAxisTickLablePosition; window['AscFormat'].builder_SetChartHorAxisMajorTickMark = builder_SetChartHorAxisMajorTickMark; window['AscFormat'].builder_SetChartHorAxisMinorTickMark = builder_SetChartHorAxisMinorTickMark; window['AscFormat'].builder_SetChartVerAxisMajorTickMark = builder_SetChartVerAxisMajorTickMark; window['AscFormat'].builder_SetChartVerAxisMinorTickMark = builder_SetChartVerAxisMinorTickMark; window['AscFormat'].builder_SetLegendFontSize = builder_SetLegendFontSize; window['AscFormat'].builder_SetHorAxisMajorGridlines = builder_SetHorAxisMajorGridlines; window['AscFormat'].builder_SetHorAxisMinorGridlines = builder_SetHorAxisMinorGridlines; window['AscFormat'].builder_SetVerAxisMajorGridlines = builder_SetVerAxisMajorGridlines; window['AscFormat'].builder_SetVerAxisMinorGridlines = builder_SetVerAxisMinorGridlines; window['AscFormat'].builder_SetHorAxisFontSize = builder_SetHorAxisFontSize; window['AscFormat'].builder_SetVerAxisFontSize = builder_SetVerAxisFontSize; window['AscFormat'].builder_SetShowPointDataLabel = builder_SetShowPointDataLabel; window['AscFormat'].Ax_Counter = Ax_Counter; window['AscFormat'].TYPE_TRACK = TYPE_TRACK; window['AscFormat'].TYPE_KIND = TYPE_KIND; window['AscFormat'].mapPrstColor = map_prst_color; window['AscFormat'].map_hightlight = map_hightlight; window['AscFormat'].ar_arrow = ar_arrow; window['AscFormat'].ar_diamond = ar_diamond; window['AscFormat'].ar_none = ar_none; window['AscFormat'].ar_oval = ar_oval; window['AscFormat'].ar_stealth = ar_stealth; window['AscFormat'].ar_triangle = ar_triangle; window['AscFormat'].LineEndType = LineEndType; window['AscFormat'].LineEndSize = LineEndSize; window['AscFormat'].LineJoinType = LineJoinType; //ั‚ะธะฟั‹ ะฟะปะตะนัั…ะพะปะดะตั€ะพะฒ window['AscFormat'].phType_body = 0; window['AscFormat'].phType_chart = 1; window['AscFormat'].phType_clipArt = 2; //(Clip Art) window['AscFormat'].phType_ctrTitle = 3; //(Centered Title) window['AscFormat'].phType_dgm = 4; //(Diagram) window['AscFormat'].phType_dt = 5; //(Date and Time) window['AscFormat'].phType_ftr = 6; //(Footer) window['AscFormat'].phType_hdr = 7; //(Header) window['AscFormat'].phType_media = 8; //(Media) window['AscFormat'].phType_obj = 9; //(Object) window['AscFormat'].phType_pic = 10; //(Picture) window['AscFormat'].phType_sldImg = 11; //(Slide Image) window['AscFormat'].phType_sldNum = 12; //(Slide Number) window['AscFormat'].phType_subTitle = 13; //(Subtitle) window['AscFormat'].phType_tbl = 14; //(Table) window['AscFormat'].phType_title = 15; //(Title) window['AscFormat'].fntStyleInd_none = 2; window['AscFormat'].fntStyleInd_major = 0; window['AscFormat'].fntStyleInd_minor = 1; window['AscFormat'].VERTICAL_ANCHOR_TYPE_BOTTOM = 0; window['AscFormat'].VERTICAL_ANCHOR_TYPE_CENTER = 1; window['AscFormat'].VERTICAL_ANCHOR_TYPE_DISTRIBUTED = 2; window['AscFormat'].VERTICAL_ANCHOR_TYPE_JUSTIFIED = 3; window['AscFormat'].VERTICAL_ANCHOR_TYPE_TOP = 4; //Vertical Text Types window['AscFormat'].nVertTTeaVert = 0; //( ( East Asian Vertical )) window['AscFormat'].nVertTThorz = 1; //( ( Horizontal )) window['AscFormat'].nVertTTmongolianVert = 2; //( ( Mongolian Vertical )) window['AscFormat'].nVertTTvert = 3; //( ( Vertical )) window['AscFormat'].nVertTTvert270 = 4;//( ( Vertical 270 )) window['AscFormat'].nVertTTwordArtVert = 5;//( ( WordArt Vertical )) window['AscFormat'].nVertTTwordArtVertRtl = 6;//(Vertical WordArt Right to Left) //Text Wrapping Types window['AscFormat'].nTWTNone = 0; window['AscFormat'].nTWTSquare = 1; window['AscFormat'].BULLET_TYPE_COLOR_NONE = 0; window['AscFormat'].BULLET_TYPE_COLOR_CLRTX = 1; window['AscFormat'].BULLET_TYPE_COLOR_CLR = 2; window['AscFormat'].BULLET_TYPE_SIZE_NONE = 0; window['AscFormat'].BULLET_TYPE_SIZE_TX = 1; window['AscFormat'].BULLET_TYPE_SIZE_PCT = 2; window['AscFormat'].BULLET_TYPE_SIZE_PTS = 3; window['AscFormat'].BULLET_TYPE_TYPEFACE_NONE = 0; window['AscFormat'].BULLET_TYPE_TYPEFACE_TX = 1; window['AscFormat'].BULLET_TYPE_TYPEFACE_BUFONT = 2; window['AscFormat'].PARRUN_TYPE_NONE = 0; window['AscFormat'].PARRUN_TYPE_RUN = 1; window['AscFormat'].PARRUN_TYPE_FLD = 2; window['AscFormat'].PARRUN_TYPE_BR = 3; window['AscFormat'].PARRUN_TYPE_MATH = 4; window['AscFormat'].PARRUN_TYPE_MATHPARA = 5; window['AscFormat']._weight_body = _weight_body; window['AscFormat']._weight_chart = _weight_chart; window['AscFormat']._weight_clipArt = _weight_clipArt; window['AscFormat']._weight_ctrTitle = _weight_ctrTitle; window['AscFormat']._weight_dgm = _weight_dgm; window['AscFormat']._weight_media = _weight_media; window['AscFormat']._weight_obj = _weight_obj; window['AscFormat']._weight_pic = _weight_pic; window['AscFormat']._weight_subTitle = _weight_subTitle; window['AscFormat']._weight_tbl = _weight_tbl; window['AscFormat']._weight_title = _weight_title; window['AscFormat']._ph_multiplier = _ph_multiplier; window['AscFormat'].nSldLtTTitle = nSldLtTTitle; window['AscFormat'].nSldLtTObj = nSldLtTObj; window['AscFormat'].nSldLtTTx = nSldLtTTx; window['AscFormat']._arr_lt_types_weight = _arr_lt_types_weight; window['AscFormat']._global_layout_summs_array = _global_layout_summs_array; window['AscFormat'].AUDIO_CD = AUDIO_CD; window['AscFormat'].WAV_AUDIO_FILE = WAV_AUDIO_FILE; window['AscFormat'].AUDIO_FILE = AUDIO_FILE; window['AscFormat'].VIDEO_FILE = VIDEO_FILE; window['AscFormat'].QUICK_TIME_FILE = QUICK_TIME_FILE; window['AscFormat'].fCreateEffectByType = fCreateEffectByType; window['AscFormat'].COuterShdw = COuterShdw; window['AscFormat'].CGlow = CGlow; window['AscFormat'].CDuotone = CDuotone; window['AscFormat'].CXfrmEffect = CXfrmEffect; window['AscFormat'].CBlur = CBlur; window['AscFormat'].CPrstShdw = CPrstShdw; window['AscFormat'].CInnerShdw = CInnerShdw; window['AscFormat'].CReflection = CReflection; window['AscFormat'].CSoftEdge = CSoftEdge; window['AscFormat'].CFillOverlay = CFillOverlay; window['AscFormat'].CAlphaCeiling = CAlphaCeiling; window['AscFormat'].CAlphaFloor = CAlphaFloor; window['AscFormat'].CTintEffect = CTintEffect; window['AscFormat'].CRelOff = CRelOff; window['AscFormat'].CLumEffect = CLumEffect; window['AscFormat'].CHslEffect = CHslEffect; window['AscFormat'].CGrayscl = CGrayscl; window['AscFormat'].CEffectElement = CEffectElement; window['AscFormat'].CAlphaRepl = CAlphaRepl; window['AscFormat'].CAlphaOutset = CAlphaOutset; window['AscFormat'].CAlphaModFix = CAlphaModFix; window['AscFormat'].CAlphaBiLevel = CAlphaBiLevel; window['AscFormat'].CBiLevel = CBiLevel; window['AscFormat'].CEffectContainer = CEffectContainer; window['AscFormat'].CFillEffect = CFillEffect; window['AscFormat'].CClrRepl = CClrRepl; window['AscFormat'].CClrChange = CClrChange; window['AscFormat'].CAlphaInv = CAlphaInv; window['AscFormat'].CAlphaMod = CAlphaMod; window['AscFormat'].CBlend = CBlend; window['AscFormat'].CreateNoneBullet = CreateNoneBullet; window['AscFormat'].ChartBuilderTypeToInternal = ChartBuilderTypeToInternal; window['AscFormat'].InitClass = InitClass; window['AscFormat'].InitClassWithoutType = InitClassWithoutType; window['AscFormat'].CBaseObject = CBaseObject; window['AscFormat'].CBaseFormatObject = CBaseFormatObject; window['AscFormat'].CBaseNoIdObject = CBaseNoIdObject; window['AscFormat'].checkRasterImageId = checkRasterImageId; window['AscFormat'].IdEntry = IdEntry; window['AscFormat'].DEFAULT_COLOR_MAP = null; window['AscFormat'].DEFAULT_THEME = null; window['AscFormat'].GetDefaultColorMap = GetDefaultColorMap; window['AscFormat'].GetDefaultTheme = GetDefaultTheme; window['AscFormat'].getPercentageValue = getPercentageValue; window['AscFormat'].getPercentageValueForWrite = getPercentageValueForWrite; window['AscFormat'].CSpTree = CSpTree; window['AscFormat'].CClrMapOvr = CClrMapOvr; window['AscFormat'].fReadXmlRasterImageId = fReadXmlRasterImageId; }) (window);
Fix bug #58595
common/Drawings/Format/Format.js
Fix bug #58595
<ide><path>ommon/Drawings/Format/Format.js <ide> blipFill.setRasterImageId(url); <ide> } <ide> }; <del> CBullet.prototype.drawSquareImage = function (divId, relativeIndent) { <del> relativeIndent = relativeIndent || 0; <del> <del> var url = this.getImageBulletURL(); <del> var Api = editor || Asc.editor; <del> if (!url || !Api) { <add> CBullet.prototype.drawSquareImage = function (sDivId, nRelativeIndent) { <add> nRelativeIndent = nRelativeIndent || 0; <add> const sImageUrl = this.getImageBulletURL(); <add> const oApi = editor || Asc.editor; <add> if (!sImageUrl || !oApi) { <ide> return; <ide> } <ide> <del> var oDiv = document.getElementById(divId); <add> const oDiv = document.getElementById(sDivId); <ide> if (!oDiv) { <ide> return; <ide> } <del> var nWidth = oDiv.clientWidth; <del> var nHeight = oDiv.clientHeight; <del> var rPR = AscCommon.AscBrowser.retinaPixelRatio; <del> var sideSize = nWidth < nHeight ? nWidth * rPR : nHeight * rPR; <del> <del> var oCanvas = oDiv.firstChild; <add> const nWidth = oDiv.clientWidth; <add> const nHeight = oDiv.clientHeight; <add> const nRPR = AscCommon.AscBrowser.retinaPixelRatio; <add> const nCanvasSide = Math.min(nWidth, nHeight) * nRPR; <add> <add> let oCanvas = oDiv.firstChild; <ide> if (!oCanvas) { <ide> oCanvas = document.createElement('canvas'); <ide> oCanvas.style.cssText = "padding:0;margin:0;user-select:none;"; <ide> oCanvas.style.width = oDiv.clientWidth + 'px'; <ide> oCanvas.style.height = oDiv.clientHeight + 'px'; <del> oCanvas.width = sideSize; <del> oCanvas.height = sideSize; <add> oCanvas.width = nCanvasSide; <add> oCanvas.height = nCanvasSide; <ide> oDiv.appendChild(oCanvas); <ide> } <ide> <del> var oContext = oCanvas.getContext('2d'); <add> const oContext = oCanvas.getContext('2d'); <ide> oContext.fillStyle = "white"; <ide> oContext.fillRect(0, 0, oCanvas.width, oCanvas.height); <del> var _img = Api.ImageLoader.map_image_index[AscCommon.getFullImageSrc2(url)]; <del> if (_img && _img.Image && _img.Status !== AscFonts.ImageLoadStatus.Loading) { <del> var absoluteIndent = sideSize * relativeIndent; <del> var _x = absoluteIndent; <del> var _y = absoluteIndent; <del> var _w = sideSize - absoluteIndent * 2; <del> var _h = sideSize - absoluteIndent * 2; <del> oContext.drawImage(_img.Image, _x, _y, _w, _h); <add> const oImage = oApi.ImageLoader.map_image_index[AscCommon.getFullImageSrc2(sImageUrl)]; <add> if (oImage && oImage.Image && oImage.Status !== AscFonts.ImageLoadStatus.Loading) { <add> const nImageWidth = oImage.Image.width; <add> const nImageHeight = oImage.Image.height; <add> const absoluteIndent = nCanvasSide * nRelativeIndent; <add> const nSideSizeWithoutIndent = nCanvasSide - 2 * absoluteIndent; <add> const nAdaptCoefficient = Math.max(nImageWidth / nSideSizeWithoutIndent, nImageHeight / nSideSizeWithoutIndent); <add> const nImageAdaptWidth = nImageWidth / nAdaptCoefficient; <add> const nImageAdaptHeight = nImageHeight / nAdaptCoefficient; <add> const nX = (nCanvasSide - nImageAdaptWidth) / 2; <add> const nY = (nCanvasSide - nImageAdaptHeight) / 2; <add> oContext.drawImage(oImage.Image, nX, nY, nImageAdaptWidth, nImageAdaptHeight); <ide> } <ide> }; <ide> CBullet.prototype.readChildXml = function (name, reader) {
Java
epl-1.0
b11a5dc2d6c9254222cb3af1d207c93dd41c2b1f
0
paritoshdave/Convert-For-Each-Loop-to-Lambda-Expression-Eclipse-Plugin,mdarefin/Convert-For-Each-Loop-to-Lambda-Expression-Eclipse-Plugin
package edu.cuny.citytech.foreachlooptolambda.ui.refactorings; import java.text.MessageFormat; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.internal.codeassist.ThrownExceptionFinder; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext; import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.NullChange; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import edu.cuny.citytech.foreachlooptolambda.ui.messages.Messages; import edu.cuny.citytech.foreachlooptolambda.ui.visitors.EnhancedForStatementVisitor; import edu.cuny.citytech.refactoring.common.core.Refactoring; /** * The activator class controls the plug-in life cycle * * @author <a href="mailto:[email protected]">Raffi * Khatchadourian</a> */ public class ForeachLoopToLambdaRefactoring extends Refactoring { /** * The methods to refactor. */ private Set<IMethod> methods; /** * Creates a new refactoring with the given methods to refactor. * * @param methods * The methods to refactor. */ public ForeachLoopToLambdaRefactoring(IMethod... methods) { this.methods = new HashSet<IMethod>(Arrays.asList(methods)); } /** * Default constructor */ public ForeachLoopToLambdaRefactoring() { } @Override public String getName() { // TODO: Please rename. return Messages.ForEachLoopToLambdaRefactoring_Name; } @Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { // TODO Empty for now. final RefactoringStatus status = new RefactoringStatus(); return status; } // this method get the EnhancedForSrarement to check the precondition private static Set<EnhancedForStatement> getEnhancedForStatements(IMethod method, IProgressMonitor pm) throws JavaModelException { ICompilationUnit iCompilationUnit = method.getCompilationUnit(); // there may be a shared AST already parsed. Let's try to get that // one. CompilationUnit compilationUnit = RefactoringASTParser.parseWithASTProvider(iCompilationUnit, true, new SubProgressMonitor(pm, 1)); // get the method declaration ASTNode. MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, compilationUnit); final Set<EnhancedForStatement> statements = new LinkedHashSet<EnhancedForStatement>(); // extract all enhanced for loop statements in the method. methodDeclarationNode.accept(new ASTVisitor() { @Override public boolean visit(EnhancedForStatement node) { statements.add(node); return super.visit(node); } }); return statements; } @Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { try { final RefactoringStatus status = new RefactoringStatus(); for (IMethod method : methods) { Set<EnhancedForStatement> statements = getEnhancedForStatements(method, new SubProgressMonitor(pm, 1)); IProgressMonitor subMonitor = new SubProgressMonitor(pm, statements.size()); // check preconditions on each. statements.stream().forEach(s -> status.merge(checkEnhancedForStatement(s,method, subMonitor))); pm.worked(1); } return status; } finally { pm.done(); } } // Checking if the EnhancedForLoop iterate over collection private static boolean checkEnhancedForStatementIteratesOverCollection(EnhancedForStatement enhancedForStatement, IProgressMonitor pm) { boolean isNotInstanceOfCollection = true; Expression expression = enhancedForStatement.getExpression(); ITypeBinding nodeBindingType = expression.resolveTypeBinding(); if (nodeBindingType.isArray()) { isNotInstanceOfCollection = true; } else { // STEP 1: getting java the element of the type, IType iTypeElement = (IType) nodeBindingType.getJavaElement(); // Debug Purpose: will be remove once code is done System.out.println("This is ITypeElement " + iTypeElement); try { // STEP 2: getting java iTypeHeirchay, ITypeHierarchy iTypeHeirchay = iTypeElement.newSupertypeHierarchy(pm); // Debug Purpose: will be remove once code is done System.out.println("this is ITypeHeirchay " + iTypeHeirchay); // STEP 3: IType[] superInterface = iTypeHeirchay.getAllInterfaces(); // Debug Purpose: will be remove once code is done for (IType iType2 : superInterface) { System.out.println(iType2); } // ---------Debug---------------// } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String typeName = nodeBindingType.getQualifiedName(); System.out.println(" name " + typeName); // passing the default method by comparing List if ((typeName.startsWith("java.util.Collection")) || (typeName.startsWith("java.util.List"))) { isNotInstanceOfCollection = false; } return isNotInstanceOfCollection; } // getting any uncaught exception public void checkException() { ThrownExceptionFinder thrownUncaughtExceptions = new ThrownExceptionFinder(); ReferenceBinding[] thrownUncaughtException = thrownUncaughtExceptions.getThrownUncaughtExceptions(); if (thrownUncaughtException.length > 0) { } } // Checking with the precondiiton, private static RefactoringStatus checkEnhancedForStatement(EnhancedForStatement enhancedForStatement, IMethod method, IProgressMonitor pm) { try { RefactoringStatus status = new RefactoringStatus(); // create the visitor. EnhancedForStatementVisitor visitor = new EnhancedForStatementVisitor(); // have the AST node "accept" the visitor. enhancedForStatement.accept(visitor); final Set<String> warningStatement = new HashSet<String>(); if (visitor.containsBreak()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainBreak, method); } if (visitor.containsContinue()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainContinue, method); } if (visitor.containsInvalidReturn()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainInvalidReturn, method); } if (visitor.containsMultipleReturn()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainMultipleReturn, method); } if (visitor.containsException()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainException, method); } if (checkEnhancedForStatementIteratesOverCollection(enhancedForStatement, pm)) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_IteratesOverCollection, method); } //status.merge(checkMethodBody(method, new SubProgressMonitor(pm, 1))); pm.worked(1); return status; // passed. } finally { pm.done(); } } protected static RefactoringStatus checkMethodBody(IMethod method, IProgressMonitor pm) { RefactoringStatus status = new RefactoringStatus(); ITypeRoot root = method.getCompilationUnit(); CompilationUnit unit = RefactoringASTParser.parseWithASTProvider(root, false, new SubProgressMonitor(pm, 1)); MethodDeclaration declaration; try { declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit); if (declaration != null) { Block body = declaration.getBody(); if (body != null) { @SuppressWarnings("rawtypes") List statements = body.statements(); if (!statements.isEmpty()) { // TODO for now. addWarning(status, Messages.ForEachLoopToLambdaRefactoring_NoMethodsWithStatements, method); } } } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } return status; } protected static void addWarning(RefactoringStatus status, String message, IMethod method) { status.addWarning(MessageFormat.format(message, method.getElementName()), JavaStatusContext.create(method)); } @Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { try { pm.beginTask(Messages.ForEachLoopToLambdaRefactoring_CreatingChange, 1); return new NullChange(getName()); } finally { pm.done(); } } }
edu.cuny.citytech.foreachlooptolambda.ui/src/edu/cuny/citytech/foreachlooptolambda/ui/refactorings/ForeachLoopToLambdaRefactoring.java
package edu.cuny.citytech.foreachlooptolambda.ui.refactorings; import java.text.MessageFormat; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.internal.codeassist.ThrownExceptionFinder; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext; import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.NullChange; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import edu.cuny.citytech.foreachlooptolambda.ui.messages.Messages; import edu.cuny.citytech.foreachlooptolambda.ui.visitors.EnhancedForStatementVisitor; import edu.cuny.citytech.refactoring.common.core.Refactoring; /** * The activator class controls the plug-in life cycle * * @author <a href="mailto:[email protected]">Raffi * Khatchadourian</a> */ public class ForeachLoopToLambdaRefactoring extends Refactoring { /** * The methods to refactor. */ private Set<IMethod> methods; /** * Creates a new refactoring with the given methods to refactor. * * @param methods * The methods to refactor. */ public ForeachLoopToLambdaRefactoring(IMethod... methods) { this.methods = new HashSet<IMethod>(Arrays.asList(methods)); } /** * Default constructor */ public ForeachLoopToLambdaRefactoring() { } @Override public String getName() { // TODO: Please rename. return Messages.ForEachLoopToLambdaRefactoring_Name; } @Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { // TODO Empty for now. final RefactoringStatus status = new RefactoringStatus(); return status; } // this method get the EnhancedForSrarement to check the precondition private static Set<EnhancedForStatement> getEnhancedForStatements(IMethod method, IProgressMonitor pm) throws JavaModelException { ICompilationUnit iCompilationUnit = method.getCompilationUnit(); // there may be a shared AST already parsed. Let's try to get that // one. CompilationUnit compilationUnit = RefactoringASTParser.parseWithASTProvider(iCompilationUnit, true, new SubProgressMonitor(pm, 1)); // get the method declaration ASTNode. MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, compilationUnit); final Set<EnhancedForStatement> statements = new LinkedHashSet<EnhancedForStatement>(); // extract all enhanced for loop statements in the method. methodDeclarationNode.accept(new ASTVisitor() { @Override public boolean visit(EnhancedForStatement node) { statements.add(node); return super.visit(node); } }); return statements; } @Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { try { final RefactoringStatus status = new RefactoringStatus(); for (IMethod method : methods) { Set<EnhancedForStatement> statements = getEnhancedForStatements(method, new SubProgressMonitor(pm, 1)); IProgressMonitor subMonitor = new SubProgressMonitor(pm, statements.size()); // check preconditions on each. statements.stream().forEach(s -> status.merge(checkEnhancedForStatement(s, subMonitor))); pm.worked(1); } return status; } finally { pm.done(); } } // Checking if the EnhancedForLoop iterate over collection private static boolean checkEnhancedForStatementIteratesOverCollection(EnhancedForStatement enhancedForStatement, IProgressMonitor pm) { boolean isNotInstanceOfCollection = true; Expression expression = enhancedForStatement.getExpression(); ITypeBinding nodeBindingType = expression.resolveTypeBinding(); if (nodeBindingType.isArray()) { isNotInstanceOfCollection = true; } else { // STEP 1: getting java the element of the type, IType iTypeElement = (IType) nodeBindingType.getJavaElement(); // Debug Purpose: will be remove once code is done System.out.println("This is ITypeElement " + iTypeElement); try { // STEP 2: getting java iTypeHeirchay, ITypeHierarchy iTypeHeirchay = iTypeElement.newSupertypeHierarchy(pm); // Debug Purpose: will be remove once code is done System.out.println("this is ITypeHeirchay " + iTypeHeirchay); // STEP 3: IType[] iType = iTypeHeirchay.getAllInterfaces(); // Debug Purpose: will be remove once code is done for (IType iType2 : iType) { System.out.println(iType2); } // ---------Debug---------------// } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String typeName = nodeBindingType.getQualifiedName(); //passing the default method by comparing List if ((typeName.startsWith("java.util.Collection"))||(typeName.startsWith("java.util.List"))) { isNotInstanceOfCollection = false; } return isNotInstanceOfCollection; } // getting any uncaught exception public void checkException() { ThrownExceptionFinder thrownUncaughtExceptions = new ThrownExceptionFinder(); ReferenceBinding[] thrownUncaughtException = thrownUncaughtExceptions.getThrownUncaughtExceptions(); if (thrownUncaughtException.length > 0) { } } // Checking with the precondiiton, private static RefactoringStatus checkEnhancedForStatement(EnhancedForStatement enhancedForStatement, IMethod method, IProgressMonitor pm) { try { RefactoringStatus status = new RefactoringStatus(); // create the visitor. EnhancedForStatementVisitor visitor = new EnhancedForStatementVisitor(); // have the AST node "accept" the visitor. enhancedForStatement.accept(visitor); final Set<String> warningStatement = new HashSet<String>(); if (visitor.containsBreak()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainBreak, method); } if (visitor.containsContinue()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainContinue, method); } if (visitor.containsInvalidReturn()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainInvalidReturn, method); } if (visitor.containsMultipleReturn()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainMultipleReturn, method); } if (visitor.containsException()) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_ContainException, method); } if (checkEnhancedForStatementIteratesOverCollection(enhancedForStatement, pm)) { addWarning(status, Messages.ForEachLoopToLambdaRefactoring_IteratesOverCollection, method); } //status.merge(checkMethodBody(method, new SubProgressMonitor(pm, 1))); pm.worked(1); return status; // passed. } finally { pm.done(); } } protected static RefactoringStatus checkMethodBody(IMethod method, IProgressMonitor pm) { RefactoringStatus status = new RefactoringStatus(); ITypeRoot root = method.getCompilationUnit(); CompilationUnit unit = RefactoringASTParser.parseWithASTProvider(root, false, new SubProgressMonitor(pm, 1)); MethodDeclaration declaration; try { declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit); if (declaration != null) { Block body = declaration.getBody(); if (body != null) { @SuppressWarnings("rawtypes") List statements = body.statements(); if (!statements.isEmpty()) { // TODO for now. addWarning(status, Messages.ForEachLoopToLambdaRefactoring_NoMethodsWithStatements, method); } } } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } return status; } protected static void addWarning(RefactoringStatus status, String message, IMethod method) { status.addWarning(MessageFormat.format(message, method.getElementName()), JavaStatusContext.create(method)); } @Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { try { pm.beginTask(Messages.ForEachLoopToLambdaRefactoring_CreatingChange, 1); return new NullChange(getName()); } finally { pm.done(); } } }
#8 some progress
edu.cuny.citytech.foreachlooptolambda.ui/src/edu/cuny/citytech/foreachlooptolambda/ui/refactorings/ForeachLoopToLambdaRefactoring.java
#8 some progress
<ide><path>du.cuny.citytech.foreachlooptolambda.ui/src/edu/cuny/citytech/foreachlooptolambda/ui/refactorings/ForeachLoopToLambdaRefactoring.java <ide> import org.eclipse.core.runtime.OperationCanceledException; <ide> import org.eclipse.core.runtime.SubProgressMonitor; <ide> import org.eclipse.jdt.core.ICompilationUnit; <del>import org.eclipse.jdt.core.IJavaElement; <ide> import org.eclipse.jdt.core.IMethod; <ide> import org.eclipse.jdt.core.IType; <ide> import org.eclipse.jdt.core.ITypeHierarchy; <add>import org.eclipse.jdt.core.ITypeRoot; <ide> import org.eclipse.jdt.core.JavaModelException; <ide> import org.eclipse.jdt.core.dom.ASTVisitor; <add>import org.eclipse.jdt.core.dom.Block; <ide> import org.eclipse.jdt.core.dom.CompilationUnit; <ide> import org.eclipse.jdt.core.dom.EnhancedForStatement; <ide> import org.eclipse.jdt.core.dom.Expression; <ide> IProgressMonitor subMonitor = new SubProgressMonitor(pm, statements.size()); <ide> <ide> // check preconditions on each. <del> statements.stream().forEach(s -> status.merge(checkEnhancedForStatement(s, subMonitor))); <add> statements.stream().forEach(s -> status.merge(checkEnhancedForStatement(s,method, subMonitor))); <ide> pm.worked(1); <ide> } <ide> return status; <ide> // Debug Purpose: will be remove once code is done <ide> System.out.println("this is ITypeHeirchay " + iTypeHeirchay); <ide> // STEP 3: <del> IType[] iType = iTypeHeirchay.getAllInterfaces(); <add> IType[] superInterface = iTypeHeirchay.getAllInterfaces(); <ide> // Debug Purpose: will be remove once code is done <del> for (IType iType2 : iType) { <add> for (IType iType2 : superInterface) { <ide> System.out.println(iType2); <ide> } <ide> // ---------Debug---------------// <ide> e.printStackTrace(); <ide> } <ide> } <del> <add> <ide> String typeName = nodeBindingType.getQualifiedName(); <del> //passing the default method by comparing List <del> if ((typeName.startsWith("java.util.Collection"))||(typeName.startsWith("java.util.List"))) { <add> System.out.println(" name " + typeName); <add> // passing the default method by comparing List <add> if ((typeName.startsWith("java.util.Collection")) || (typeName.startsWith("java.util.List"))) { <ide> isNotInstanceOfCollection = false; <ide> } <ide>
Java
apache-2.0
error: pathspec 'src/main/java/gr/forth/DateRangeLabel.java' did not match any file(s) known to git
a10b7b1a8cb48998da6d5fc5d7eb552907d74824
1
isl/x3ml,isl/x3ml,isl/x3ml
/*============================================================================== 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 gr.forth; import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator; import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException; /** * */ public class DateRangeLabel implements CustomGenerator { private String date1 = ""; private String date2 = ""; @Override public void setArg(String name, String value) throws CustomGeneratorException { if ("date1".equals(name)) { date1 = value; } else if ("date2".equals(name)) { date2 = value; } else { throw new CustomGeneratorException("Unrecognized argument name: " + name); } } @Override public String getValue() throws CustomGeneratorException { if (date1.equalsIgnoreCase(date2)) { return date1; } if (!date1.isEmpty() && !date2.isEmpty()) { return (date1 + " - " + date2); } if (date1.isEmpty()) { return date2; } else { return date1; } } @Override public String getValueType() throws CustomGeneratorException { return "Literal"; } }
src/main/java/gr/forth/DateRangeLabel.java
added a new LabelGenerator (provided by BritishMuseum)
src/main/java/gr/forth/DateRangeLabel.java
added a new LabelGenerator (provided by BritishMuseum)
<ide><path>rc/main/java/gr/forth/DateRangeLabel.java <add>/*============================================================================== <add>Licensed to the Apache Software Foundation (ASF) under one <add>or more contributor license agreements. See the NOTICE file <add>distributed with this work for additional information <add>regarding copyright ownership. The ASF licenses this file <add>to you under the Apache License, Version 2.0 (the <add>"License"); you may not use this file except in compliance <add>with the License. You may obtain a copy of the License at <add> <add> http://www.apache.org/licenses/LICENSE-2.0 <add> <add>Unless required by applicable law or agreed to in writing, <add>software distributed under the License is distributed on an <add>"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add>KIND, either express or implied. See the License for the <add>specific language governing permissions and limitations <add>under the License. <add>==============================================================================*/ <add>package gr.forth; <add> <add>import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator; <add>import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException; <add> <add>/** <add> * <add> */ <add>public class DateRangeLabel implements CustomGenerator { <add> <add> private String date1 = ""; <add> private String date2 = ""; <add> <add> @Override <add> public void setArg(String name, String value) throws CustomGeneratorException { <add> if ("date1".equals(name)) { <add> date1 = value; <add> } else if ("date2".equals(name)) { <add> date2 = value; <add> } else { <add> throw new CustomGeneratorException("Unrecognized argument name: " + name); <add> } <add> } <add> <add> @Override <add> public String getValue() throws CustomGeneratorException { <add> if (date1.equalsIgnoreCase(date2)) { <add> return date1; <add> } <add> if (!date1.isEmpty() && !date2.isEmpty()) { <add> <add> return (date1 + " - " + date2); <add> } <add> if (date1.isEmpty()) { <add> return date2; <add> } else { <add> return date1; <add> } <add> } <add> <add> @Override <add> public String getValueType() throws CustomGeneratorException { <add> return "Literal"; <add> } <add>}
Java
agpl-3.0
a14fef5417a0689a4c764afcf2a605c3606ef43f
0
RBGKew/eMonocot,RBGKew/eMonocot,RBGKew/eMonocot
package org.emonocot.checklist.view.oai; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.Validator; import org.custommonkey.xmlunit.XMLTestCase; import org.custommonkey.xmlunit.XMLUnit; import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier; import org.dozer.Mapper; import org.dozer.spring.DozerBeanMapperFactoryBean; import org.emonocot.model.marshall.xml.StaxDriver; import org.emonocot.model.marshall.xml.UriConverter; import org.emonocot.model.marshall.xml.XStreamMarshaller; import org.emonocot.test.xml.IgnoreXPathDifferenceListener; import org.openarchives.pmh.marshall.xml.OpenArchivesQNameMapFactory; import org.openarchives.pmh.marshall.xml.ReflectionProviderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.xml.sax.InputSource; import com.bea.xml.stream.XMLOutputFactoryBase; import com.thoughtworks.xstream.converters.ConverterMatcher; /** * * @author ben * */ public abstract class AbstractOaiPmhViewTestCase extends XMLTestCase { /** * */ private static Logger logger = LoggerFactory.getLogger(AbstractOaiPmhViewTestCase.class); /** * */ private AbstractOaiPmhResponseView view; /** * */ private Map model; /** * */ private HttpServletRequest request; /** * */ private HttpServletResponse response; /** * */ private boolean validateAgainstSchemas = true; /** * * @param validate * should we validate against the provided schemas */ public final void setValidateAgainstSchemas(final boolean validate) { this.validateAgainstSchemas = validate; } /** * * @throws Exception if there is a problem parsing the xml */ public final void setUp() throws Exception { view = setView(); XMLUnit.setControlParser( "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); XMLUnit.setTestParser( "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); XMLUnit.setSAXParserFactory( "org.apache.xerces.jaxp.SAXParserFactoryImpl"); XMLUnit.setIgnoreWhitespace(true); ReflectionProviderFactory reflectionProviderFactory = new ReflectionProviderFactory(); reflectionProviderFactory.afterPropertiesSet(); OpenArchivesQNameMapFactory qNameMapFactory = new OpenArchivesQNameMapFactory(); qNameMapFactory.afterPropertiesSet(); XStreamMarshaller marshaller = new XStreamMarshaller(); marshaller.setAutodetectAnnotations(true); marshaller.setConverters(new ConverterMatcher[]{new UriConverter()}); marshaller.setReflectionProvider(reflectionProviderFactory.getObject()); StaxDriver staxDriver = new StaxDriver(qNameMapFactory.getObject()); staxDriver.setXmlOutputFactory(new XMLOutputFactoryBase()); staxDriver.setRepairingNamespace(false); staxDriver.setStartDocument(false); marshaller.setStreamDriver(staxDriver); marshaller.afterPropertiesSet(); view.setMarshaller(marshaller); DozerBeanMapperFactoryBean mapperFactory = new DozerBeanMapperFactoryBean(); mapperFactory.setMappingFiles(new Resource[]{ new ClassPathResource( "/org/emonocot/checklist/view/assembler/mapping.xml"), new ClassPathResource( "/org/emonocot/checklist/view/assembler/test.mapping.xml") }); mapperFactory.afterPropertiesSet(); view.setMapper((Mapper) mapperFactory.getObject()); model = new HashMap(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); doSetup(model); } /** * * @return an instance of the oai pmh response to render */ public abstract AbstractOaiPmhResponseView setView(); /** * * @param newModel Populate the model with test data */ public abstract void doSetup(final Map newModel); /** * * @return the expected response as a string */ public abstract String getExpected(); /** * * @throws Exception if there is a problem validating the generated xml */ public final void testView() throws Exception { view.render(model, request, response); logger.info(((MockHttpServletResponse) response) .getContentAsString()); Diff difference = new Diff(getExpected(), ((MockHttpServletResponse) response).getContentAsString()); difference .overrideDifferenceListener(new IgnoreXPathDifferenceListener( "/OAI-PMH[1]/responseDate[1]/text()[1]", "/OAI-PMH[1]/ListIdentifiers[1]/resumptionToken[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/resumptionToken[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[1]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[2]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[3]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[4]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[5]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[6]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[7]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[8]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[9]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[10]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/hasRelationship[1]/Relationship[1]/" + "toTaxon[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/hasRelationship[2]/Relationship[1]/" + "toTaxon[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[1]/Distribution[1]/hasValue[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[2]/hasContent[1]/text()[1]", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[3]/Distribution[1]/hasValue[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[4]/Distribution[1]/hasValue[1]/@resource")); difference .overrideElementQualifier( new RecursiveElementNameAndTextQualifier()); if (!difference.similar()) { logger.warn(difference.toString()); } assertTrue("test XML does not match control skeleton XML", difference.similar()); if (validateAgainstSchemas) { InputSource inputSource = new InputSource(new StringReader( ((MockHttpServletResponse) response).getContentAsString())); Validator validator = new Validator(inputSource); validator.useXMLSchema(true); validator.setJAXP12SchemaSource(new String[] { "target/test-classes/org/openarchives/pmh/oai-pmh.xsd", "target/test-classes/org/openarchives/pmh/oai_dc.xsd" }); validator.assertIsValid(); } } }
emonocot-checklist/src/test/java/org/emonocot/checklist/view/oai/AbstractOaiPmhViewTestCase.java
package org.emonocot.checklist.view.oai; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.Validator; import org.custommonkey.xmlunit.XMLTestCase; import org.custommonkey.xmlunit.XMLUnit; import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier; import org.dozer.Mapper; import org.dozer.spring.DozerBeanMapperFactoryBean; import org.emonocot.model.marshall.xml.StaxDriver; import org.emonocot.model.marshall.xml.UriConverter; import org.emonocot.model.marshall.xml.XStreamMarshaller; import org.emonocot.test.xml.IgnoreXPathDifferenceListener; import org.openarchives.pmh.marshall.xml.OpenArchivesQNameMapFactory; import org.openarchives.pmh.marshall.xml.ReflectionProviderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.xml.sax.InputSource; import com.bea.xml.stream.XMLOutputFactoryBase; import com.thoughtworks.xstream.converters.ConverterMatcher; /** * * @author ben * */ public abstract class AbstractOaiPmhViewTestCase extends XMLTestCase { /** * */ private static Logger logger = LoggerFactory.getLogger(AbstractOaiPmhViewTestCase.class); /** * */ private AbstractOaiPmhResponseView view; /** * */ private Map model; /** * */ private HttpServletRequest request; /** * */ private HttpServletResponse response; /** * */ private boolean validateAgainstSchemas = true; /** * * @param validate * should we validate against the provided schemas */ public final void setValidateAgainstSchemas(final boolean validate) { this.validateAgainstSchemas = validate; } /** * * @throws Exception if there is a problem parsing the xml */ public final void setUp() throws Exception { view = setView(); XMLUnit.setControlParser( "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); XMLUnit.setTestParser( "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); XMLUnit.setSAXParserFactory( "org.apache.xerces.jaxp.SAXParserFactoryImpl"); XMLUnit.setIgnoreWhitespace(true); ReflectionProviderFactory reflectionProviderFactory = new ReflectionProviderFactory(); reflectionProviderFactory.afterPropertiesSet(); OpenArchivesQNameMapFactory qNameMapFactory = new OpenArchivesQNameMapFactory(); qNameMapFactory.afterPropertiesSet(); XStreamMarshaller marshaller = new XStreamMarshaller(); marshaller.setAutodetectAnnotations(true); marshaller.setConverters(new ConverterMatcher[]{new UriConverter()}); marshaller.setReflectionProvider(reflectionProviderFactory.getObject()); StaxDriver staxDriver = new StaxDriver(qNameMapFactory.getObject()); staxDriver.setXmlOutputFactory(new XMLOutputFactoryBase()); staxDriver.setRepairingNamespace(false); staxDriver.setStartDocument(false); marshaller.setStreamDriver(staxDriver); marshaller.afterPropertiesSet(); view.setMarshaller(marshaller); DozerBeanMapperFactoryBean mapperFactory = new DozerBeanMapperFactoryBean(); mapperFactory.setMappingFiles(new Resource[]{ new ClassPathResource( "/org/emonocot/checklist/view/assembler/mapping.xml"), new ClassPathResource( "/org/emonocot/checklist/view/assembler/test.mapping.xml") }); mapperFactory.afterPropertiesSet(); view.setMapper((Mapper) mapperFactory.getObject()); model = new HashMap(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); doSetup(model); } /** * * @return an instance of the oai pmh response to render */ public abstract AbstractOaiPmhResponseView setView(); /** * * @param newModel Populate the model with test data */ public abstract void doSetup(final Map newModel); /** * * @return the expected response as a string */ public abstract String getExpected(); /** * * @throws Exception if there is a problem validating the generated xml */ public final void testView() throws Exception { view.render(model, request, response); System.out.println(((MockHttpServletResponse) response) .getContentAsString()); Diff difference = new Diff(getExpected(), ((MockHttpServletResponse) response).getContentAsString()); difference .overrideDifferenceListener(new IgnoreXPathDifferenceListener( "/OAI-PMH[1]/responseDate[1]/text()[1]", "/OAI-PMH[1]/ListIdentifiers[1]/resumptionToken[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/resumptionToken[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[1]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[2]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[3]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[4]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[5]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[6]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[7]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[8]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[9]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/ListRecords[1]/record[10]/metadata[1]/dc[1]/" + "date[1]/text()[1]", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/hasRelationship[1]/Relationship[1]/" + "toTaxon[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/hasRelationship[2]/Relationship[1]/" + "toTaxon[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[1]/Distribution[1]/hasValue[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[2]/hasContent[1]/text()[1]", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[3]/Distribution[1]/hasValue[1]/@resource", "/OAI-PMH[1]/GetRecord[1]/record[1]/metadata[1]/" + "TaxonConcept[1]/describedBy[1]/SpeciesProfileModel[1]/" + "hasInformation[4]/Distribution[1]/hasValue[1]/@resource")); difference .overrideElementQualifier( new RecursiveElementNameAndTextQualifier()); if (!difference.similar()) { logger.warn(difference.toString()); } assertTrue("test XML does not match control skeleton XML", difference.similar()); if (validateAgainstSchemas) { InputSource inputSource = new InputSource(new StringReader( ((MockHttpServletResponse) response).getContentAsString())); Validator validator = new Validator(inputSource); validator.useXMLSchema(true); validator.setJAXP12SchemaSource(new String[] { "target/test-classes/org/openarchives/pmh/oai-pmh.xsd", "target/test-classes/org/openarchives/pmh/oai_dc.xsd" }); validator.assertIsValid(); } } }
Last commit failed - "Just fixing bug trapped by test (Inherited XStream elements)"
emonocot-checklist/src/test/java/org/emonocot/checklist/view/oai/AbstractOaiPmhViewTestCase.java
Last commit failed - "Just fixing bug trapped by test (Inherited XStream elements)"
<ide><path>monocot-checklist/src/test/java/org/emonocot/checklist/view/oai/AbstractOaiPmhViewTestCase.java <ide> */ <ide> public final void testView() throws Exception { <ide> view.render(model, request, response); <del> System.out.println(((MockHttpServletResponse) response) <add> logger.info(((MockHttpServletResponse) response) <ide> .getContentAsString()); <ide> <ide> Diff difference = new Diff(getExpected(),
Java
lgpl-2.1
04ec1567bcaa8aae196bd92c5e3523782c2ada95
0
xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.plugin.feed; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.xwiki.cache.Cache; import org.xwiki.cache.CacheException; import org.xwiki.cache.config.CacheConfiguration; import org.xwiki.cache.eviction.LRUEvictionConfiguration; import com.sun.syndication.feed.synd.SyndCategory; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.feed.synd.SyndImage; import com.sun.syndication.feed.synd.SyndImageImpl; import com.sun.syndication.io.SyndFeedOutput; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.plugin.XWikiDefaultPlugin; import com.xpn.xwiki.plugin.XWikiPluginInterface; import com.xpn.xwiki.user.api.XWikiRightService; public class FeedPlugin extends XWikiDefaultPlugin implements XWikiPluginInterface { private Cache<SyndFeed> feedCache; private int refreshPeriod; private Map<String, UpdateThread> updateThreads = new HashMap<String, UpdateThread>(); public static class SyndEntryComparator implements Comparator<SyndEntry> { public int compare(SyndEntry entry1, SyndEntry entry2) { if ((entry1.getPublishedDate() == null) && (entry2.getPublishedDate() == null)) { return 0; } if (entry1.getPublishedDate() == null) { return 1; } if (entry2.getPublishedDate() == null) { return -1; } return (-entry1.getPublishedDate().compareTo(entry2.getPublishedDate())); } } public static class EntriesComparator implements Comparator<com.xpn.xwiki.api.Object> { public int compare(com.xpn.xwiki.api.Object entry1, com.xpn.xwiki.api.Object entry2) { BaseObject bobj1 = entry1.getXWikiObject(); BaseObject bobj2 = entry1.getXWikiObject(); if ((bobj1.getDateValue("date") == null) && (bobj2.getDateValue("date") == null)) { return 0; } if (bobj1.getDateValue("date") == null) { return 1; } if (bobj2.getDateValue("date") == null) { return -1; } return (-bobj1.getDateValue("date").compareTo(bobj2.getDateValue("date"))); } } public FeedPlugin(String name, String className, XWikiContext context) { super(name, className, context); init(context); } @Override public String getName() { return "feed"; } @Override public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) { return new FeedPluginApi((FeedPlugin) plugin, context); } @Override public void flushCache() { if (this.feedCache != null) { this.feedCache.removeAll(); } this.feedCache = null; } @Override public void init(XWikiContext context) { super.init(context); prepareCache(context); this.refreshPeriod = (int) context.getWiki().ParamAsLong("xwiki.plugins.feed.cacherefresh", 3600); // Make sure we have this class try { getAggregatorURLClass(context); } catch (XWikiException e) { } // Make sure we have this class try { getFeedEntryClass(context); } catch (XWikiException e) { } } public void initCache(XWikiContext context) throws XWikiException { int iCapacity = 100; try { String capacity = context.getWiki().Param("xwiki.plugins.feed.cache.capacity"); if (capacity != null) { iCapacity = Integer.parseInt(capacity); } } catch (Exception e) { } initCache(iCapacity, context); } public void initCache(int iCapacity, XWikiContext context) throws XWikiException { try { CacheConfiguration configuration = new CacheConfiguration(); configuration.setConfigurationId("xwiki.plugin.feedcache"); LRUEvictionConfiguration lru = new LRUEvictionConfiguration(); lru.setMaxEntries(iCapacity); lru.setTimeToLive(this.refreshPeriod); configuration.put(LRUEvictionConfiguration.CONFIGURATIONID, lru); this.feedCache = context.getWiki().getLocalCacheFactory().newCache(configuration); } catch (CacheException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_CACHE, XWikiException.ERROR_CACHE_INITIALIZING, "Failed to create cache"); } } protected void prepareCache(XWikiContext context) { try { if (this.feedCache == null) { initCache(context); } } catch (XWikiException e) { } } public SyndFeed getFeeds(String sfeeds, XWikiContext context) throws IOException { return getFeeds(sfeeds, false, true, context); } public SyndFeed getFeeds(String sfeeds, boolean force, XWikiContext context) throws IOException { return getFeeds(sfeeds, false, force, context); } public SyndFeed getFeeds(String sfeeds, boolean ignoreInvalidFeeds, boolean force, XWikiContext context) throws IOException { String[] feeds; if (sfeeds.indexOf("\n") != -1) { feeds = sfeeds.split("\n"); } else { feeds = sfeeds.split("\\|"); } List<SyndEntry> entries = new ArrayList<SyndEntry>(); SyndFeed outputFeed = new SyndFeedImpl(); if (context.getDoc() != null) { outputFeed.setTitle(context.getDoc().getFullName()); outputFeed.setUri(context.getWiki().getURL(context.getDoc().getFullName(), "view", context)); outputFeed.setAuthor(context.getDoc().getAuthor()); } else { outputFeed.setTitle("XWiki Feeds"); outputFeed.setAuthor("XWiki Team"); } for (int i = 0; i < feeds.length; i++) { SyndFeed feed = getFeed(feeds[i], ignoreInvalidFeeds, force, context); if (feed != null) { entries.addAll(feed.getEntries()); } } SyndEntryComparator comp = new SyndEntryComparator(); Collections.sort(entries, comp); outputFeed.setEntries(entries); return outputFeed; } public SyndFeed getFeed(String sfeed, XWikiContext context) throws IOException { return getFeed(sfeed, true, false, context); } public SyndFeed getFeed(String sfeed, boolean force, XWikiContext context) throws IOException { return getFeed(sfeed, true, force, context); } public SyndFeed getFeed(String sfeed, boolean ignoreInvalidFeeds, boolean force, XWikiContext context) throws IOException { SyndFeed feed = null; prepareCache(context); if (!force) { feed = this.feedCache.get(sfeed); } if (feed == null) { feed = getFeedForce(sfeed, ignoreInvalidFeeds, context); } if (feed != null) { this.feedCache.set(sfeed, feed); } return feed; } public SyndFeed getFeedForce(String sfeed, boolean ignoreInvalidFeeds, XWikiContext context) throws IOException { try { URL feedURL = new URL(sfeed); XWikiFeedFetcher feedFetcher = new XWikiFeedFetcher(); feedFetcher.setUserAgent(context.getWiki().Param("xwiki.plugins.feed.useragent", context.getWiki().getHttpUserAgent(context))); SyndFeed feed = feedFetcher.retrieveFeed(feedURL, (int) context.getWiki().ParamAsLong("xwiki.plugins.feed.timeout", context.getWiki().getHttpTimeout(context))); return feed; } catch (Exception ex) { if (ignoreInvalidFeeds) { @SuppressWarnings("unchecked") Map<String, Exception> map = (Map<String, Exception>) context.get("invalidFeeds"); if (map == null) { map = new HashMap<String, Exception>(); context.put("invalidFeeds", map); } map.put(sfeed, ex); return null; } throw new java.io.IOException("Error processing " + sfeed + ": " + ex.getMessage()); } } public int updateFeeds(XWikiContext context) throws XWikiException { return updateFeeds("XWiki.FeedList", context); } public int updateFeeds(String feedDoc, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, false, context); } public int updateFeeds(String feedDoc, boolean fullContent, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, fullContent, true, context); } public int updateFeeds(String feedDoc, boolean fullContent, boolean oneDocPerEntry, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, fullContent, oneDocPerEntry, false, context); } public int updateFeeds(String feedDoc, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, fullContent, oneDocPerEntry, force, "Feeds", context); } public int updateFeeds(String feedDoc, boolean fullContent, boolean oneDocPerEntry, boolean force, String space, XWikiContext context) throws XWikiException { // Make sure we have this class getAggregatorURLClass(context); XWikiDocument doc = context.getWiki().getDocument(feedDoc, context); Vector<BaseObject> objs = doc.getObjects("XWiki.AggregatorURLClass"); if (objs == null) { return 0; } int total = 0; int nbfeeds = 0; int nbfeedsErrors = 0; for (BaseObject obj : objs) { if (obj != null) { String feedurl = obj.getStringValue("url"); String feedname = obj.getStringValue("name"); nbfeeds++; int nb = updateFeed(feedname, feedurl, fullContent, oneDocPerEntry, force, space, context); if (nb != -1) { total += nb; } else { nbfeedsErrors++; } UpdateThread updateThread = this.updateThreads.get(space); if (updateThread != null) { updateThread.setNbLoadedFeeds(nbfeeds + updateThread.getNbLoadedFeeds()); updateThread.setNbLoadedFeedsErrors(nbfeedsErrors + updateThread.getNbLoadedFeedsErrors()); } if (context.get("feedimgurl") != null) { obj.set("imgurl", context.get("feedimgurl"), context); context.remove("feedimgurl"); } obj.set("nb", new Integer(nb), context); obj.set("date", new Date(), context); // Update original document context.getWiki().saveDocument(doc, context); } } return total; } public int updateFeedsInSpace(String space, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) throws XWikiException { // Make sure we have this class getAggregatorURLClass(context); String sql = ", BaseObject as obj where doc.fullName=obj.name and obj.className='XWiki.AggregatorURLClass' and doc.space='" + space + "'"; int total = 0; List<String> feedDocList = context.getWiki().getStore().searchDocumentsNames(sql, context); if (feedDocList != null) { for (int i = 0; i < feedDocList.size(); i++) { String feedDocName = feedDocList.get(i); total += updateFeeds(feedDocName, fullContent, oneDocPerEntry, force, space, context); } } return total; } public boolean startUpdateFeedsInSpace(String space, boolean fullContent, int scheduleTimer, XWikiContext context) throws XWikiException { UpdateThread updateThread = this.updateThreads.get(context.getDatabase() + ":" + space); if (updateThread == null) { updateThread = new UpdateThread(space, fullContent, scheduleTimer, this, context); this.updateThreads.put(context.getDatabase() + ":" + space, updateThread); Thread thread = new Thread(updateThread); thread.start(); return true; } else { return false; } } public void stopUpdateFeedsInSpace(String space, XWikiContext context) throws XWikiException { UpdateThread updateThread = this.updateThreads.get(context.getDatabase() + ":" + space); if (updateThread != null) { updateThread.stopUpdate(); } } public void removeUpdateThread(String space, UpdateThread thread, XWikiContext context) { // make sure the update thread is removed. // this is called by the update thread when the loop is last exited if (thread == this.updateThreads.get(context.getDatabase() + ":" + space)) { this.updateThreads.remove(context.getDatabase() + ":" + space); } } public UpdateThread getUpdateThread(String space, XWikiContext context) { return this.updateThreads.get(context.getDatabase() + ":" + space); } public Collection<String> getActiveUpdateThreads() { return this.updateThreads.keySet(); } public int updateFeed(String feedname, String feedurl, boolean oneDocPerEntry, XWikiContext context) { return updateFeed(feedname, feedurl, false, oneDocPerEntry, context); } public int updateFeed(String feedname, String feedurl, boolean fullContent, boolean oneDocPerEntry, XWikiContext context) { return updateFeed(feedname, feedurl, fullContent, oneDocPerEntry, false, context); } public int updateFeed(String feedname, String feedurl, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) { return updateFeed(feedname, feedurl, fullContent, oneDocPerEntry, force, "Feeds", context); } public int updateFeed(String feedname, String feedurl, boolean fullContent, boolean oneDocPerEntry, boolean force, String space, XWikiContext context) { try { // Make sure we have this class getFeedEntryClass(context); SyndFeed feed = getFeedForce(feedurl, true, context); if (feed != null) { if (feed.getImage() != null) { context.put("feedimgurl", feed.getImage().getUrl()); } return saveFeed(feedname, feedurl, feed, fullContent, oneDocPerEntry, force, space, context); } else { return 0; } } catch (Exception e) { @SuppressWarnings("unchecked") Map<String, Exception> map = (Map<String, Exception>) context.get("updateFeedError"); if (map == null) { map = new HashMap<String, Exception>(); context.put("updateFeedError", map); } map.put(feedurl, e); } return -1; } private int saveFeed(String feedname, String feedurl, SyndFeed feed, boolean fullContent, boolean oneDocPerEntry, boolean force, String space, XWikiContext context) throws XWikiException { XWikiDocument doc = null; Vector<BaseObject> objs = null; int nbtotal = 0; String prefix = space + ".Feed"; if (!oneDocPerEntry) { doc = context.getWiki().getDocument( prefix + "_" + context.getWiki().clearName(feedname, true, true, context), context); objs = doc.getObjects("XWiki.FeedEntryClass"); if ((doc.getContent() == null) || doc.getContent().trim().equals("")) { doc.setContent("#includeForm(\"XWiki.FeedEntryClassSheet\")"); doc.setSyntaxId(XWikiDocument.XWIKI10_SYNTAXID); } } @SuppressWarnings("unchecked") List<SyndEntry> entries = feed.getEntries(); int nb = entries.size(); for (int i = nb - 1; i >= 0; i--) { SyndEntry entry = entries.get(i); if (oneDocPerEntry) { String hashCode = "" + entry.getLink().hashCode(); String pagename = feedname + "_" + hashCode.replaceAll("-", "") + "_" + entry.getTitle(); doc = context.getWiki().getDocument( prefix + "_" + context.getWiki().clearName(pagename, true, true, context), context); if (doc.isNew() || force) { // Set the document date to the current date doc.setDate(new Date()); // Set the creation date to the feed date if it exists, otherwise the current date Date adate = (entry.getPublishedDate() == null) ? new Date() : entry.getPublishedDate(); doc.setCreationDate(adate); if ((doc.getContent() == null) || doc.getContent().trim().equals("")) { doc.setContent("#includeForm(\"XWiki.FeedEntryClassSheet\")"); doc.setSyntaxId(XWikiDocument.XWIKI10_SYNTAXID); } if (force) { BaseObject obj = doc.getObject("XWiki.FeedEntryClass"); if (obj == null) { saveEntry(feedname, feedurl, entry, doc, fullContent, context); } else { saveEntry(feedname, feedurl, entry, doc, obj, fullContent, context); } } else { saveEntry(feedname, feedurl, entry, doc, fullContent, context); } nbtotal++; context.getWiki().saveDocument(doc, context); } } else { BaseObject obj = postExist(objs, entry, context); if (obj == null) { saveEntry(feedname, feedurl, entry, doc, fullContent, context); nbtotal++; } else if (force) { saveEntry(feedname, feedurl, entry, doc, obj, fullContent, context); nbtotal++; } } } if (!oneDocPerEntry) { context.getWiki().saveDocument(doc, context); } return nbtotal; } public BaseClass getAggregatorURLClass(XWikiContext context) throws XWikiException { XWikiDocument doc; boolean needsUpdate = false; doc = context.getWiki().getDocument("XWiki.AggregatorURLClass", context); BaseClass bclass = doc.getxWikiClass(); if (context.get("initdone") != null) { return bclass; } bclass.setName("XWiki.AggregatorURLClass"); if (!"internal".equals(bclass.getCustomMapping())) { needsUpdate = true; bclass.setCustomMapping("internal"); } needsUpdate |= bclass.addTextField("name", "Name", 80); needsUpdate |= bclass.addTextField("url", "url", 80); needsUpdate |= bclass.addTextField("imgurl", "Image url", 80); needsUpdate |= bclass.addDateField("date", "date", "dd/MM/yyyy HH:mm:ss"); needsUpdate |= bclass.addNumberField("nb", "nb", 5, "integer"); if (StringUtils.isBlank(doc.getCreator())) { needsUpdate = true; doc.setCreator(XWikiRightService.SUPERADMIN_USER); } if (StringUtils.isBlank(doc.getAuthor())) { needsUpdate = true; doc.setAuthor(doc.getCreator()); } if (StringUtils.isBlank(doc.getTitle())) { needsUpdate = true; doc.setTitle("XWiki Aggregator URL Class"); } if (StringUtils.isBlank(doc.getContent()) || !XWikiDocument.XWIKI20_SYNTAXID.equals(doc.getSyntaxId())) { needsUpdate = true; doc.setContent("{{include document=\"XWiki.ClassSheet\" /}}"); doc.setSyntaxId(XWikiDocument.XWIKI20_SYNTAXID); } if (StringUtils.isBlank(doc.getParent())) { needsUpdate = true; doc.setParent("XWiki.XWikiClasses"); } if (needsUpdate) { context.getWiki().saveDocument(doc, context); } return bclass; } public BaseClass getFeedEntryClass(XWikiContext context) throws XWikiException { XWikiDocument doc; boolean needsUpdate = false; doc = context.getWiki().getDocument("XWiki.FeedEntryClass", context); BaseClass bclass = doc.getxWikiClass(); if (context.get("initdone") != null) { return bclass; } bclass.setName("XWiki.FeedEntryClass"); if (!"internal".equals(bclass.getCustomMapping())) { needsUpdate = true; bclass.setCustomMapping("internal"); } needsUpdate |= bclass.addTextField("title", "Title", 80); needsUpdate |= bclass.addTextField("author", "Author", 40); needsUpdate |= bclass.addTextField("feedurl", "Feed URL", 80); needsUpdate |= bclass.addTextField("feedname", "Feed Name", 40); needsUpdate |= bclass.addTextField("url", "URL", 80); needsUpdate |= bclass.addTextField("category", "Category", 255); needsUpdate |= bclass.addTextAreaField("content", "Content", 80, 10); needsUpdate |= bclass.addTextAreaField("fullContent", "Full Content", 80, 10); needsUpdate |= bclass.addTextAreaField("xml", "XML", 80, 10); needsUpdate |= bclass.addDateField("date", "date", "dd/MM/yyyy HH:mm:ss"); needsUpdate |= bclass.addNumberField("flag", "Flag", 5, "integer"); needsUpdate |= bclass.addNumberField("read", "Read", 5, "integer"); needsUpdate |= bclass.addStaticListField("tags", "Tags", 1, true, true, "", null, null); if (StringUtils.isBlank(doc.getCreator())) { needsUpdate = true; doc.setCreator(XWikiRightService.SUPERADMIN_USER); } if (StringUtils.isBlank(doc.getAuthor())) { needsUpdate = true; doc.setAuthor(doc.getCreator()); } if (StringUtils.isBlank(doc.getTitle())) { needsUpdate = true; doc.setTitle("XWiki Feed Entry Class"); } if (StringUtils.isBlank(doc.getContent()) || !XWikiDocument.XWIKI20_SYNTAXID.equals(doc.getSyntaxId())) { needsUpdate = true; doc.setContent("{{include document=\"XWiki.ClassSheet\" /}}"); doc.setSyntaxId(XWikiDocument.XWIKI20_SYNTAXID); } if (StringUtils.isBlank(doc.getParent())) { needsUpdate = true; doc.setParent("XWiki.XWikiClasses"); } if (needsUpdate) { context.getWiki().saveDocument(doc, context); } return bclass; } private void saveEntry(String feedname, String feedurl, SyndEntry entry, XWikiDocument doc, boolean fullContent, XWikiContext context) throws XWikiException { int id = doc.createNewObject("XWiki.FeedEntryClass", context); BaseObject obj = doc.getObject("XWiki.FeedEntryClass", id); saveEntry(feedname, feedurl, entry, doc, obj, fullContent, context); } private void saveEntry(String feedname, String feedurl, SyndEntry entry, XWikiDocument doc, BaseObject obj, boolean fullContent, XWikiContext context) throws XWikiException { obj.setStringValue("feedname", feedname); obj.setStringValue("title", entry.getTitle()); // set document title to the feed title doc.setTitle(entry.getTitle()); obj.setIntValue("flag", 0); @SuppressWarnings("unchecked") List<SyndCategory> categList = entry.getCategories(); StringBuffer categs = new StringBuffer(""); if (categList != null) { for (SyndCategory categ : categList) { if (categs.length() != 0) { categs.append(", "); } categs.append(categ.getName()); } } obj.setStringValue("category", categs.toString()); StringBuffer contents = new StringBuffer(""); String description = (entry.getDescription() == null) ? null : entry.getDescription().getValue(); @SuppressWarnings("unchecked") List<SyndContent> contentList = entry.getContents(); if (contentList != null && contentList.size() > 0) { for (SyndContent content : contentList) { if (contents.length() != 0) { contents.append("\n"); } contents.append(content.getValue()); } } // If we find more data in the description we will use that one instead of the content field if ((description != null) && (description.length() > contents.length())) { obj.setLargeStringValue("content", description); } else { obj.setLargeStringValue("content", contents.toString()); } Date edate = entry.getPublishedDate(); if (edate == null) { edate = new Date(); } obj.setDateValue("date", edate); obj.setStringValue("url", entry.getLink()); obj.setStringValue("author", entry.getAuthor()); obj.setStringValue("feedurl", feedurl); // TODO: need to get entry xml or serialization // obj.setLargeStringValue("xml", entry.toString()); obj.setLargeStringValue("xml", ""); if (fullContent) { String url = entry.getLink(); if ((url != null) && (!url.trim().equals(""))) { try { String sfullContent = context.getWiki().getURLContent(url, context); obj.setLargeStringValue("fullContent", (sfullContent.length() > 65000) ? sfullContent.substring(0, 65000) : sfullContent); } catch (Exception e) { obj.setLargeStringValue("fullContent", "Exception while reading fullContent: " + e.getMessage()); } } else { obj.setLargeStringValue("fullContent", "No url"); } } } private BaseObject postExist(Vector<BaseObject> objs, SyndEntry entry, XWikiContext context) { if (objs == null) { return null; } String title = context.getWiki().clearName(entry.getTitle(), true, true, context); for (BaseObject obj : objs) { if (obj != null) { String title2 = obj.getStringValue("title"); if (title2 == null) { title2 = ""; } else { title2 = context.getWiki().clearName(title2, true, true, context); } if (title2.compareTo(title) == 0) { return obj; } } } return null; } public List<com.xpn.xwiki.api.Object> search(String query, XWikiContext context) throws XWikiException { String[] queryTab = query.split(" "); if (queryTab.length > 0) { String sql = "select distinct obj.number, obj.name from BaseObject as obj, StringProperty as prop , LargeStringProperty as lprop " + "where obj.className='XWiki.FeedEntryClass' and obj.id=prop.id.id and obj.id=lprop.id.id "; for (int i = 0; i < queryTab.length; i++) { sql += " and (prop.value LIKE '%" + queryTab[i] + "%' or lprop.value LIKE '%" + queryTab[i] + "%')"; } List<Object[]> res = context.getWiki().search(sql, context); if (res == null) { return null; } List<com.xpn.xwiki.api.Object> apiObjs = new ArrayList<com.xpn.xwiki.api.Object>(); for (Object obj[] : res) { try { XWikiDocument doc = context.getWiki().getDocument((String) obj[1], context); if (context.getWiki().getRightService().checkAccess("view", doc, context)) { BaseObject bObj = doc.getObject("XWiki.FeedEntryClass", ((Integer) obj[0]).intValue()); com.xpn.xwiki.api.Object apiObj = new com.xpn.xwiki.api.Object(bObj, context); apiObjs.add(apiObj); } } catch (Exception e) { @SuppressWarnings("unchecked") Map<String, Exception> map = (Map<String, Exception>) context.get("searchFeedError"); if (map == null) { map = new HashMap<String, Exception>(); context.put("searchFeedError", map); } map.put(query, e); } } Collections.sort(apiObjs, new EntriesComparator()); return apiObjs; } return null; } public com.xpn.xwiki.api.Object getFeedInfosbyGuid(String guid, XWikiContext context) throws XWikiException { return getFeedInfosbyGuid("XWiki.FeedList", guid, context); } public com.xpn.xwiki.api.Object getFeedInfosbyGuid(String feedDoc, String guid, XWikiContext context) throws XWikiException { XWikiDocument doc = context.getWiki().getDocument(feedDoc, context); Vector<BaseObject> objs = doc.getObjects("XWiki.AggregatorURLClass"); for (BaseObject obj : objs) { if (guid.compareTo(obj.getStringValue("guid")) == 0) { return new com.xpn.xwiki.api.Object(obj, context); } } return null; } /** * @see FeedPluginApi#getSyndEntrySource(String, Map) */ public SyndEntrySource getSyndEntrySource(String className, Map<String, Object> params, XWikiContext context) throws XWikiException { try { Class< ? extends SyndEntrySource> sesc = Class.forName(className).asSubclass(SyndEntrySource.class); Constructor< ? extends SyndEntrySource> ctor = null; if (params != null) { try { ctor = sesc.getConstructor(new Class[] {Map.class}); return ctor.newInstance(new Object[] {params}); } catch (Throwable t) { } } ctor = sesc.getConstructor(new Class[] {}); return ctor.newInstance(new Object[] {}); } catch (Throwable t) { throw new XWikiException(XWikiException.MODULE_XWIKI_PLUGINS, XWikiException.ERROR_XWIKI_UNKNOWN, "", t); } } /** * @see FeedPluginApi#getFeedEntry() */ public SyndEntry getFeedEntry(XWikiContext context) { return new SyndEntryImpl(); } /** * @see FeedPluginApi#getFeedImage() */ public SyndImage getFeedImage(XWikiContext context) { return new SyndImageImpl(); } /** * @see FeedPluginApi#getFeed() */ public SyndFeed getFeed(XWikiContext context) { return new SyndFeedImpl(); } /** * @see FeedPluginApi#getFeed(List, SyndEntrySourceApi, Map) */ public SyndFeed getFeed(List<Object> list, SyndEntrySource source, Map<String, Object> sourceParams, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(context); List<SyndEntry> entries = new ArrayList<SyndEntry>(); for (int i = 0; i < list.size(); i++) { SyndEntry entry = getFeedEntry(context); try { source.source(entry, list.get(i), sourceParams, context); entries.add(entry); } catch (Throwable t) { // skip this entry } } feed.setEntries(entries); return feed; } /** * @see FeedPluginApi#getFeed(String, int, int, SyndEntrySourceApi, Map) */ public SyndFeed getFeed(String query, int count, int start, SyndEntrySource source, Map<String, Object> sourceParams, XWikiContext context) throws XWikiException { List<Object> entries = new ArrayList<Object>(); entries.addAll(context.getWiki().getStore().searchDocumentsNames(query, count, start, context)); return getFeed(entries, source, sourceParams, context); } /** * @see FeedPluginApi#getFeed(List, SyndEntrySourceApi, Map, Map) */ public SyndFeed getFeed(List<Object> list, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(list, source, sourceParams, context); fillFeedMetadata(feed, metadata); return feed; } /** * @see FeedPluginApi#getFeed(String, int, int, SyndEntrySourceApi, Map, Map) */ public SyndFeed getFeed(String query, int count, int start, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(query, count, start, source, sourceParams, context); fillFeedMetadata(feed, metadata); return feed; } private void fillFeedMetadata(SyndFeed feed, Map<String, Object> metadata) { feed.setAuthor(String.valueOf(metadata.get("author"))); feed.setDescription(String.valueOf(metadata.get("description"))); feed.setCopyright(String.valueOf(metadata.get("copyright"))); feed.setEncoding(String.valueOf(metadata.get("encoding"))); // TODO: rename "url" to "link" for consistency ? feed.setLink(String.valueOf(metadata.get("url"))); feed.setTitle(String.valueOf(metadata.get("title"))); feed.setLanguage(String.valueOf(metadata.get("language"))); } /** * @see FeedPluginApi#getFeedOutput(SyndFeed, String) */ public String getFeedOutput(SyndFeed feed, String type, XWikiContext context) { feed.setFeedType(type); StringWriter writer = new StringWriter(); SyndFeedOutput output = new SyndFeedOutput(); try { output.output(feed, writer); writer.close(); return writer.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * @see FeedPluginApi#getFeedOutput(List, SyndEntrySourceApi, Map, Map, String) */ public String getFeedOutput(List<Object> list, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, String type, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(list, source, sourceParams, metadata, context); return getFeedOutput(feed, type, context); } /** * @see FeedPluginApi#getFeedOutput(String, int, int, SyndEntrySourceApi, Map, Map, String) */ public String getFeedOutput(String query, int count, int start, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, String type, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(query, count, start, source, sourceParams, metadata, context); return getFeedOutput(feed, type, context); } }
xwiki-core/src/main/java/com/xpn/xwiki/plugin/feed/FeedPlugin.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.plugin.feed; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.xwiki.cache.Cache; import org.xwiki.cache.CacheException; import org.xwiki.cache.config.CacheConfiguration; import org.xwiki.cache.eviction.LRUEvictionConfiguration; import com.sun.syndication.feed.synd.SyndCategory; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.feed.synd.SyndImage; import com.sun.syndication.feed.synd.SyndImageImpl; import com.sun.syndication.io.SyndFeedOutput; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.plugin.XWikiDefaultPlugin; import com.xpn.xwiki.plugin.XWikiPluginInterface; import com.xpn.xwiki.user.api.XWikiRightService; public class FeedPlugin extends XWikiDefaultPlugin implements XWikiPluginInterface { private Cache<SyndFeed> feedCache; private int refreshPeriod; private Map<String, UpdateThread> updateThreads = new HashMap<String, UpdateThread>(); public static class SyndEntryComparator implements Comparator<SyndEntry> { public int compare(SyndEntry entry1, SyndEntry entry2) { if ((entry1.getPublishedDate() == null) && (entry2.getPublishedDate() == null)) { return 0; } if (entry1.getPublishedDate() == null) { return 1; } if (entry2.getPublishedDate() == null) { return -1; } return (-entry1.getPublishedDate().compareTo(entry2.getPublishedDate())); } } public static class EntriesComparator implements Comparator<com.xpn.xwiki.api.Object> { public int compare(com.xpn.xwiki.api.Object entry1, com.xpn.xwiki.api.Object entry2) { BaseObject bobj1 = entry1.getXWikiObject(); BaseObject bobj2 = entry1.getXWikiObject(); if ((bobj1.getDateValue("date") == null) && (bobj2.getDateValue("date") == null)) { return 0; } if (bobj1.getDateValue("date") == null) { return 1; } if (bobj2.getDateValue("date") == null) { return -1; } return (-bobj1.getDateValue("date").compareTo(bobj2.getDateValue("date"))); } } public FeedPlugin(String name, String className, XWikiContext context) { super(name, className, context); init(context); } @Override public String getName() { return "feed"; } @Override public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) { return new FeedPluginApi((FeedPlugin) plugin, context); } @Override public void flushCache() { if (this.feedCache != null) { this.feedCache.removeAll(); } this.feedCache = null; } @Override public void init(XWikiContext context) { super.init(context); prepareCache(context); this.refreshPeriod = (int) context.getWiki().ParamAsLong("xwiki.plugins.feed.cacherefresh", 3600); // Make sure we have this class try { getAggregatorURLClass(context); } catch (XWikiException e) { } // Make sure we have this class try { getFeedEntryClass(context); } catch (XWikiException e) { } } public void initCache(XWikiContext context) throws XWikiException { int iCapacity = 100; try { String capacity = context.getWiki().Param("xwiki.plugins.feed.cache.capacity"); if (capacity != null) { iCapacity = Integer.parseInt(capacity); } } catch (Exception e) { } initCache(iCapacity, context); } public void initCache(int iCapacity, XWikiContext context) throws XWikiException { try { CacheConfiguration configuration = new CacheConfiguration(); configuration.setConfigurationId("xwiki.plugin.feedcache"); LRUEvictionConfiguration lru = new LRUEvictionConfiguration(); lru.setMaxEntries(iCapacity); lru.setTimeToLive(this.refreshPeriod); configuration.put(LRUEvictionConfiguration.CONFIGURATIONID, lru); this.feedCache = context.getWiki().getLocalCacheFactory().newCache(configuration); } catch (CacheException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_CACHE, XWikiException.ERROR_CACHE_INITIALIZING, "Failed to create cache"); } } protected void prepareCache(XWikiContext context) { try { if (this.feedCache == null) { initCache(context); } } catch (XWikiException e) { } } public SyndFeed getFeeds(String sfeeds, XWikiContext context) throws IOException { return getFeeds(sfeeds, false, true, context); } public SyndFeed getFeeds(String sfeeds, boolean force, XWikiContext context) throws IOException { return getFeeds(sfeeds, false, force, context); } public SyndFeed getFeeds(String sfeeds, boolean ignoreInvalidFeeds, boolean force, XWikiContext context) throws IOException { String[] feeds; if (sfeeds.indexOf("\n") != -1) { feeds = sfeeds.split("\n"); } else { feeds = sfeeds.split("\\|"); } List<SyndEntry> entries = new ArrayList<SyndEntry>(); SyndFeed outputFeed = new SyndFeedImpl(); if (context.getDoc() != null) { outputFeed.setTitle(context.getDoc().getFullName()); outputFeed.setUri(context.getWiki().getURL(context.getDoc().getFullName(), "view", context)); outputFeed.setAuthor(context.getDoc().getAuthor()); } else { outputFeed.setTitle("XWiki Feeds"); outputFeed.setAuthor("XWiki Team"); } for (int i = 0; i < feeds.length; i++) { SyndFeed feed = getFeed(feeds[i], ignoreInvalidFeeds, force, context); if (feed != null) { entries.addAll(feed.getEntries()); } } SyndEntryComparator comp = new SyndEntryComparator(); Collections.sort(entries, comp); outputFeed.setEntries(entries); return outputFeed; } public SyndFeed getFeed(String sfeed, XWikiContext context) throws IOException { return getFeed(sfeed, true, false, context); } public SyndFeed getFeed(String sfeed, boolean force, XWikiContext context) throws IOException { return getFeed(sfeed, true, force, context); } public SyndFeed getFeed(String sfeed, boolean ignoreInvalidFeeds, boolean force, XWikiContext context) throws IOException { SyndFeed feed = null; prepareCache(context); if (!force) { feed = this.feedCache.get(sfeed); } if (feed == null) { feed = getFeedForce(sfeed, ignoreInvalidFeeds, context); } if (feed != null) { this.feedCache.set(sfeed, feed); } return feed; } public SyndFeed getFeedForce(String sfeed, boolean ignoreInvalidFeeds, XWikiContext context) throws IOException { try { URL feedURL = new URL(sfeed); XWikiFeedFetcher feedFetcher = new XWikiFeedFetcher(); feedFetcher.setUserAgent(context.getWiki().Param("xwiki.plugins.feed.useragent", context.getWiki().getHttpUserAgent(context))); SyndFeed feed = feedFetcher.retrieveFeed(feedURL, (int) context.getWiki().ParamAsLong("xwiki.plugins.feed.timeout", context.getWiki().getHttpTimeout(context))); return feed; } catch (Exception ex) { if (ignoreInvalidFeeds) { Map<String, Exception> map = (Map<String, Exception>) context.get("invalidFeeds"); if (map == null) { map = new HashMap<String, Exception>(); context.put("invalidFeeds", map); } map.put(sfeed, ex); return null; } throw new java.io.IOException("Error processing " + sfeed + ": " + ex.getMessage()); } } public int updateFeeds(XWikiContext context) throws XWikiException { return updateFeeds("XWiki.FeedList", context); } public int updateFeeds(String feedDoc, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, false, context); } public int updateFeeds(String feedDoc, boolean fullContent, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, fullContent, true, context); } public int updateFeeds(String feedDoc, boolean fullContent, boolean oneDocPerEntry, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, fullContent, oneDocPerEntry, false, context); } public int updateFeeds(String feedDoc, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) throws XWikiException { return updateFeeds(feedDoc, fullContent, oneDocPerEntry, force, "Feeds", context); } public int updateFeeds(String feedDoc, boolean fullContent, boolean oneDocPerEntry, boolean force, String space, XWikiContext context) throws XWikiException { // Make sure we have this class getAggregatorURLClass(context); XWikiDocument doc = context.getWiki().getDocument(feedDoc, context); Vector<BaseObject> objs = doc.getObjects("XWiki.AggregatorURLClass"); if (objs == null) { return 0; } int total = 0; int nbfeeds = 0; int nbfeedsErrors = 0; for (BaseObject obj : objs) { if (obj != null) { String feedurl = obj.getStringValue("url"); String feedname = obj.getStringValue("name"); nbfeeds++; int nb = updateFeed(feedname, feedurl, fullContent, oneDocPerEntry, force, space, context); if (nb != -1) { total += nb; } else { nbfeedsErrors++; } UpdateThread updateThread = this.updateThreads.get(space); if (updateThread != null) { updateThread.setNbLoadedFeeds(nbfeeds + updateThread.getNbLoadedFeeds()); updateThread.setNbLoadedFeedsErrors(nbfeedsErrors + updateThread.getNbLoadedFeedsErrors()); } if (context.get("feedimgurl") != null) { obj.set("imgurl", context.get("feedimgurl"), context); context.remove("feedimgurl"); } obj.set("nb", new Integer(nb), context); obj.set("date", new Date(), context); // Update original document context.getWiki().saveDocument(doc, context); } } return total; } public int updateFeedsInSpace(String space, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) throws XWikiException { // Make sure we have this class getAggregatorURLClass(context); String sql = ", BaseObject as obj where doc.fullName=obj.name and obj.className='XWiki.AggregatorURLClass' and doc.space='" + space + "'"; int total = 0; List<String> feedDocList = context.getWiki().getStore().searchDocumentsNames(sql, context); if (feedDocList != null) { for (int i = 0; i < feedDocList.size(); i++) { String feedDocName = feedDocList.get(i); total += updateFeeds(feedDocName, fullContent, oneDocPerEntry, force, space, context); } } return total; } public boolean startUpdateFeedsInSpace(String space, boolean fullContent, int scheduleTimer, XWikiContext context) throws XWikiException { UpdateThread updateThread = this.updateThreads.get(context.getDatabase() + ":" + space); if (updateThread == null) { updateThread = new UpdateThread(space, fullContent, scheduleTimer, this, context); this.updateThreads.put(context.getDatabase() + ":" + space, updateThread); Thread thread = new Thread(updateThread); thread.start(); return true; } else { return false; } } public void stopUpdateFeedsInSpace(String space, XWikiContext context) throws XWikiException { UpdateThread updateThread = this.updateThreads.get(context.getDatabase() + ":" + space); if (updateThread != null) { updateThread.stopUpdate(); } } public void removeUpdateThread(String space, UpdateThread thread, XWikiContext context) { // make sure the update thread is removed. // this is called by the update thread when the loop is last exited if (thread == this.updateThreads.get(context.getDatabase() + ":" + space)) { this.updateThreads.remove(context.getDatabase() + ":" + space); } } public UpdateThread getUpdateThread(String space, XWikiContext context) { return this.updateThreads.get(context.getDatabase() + ":" + space); } public Collection<String> getActiveUpdateThreads() { return this.updateThreads.keySet(); } public int updateFeed(String feedname, String feedurl, boolean oneDocPerEntry, XWikiContext context) { return updateFeed(feedname, feedurl, false, oneDocPerEntry, context); } public int updateFeed(String feedname, String feedurl, boolean fullContent, boolean oneDocPerEntry, XWikiContext context) { return updateFeed(feedname, feedurl, fullContent, oneDocPerEntry, false, context); } public int updateFeed(String feedname, String feedurl, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) { return updateFeed(feedname, feedurl, fullContent, oneDocPerEntry, force, "Feeds", context); } public int updateFeed(String feedname, String feedurl, boolean fullContent, boolean oneDocPerEntry, boolean force, String space, XWikiContext context) { try { // Make sure we have this class getFeedEntryClass(context); SyndFeed feed = getFeedForce(feedurl, true, context); if (feed != null) { if (feed.getImage() != null) { context.put("feedimgurl", feed.getImage().getUrl()); } return saveFeed(feedname, feedurl, feed, fullContent, oneDocPerEntry, force, space, context); } else { return 0; } } catch (Exception e) { Map<String, Exception> map = (Map<String, Exception>) context.get("updateFeedError"); if (map == null) { map = new HashMap<String, Exception>(); context.put("updateFeedError", map); } map.put(feedurl, e); } return -1; } private int saveFeed(String feedname, String feedurl, SyndFeed feed, boolean fullContent, boolean oneDocPerEntry, boolean force, XWikiContext context) throws XWikiException { return saveFeed(feedname, feedurl, feed, fullContent, oneDocPerEntry, force, "Feeds", context); } private int saveFeed(String feedname, String feedurl, SyndFeed feed, boolean fullContent, boolean oneDocPerEntry, boolean force, String space, XWikiContext context) throws XWikiException { XWikiDocument doc = null; Vector<BaseObject> objs = null; int nbtotal = 0; String prefix = space + ".Feed"; if (!oneDocPerEntry) { doc = context.getWiki().getDocument( prefix + "_" + context.getWiki().clearName(feedname, true, true, context), context); objs = doc.getObjects("XWiki.FeedEntryClass"); if ((doc.getContent() == null) || doc.getContent().trim().equals("")) { doc.setContent("#includeForm(\"XWiki.FeedEntryClassSheet\")"); doc.setSyntaxId(XWikiDocument.XWIKI10_SYNTAXID); } } List<SyndEntry> entries = feed.getEntries(); int nb = entries.size(); for (int i = nb - 1; i >= 0; i--) { SyndEntry entry = entries.get(i); if (oneDocPerEntry) { String hashCode = "" + entry.getLink().hashCode(); String pagename = feedname + "_" + hashCode.replaceAll("-", "") + "_" + entry.getTitle(); doc = context.getWiki().getDocument( prefix + "_" + context.getWiki().clearName(pagename, true, true, context), context); if (doc.isNew() || force) { // Set the document date to the current date doc.setDate(new Date()); // Set the creation date to the feed date if it exists, otherwise the current date Date adate = (entry.getPublishedDate() == null) ? new Date() : entry.getPublishedDate(); doc.setCreationDate(adate); if ((doc.getContent() == null) || doc.getContent().trim().equals("")) { doc.setContent("#includeForm(\"XWiki.FeedEntryClassSheet\")"); doc.setSyntaxId(XWikiDocument.XWIKI10_SYNTAXID); } if (force) { BaseObject obj = doc.getObject("XWiki.FeedEntryClass"); if (obj == null) { saveEntry(feedname, feedurl, entry, doc, fullContent, context); } else { saveEntry(feedname, feedurl, entry, doc, obj, fullContent, context); } } else { saveEntry(feedname, feedurl, entry, doc, fullContent, context); } nbtotal++; context.getWiki().saveDocument(doc, context); } } else { BaseObject obj = postExist(objs, entry, context); if (obj == null) { saveEntry(feedname, feedurl, entry, doc, fullContent, context); nbtotal++; } else if (force) { saveEntry(feedname, feedurl, entry, doc, obj, fullContent, context); nbtotal++; } } } if (!oneDocPerEntry) { context.getWiki().saveDocument(doc, context); } return nbtotal; } public BaseClass getAggregatorURLClass(XWikiContext context) throws XWikiException { XWikiDocument doc; boolean needsUpdate = false; doc = context.getWiki().getDocument("XWiki.AggregatorURLClass", context); BaseClass bclass = doc.getxWikiClass(); if (context.get("initdone") != null) { return bclass; } bclass.setName("XWiki.AggregatorURLClass"); if (!"internal".equals(bclass.getCustomMapping())) { needsUpdate = true; bclass.setCustomMapping("internal"); } needsUpdate |= bclass.addTextField("name", "Name", 80); needsUpdate |= bclass.addTextField("url", "url", 80); needsUpdate |= bclass.addTextField("imgurl", "Image url", 80); needsUpdate |= bclass.addDateField("date", "date", "dd/MM/yyyy HH:mm:ss"); needsUpdate |= bclass.addNumberField("nb", "nb", 5, "integer"); if (StringUtils.isBlank(doc.getCreator())) { needsUpdate = true; doc.setCreator(XWikiRightService.SUPERADMIN_USER); } if (StringUtils.isBlank(doc.getAuthor())) { needsUpdate = true; doc.setAuthor(doc.getCreator()); } if (StringUtils.isBlank(doc.getTitle())) { needsUpdate = true; doc.setTitle("XWiki Aggregator URL Class"); } if (StringUtils.isBlank(doc.getContent()) || !XWikiDocument.XWIKI20_SYNTAXID.equals(doc.getSyntaxId())) { needsUpdate = true; doc.setContent("{{include document=\"XWiki.ClassSheet\" /}}"); doc.setSyntaxId(XWikiDocument.XWIKI20_SYNTAXID); } if (StringUtils.isBlank(doc.getParent())) { needsUpdate = true; doc.setParent("XWiki.XWikiClasses"); } if (needsUpdate) { context.getWiki().saveDocument(doc, context); } return bclass; } public BaseClass getFeedEntryClass(XWikiContext context) throws XWikiException { XWikiDocument doc; boolean needsUpdate = false; doc = context.getWiki().getDocument("XWiki.FeedEntryClass", context); BaseClass bclass = doc.getxWikiClass(); if (context.get("initdone") != null) { return bclass; } bclass.setName("XWiki.FeedEntryClass"); if (!"internal".equals(bclass.getCustomMapping())) { needsUpdate = true; bclass.setCustomMapping("internal"); } needsUpdate |= bclass.addTextField("title", "Title", 80); needsUpdate |= bclass.addTextField("author", "Author", 40); needsUpdate |= bclass.addTextField("feedurl", "Feed URL", 80); needsUpdate |= bclass.addTextField("feedname", "Feed Name", 40); needsUpdate |= bclass.addTextField("url", "URL", 80); needsUpdate |= bclass.addTextField("category", "Category", 255); needsUpdate |= bclass.addTextAreaField("content", "Content", 80, 10); needsUpdate |= bclass.addTextAreaField("fullContent", "Full Content", 80, 10); needsUpdate |= bclass.addTextAreaField("xml", "XML", 80, 10); needsUpdate |= bclass.addDateField("date", "date", "dd/MM/yyyy HH:mm:ss"); needsUpdate |= bclass.addNumberField("flag", "Flag", 5, "integer"); needsUpdate |= bclass.addNumberField("read", "Read", 5, "integer"); needsUpdate |= bclass.addStaticListField("tags", "Tags", 1, true, true, "", null, null); if (StringUtils.isBlank(doc.getCreator())) { needsUpdate = true; doc.setCreator(XWikiRightService.SUPERADMIN_USER); } if (StringUtils.isBlank(doc.getAuthor())) { needsUpdate = true; doc.setAuthor(doc.getCreator()); } if (StringUtils.isBlank(doc.getTitle())) { needsUpdate = true; doc.setTitle("XWiki Feed Entry Class"); } if (StringUtils.isBlank(doc.getContent()) || !XWikiDocument.XWIKI20_SYNTAXID.equals(doc.getSyntaxId())) { needsUpdate = true; doc.setContent("{{include document=\"XWiki.ClassSheet\" /}}"); doc.setSyntaxId(XWikiDocument.XWIKI20_SYNTAXID); } if (StringUtils.isBlank(doc.getParent())) { needsUpdate = true; doc.setParent("XWiki.XWikiClasses"); } if (needsUpdate) { context.getWiki().saveDocument(doc, context); } return bclass; } private void saveEntry(String feedname, String feedurl, SyndEntry entry, XWikiDocument doc, boolean fullContent, XWikiContext context) throws XWikiException { int id = doc.createNewObject("XWiki.FeedEntryClass", context); BaseObject obj = doc.getObject("XWiki.FeedEntryClass", id); saveEntry(feedname, feedurl, entry, doc, obj, fullContent, context); } private void saveEntry(String feedname, String feedurl, SyndEntry entry, XWikiDocument doc, BaseObject obj, boolean fullContent, XWikiContext context) throws XWikiException { obj.setStringValue("feedname", feedname); obj.setStringValue("title", entry.getTitle()); // set document title to the feed title doc.setTitle(entry.getTitle()); obj.setIntValue("flag", 0); List<SyndCategory> categList = entry.getCategories(); StringBuffer categs = new StringBuffer(""); if (categList != null) { for (SyndCategory categ : categList) { if (categs.length() != 0) { categs.append(", "); } categs.append(categ.getName()); } } obj.setStringValue("category", categs.toString()); StringBuffer contents = new StringBuffer(""); String description = (entry.getDescription() == null) ? null : entry.getDescription().getValue(); List<SyndContent> contentList = entry.getContents(); if (contentList != null && contentList.size() > 0) { for (SyndContent content : contentList) { if (contents.length() != 0) { contents.append("\n"); } contents.append(content.getValue()); } } // If we find more data in the description we will use that one instead of the content field if ((description != null) && (description.length() > contents.length())) { obj.setLargeStringValue("content", description); } else { obj.setLargeStringValue("content", contents.toString()); } Date edate = entry.getPublishedDate(); if (edate == null) { edate = new Date(); } obj.setDateValue("date", edate); obj.setStringValue("url", entry.getLink()); obj.setStringValue("author", entry.getAuthor()); obj.setStringValue("feedurl", feedurl); // TODO: need to get entry xml or serialization // obj.setLargeStringValue("xml", entry.toString()); obj.setLargeStringValue("xml", ""); if (fullContent) { String url = entry.getLink(); if ((url != null) && (!url.trim().equals(""))) { try { String sfullContent = context.getWiki().getURLContent(url, context); obj.setLargeStringValue("fullContent", (sfullContent.length() > 65000) ? sfullContent.substring(0, 65000) : sfullContent); } catch (Exception e) { obj.setLargeStringValue("fullContent", "Exception while reading fullContent: " + e.getMessage()); } } else { obj.setLargeStringValue("fullContent", "No url"); } } } private BaseObject postExist(Vector<BaseObject> objs, SyndEntry entry, XWikiContext context) { if (objs == null) { return null; } String title = context.getWiki().clearName(entry.getTitle(), true, true, context); for (BaseObject obj : objs) { if (obj != null) { String title2 = obj.getStringValue("title"); if (title2 == null) { title2 = ""; } else { title2 = context.getWiki().clearName(title2, true, true, context); } if (title2.compareTo(title) == 0) { return obj; } } } return null; } public List search(String query, XWikiContext context) throws XWikiException { String[] queryTab = query.split(" "); if (queryTab.length > 0) { String sql = "select distinct obj.number, obj.name from BaseObject as obj, StringProperty as prop , LargeStringProperty as lprop " + "where obj.className='XWiki.FeedEntryClass' and obj.id=prop.id.id and obj.id=lprop.id.id "; for (int i = 0; i < queryTab.length; i++) { sql += " and (prop.value LIKE '%" + queryTab[i] + "%' or lprop.value LIKE '%" + queryTab[i] + "%')"; } List<Object[]> res = context.getWiki().search(sql, context); if (res == null) { return null; } List<com.xpn.xwiki.api.Object> apiObjs = new ArrayList<com.xpn.xwiki.api.Object>(); for (Object obj[] : res) { try { XWikiDocument doc = context.getWiki().getDocument((String) obj[1], context); if (context.getWiki().getRightService().checkAccess("view", doc, context)) { BaseObject bObj = doc.getObject("XWiki.FeedEntryClass", ((Integer) obj[0]).intValue()); com.xpn.xwiki.api.Object apiObj = new com.xpn.xwiki.api.Object(bObj, context); apiObjs.add(apiObj); } } catch (Exception e) { Map<String, Exception> map = (Map<String, Exception>) context.get("searchFeedError"); if (map == null) { map = new HashMap<String, Exception>(); context.put("searchFeedError", map); } map.put(query, e); } } Collections.sort(apiObjs, new EntriesComparator()); return apiObjs; } return null; } public com.xpn.xwiki.api.Object getFeedInfosbyGuid(String guid, XWikiContext context) throws XWikiException { return getFeedInfosbyGuid("XWiki.FeedList", guid, context); } public com.xpn.xwiki.api.Object getFeedInfosbyGuid(String feedDoc, String guid, XWikiContext context) throws XWikiException { XWikiDocument doc = context.getWiki().getDocument(feedDoc, context); Vector<BaseObject> objs = doc.getObjects("XWiki.AggregatorURLClass"); for (BaseObject obj : objs) { if (guid.compareTo(obj.getStringValue("guid")) == 0) { return new com.xpn.xwiki.api.Object(obj, context); } } return null; } /** * @see FeedPluginApi#getSyndEntrySource(String, Map) */ public SyndEntrySource getSyndEntrySource(String className, Map<String, Object> params, XWikiContext context) throws XWikiException { try { Class< ? extends SyndEntrySource> sesc = Class.forName(className).asSubclass(SyndEntrySource.class); Constructor< ? extends SyndEntrySource> ctor = null; if (params != null) { try { ctor = sesc.getConstructor(new Class[] {Map.class}); return ctor.newInstance(new Object[] {params}); } catch (Throwable t) { } } ctor = sesc.getConstructor(new Class[] {}); return ctor.newInstance(new Object[] {}); } catch (Throwable t) { throw new XWikiException(XWikiException.MODULE_XWIKI_PLUGINS, XWikiException.ERROR_XWIKI_UNKNOWN, "", t); } } /** * @see FeedPluginApi#getFeedEntry() */ public SyndEntry getFeedEntry(XWikiContext context) { return new SyndEntryImpl(); } /** * @see FeedPluginApi#getFeedImage() */ public SyndImage getFeedImage(XWikiContext context) { return new SyndImageImpl(); } /** * @see FeedPluginApi#getFeed() */ public SyndFeed getFeed(XWikiContext context) { return new SyndFeedImpl(); } /** * @see FeedPluginApi#getFeed(List, SyndEntrySourceApi, Map) */ public SyndFeed getFeed(List<Object> list, SyndEntrySource source, Map<String, Object> sourceParams, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(context); List<SyndEntry> entries = new ArrayList<SyndEntry>(); for (int i = 0; i < list.size(); i++) { SyndEntry entry = getFeedEntry(context); try { source.source(entry, list.get(i), sourceParams, context); entries.add(entry); } catch (Throwable t) { // skip this entry } } feed.setEntries(entries); return feed; } /** * @see FeedPluginApi#getFeed(String, int, int, SyndEntrySourceApi, Map) */ public SyndFeed getFeed(String query, int count, int start, SyndEntrySource source, Map<String, Object> sourceParams, XWikiContext context) throws XWikiException { List<Object> entries = new ArrayList<Object>(); entries.addAll(context.getWiki().getStore().searchDocumentsNames(query, count, start, context)); return getFeed(entries, source, sourceParams, context); } /** * @see FeedPluginApi#getFeed(List, SyndEntrySourceApi, Map, Map) */ public SyndFeed getFeed(List<Object> list, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(list, source, sourceParams, context); fillFeedMetadata(feed, metadata); return feed; } /** * @see FeedPluginApi#getFeed(String, int, int, SyndEntrySourceApi, Map, Map) */ public SyndFeed getFeed(String query, int count, int start, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(query, count, start, source, sourceParams, context); fillFeedMetadata(feed, metadata); return feed; } private void fillFeedMetadata(SyndFeed feed, Map<String, Object> metadata) { feed.setAuthor(String.valueOf(metadata.get("author"))); feed.setDescription(String.valueOf(metadata.get("description"))); feed.setCopyright(String.valueOf(metadata.get("copyright"))); feed.setEncoding(String.valueOf(metadata.get("encoding"))); // TODO: rename "url" to "link" for consistency ? feed.setLink(String.valueOf(metadata.get("url"))); feed.setTitle(String.valueOf(metadata.get("title"))); feed.setLanguage(String.valueOf(metadata.get("language"))); } /** * @see FeedPluginApi#getFeedOutput(SyndFeed, String) */ public String getFeedOutput(SyndFeed feed, String type, XWikiContext context) { feed.setFeedType(type); StringWriter writer = new StringWriter(); SyndFeedOutput output = new SyndFeedOutput(); try { output.output(feed, writer); writer.close(); return writer.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * @see FeedPluginApi#getFeedOutput(List, SyndEntrySourceApi, Map, Map, String) */ public String getFeedOutput(List<Object> list, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, String type, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(list, source, sourceParams, metadata, context); return getFeedOutput(feed, type, context); } /** * @see FeedPluginApi#getFeedOutput(String, int, int, SyndEntrySourceApi, Map, Map, String) */ public String getFeedOutput(String query, int count, int start, SyndEntrySource source, Map<String, Object> sourceParams, Map<String, Object> metadata, String type, XWikiContext context) throws XWikiException { SyndFeed feed = getFeed(query, count, start, source, sourceParams, metadata, context); return getFeedOutput(feed, type, context); } }
[cleanup] Improved codestyle git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@25710 f329d543-caf0-0310-9063-dda96c69346f
xwiki-core/src/main/java/com/xpn/xwiki/plugin/feed/FeedPlugin.java
[cleanup] Improved codestyle
<ide><path>wiki-core/src/main/java/com/xpn/xwiki/plugin/feed/FeedPlugin.java <ide> return feed; <ide> } catch (Exception ex) { <ide> if (ignoreInvalidFeeds) { <add> @SuppressWarnings("unchecked") <ide> Map<String, Exception> map = (Map<String, Exception>) context.get("invalidFeeds"); <ide> if (map == null) { <ide> map = new HashMap<String, Exception>(); <ide> return 0; <ide> } <ide> } catch (Exception e) { <add> @SuppressWarnings("unchecked") <ide> Map<String, Exception> map = (Map<String, Exception>) context.get("updateFeedError"); <ide> if (map == null) { <ide> map = new HashMap<String, Exception>(); <ide> map.put(feedurl, e); <ide> } <ide> return -1; <del> } <del> <del> private int saveFeed(String feedname, String feedurl, SyndFeed feed, boolean fullContent, boolean oneDocPerEntry, <del> boolean force, XWikiContext context) throws XWikiException <del> { <del> return saveFeed(feedname, feedurl, feed, fullContent, oneDocPerEntry, force, "Feeds", context); <ide> } <ide> <ide> private int saveFeed(String feedname, String feedurl, SyndFeed feed, boolean fullContent, boolean oneDocPerEntry, <ide> } <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> List<SyndEntry> entries = feed.getEntries(); <ide> int nb = entries.size(); <ide> for (int i = nb - 1; i >= 0; i--) { <ide> // set document title to the feed title <ide> doc.setTitle(entry.getTitle()); <ide> obj.setIntValue("flag", 0); <add> @SuppressWarnings("unchecked") <ide> List<SyndCategory> categList = entry.getCategories(); <ide> StringBuffer categs = new StringBuffer(""); <ide> if (categList != null) { <ide> StringBuffer contents = new StringBuffer(""); <ide> String description = (entry.getDescription() == null) ? null : entry.getDescription().getValue(); <ide> <add> @SuppressWarnings("unchecked") <ide> List<SyndContent> contentList = entry.getContents(); <ide> if (contentList != null && contentList.size() > 0) { <ide> for (SyndContent content : contentList) { <ide> return null; <ide> } <ide> <del> public List search(String query, XWikiContext context) throws XWikiException <add> public List<com.xpn.xwiki.api.Object> search(String query, XWikiContext context) throws XWikiException <ide> { <ide> String[] queryTab = query.split(" "); <ide> <ide> apiObjs.add(apiObj); <ide> } <ide> } catch (Exception e) { <add> @SuppressWarnings("unchecked") <ide> Map<String, Exception> map = (Map<String, Exception>) context.get("searchFeedError"); <ide> if (map == null) { <ide> map = new HashMap<String, Exception>();
Java
mit
7fc601af00c99afad9300cf3b930d7246f7ae04d
0
mairdl/jabref,Siedlerchr/jabref,Mr-DLib/jabref,Braunch/jabref,ayanai1/jabref,tschechlovdev/jabref,jhshinn/jabref,Siedlerchr/jabref,shitikanth/jabref,mairdl/jabref,JabRef/jabref,obraliar/jabref,oscargus/jabref,mredaelli/jabref,tobiasdiez/jabref,sauliusg/jabref,Mr-DLib/jabref,oscargus/jabref,bartsch-dev/jabref,Braunch/jabref,obraliar/jabref,jhshinn/jabref,Braunch/jabref,sauliusg/jabref,obraliar/jabref,mredaelli/jabref,zellerdev/jabref,motokito/jabref,mairdl/jabref,Siedlerchr/jabref,ayanai1/jabref,Mr-DLib/jabref,Braunch/jabref,zellerdev/jabref,JabRef/jabref,tschechlovdev/jabref,jhshinn/jabref,JabRef/jabref,Mr-DLib/jabref,mairdl/jabref,zellerdev/jabref,Braunch/jabref,oscargus/jabref,shitikanth/jabref,JabRef/jabref,Mr-DLib/jabref,grimes2/jabref,mredaelli/jabref,mredaelli/jabref,tobiasdiez/jabref,motokito/jabref,ayanai1/jabref,oscargus/jabref,motokito/jabref,bartsch-dev/jabref,Siedlerchr/jabref,mairdl/jabref,shitikanth/jabref,motokito/jabref,tobiasdiez/jabref,oscargus/jabref,mredaelli/jabref,grimes2/jabref,obraliar/jabref,motokito/jabref,ayanai1/jabref,grimes2/jabref,bartsch-dev/jabref,tobiasdiez/jabref,sauliusg/jabref,shitikanth/jabref,zellerdev/jabref,zellerdev/jabref,bartsch-dev/jabref,shitikanth/jabref,jhshinn/jabref,bartsch-dev/jabref,grimes2/jabref,grimes2/jabref,obraliar/jabref,jhshinn/jabref,sauliusg/jabref,ayanai1/jabref,tschechlovdev/jabref,tschechlovdev/jabref,tschechlovdev/jabref
/////////////////////////////////////////////////////////////////////////////// // Filename: $RCSfile$ // Purpose: Atom representation. // Language: Java // Compiler: JDK 1.4 // Authors: Joerg K. Wegner // Version: $Revision$ // $Date$ // $Author$ // // Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany // // 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 version 2 of the License. // // 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. /////////////////////////////////////////////////////////////////////////////// package net.sf.jabref.export.layout.format; import net.sf.jabref.export.layout.LayoutFormatter; /** * Remove non printable character formatter. * * Based on the RemoveBrackets.java class (Revision 1.2) by mortenalver * * @author $author$ * @version $Revision$ */ public class RemoveWhitespace implements LayoutFormatter { public String format(String fieldEntry) { StringBuilder sb = new StringBuilder(fieldEntry.length()); for (char c : fieldEntry.toCharArray()) { if (!Character.isWhitespace(c) || Character.isSpaceChar(c)) { sb.append(c); } } return sb.toString(); } }
src/java/net/sf/jabref/export/layout/format/RemoveWhitespace.java
/////////////////////////////////////////////////////////////////////////////// // Filename: $RCSfile$ // Purpose: Atom representation. // Language: Java // Compiler: JDK 1.4 // Authors: Joerg K. Wegner // Version: $Revision$ // $Date$ // $Author$ // // Copyright (c) Dept. Computer Architecture, University of Tuebingen, Germany // // 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 version 2 of the License. // // 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. /////////////////////////////////////////////////////////////////////////////// package net.sf.jabref.export.layout.format; import net.sf.jabref.export.layout.LayoutFormatter; /** * Remove non printable character formatter. * * Based on the RemoveBrackets.java class (Revision 1.2) by mortenalver * @author $author$ * @version $Revision$ */ public class RemoveWhitespace implements LayoutFormatter { //~ Methods //////////////////////////////////////////////////////////////// public String format(String fieldText) { String fieldEntry = fieldText; StringBuffer sb = new StringBuffer(fieldEntry.length()); for (int i = 0; i < fieldEntry.length(); i++) { //System.out.print(fieldEntry.charAt(i)); if ( !Character.isWhitespace(fieldEntry.charAt(i)) || Character.isSpaceChar(fieldEntry.charAt(i))) { //System.out.print(fieldEntry.charAt(i)); sb.append(fieldEntry.charAt(i)); } } fieldEntry = sb.toString(); return fieldEntry; } } /////////////////////////////////////////////////////////////////////////////// // END OF FILE. ///////////////////////////////////////////////////////////////////////////////
Reformatted for readability. Some improvements for speed-up.
src/java/net/sf/jabref/export/layout/format/RemoveWhitespace.java
Reformatted for readability.
<ide><path>rc/java/net/sf/jabref/export/layout/format/RemoveWhitespace.java <ide> <ide> import net.sf.jabref.export.layout.LayoutFormatter; <ide> <del> <ide> /** <ide> * Remove non printable character formatter. <del> * <add> * <ide> * Based on the RemoveBrackets.java class (Revision 1.2) by mortenalver <add> * <ide> * @author $author$ <ide> * @version $Revision$ <ide> */ <del>public class RemoveWhitespace implements LayoutFormatter <del>{ <del> //~ Methods //////////////////////////////////////////////////////////////// <add>public class RemoveWhitespace implements LayoutFormatter { <ide> <del> public String format(String fieldText) <del> { <del> String fieldEntry = fieldText; <del> StringBuffer sb = new StringBuffer(fieldEntry.length()); <add> public String format(String fieldEntry) { <ide> <del> for (int i = 0; i < fieldEntry.length(); i++) <del> { <del> //System.out.print(fieldEntry.charAt(i)); <del> if ( !Character.isWhitespace(fieldEntry.charAt(i)) || Character.isSpaceChar(fieldEntry.charAt(i))) <del> { <del> //System.out.print(fieldEntry.charAt(i)); <del> sb.append(fieldEntry.charAt(i)); <add> StringBuilder sb = new StringBuilder(fieldEntry.length()); <add> <add> for (char c : fieldEntry.toCharArray()) { <add> if (!Character.isWhitespace(c) || Character.isSpaceChar(c)) { <add> sb.append(c); <ide> } <ide> } <ide> <del> fieldEntry = sb.toString(); <del> return fieldEntry; <add> return sb.toString(); <ide> } <ide> } <del>/////////////////////////////////////////////////////////////////////////////// <del>// END OF FILE. <del>///////////////////////////////////////////////////////////////////////////////
Java
apache-2.0
1bec95ee186451bb02dda3b5b8fed212207c81e3
0
vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,ibinti/intellij-community,allotria/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,FHannes/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,signed/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,FHannes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ibinti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,signed/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,allotria/intellij-community,suncycheng/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,ibinti/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,vvv1559/intellij-community,signed/intellij-community,mglukhikh/intellij-community
/* /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui.tree; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.lang.LanguagePerFileMappings; import com.intellij.lang.PerFileMappings; import com.intellij.lang.PerFileMappingsBase; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.actionSystem.impl.SimpleDataContext; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.ui.components.JBLabel; import com.intellij.ui.speedSearch.SpeedSearchUtil; import com.intellij.ui.table.JBTable; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.AbstractTableCellEditor; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.MouseEvent; import java.io.File; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static com.intellij.ui.IdeBorderFactory.*; /** * @author peter */ public abstract class PerFileConfigurableBase<T> implements SearchableConfigurable, Configurable.NoScroll { protected static final Key<String> DESCRIPTION = KeyWithDefaultValue.create("DESCRIPTION", ""); protected static final Key<String> TARGET_TITLE = KeyWithDefaultValue.create("TARGET_TITLE", "Path"); protected static final Key<String> MAPPING_TITLE = KeyWithDefaultValue.create("MAPPING_TITLE", "Mapping"); protected static final Key<String> EMPTY_TEXT = KeyWithDefaultValue.create("EMPTY_TEXT", "New Mapping $addShortcut"); protected static final Key<String> OVERRIDE_QUESTION = Key.create("OVERRIDE_QUESTION"); protected static final Key<String> OVERRIDE_TITLE = Key.create("OVERRIDE_TITLE"); protected static final Key<String> CLEAR_TEXT = KeyWithDefaultValue.create("CLEAR_TEXT", "<Clear>"); protected static final Key<String> NULL_TEXT = KeyWithDefaultValue.create("NULL_TEXT", "<None>"); protected final Project myProject; protected final PerFileMappings<T> myMappings; /** @noinspection FieldCanBeLocal */ private JPanel myPanel; private JBTable myTable; private MyModel<T> myModel; private final List<Runnable> myResetRunnables = ContainerUtil.newArrayList(); private final Map<String, T> myDefaultVals = ContainerUtil.newHashMap(); private final List<Trinity<String, Producer<T>, Consumer<T>>> myDefaultProps = ContainerUtil.newArrayList(); private VirtualFile myFileToSelect; protected PerFileConfigurableBase(@NotNull Project project, @NotNull PerFileMappings<T> mappings) { myProject = project; myMappings = mappings; } @Override @NotNull public String getId() { return getDisplayName(); } @Nullable protected abstract <S> Object getParameter(@NotNull Key<S> key); @NotNull protected List<Trinity<String, Producer<T>, Consumer<T>>> getDefaultMappings() { return ContainerUtil.emptyList(); } protected boolean canRemoveTarget(@Nullable Object target) { return true; } protected boolean canEditTarget(@Nullable Object target, T value) { return true; } protected T adjustChosenValue(@Nullable Object target, T chosen) { return chosen; } protected abstract void renderValue(@Nullable Object target, @NotNull T t, @NotNull ColoredTextContainer renderer); protected void renderDefaultValue(@Nullable Object target, @NotNull ColoredTextContainer renderer) { } private <S> S param(@NotNull Key<S> key) { Object o = getParameter(key); if (o == null && key instanceof KeyWithDefaultValue) return ((KeyWithDefaultValue<S>)key).getDefaultValue(); //noinspection unchecked return (S)o; } @NotNull @Override public JComponent createComponent() { //todo multi-editing, separate project/ide combos _if_ needed by specific configurable (SQL, no Web) myPanel = new JPanel(new BorderLayout()); myTable = new JBTable(myModel = new MyModel<>(param(TARGET_TITLE), param(MAPPING_TITLE))) { @Override public String getToolTipText(@NotNull MouseEvent event) { Point point = event.getPoint(); int row = rowAtPoint(point); int col = columnAtPoint(point); if (row != -1 && col == 1) return getToolTipFor((T)getValueAt(convertRowIndexToModel(row), col)); return super.getToolTipText(event); } }; setupPerFileTable(); JPanel tablePanel = ToolbarDecorator.createDecorator(myTable) .disableUpAction() .disableDownAction() .setAddAction(button -> doAddAction(button)) .setRemoveAction(button -> doRemoveAction(button)) .setEditAction(button -> doEditAction(button)) .setEditActionUpdater(e -> myTable.getSelectedRows().length > 0) .createPanel(); myTable.getEmptyText().setText(param(EMPTY_TEXT).replace( "$addShortcut", KeymapUtil.getFirstKeyboardShortcutText(CommonActionsPanel.getCommonShortcut(CommonActionsPanel.Buttons.ADD)))); JBLabel label = new JBLabel(param(DESCRIPTION)); label.setBorder(BorderFactory.createEmptyBorder(TITLED_BORDER_TOP_INSET, TITLED_BORDER_INDENT, TITLED_BORDER_BOTTOM_INSET, 0)); label.setComponentStyle(UIUtil.ComponentStyle.SMALL); JComponent north = createDefaultMappingComponent(); if (north != null) { myPanel.add(north, BorderLayout.NORTH); } myPanel.add(label, BorderLayout.SOUTH); myPanel.add(tablePanel, BorderLayout.CENTER); return myPanel; } protected String getToolTipFor(T value) { return null; } @Nullable protected JComponent createDefaultMappingComponent() { myDefaultProps.addAll(getDefaultMappings()); if (myMappings instanceof LanguagePerFileMappings) { myDefaultProps.add(Trinity.create("Project " + StringUtil.capitalize(param(MAPPING_TITLE)), () -> ((LanguagePerFileMappings<T>)myMappings).getConfiguredMapping(null), o -> myMappings.setMapping(null, o))); } if (myDefaultProps.size() == 0) return null; JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints cons1 = new GridBagConstraints(); cons1.fill = GridBagConstraints.HORIZONTAL; cons1.weightx = 0; cons1.gridx = 0; cons1.insets = JBUI.insets(0, 0, 5, UIUtil.DEFAULT_HGAP); GridBagConstraints cons2 = new GridBagConstraints(); cons2.fill = GridBagConstraints.NONE; cons2.anchor = GridBagConstraints.WEST; cons2.weightx = 0; cons2.gridx = 1; cons2.insets = cons1.insets; panel.add(Box.createGlue(), new GridBagConstraints(2, 0, 1, 1, 1., 1., GridBagConstraints.CENTER, GridBagConstraints.NONE, JBUI.emptyInsets(), 0, 0)); for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { myDefaultVals.put(prop.first, prop.second.produce()); JPanel p = createActionPanel(null, () -> myDefaultVals.get(prop.first), o -> myDefaultVals.put(prop.first, adjustChosenValue(null, o))); panel.add(new JBLabel(prop.first + ":"), cons1); panel.add(p, cons2); } return panel; } private void doAddAction(@NotNull AnActionButton button) { TableCellEditor editor = myTable.getCellEditor(); if (editor != null) editor.cancelCellEditing(); int row = myTable.getSelectedRow(); Object selectedTarget = row >= 0 ? myModel.data.get(myTable.convertRowIndexToModel(row)).first : null; VirtualFile toSelect = myFileToSelect != null ? myFileToSelect : ObjectUtils.tryCast(selectedTarget, VirtualFile.class); FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, true, true, true, true); Set<VirtualFile> chosen = ContainerUtil.newHashSet(FileChooser.chooseFiles(descriptor, myProject, toSelect)); if (chosen.isEmpty()) return; Set<Object> set = myModel.data.stream().map(o -> o.first).collect(Collectors.toSet()); for (VirtualFile file : chosen) { if (!set.add(file)) continue; myModel.data.add(Pair.create(file, null)); } fireMappingChanged(); TIntArrayList rowList = new TIntArrayList(); for (int i = 0, size = myModel.data.size(); i < size; i++) { if (chosen.contains(myModel.data.get(i).first)) rowList.add(i); } int[] rows = rowList.toNativeArray(); for (int i = 0; i < rows.length; i++) { rows[i] = myTable.convertRowIndexToView(rows[i]); } TableUtil.selectRows(myTable, rows); } private void doRemoveAction(@NotNull AnActionButton button) { TableCellEditor editor = myTable.getCellEditor(); if (editor != null) editor.cancelCellEditing(); int[] rows = myTable.getSelectedRows(); int firstRow = rows[0]; Object[] keys = new Object[rows.length]; for (int i = 0; i < rows.length; i++) { keys[i] = myModel.data.get(myTable.convertRowIndexToModel(rows[i])).first; } if (clearSubdirectoriesOnDemandOrCancel(true, keys)) { int toSelect = Math.min(myModel.data.size() - 1, firstRow); if (toSelect >= 0) { TableUtil.selectRows(myTable, new int[]{toSelect}); } } } private void doEditAction(@NotNull AnActionButton button) { TableUtil.editCellAt(myTable, myTable.getSelectedRow(), 1); } @Nullable public T getNewMapping(VirtualFile file) { for (Pair<Object, T> p : ContainerUtil.reverse(myModel.data)) { if (keyMatches(p.first, file, false) && p.second != null) return p.second; } for (Trinity<String, Producer<T>, Consumer<T>> prop : ContainerUtil.reverse(myDefaultProps)) { if (prop.first.startsWith("Project ") || prop.first.startsWith("Global ")) { T t = myDefaultVals.get(prop.first); if (t != null) return t; } } return myMappings.getDefaultMapping(file); } private boolean keyMatches(Object key, VirtualFile file, boolean strict) { if (key instanceof VirtualFile) return VfsUtilCore.isAncestor((VirtualFile)key, file, strict); // todo also patterns if (key == null) return true; return false; } @Override public boolean isModified() { for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { if (!Comparing.equal(prop.second.produce(), myDefaultVals.get(prop.first))) { return true; } } Map<VirtualFile, T> oldMapping = myMappings.getMappings(); Map<VirtualFile, T> newMapping = getNewMappings(); return !newMapping.equals(oldMapping); } @Override public void apply() throws ConfigurationException { myMappings.setMappings(getNewMappings()); for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { prop.third.consume(myDefaultVals.get(prop.first)); } } @Override public void reset() { myModel.data.clear(); for (Map.Entry<VirtualFile, T> e : myMappings.getMappings().entrySet()) { if (myMappings instanceof LanguagePerFileMappings && e.getKey() == null) continue; myModel.data.add(Pair.create(e.getKey(), e.getValue())); } for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { myDefaultVals.put(prop.first, prop.second.produce()); } for (Runnable runnable : myResetRunnables) { runnable.run(); } int[] rows = myTable.getSelectedRows(); fireMappingChanged(); TableUtil.selectRows(myTable, rows); } protected void fireMappingChanged() { Collections.sort(myModel.data, (o1, o2) -> StringUtil.naturalCompare(keyToString(o1.first), keyToString(o2.first))); myModel.fireTableDataChanged(); } protected Map<VirtualFile, T> getNewMappings() { HashMap<VirtualFile, T> map = ContainerUtil.newHashMap(); for (Pair<Object, T> p : myModel.data) { if (p.second != null) { map.put((VirtualFile)p.first, p.second); } } if (myMappings instanceof LanguagePerFileMappings) { for (Trinity<String, Producer<T>, Consumer<T>> prop : ContainerUtil.reverse(myDefaultProps)) { if (prop.first.startsWith("Project ")) { T t = myDefaultVals.get(prop.first); if (t != null) map.put(null, t); break; } } } return map; } public void selectFile(@NotNull VirtualFile virtualFile) { VirtualFile file = virtualFile instanceof VirtualFileWindow ? ((VirtualFileWindow)virtualFile).getDelegate() : virtualFile; int[] rows = findRow(file, false, false); for (int i = 0; i < rows.length; i++) { rows[i] = myTable.convertRowIndexToView(rows[i]); } TableUtil.selectRows(myTable, rows); TableUtil.scrollSelectionToVisible(myTable); myFileToSelect = file; } protected int[] findRow(VirtualFile file, boolean strict, boolean all) { TIntArrayList rows = new TIntArrayList(); List<Pair<Object, T>> reversed = ContainerUtil.reverse(myModel.data); for (int i = 0, size = reversed.size(); i < size; i++) { Pair<Object, T> p = reversed.get(i); if (keyMatches(p.first, file, strict)) { rows.add(size - i - 1); if (!all) break; } } return rows.toNativeArray(); } private static String keyToString(Object o) { if (o == null) return ""; if (o instanceof String) return (String)o; if (o instanceof VirtualFile) return ((VirtualFile)o).getPath(); return String.valueOf(o); } private void setupPerFileTable() { myTable.setEnableAntialiasing(true); myTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); myTable.setRowSelectionAllowed(true); myTable.setShowGrid(false); myTable.getColumnModel().setColumnMargin(0); myTable.getTableHeader().setReorderingAllowed(false); TableRowSorter<MyModel<T>> sorter = new TableRowSorter<>(myModel); sorter.setStringConverter(new TableStringConverter() { final SimpleColoredText text = new SimpleColoredText(); @Override public String toString(TableModel model, int row, int column) { text.clear(); Pair<Object, T> pair = myModel.data.get(row); if (column == 0) renderTarget(pair.first, text); else if (pair.second != null) renderValue(pair.first, pair.second, text); else renderDefaultValue(pair.first, text); return StringUtil.toLowerCase(text.toString()); } }); sorter.setSortable(0, true); sorter.setSortable(1, true); myTable.setRowSorter(sorter); new TableSpeedSearch(myTable, o -> keyToString(o)); FontMetrics metrics = myTable.getFontMetrics(myTable.getFont()); int maxValueWidth = 2 * metrics.stringWidth(myTable.getModel().getColumnName(1)); SimpleColoredText text = new SimpleColoredText(); for (T t : getValueVariants(null)) { text.clear(); renderValue(null, t, text); maxValueWidth = Math.max(metrics.stringWidth(text.toString()), maxValueWidth); } myTable.getColumnModel().getColumn(1).setMinWidth(maxValueWidth); myTable.getColumnModel().getColumn(1).setMaxWidth(2 * maxValueWidth); myTable.getColumnModel().getColumn(0).setCellRenderer(new ColoredTableCellRenderer() { @Override public void acquireState(JTable table, boolean isSelected, boolean hasFocus, int row, int column) { super.acquireState(table, isSelected, false, row, column); } @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) { renderTarget(value, this); SpeedSearchUtil.applySpeedSearchHighlighting(table, this, false, selected); } }); myTable.getColumnModel().getColumn(1).setCellRenderer(new ColoredTableCellRenderer() { @Override public void acquireState(JTable table, boolean isSelected, boolean hasFocus, int row, int column) { super.acquireState(table, isSelected, false, row, column); } @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) { Pair<Object, T> p = myModel.data.get(myTable.convertRowIndexToModel(row)); if (p.second != null) { setTransparentIconBackground(true); renderValue(p.first, p.second, this); } else { renderDefaultValue(p.first, this); } } }); myTable.getColumnModel().getColumn(1).setCellEditor(new AbstractTableCellEditor() { T editorValue; @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { int modelRow = myTable.convertRowIndexToModel(row); Pair<Object, T> pair = myModel.data.get(modelRow); Object target = pair.first; editorValue = pair.second; // (T)value if (!canEditTarget(target, editorValue)) return null; VirtualFile targetFile = target instanceof Project ? null : (VirtualFile)target; JPanel panel = createActionPanel(target, () -> editorValue, chosen -> { editorValue = adjustChosenValue(target, chosen); TableUtil.stopEditing(myTable); if (Comparing.equal(editorValue, chosen)) { // do nothing } else if (clearSubdirectoriesOnDemandOrCancel(false, targetFile)) { myModel.setValueAt(editorValue, modelRow, column); myModel.fireTableDataChanged(); selectFile(targetFile); } }, true); AbstractButton button = UIUtil.uiTraverser(panel).filter(JButton.class).first(); if (button != null) { AtomicInteger clickCount = new AtomicInteger(); button.addActionListener(e -> clickCount.incrementAndGet()); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { if (clickCount.get() == 0 && myTable.getEditorComponent() == panel) { button.doClick(); } }); } return panel; } @Override public Object getCellEditorValue() { return editorValue; } }); } @NotNull protected JPanel createActionPanel(@Nullable Object target, Producer<T> value, @NotNull Consumer<T> consumer) { return createActionPanel(target, value, consumer, false); } @NotNull private JPanel createActionPanel(@Nullable Object target, Producer<T> value, @NotNull Consumer<T> consumer, boolean editor) { AnAction changeAction = createValueAction(target, value, consumer); JComponent comboComponent = ((CustomComponentAction)changeAction).createCustomComponent(changeAction.getTemplatePresentation()); JPanel panel = new JPanel(new BorderLayout()) { @Override public Color getBackground() { // track "Table.selectionInactiveBackground" switch Container parent = getParent(); return parent instanceof JTable ? ((JTable)parent).getSelectionBackground() : super.getBackground(); } }; panel.add(comboComponent, BorderLayout.CENTER); comboComponent.setOpaque(false); DataContext dataContext = SimpleDataContext.getProjectContext(myProject); AnActionEvent event = AnActionEvent.createFromAnAction(changeAction, null, ActionPlaces.UNKNOWN, dataContext); changeAction.update(event); panel.revalidate(); if (!editor) myResetRunnables.add(() -> changeAction.update(null)); return panel; } private boolean clearSubdirectoriesOnDemandOrCancel(boolean keysToo, Object... keys) { TIntArrayList rows = new TIntArrayList(); boolean toOverride = false; for (int i = 0, size = myModel.data.size(); i < size; i++) { Pair<Object, T> p = myModel.data.get(i); if (p.first instanceof VirtualFile) { for (Object key : keys) { if (key == p.first) { if (keysToo) rows.add(-i - 1); break; } else if (keyMatches(key, (VirtualFile)p.first, true)) { toOverride = true; rows.add(i); break; } } } } int ret = !toOverride ? Messages.NO : askUserToOverrideSubdirectories(); if (ret == Messages.CANCEL) return false; int count = 0; for (int i : rows.toNativeArray()) { if (i >= 0 && ret == Messages.NO) continue; int index = (i >= 0 ? i : -i - 1) - count; if (canRemoveTarget(myModel.data.get(index).first)) { myModel.data.remove(index); count ++; } else { myModel.data.set(index, Pair.create(myModel.data.get(0).first, null)); } } if (!rows.isEmpty()) fireMappingChanged(); return true; } private int askUserToOverrideSubdirectories() { String question = param(OVERRIDE_QUESTION); String title = param(OVERRIDE_TITLE); if (question == null || title == null) return Messages.NO; return Messages.showYesNoCancelDialog( myProject, question, title, "Override", "Do Not Override", "Cancel", Messages.getWarningIcon()); } private String renderValue(@Nullable Object value, @NotNull String nullValue) { if (value == null) { return nullValue; } else { SimpleColoredText text = new SimpleColoredText(); renderValue(null, (T)value, text); return text.toString(); } } protected void renderTarget(@Nullable Object target, @NotNull ColoredTextContainer renderer) { VirtualFile file = target instanceof VirtualFile ? (VirtualFile)target : null; if (file != null) { renderer.setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); VirtualFile parent = file.getParent(); if (parent != null) { String parentPath = FileUtil.toSystemDependentName(parent.getPath()); renderer.append(parentPath, SimpleTextAttributes.GRAY_ATTRIBUTES); if (!parentPath.endsWith(File.separator)) { renderer.append(File.separator, SimpleTextAttributes.GRAY_ATTRIBUTES); } } renderer.append(file.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } else if (target == null) { renderer.append("Project", SimpleTextAttributes.GRAY_ATTRIBUTES); } } @NotNull protected final AnAction createValueAction(@Nullable Object target, Producer<T> value, @NotNull Consumer<T> consumer) { return new ComboBoxAction() { void updateText() { getTemplatePresentation().setText(renderValue(value.produce(), getNullValueText(target))); } @Override public void update(AnActionEvent e) { updateText(); } @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { throw new UnsupportedOperationException(); } @Override protected ComboBoxButton createComboBoxButton(Presentation presentation) { return new ComboBoxButton(presentation) { protected JBPopup createPopup(Runnable onDispose) { JBPopup popup = createValueEditorPopup(target, value.produce(), onDispose, getDataContext(), o -> { consumer.consume(o); updateText(); }); popup.setMinimumSize(new Dimension(getMinWidth(), getMinHeight())); return popup; } }; } }; } @NotNull protected JBPopup createValueEditorPopup(@Nullable Object target, @Nullable T value, @Nullable Runnable onDispose, @NotNull DataContext dataContext, @NotNull Consumer<T> onChosen) { return createValueEditorActionListPopup(target, onDispose, dataContext, onChosen); } @NotNull protected final JBPopup createValueEditorActionListPopup(@Nullable Object target, @Nullable Runnable onDispose, @NotNull DataContext dataContext, @NotNull Consumer<T> onChosen) { ActionGroup group = createActionListGroup(target, onChosen); return JBPopupFactory.getInstance().createActionGroupPopup( null, group, dataContext, false, false, false, onDispose, 30, null); } @Nullable protected Icon getActionListIcon(@Nullable Object target, T t) { return null; } @Nullable protected String getClearValueText(@Nullable Object target) { return target == null ? getNullValueText(null) : param(CLEAR_TEXT); } @Nullable protected String getNullValueText(@Nullable Object target) { return param(NULL_TEXT); } @NotNull protected Collection<T> getValueVariants(@Nullable Object target) { if (myMappings instanceof PerFileMappingsBase) return ((PerFileMappingsBase<T>)myMappings).getAvailableValues(); throw new UnsupportedOperationException(); } @NotNull protected ActionGroup createActionListGroup(@Nullable Object target, @NotNull Consumer<T> onChosen) { DefaultActionGroup group = new DefaultActionGroup(); String clearText = getClearValueText(target); Function<T, AnAction> choseAction = t -> { String nullValue = StringUtil.notNullize(clearText); AnAction a = new DumbAwareAction(renderValue(t, nullValue), "", getActionListIcon(target, t)) { @Override public void actionPerformed(AnActionEvent e) { onChosen.consume(t); } }; a.getTemplatePresentation().setText(renderValue(t, nullValue)); return a; }; if (clearText != null) { group.add(choseAction.fun(null)); } SimpleColoredText text = new SimpleColoredText(); List<T> values = new ArrayList<>(getValueVariants(target)); Function<T, String> toString = o -> { text.clear(); renderValue(target, o, text); return text.toString(); }; Collections.sort(values, (o1, o2) -> StringUtil.naturalCompare(toString.fun(o1), toString.fun(o2))); for (T t : values) { group.add(choseAction.fun(t)); } return group; } private static class MyModel<T> extends AbstractTableModel { final String[] columnNames; final List<Pair<Object, T>> data = ContainerUtil.newArrayList(); public MyModel(String... names) { columnNames = names; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex > 0; } @Override public int getRowCount() { return data.size(); } @Override public String getColumnName(int column) { return columnNames[column]; } @Override public int getColumnCount() { return columnNames.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return columnIndex == 0 ? data.get(rowIndex).first : data.get(rowIndex).second; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { data.set(rowIndex, Pair.create(data.get(rowIndex).first, (T)aValue)); } } }
platform/lang-impl/src/com/intellij/util/ui/tree/PerFileConfigurableBase.java
/* /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui.tree; import com.intellij.injected.editor.VirtualFileWindow; import com.intellij.lang.LanguagePerFileMappings; import com.intellij.lang.PerFileMappings; import com.intellij.lang.PerFileMappingsBase; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.actionSystem.impl.SimpleDataContext; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.ui.components.JBLabel; import com.intellij.ui.speedSearch.SpeedSearchUtil; import com.intellij.ui.table.JBTable; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.AbstractTableCellEditor; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.*; import java.awt.*; import java.io.File; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static com.intellij.ui.IdeBorderFactory.*; /** * @author peter */ public abstract class PerFileConfigurableBase<T> implements SearchableConfigurable, Configurable.NoScroll { protected static final Key<String> DESCRIPTION = KeyWithDefaultValue.create("DESCRIPTION", ""); protected static final Key<String> TARGET_TITLE = KeyWithDefaultValue.create("TARGET_TITLE", "Path"); protected static final Key<String> MAPPING_TITLE = KeyWithDefaultValue.create("MAPPING_TITLE", "Mapping"); protected static final Key<String> EMPTY_TEXT = KeyWithDefaultValue.create("EMPTY_TEXT", "New Mapping $addShortcut"); protected static final Key<String> OVERRIDE_QUESTION = Key.create("OVERRIDE_QUESTION"); protected static final Key<String> OVERRIDE_TITLE = Key.create("OVERRIDE_TITLE"); protected static final Key<String> CLEAR_TEXT = KeyWithDefaultValue.create("CLEAR_TEXT", "<Clear>"); protected static final Key<String> NULL_TEXT = KeyWithDefaultValue.create("NULL_TEXT", "<None>"); protected final Project myProject; protected final PerFileMappings<T> myMappings; /** @noinspection FieldCanBeLocal */ private JPanel myPanel; private JBTable myTable; private MyModel<T> myModel; private final List<Runnable> myResetRunnables = ContainerUtil.newArrayList(); private final Map<String, T> myDefaultVals = ContainerUtil.newHashMap(); private final List<Trinity<String, Producer<T>, Consumer<T>>> myDefaultProps = ContainerUtil.newArrayList(); private VirtualFile myFileToSelect; protected PerFileConfigurableBase(@NotNull Project project, @NotNull PerFileMappings<T> mappings) { myProject = project; myMappings = mappings; } @Override @NotNull public String getId() { return getDisplayName(); } @Nullable protected abstract <S> Object getParameter(@NotNull Key<S> key); @NotNull protected List<Trinity<String, Producer<T>, Consumer<T>>> getDefaultMappings() { return ContainerUtil.emptyList(); } protected boolean canRemoveTarget(@Nullable Object target) { return true; } protected boolean canEditTarget(@Nullable Object target, T value) { return true; } protected T adjustChosenValue(@Nullable Object target, T chosen) { return chosen; } protected abstract void renderValue(@Nullable Object target, @NotNull T t, @NotNull ColoredTextContainer renderer); protected void renderDefaultValue(@Nullable Object target, @NotNull ColoredTextContainer renderer) { } private <S> S param(@NotNull Key<S> key) { Object o = getParameter(key); if (o == null && key instanceof KeyWithDefaultValue) return ((KeyWithDefaultValue<S>)key).getDefaultValue(); //noinspection unchecked return (S)o; } @NotNull @Override public JComponent createComponent() { //todo multi-editing, separate project/ide combos _if_ needed by specific configurable (SQL, no Web) myPanel = new JPanel(new BorderLayout()); myTable = new JBTable(myModel = new MyModel<>(param(TARGET_TITLE), param(MAPPING_TITLE))); setupPerFileTable(); JPanel tablePanel = ToolbarDecorator.createDecorator(myTable) .disableUpAction() .disableDownAction() .setAddAction(button -> doAddAction(button)) .setRemoveAction(button -> doRemoveAction(button)) .setEditAction(button -> doEditAction(button)) .setEditActionUpdater(e -> myTable.getSelectedRows().length > 0) .createPanel(); myTable.getEmptyText().setText(param(EMPTY_TEXT).replace( "$addShortcut", KeymapUtil.getFirstKeyboardShortcutText(CommonActionsPanel.getCommonShortcut(CommonActionsPanel.Buttons.ADD)))); JBLabel label = new JBLabel(param(DESCRIPTION)); label.setBorder(BorderFactory.createEmptyBorder(TITLED_BORDER_TOP_INSET, TITLED_BORDER_INDENT, TITLED_BORDER_BOTTOM_INSET, 0)); label.setComponentStyle(UIUtil.ComponentStyle.SMALL); JComponent north = createDefaultMappingComponent(); if (north != null) { myPanel.add(north, BorderLayout.NORTH); } myPanel.add(label, BorderLayout.SOUTH); myPanel.add(tablePanel, BorderLayout.CENTER); return myPanel; } @Nullable protected JComponent createDefaultMappingComponent() { myDefaultProps.addAll(getDefaultMappings()); if (myMappings instanceof LanguagePerFileMappings) { myDefaultProps.add(Trinity.create("Project " + StringUtil.capitalize(param(MAPPING_TITLE)), () -> ((LanguagePerFileMappings<T>)myMappings).getConfiguredMapping(null), o -> myMappings.setMapping(null, o))); } if (myDefaultProps.size() == 0) return null; JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints cons1 = new GridBagConstraints(); cons1.fill = GridBagConstraints.HORIZONTAL; cons1.weightx = 0; cons1.gridx = 0; cons1.insets = JBUI.insets(0, 0, 5, UIUtil.DEFAULT_HGAP); GridBagConstraints cons2 = new GridBagConstraints(); cons2.fill = GridBagConstraints.NONE; cons2.anchor = GridBagConstraints.WEST; cons2.weightx = 0; cons2.gridx = 1; cons2.insets = cons1.insets; panel.add(Box.createGlue(), new GridBagConstraints(2, 0, 1, 1, 1., 1., GridBagConstraints.CENTER, GridBagConstraints.NONE, JBUI.emptyInsets(), 0, 0)); for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { myDefaultVals.put(prop.first, prop.second.produce()); JPanel p = createActionPanel(null, () -> myDefaultVals.get(prop.first), o -> myDefaultVals.put(prop.first, adjustChosenValue(null, o))); panel.add(new JBLabel(prop.first + ":"), cons1); panel.add(p, cons2); } return panel; } private void doAddAction(@NotNull AnActionButton button) { TableCellEditor editor = myTable.getCellEditor(); if (editor != null) editor.cancelCellEditing(); int row = myTable.getSelectedRow(); Object selectedTarget = row >= 0 ? myModel.data.get(myTable.convertRowIndexToModel(row)).first : null; VirtualFile toSelect = myFileToSelect != null ? myFileToSelect : ObjectUtils.tryCast(selectedTarget, VirtualFile.class); FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, true, true, true, true); Set<VirtualFile> chosen = ContainerUtil.newHashSet(FileChooser.chooseFiles(descriptor, myProject, toSelect)); if (chosen.isEmpty()) return; Set<Object> set = myModel.data.stream().map(o -> o.first).collect(Collectors.toSet()); for (VirtualFile file : chosen) { if (!set.add(file)) continue; myModel.data.add(Pair.create(file, null)); } fireMappingChanged(); TIntArrayList rowList = new TIntArrayList(); for (int i = 0, size = myModel.data.size(); i < size; i++) { if (chosen.contains(myModel.data.get(i).first)) rowList.add(i); } int[] rows = rowList.toNativeArray(); for (int i = 0; i < rows.length; i++) { rows[i] = myTable.convertRowIndexToView(rows[i]); } TableUtil.selectRows(myTable, rows); } private void doRemoveAction(@NotNull AnActionButton button) { TableCellEditor editor = myTable.getCellEditor(); if (editor != null) editor.cancelCellEditing(); int[] rows = myTable.getSelectedRows(); int firstRow = rows[0]; Object[] keys = new Object[rows.length]; for (int i = 0; i < rows.length; i++) { keys[i] = myModel.data.get(myTable.convertRowIndexToModel(rows[i])).first; } if (clearSubdirectoriesOnDemandOrCancel(true, keys)) { int toSelect = Math.min(myModel.data.size() - 1, firstRow); if (toSelect >= 0) { TableUtil.selectRows(myTable, new int[]{toSelect}); } } } private void doEditAction(@NotNull AnActionButton button) { TableUtil.editCellAt(myTable, myTable.getSelectedRow(), 1); } @Nullable public T getNewMapping(VirtualFile file) { for (Pair<Object, T> p : ContainerUtil.reverse(myModel.data)) { if (keyMatches(p.first, file, false) && p.second != null) return p.second; } for (Trinity<String, Producer<T>, Consumer<T>> prop : ContainerUtil.reverse(myDefaultProps)) { if (prop.first.startsWith("Project ") || prop.first.startsWith("Global ")) { T t = myDefaultVals.get(prop.first); if (t != null) return t; } } return myMappings.getDefaultMapping(file); } private boolean keyMatches(Object key, VirtualFile file, boolean strict) { if (key instanceof VirtualFile) return VfsUtilCore.isAncestor((VirtualFile)key, file, strict); // todo also patterns if (key == null) return true; return false; } @Override public boolean isModified() { for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { if (!Comparing.equal(prop.second.produce(), myDefaultVals.get(prop.first))) { return true; } } Map<VirtualFile, T> oldMapping = myMappings.getMappings(); Map<VirtualFile, T> newMapping = getNewMappings(); return !newMapping.equals(oldMapping); } @Override public void apply() throws ConfigurationException { myMappings.setMappings(getNewMappings()); for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { prop.third.consume(myDefaultVals.get(prop.first)); } } @Override public void reset() { myModel.data.clear(); for (Map.Entry<VirtualFile, T> e : myMappings.getMappings().entrySet()) { if (myMappings instanceof LanguagePerFileMappings && e.getKey() == null) continue; myModel.data.add(Pair.create(e.getKey(), e.getValue())); } for (Trinity<String, Producer<T>, Consumer<T>> prop : myDefaultProps) { myDefaultVals.put(prop.first, prop.second.produce()); } for (Runnable runnable : myResetRunnables) { runnable.run(); } int[] rows = myTable.getSelectedRows(); fireMappingChanged(); TableUtil.selectRows(myTable, rows); } protected void fireMappingChanged() { Collections.sort(myModel.data, (o1, o2) -> StringUtil.naturalCompare(keyToString(o1.first), keyToString(o2.first))); myModel.fireTableDataChanged(); } protected Map<VirtualFile, T> getNewMappings() { HashMap<VirtualFile, T> map = ContainerUtil.newHashMap(); for (Pair<Object, T> p : myModel.data) { if (p.second != null) { map.put((VirtualFile)p.first, p.second); } } if (myMappings instanceof LanguagePerFileMappings) { for (Trinity<String, Producer<T>, Consumer<T>> prop : ContainerUtil.reverse(myDefaultProps)) { if (prop.first.startsWith("Project ")) { T t = myDefaultVals.get(prop.first); if (t != null) map.put(null, t); break; } } } return map; } public void selectFile(@NotNull VirtualFile virtualFile) { VirtualFile file = virtualFile instanceof VirtualFileWindow ? ((VirtualFileWindow)virtualFile).getDelegate() : virtualFile; int[] rows = findRow(file, false, false); for (int i = 0; i < rows.length; i++) { rows[i] = myTable.convertRowIndexToView(rows[i]); } TableUtil.selectRows(myTable, rows); TableUtil.scrollSelectionToVisible(myTable); myFileToSelect = file; } protected int[] findRow(VirtualFile file, boolean strict, boolean all) { TIntArrayList rows = new TIntArrayList(); List<Pair<Object, T>> reversed = ContainerUtil.reverse(myModel.data); for (int i = 0, size = reversed.size(); i < size; i++) { Pair<Object, T> p = reversed.get(i); if (keyMatches(p.first, file, strict)) { rows.add(size - i - 1); if (!all) break; } } return rows.toNativeArray(); } private static String keyToString(Object o) { if (o == null) return ""; if (o instanceof String) return (String)o; if (o instanceof VirtualFile) return ((VirtualFile)o).getPath(); return String.valueOf(o); } private void setupPerFileTable() { myTable.setEnableAntialiasing(true); myTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); myTable.setRowSelectionAllowed(true); myTable.setShowGrid(false); myTable.getColumnModel().setColumnMargin(0); myTable.getTableHeader().setReorderingAllowed(false); TableRowSorter<MyModel<T>> sorter = new TableRowSorter<>(myModel); sorter.setStringConverter(new TableStringConverter() { final SimpleColoredText text = new SimpleColoredText(); @Override public String toString(TableModel model, int row, int column) { text.clear(); Pair<Object, T> pair = myModel.data.get(row); if (column == 0) renderTarget(pair.first, text); else if (pair.second != null) renderValue(pair.first, pair.second, text); else renderDefaultValue(pair.first, text); return StringUtil.toLowerCase(text.toString()); } }); sorter.setSortable(0, true); sorter.setSortable(1, true); myTable.setRowSorter(sorter); new TableSpeedSearch(myTable, o -> keyToString(o)); FontMetrics metrics = myTable.getFontMetrics(myTable.getFont()); int maxValueWidth = 2 * metrics.stringWidth(myTable.getModel().getColumnName(1)); SimpleColoredText text = new SimpleColoredText(); for (T t : getValueVariants(null)) { text.clear(); renderValue(null, t, text); maxValueWidth = Math.max(metrics.stringWidth(text.toString()), maxValueWidth); } myTable.getColumnModel().getColumn(1).setMinWidth(maxValueWidth); myTable.getColumnModel().getColumn(1).setMaxWidth(2 * maxValueWidth); myTable.getColumnModel().getColumn(0).setCellRenderer(new ColoredTableCellRenderer() { @Override public void acquireState(JTable table, boolean isSelected, boolean hasFocus, int row, int column) { super.acquireState(table, isSelected, false, row, column); } @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) { renderTarget(value, this); SpeedSearchUtil.applySpeedSearchHighlighting(table, this, false, selected); } }); myTable.getColumnModel().getColumn(1).setCellRenderer(new ColoredTableCellRenderer() { @Override public void acquireState(JTable table, boolean isSelected, boolean hasFocus, int row, int column) { super.acquireState(table, isSelected, false, row, column); } @Override protected void customizeCellRenderer(JTable table, @Nullable Object value, boolean selected, boolean hasFocus, int row, int column) { Pair<Object, T> p = myModel.data.get(myTable.convertRowIndexToModel(row)); if (p.second != null) { setTransparentIconBackground(true); renderValue(p.first, p.second, this); } else { renderDefaultValue(p.first, this); } } }); myTable.getColumnModel().getColumn(1).setCellEditor(new AbstractTableCellEditor() { T editorValue; @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { int modelRow = myTable.convertRowIndexToModel(row); Pair<Object, T> pair = myModel.data.get(modelRow); Object target = pair.first; editorValue = pair.second; // (T)value if (!canEditTarget(target, editorValue)) return null; VirtualFile targetFile = target instanceof Project ? null : (VirtualFile)target; JPanel panel = createActionPanel(target, () -> editorValue, chosen -> { editorValue = adjustChosenValue(target, chosen); TableUtil.stopEditing(myTable); if (Comparing.equal(editorValue, chosen)) { // do nothing } else if (clearSubdirectoriesOnDemandOrCancel(false, targetFile)) { myModel.setValueAt(editorValue, modelRow, column); myModel.fireTableDataChanged(); selectFile(targetFile); } }, true); AbstractButton button = UIUtil.uiTraverser(panel).filter(JButton.class).first(); if (button != null) { AtomicInteger clickCount = new AtomicInteger(); button.addActionListener(e -> clickCount.incrementAndGet()); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { if (clickCount.get() == 0 && myTable.getEditorComponent() == panel) { button.doClick(); } }); } return panel; } @Override public Object getCellEditorValue() { return editorValue; } }); } @NotNull protected JPanel createActionPanel(@Nullable Object target, Producer<T> value, @NotNull Consumer<T> consumer) { return createActionPanel(target, value, consumer, false); } @NotNull private JPanel createActionPanel(@Nullable Object target, Producer<T> value, @NotNull Consumer<T> consumer, boolean editor) { AnAction changeAction = createValueAction(target, value, consumer); JComponent comboComponent = ((CustomComponentAction)changeAction).createCustomComponent(changeAction.getTemplatePresentation()); JPanel panel = new JPanel(new BorderLayout()) { @Override public Color getBackground() { // track "Table.selectionInactiveBackground" switch Container parent = getParent(); return parent instanceof JTable ? ((JTable)parent).getSelectionBackground() : super.getBackground(); } }; panel.add(comboComponent, BorderLayout.CENTER); comboComponent.setOpaque(false); DataContext dataContext = SimpleDataContext.getProjectContext(myProject); AnActionEvent event = AnActionEvent.createFromAnAction(changeAction, null, ActionPlaces.UNKNOWN, dataContext); changeAction.update(event); panel.revalidate(); if (!editor) myResetRunnables.add(() -> changeAction.update(null)); return panel; } private boolean clearSubdirectoriesOnDemandOrCancel(boolean keysToo, Object... keys) { TIntArrayList rows = new TIntArrayList(); boolean toOverride = false; for (int i = 0, size = myModel.data.size(); i < size; i++) { Pair<Object, T> p = myModel.data.get(i); if (p.first instanceof VirtualFile) { for (Object key : keys) { if (key == p.first) { if (keysToo) rows.add(-i - 1); break; } else if (keyMatches(key, (VirtualFile)p.first, true)) { toOverride = true; rows.add(i); break; } } } } int ret = !toOverride ? Messages.NO : askUserToOverrideSubdirectories(); if (ret == Messages.CANCEL) return false; int count = 0; for (int i : rows.toNativeArray()) { if (i >= 0 && ret == Messages.NO) continue; int index = (i >= 0 ? i : -i - 1) - count; if (canRemoveTarget(myModel.data.get(index).first)) { myModel.data.remove(index); count ++; } else { myModel.data.set(index, Pair.create(myModel.data.get(0).first, null)); } } if (!rows.isEmpty()) fireMappingChanged(); return true; } private int askUserToOverrideSubdirectories() { String question = param(OVERRIDE_QUESTION); String title = param(OVERRIDE_TITLE); if (question == null || title == null) return Messages.NO; return Messages.showYesNoCancelDialog( myProject, question, title, "Override", "Do Not Override", "Cancel", Messages.getWarningIcon()); } private String renderValue(@Nullable Object value, @NotNull String nullValue) { if (value == null) { return nullValue; } else { SimpleColoredText text = new SimpleColoredText(); renderValue(null, (T)value, text); return text.toString(); } } protected void renderTarget(@Nullable Object target, @NotNull ColoredTextContainer renderer) { VirtualFile file = target instanceof VirtualFile ? (VirtualFile)target : null; if (file != null) { renderer.setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); VirtualFile parent = file.getParent(); if (parent != null) { String parentPath = FileUtil.toSystemDependentName(parent.getPath()); renderer.append(parentPath, SimpleTextAttributes.GRAY_ATTRIBUTES); if (!parentPath.endsWith(File.separator)) { renderer.append(File.separator, SimpleTextAttributes.GRAY_ATTRIBUTES); } } renderer.append(file.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } else if (target == null) { renderer.append("Project", SimpleTextAttributes.GRAY_ATTRIBUTES); } } @NotNull protected final AnAction createValueAction(@Nullable Object target, Producer<T> value, @NotNull Consumer<T> consumer) { return new ComboBoxAction() { void updateText() { getTemplatePresentation().setText(renderValue(value.produce(), getNullValueText(target))); } @Override public void update(AnActionEvent e) { updateText(); } @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { throw new UnsupportedOperationException(); } @Override protected ComboBoxButton createComboBoxButton(Presentation presentation) { return new ComboBoxButton(presentation) { protected JBPopup createPopup(Runnable onDispose) { JBPopup popup = createValueEditorPopup(target, value.produce(), onDispose, getDataContext(), o -> { consumer.consume(o); updateText(); }); popup.setMinimumSize(new Dimension(getMinWidth(), getMinHeight())); return popup; } }; } }; } @NotNull protected JBPopup createValueEditorPopup(@Nullable Object target, @Nullable T value, @Nullable Runnable onDispose, @NotNull DataContext dataContext, @NotNull Consumer<T> onChosen) { return createValueEditorActionListPopup(target, onDispose, dataContext, onChosen); } @NotNull protected final JBPopup createValueEditorActionListPopup(@Nullable Object target, @Nullable Runnable onDispose, @NotNull DataContext dataContext, @NotNull Consumer<T> onChosen) { ActionGroup group = createActionListGroup(target, onChosen); return JBPopupFactory.getInstance().createActionGroupPopup( null, group, dataContext, false, false, false, onDispose, 30, null); } @Nullable protected Icon getActionListIcon(@Nullable Object target, T t) { return null; } @Nullable protected String getClearValueText(@Nullable Object target) { return target == null ? getNullValueText(null) : param(CLEAR_TEXT); } @Nullable protected String getNullValueText(@Nullable Object target) { return param(NULL_TEXT); } @NotNull protected Collection<T> getValueVariants(@Nullable Object target) { if (myMappings instanceof PerFileMappingsBase) return ((PerFileMappingsBase<T>)myMappings).getAvailableValues(); throw new UnsupportedOperationException(); } @NotNull protected ActionGroup createActionListGroup(@Nullable Object target, @NotNull Consumer<T> onChosen) { DefaultActionGroup group = new DefaultActionGroup(); String clearText = getClearValueText(target); Function<T, AnAction> choseAction = t -> { String nullValue = StringUtil.notNullize(clearText); AnAction a = new DumbAwareAction(renderValue(t, nullValue), "", getActionListIcon(target, t)) { @Override public void actionPerformed(AnActionEvent e) { onChosen.consume(t); } }; a.getTemplatePresentation().setText(renderValue(t, nullValue)); return a; }; if (clearText != null) { group.add(choseAction.fun(null)); } SimpleColoredText text = new SimpleColoredText(); List<T> values = new ArrayList<>(getValueVariants(target)); Function<T, String> toString = o -> { text.clear(); renderValue(target, o, text); return text.toString(); }; Collections.sort(values, (o1, o2) -> StringUtil.naturalCompare(toString.fun(o1), toString.fun(o2))); for (T t : values) { group.add(choseAction.fun(t)); } return group; } private static class MyModel<T> extends AbstractTableModel { final String[] columnNames; final List<Pair<Object, T>> data = ContainerUtil.newArrayList(); public MyModel(String... names) { columnNames = names; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex > 0; } @Override public int getRowCount() { return data.size(); } @Override public String getColumnName(int column) { return columnNames[column]; } @Override public int getColumnCount() { return columnNames.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return columnIndex == 0 ? data.get(rowIndex).first : data.get(rowIndex).second; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { data.set(rowIndex, Pair.create(data.get(rowIndex).first, (T)aValue)); } } }
DBE: tooltips
platform/lang-impl/src/com/intellij/util/ui/tree/PerFileConfigurableBase.java
DBE: tooltips
<ide><path>latform/lang-impl/src/com/intellij/util/ui/tree/PerFileConfigurableBase.java <ide> import javax.swing.*; <ide> import javax.swing.table.*; <ide> import java.awt.*; <add>import java.awt.event.MouseEvent; <ide> import java.io.File; <ide> import java.util.*; <ide> import java.util.List; <ide> public JComponent createComponent() { <ide> //todo multi-editing, separate project/ide combos _if_ needed by specific configurable (SQL, no Web) <ide> myPanel = new JPanel(new BorderLayout()); <del> myTable = new JBTable(myModel = new MyModel<>(param(TARGET_TITLE), param(MAPPING_TITLE))); <add> myTable = new JBTable(myModel = new MyModel<>(param(TARGET_TITLE), param(MAPPING_TITLE))) { <add> @Override <add> public String getToolTipText(@NotNull MouseEvent event) { <add> Point point = event.getPoint(); <add> int row = rowAtPoint(point); <add> int col = columnAtPoint(point); <add> if (row != -1 && col == 1) return getToolTipFor((T)getValueAt(convertRowIndexToModel(row), col)); <add> return super.getToolTipText(event); <add> } <add> }; <ide> setupPerFileTable(); <ide> JPanel tablePanel = ToolbarDecorator.createDecorator(myTable) <ide> .disableUpAction() <ide> myPanel.add(tablePanel, BorderLayout.CENTER); <ide> <ide> return myPanel; <add> } <add> <add> protected String getToolTipFor(T value) { <add> return null; <ide> } <ide> <ide> @Nullable
Java
mit
ad1afd44c29026c0dbf45998517481812f7371dd
0
hamadycisse/hackathon2017
app/src/main/java/hackathon/rc/ca/hackathon/client/TestRebaseBoris.java
package hackathon.rc.ca.hackathon.client; /** * Created by Boris on 2017-03-25. */ public class TestRebaseBoris { }
Test un peu con de la classe TestRebaseBoris dans Client
app/src/main/java/hackathon/rc/ca/hackathon/client/TestRebaseBoris.java
Test un peu con de la classe TestRebaseBoris dans Client
<ide><path>pp/src/main/java/hackathon/rc/ca/hackathon/client/TestRebaseBoris.java <del>package hackathon.rc.ca.hackathon.client; <del> <del>/** <del> * Created by Boris on 2017-03-25. <del> */ <del> <del>public class TestRebaseBoris { <del>}
JavaScript
mit
ed711e5f2b5b9c384cebea7574f397a50ac214b7
0
nabab/bbn-vue,nabab/bbn-vue
/** * @file bbn-markdown component * * @description bbn-markdown is a component that allows you to easily format the Markdown text. * It's an editor that enable you to create textual content, to insert lists, image management and hyperlinks. * * @copyright BBN Solutions * * @author BBN Solutions */ //Markdown editor use simpleMDe (function(bbn, SimpleMDE){ "use strict"; const toolbar = [ { "name": "bold", "className": "nf nf-fa-bold", "title": bbn._("Bold"), "default": true }, { "name": "italic", "className": "nf nf-fa-italic", "title": bbn._("Italic"), "default": true }, { "name": "heading", "className": "nf nf-fa-header", "title": bbn._("Heading"), "default": true }, "|", { "name": "quote", "className": "nf nf-fa-quote-left", "title": bbn._("Quote"), "default": true }, { "name": "unordered-list", "className": "nf nf-fa-list-ul", "title": bbn._("Generic List"), "default": true }, { "name": "ordered-list", "className": "nf nf-fa-list-ol", "title": bbn._("Numbered List"), "default": true }, "|", { "name": "link", "className": "nf nf-fa-link", "title": bbn._("Create Link"), "default": true }, { "name": "image", "className": "fas fa-image", "title": bbn._("Insert Image"), "default": true }, "|", { "name": "preview", "className": "nf nf-fa-eye no-disable", "title": bbn._("Toggle Preview"), "default": true }, { "name": "side-by-side", "className": "nf nf-fa-columns no-disable no-mobile", "title": bbn._("Toggle Side by Side"), "default": true }, { "name": "fullscreen", "className": "nf nf-fa-arrows-alt no-disable no-mobile", "title": bbn._("Toggle Fullscreen"), "default": true }/*, "|", { "name": "guide", "action": "https://simplemde.com/markdown-guide", "className": "nf nf-fa-question-circle", "title": bbn._("Markdown Guide"), "default": true }, "|" */ ]; Vue.component('bbn-markdown', { /** * @mixin bbn.vue.basicComponent * @mixin bbn.vue.inputComponent * @mixin bbn.vue.eventsComponent */ mixins: [bbn.vue.basicComponent, bbn.vue.inputComponent, bbn.vue.eventsComponent], props: { /** * The object of configuration * @prop {Object} cfg */ cfg: { type: Object, default(){ return {}; } }, //@todo not used toolbar: { type: Array }, //@todo not used hideIcons: { type: Array } }, data(){ return { widgetName: "SimpleMDE", autoDownloadFontAwesome: this.cfg.autoDownloadFontAwesome || false, spellChecker: this.cfg.spellChecker || false, indentWithTabs: this.cfg.indentWithTabs === undefined ? true : this.cfg.indentWithTabs, initialValue: this.cfg.initialValue || '', insertTexts: { horizontalRule: ["", "\n\n-----\n\n"], image: ["![](http://", ")"], link: ["[", "](http://)"], table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"], }, renderingConfig: { singleLineBreaks: true, codeSyntaxHighlighting: true, }, toolbar: this.toolbar || toolbar, status: false, tabSize: this.cfg.tabSize || 2, toolbarTips: true, shortcuts: { drawTable: "Cmd-Alt-T" } }; }, methods: { disableWidget(v){ this.widget.codemirror.setOption('disableInput', !!v); if ( !v && !this.readonly ){ this.widget.codemirror.setOption('readOnly', false); this.$el.querySelector("div.editor-toolbar").display = 'block' } else { this.widget.codemirror.setOption('readOnly', true); this.$el.querySelector("div.editor-toolbar").display = 'none' } }, readonlyWidget(v){ this.widget.codemirror.setOption('readOnly', !!v); if ( !v && !this.disabled ){ this.$el.querySelector("div.editor-toolbar").display = 'block' } else { this.$el.querySelector("div.editor-toolbar").display = 'none' } } }, watch: { disabled(newVal){ this.disableWidget(newVal); }, readonly(newVal){ this.readonlyWidget(newVal); } }, mounted(){ const vm = this; /*let cfg = bbn.fn.extend(vm.getOptions(), { change: function(e){ vm.emitInput(vm.widget.value()); return true } });*/ this.widget = new SimpleMDE(bbn.fn.extend({ element: this.$refs.element }, this.$data)); this.widget.codemirror.on("change", () => { this.emitInput(this.widget.value()); }); if ( this.disabled ){ this.disableWidget(true); } if ( this.readonly ){ this.readonlyWidget(true); } this.ready = true; }, }); })(bbn, SimpleMDE);
src/components/markdown/markdown.js
/** * @file bbn-markdown component * * @description bbn-markdown is a component that allows you to easily format the Markdown text. * It's an editor that enable you to create textual content, to insert lists, image management and hyperlinks. * * @copyright BBN Solutions * * @author BBN Solutions */ //Markdown editor use simpleMDe (function(bbn, SimpleMDE){ "use strict"; Vue.component('bbn-markdown', { /** * @mixin bbn.vue.basicComponent * @mixin bbn.vue.inputComponent * @mixin bbn.vue.eventsComponent */ mixins: [bbn.vue.basicComponent, bbn.vue.inputComponent, bbn.vue.eventsComponent], props: { /** * The object of configuration * @prop {Object} cfg */ cfg: { type: Object, default(){ return {}; } }, //@todo not used toolbar: { type: Array }, //@todo not used hideIcons: { type: Array } }, data(){ return { widgetName: "SimpleMDE", autoDownloadFontAwesome: this.cfg.autoDownloadFontAwesome || false, spellChecker: this.cfg.spellChecker || false, indentWithTabs: this.cfg.indentWithTabs === undefined ? true : this.cfg.indentWithTabs, initialValue: this.cfg.initialValue || '', insertTexts: { horizontalRule: ["", "\n\n-----\n\n"], image: ["![](http://", ")"], link: ["[", "](http://)"], table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"], }, renderingConfig: { singleLineBreaks: true, codeSyntaxHighlighting: true, }, status: false, tabSize: this.cfg.tabSize || 2, toolbarTips: true, shortcuts: { drawTable: "Cmd-Alt-T" } }; }, methods: { disableWidget(v){ this.widget.codemirror.setOption('disableInput', !!v); if ( !v && !this.readonly ){ this.widget.codemirror.setOption('readOnly', false); this.$el.querySelector("div.editor-toolbar").display = 'block' } else { this.widget.codemirror.setOption('readOnly', true); this.$el.querySelector("div.editor-toolbar").display = 'none' } }, readonlyWidget(v){ this.widget.codemirror.setOption('readOnly', !!v); if ( !v && !this.disabled ){ this.$el.querySelector("div.editor-toolbar").display = 'block' } else { this.$el.querySelector("div.editor-toolbar").display = 'none' } } }, watch: { disabled(newVal){ this.disableWidget(newVal); }, readonly(newVal){ this.readonlyWidget(newVal); } }, mounted(){ const vm = this; /*let cfg = bbn.fn.extend(vm.getOptions(), { change: function(e){ vm.emitInput(vm.widget.value()); return true } });*/ this.widget = new SimpleMDE(bbn.fn.extend({ element: this.$refs.element }, this.$data)); this.widget.codemirror.on("change", () => { this.emitInput(this.widget.value()); }); if ( this.disabled ){ this.disableWidget(true); } if ( this.readonly ){ this.readonlyWidget(true); } this.ready = true; }, }); })(bbn, SimpleMDE);
Markdown w/ Nerd fonts
src/components/markdown/markdown.js
Markdown w/ Nerd fonts
<ide><path>rc/components/markdown/markdown.js <ide> //Markdown editor use simpleMDe <ide> (function(bbn, SimpleMDE){ <ide> "use strict"; <add> <add> const toolbar = [ <add> { <add> "name": "bold", <add> "className": "nf nf-fa-bold", <add> "title": bbn._("Bold"), <add> "default": true <add> }, <add> { <add> "name": "italic", <add> "className": "nf nf-fa-italic", <add> "title": bbn._("Italic"), <add> "default": true <add> }, <add> { <add> "name": "heading", <add> "className": "nf nf-fa-header", <add> "title": bbn._("Heading"), <add> "default": true <add> }, <add> "|", <add> { <add> "name": "quote", <add> "className": "nf nf-fa-quote-left", <add> "title": bbn._("Quote"), <add> "default": true <add> }, <add> { <add> "name": "unordered-list", <add> "className": "nf nf-fa-list-ul", <add> "title": bbn._("Generic List"), <add> "default": true <add> }, <add> { <add> "name": "ordered-list", <add> "className": "nf nf-fa-list-ol", <add> "title": bbn._("Numbered List"), <add> "default": true <add> }, <add> "|", <add> { <add> "name": "link", <add> "className": "nf nf-fa-link", <add> "title": bbn._("Create Link"), <add> "default": true <add> }, <add> { <add> "name": "image", <add> "className": "fas fa-image", <add> "title": bbn._("Insert Image"), <add> "default": true <add> }, <add> "|", <add> { <add> "name": "preview", <add> "className": "nf nf-fa-eye no-disable", <add> "title": bbn._("Toggle Preview"), <add> "default": true <add> }, <add> { <add> "name": "side-by-side", <add> "className": "nf nf-fa-columns no-disable no-mobile", <add> "title": bbn._("Toggle Side by Side"), <add> "default": true <add> }, <add> { <add> "name": "fullscreen", <add> "className": "nf nf-fa-arrows-alt no-disable no-mobile", <add> "title": bbn._("Toggle Fullscreen"), <add> "default": true <add> }/*, <add> "|", <add> { <add> "name": "guide", <add> "action": "https://simplemde.com/markdown-guide", <add> "className": "nf nf-fa-question-circle", <add> "title": bbn._("Markdown Guide"), <add> "default": true <add> }, <add> "|" */ <add> ]; <ide> <ide> Vue.component('bbn-markdown', { <ide> /** <ide> singleLineBreaks: true, <ide> codeSyntaxHighlighting: true, <ide> }, <add> toolbar: this.toolbar || toolbar, <ide> status: false, <ide> tabSize: this.cfg.tabSize || 2, <ide> toolbarTips: true,
Java
mit
error: pathspec 'src/main/java/kr/co/leehana/controller/MainController.java' did not match any file(s) known to git
62e3be0da396c7b48ecd4f5f0534534fa3b65814
1
Hana-Lee/pc-bang
package kr.co.leehana.controller; import kr.co.leehana.view.LoginFrame; import kr.co.leehana.view.ManageView; /** * @author Hana Lee * @since 2015-11-14 03-28 */ public class MainController { private LoginFrame loginFrame; private ManageView manageView; }
src/main/java/kr/co/leehana/controller/MainController.java
์„œ๋ฒ„์™€ ํด๋ผ์ด์–ธํŠธ ํ†ต์‹  ๋ฐ ์‚ฌ์šฉ์ž ํ™”๋ฉด๋“ค์„ ๊ด€๋ฆฌ ํ•˜๊ธฐ ์œ„ํ•œ ๋ฉ”์ธ ์ปจํŠธ๋กค ํด๋ž˜์Šค ์ถ”๊ฐ€.
src/main/java/kr/co/leehana/controller/MainController.java
์„œ๋ฒ„์™€ ํด๋ผ์ด์–ธํŠธ ํ†ต์‹  ๋ฐ ์‚ฌ์šฉ์ž ํ™”๋ฉด๋“ค์„ ๊ด€๋ฆฌ ํ•˜๊ธฐ ์œ„ํ•œ ๋ฉ”์ธ ์ปจํŠธ๋กค ํด๋ž˜์Šค ์ถ”๊ฐ€.
<ide><path>rc/main/java/kr/co/leehana/controller/MainController.java <add>package kr.co.leehana.controller; <add> <add>import kr.co.leehana.view.LoginFrame; <add>import kr.co.leehana.view.ManageView; <add> <add>/** <add> * @author Hana Lee <add> * @since 2015-11-14 03-28 <add> */ <add>public class MainController { <add> <add> private LoginFrame loginFrame; <add> private ManageView manageView; <add> <add>}